test.cc 842 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // Empty quality value
  892. EXPECT_FALSE(
  893. detail::parse_accept_header("text/html;q=,application/json", result));
  894. // Invalid media type format (no slash and not wildcard)
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("invalidtype,application/json", result));
  897. // Valid cases should still work
  898. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  899. EXPECT_EQ(result.size(), 1U);
  900. EXPECT_EQ(result[0], "*/*");
  901. EXPECT_TRUE(detail::parse_accept_header("*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*");
  904. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "text/*");
  907. }
  908. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  909. // elements, so a leading, trailing or doubled comma is a legal Accept value
  910. // and must not be answered with 400 Bad Request.
  911. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  912. struct {
  913. const char *value;
  914. std::vector<std::string> expected;
  915. } cases[] = {
  916. {",application/json", {"application/json"}},
  917. {"text/html,", {"text/html"}},
  918. {"text/html,,*/*", {"text/html", "*/*"}},
  919. // An empty element may be spelled with whitespace in it
  920. {"text/html, , application/json", {"text/html", "application/json"}},
  921. // Nothing but empty elements is an empty list, which means the same
  922. // thing as no Accept header at all
  923. {",,,", {}},
  924. // Quality values still apply across ignored empty elements
  925. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  926. };
  927. for (const auto &c : cases) {
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  930. << "value: " << c.value;
  931. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  932. }
  933. // An invalid entry is still rejected when empty elements surround it
  934. std::vector<std::string> result;
  935. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  936. }
  937. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  938. Server svr;
  939. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  940. EXPECT_EQ(req.accept_content_types.size(), 3U);
  941. EXPECT_EQ(req.accept_content_types[0], "application/json");
  942. EXPECT_EQ(req.accept_content_types[1], "text/html");
  943. EXPECT_EQ(req.accept_content_types[2], "*/*");
  944. res.set_content("ok", "text/plain");
  945. });
  946. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  947. EXPECT_TRUE(false);
  948. res.set_content("bad request", "text/plain");
  949. });
  950. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  951. auto se = detail::scope_exit([&] {
  952. svr.stop();
  953. listen_thread.join();
  954. ASSERT_FALSE(svr.is_running());
  955. });
  956. svr.wait_until_ready();
  957. Client cli("localhost", PORT);
  958. {
  959. auto res = cli.Get(
  960. "/accept_ok",
  961. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  963. EXPECT_EQ(StatusCode::OK_200, res->status);
  964. }
  965. {
  966. auto res = cli.Get("/accept_bad_request",
  967. Headers{{"Accept", "text/html;q=abc,application/json"}});
  968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  970. }
  971. }
  972. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  973. Server svr;
  974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  975. res.set_content("ok", "text/plain");
  976. });
  977. std::atomic<int> start_count{0};
  978. std::atomic<bool> running_when_called{false};
  979. svr.set_start_handler([&]() {
  980. running_when_called = svr.is_running();
  981. start_count++;
  982. });
  983. auto port = svr.bind_to_any_port(HOST);
  984. std::thread t([&]() { svr.listen_after_bind(); });
  985. auto se = detail::scope_exit([&] {
  986. svr.stop();
  987. t.join();
  988. ASSERT_FALSE(svr.is_running());
  989. });
  990. svr.wait_until_ready();
  991. // A successful request proves the accept loop is running, which the start
  992. // handler precedes; so by now the handler must have run exactly once.
  993. Client cli(HOST, port);
  994. cli.set_connection_timeout(std::chrono::seconds(5));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  997. EXPECT_EQ(StatusCode::OK_200, res->status);
  998. EXPECT_EQ(1, start_count.load());
  999. EXPECT_TRUE(running_when_called.load());
  1000. }
  1001. TEST(DivideTest, DivideStringTests) {
  1002. auto divide = [](const std::string &str, char d) {
  1003. std::string lhs;
  1004. std::string rhs;
  1005. detail::divide(str, d,
  1006. [&](const char *lhs_data, std::size_t lhs_size,
  1007. const char *rhs_data, std::size_t rhs_size) {
  1008. lhs.assign(lhs_data, lhs_size);
  1009. rhs.assign(rhs_data, rhs_size);
  1010. });
  1011. return std::make_pair(std::move(lhs), std::move(rhs));
  1012. };
  1013. {
  1014. const auto res = divide("", '=');
  1015. EXPECT_EQ(res.first, "");
  1016. EXPECT_EQ(res.second, "");
  1017. }
  1018. {
  1019. const auto res = divide("=", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide(" ", '=');
  1025. EXPECT_EQ(res.first, " ");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide("a", '=');
  1030. EXPECT_EQ(res.first, "a");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a=", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("=b", '=');
  1040. EXPECT_EQ(res.first, "");
  1041. EXPECT_EQ(res.second, "b");
  1042. }
  1043. {
  1044. const auto res = divide("a=b", '=');
  1045. EXPECT_EQ(res.first, "a");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b=", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b=");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=c", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=c");
  1057. }
  1058. }
  1059. TEST(SplitTest, ParseQueryString) {
  1060. string s = "key1=val1&key2=val2&key3=val3";
  1061. Params dic;
  1062. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1063. [&](const char *b, const char *e) {
  1064. string key, val;
  1065. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1066. if (key.empty()) {
  1067. key.assign(b2, e2);
  1068. } else {
  1069. val.assign(b2, e2);
  1070. }
  1071. });
  1072. dic.emplace(key, val);
  1073. });
  1074. EXPECT_EQ("val1", dic.find("key1")->second);
  1075. EXPECT_EQ("val2", dic.find("key2")->second);
  1076. EXPECT_EQ("val3", dic.find("key3")->second);
  1077. }
  1078. TEST(SplitTest, ParseInvalidQueryTests) {
  1079. {
  1080. string s = " ";
  1081. Params dict;
  1082. detail::parse_query_text(s, dict);
  1083. EXPECT_TRUE(dict.empty());
  1084. }
  1085. {
  1086. string s = " = =";
  1087. Params dict;
  1088. detail::parse_query_text(s, dict);
  1089. EXPECT_TRUE(dict.empty());
  1090. }
  1091. }
  1092. TEST(ParseQueryTest, ParseQueryString) {
  1093. {
  1094. std::string s = "key1=val1&key2=val2&key3=val3";
  1095. Params dic;
  1096. detail::parse_query_text(s, dic);
  1097. EXPECT_EQ("val1", dic.find("key1")->second);
  1098. EXPECT_EQ("val2", dic.find("key2")->second);
  1099. EXPECT_EQ("val3", dic.find("key3")->second);
  1100. }
  1101. {
  1102. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1103. Params dic;
  1104. detail::parse_query_text(s, dic);
  1105. EXPECT_EQ("", dic.find("key1")->second);
  1106. EXPECT_EQ("val1", dic.find("key2")->second);
  1107. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1108. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1109. }
  1110. }
  1111. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1112. Params dic;
  1113. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1114. dic.emplace("key1", "val1");
  1115. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1116. dic.emplace("key2", "val2");
  1117. dic.emplace("key3", "val3");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1119. }
  1120. // Joins every entry of a Headers or Params into "key=value " so a whole
  1121. // traversal can be compared in one assertion. Both are instantiations of the
  1122. // same insertion-ordered container, so one helper serves both.
  1123. template <typename Map> static std::string entries_to_string(const Map &m) {
  1124. std::string s;
  1125. for (const auto &entry : m) {
  1126. s += entry.first + "=" + entry.second + " ";
  1127. }
  1128. return s;
  1129. }
  1130. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1131. // Params used to be a std::multimap, which sorted by name and handed the
  1132. // caller's query back alphabetised. A client signing its query string could
  1133. // not reproduce the order it asked for.
  1134. Params dic;
  1135. dic.emplace("zulu", "1");
  1136. dic.emplace("alpha", "2");
  1137. dic.emplace("mike", "3");
  1138. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1139. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1140. }
  1141. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1142. Params dic;
  1143. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1144. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1145. }
  1146. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1147. Request req;
  1148. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1149. req.params);
  1150. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1151. EXPECT_EQ("first", req.get_param_value("tag"));
  1152. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1153. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1154. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1155. EXPECT_EQ("", req.get_param_value("tag", 3));
  1156. }
  1157. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1158. // Params shares its container with Headers, which matches field names
  1159. // case-insensitively. Parameter names must not pick that up.
  1160. Params dic;
  1161. dic.emplace("Key", "upper");
  1162. dic.emplace("key", "lower");
  1163. EXPECT_EQ(2U, dic.size());
  1164. EXPECT_EQ(1U, dic.count("Key"));
  1165. EXPECT_EQ(1U, dic.count("key"));
  1166. EXPECT_EQ("upper", dic.find("Key")->second);
  1167. EXPECT_EQ("lower", dic.find("key")->second);
  1168. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1169. }
  1170. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1171. Server svr;
  1172. std::string order;
  1173. svr.Get("/order", [&](const Request &req, Response &res) {
  1174. order = entries_to_string(req.params);
  1175. res.set_content("ok", "text/plain");
  1176. });
  1177. auto port = svr.bind_to_any_port(HOST);
  1178. thread t = thread([&] { svr.listen_after_bind(); });
  1179. auto se = detail::scope_exit([&] {
  1180. svr.stop();
  1181. t.join();
  1182. ASSERT_FALSE(svr.is_running());
  1183. });
  1184. svr.wait_until_ready();
  1185. Client cli(HOST, port);
  1186. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1189. }
  1190. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1191. Server svr;
  1192. std::string field_order, file_order;
  1193. svr.Post("/order", [&](const Request &req, Response &res) {
  1194. for (const auto &field : req.form.fields) {
  1195. field_order += field.first + "=" + field.second.content + " ";
  1196. }
  1197. for (const auto &file : req.form.files) {
  1198. file_order += file.first + "=" + file.second.filename + " ";
  1199. }
  1200. res.set_content("ok", "text/plain");
  1201. });
  1202. auto port = svr.bind_to_any_port(HOST);
  1203. thread t = thread([&] { svr.listen_after_bind(); });
  1204. auto se = detail::scope_exit([&] {
  1205. svr.stop();
  1206. t.join();
  1207. ASSERT_FALSE(svr.is_running());
  1208. });
  1209. svr.wait_until_ready();
  1210. UploadFormDataItems items = {
  1211. {"zulu", "1", "", ""},
  1212. {"alpha", "2", "", ""},
  1213. {"mike", "3", "", ""},
  1214. {"zebra", "z", "z.txt", "text/plain"},
  1215. {"apple", "a", "a.txt", "text/plain"},
  1216. };
  1217. Client cli(HOST, port);
  1218. auto res = cli.Post("/order", items);
  1219. ASSERT_TRUE(res);
  1220. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1221. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1222. }
  1223. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1224. Server svr;
  1225. std::vector<std::string> values;
  1226. std::string first, second, out_of_range, order;
  1227. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1228. values = req.form.get_fields("tag");
  1229. first = req.form.get_field("tag", 0);
  1230. second = req.form.get_field("tag", 1);
  1231. out_of_range = req.form.get_field("tag", 2);
  1232. for (const auto &field : req.form.fields) {
  1233. order += field.first + "=" + field.second.content + " ";
  1234. }
  1235. res.set_content("ok", "text/plain");
  1236. });
  1237. auto port = svr.bind_to_any_port(HOST);
  1238. thread t = thread([&] { svr.listen_after_bind(); });
  1239. auto se = detail::scope_exit([&] {
  1240. svr.stop();
  1241. t.join();
  1242. ASSERT_FALSE(svr.is_running());
  1243. });
  1244. svr.wait_until_ready();
  1245. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1246. // not adjacent in the container.
  1247. UploadFormDataItems items = {
  1248. {"tag", "first", "", ""},
  1249. {"other", "x", "", ""},
  1250. {"tag", "second", "", ""},
  1251. };
  1252. Client cli(HOST, port);
  1253. auto res = cli.Post("/repeated", items);
  1254. ASSERT_TRUE(res);
  1255. ASSERT_EQ(2U, values.size());
  1256. EXPECT_EQ("first", values[0]);
  1257. EXPECT_EQ("second", values[1]);
  1258. EXPECT_EQ("first", first);
  1259. EXPECT_EQ("second", second);
  1260. // std::multimap already kept entries sharing a name in insertion order, so
  1261. // everything above passes without this change too. The whole traversal is
  1262. // what tells the two apart: sorting by name would hoist "other" to the front
  1263. // and the two "tag" parts would end up adjacent.
  1264. EXPECT_EQ("tag=first other=x tag=second ", order);
  1265. // Advancing past the last entry of a name used to run off the container;
  1266. // the container's saturating increment makes it return the default instead.
  1267. EXPECT_EQ("", out_of_range);
  1268. }
  1269. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1270. // Server::read_content() keeps a FormFields::iterator alive across the
  1271. // content callbacks that fill the part it points at. The container is
  1272. // vector-backed, so a later emplace can reallocate and invalidate an older
  1273. // iterator; 64 parts grow the vector through seven reallocations, which
  1274. // checks that every part's content still lands in its own entry.
  1275. const size_t part_count = 64;
  1276. // One formula for both the parts sent and the values expected back, so the
  1277. // two cannot drift apart.
  1278. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1279. auto content_of = [](size_t i) {
  1280. return std::string(64, static_cast<char>('a' + (i % 26)));
  1281. };
  1282. Server svr;
  1283. std::vector<std::pair<std::string, std::string>> received;
  1284. svr.Post("/many", [&](const Request &req, Response &res) {
  1285. for (const auto &field : req.form.fields) {
  1286. received.emplace_back(field.first, field.second.content);
  1287. }
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. auto port = svr.bind_to_any_port(HOST);
  1291. thread t = thread([&] { svr.listen_after_bind(); });
  1292. auto se = detail::scope_exit([&] {
  1293. svr.stop();
  1294. t.join();
  1295. ASSERT_FALSE(svr.is_running());
  1296. });
  1297. svr.wait_until_ready();
  1298. UploadFormDataItems items;
  1299. for (size_t i = 0; i < part_count; i++) {
  1300. items.push_back({name_of(i), content_of(i), "", ""});
  1301. }
  1302. Client cli(HOST, port);
  1303. auto res = cli.Post("/many", items);
  1304. ASSERT_TRUE(res);
  1305. ASSERT_EQ(part_count, received.size());
  1306. for (size_t i = 0; i < part_count; i++) {
  1307. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1308. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1309. }
  1310. }
  1311. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1312. string content_type = "multipart/form-data; boundary=something";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "something");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1319. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1320. string boundary;
  1321. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1322. EXPECT_TRUE(ret);
  1323. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1324. }
  1325. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1326. string content_type =
  1327. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1328. string boundary;
  1329. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1330. EXPECT_TRUE(ret);
  1331. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1334. string content_type =
  1335. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1336. string boundary;
  1337. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1338. EXPECT_TRUE(ret);
  1339. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1340. }
  1341. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1342. const string boundary(70, 'a');
  1343. string content_type = "multipart/form-data; boundary=" + boundary;
  1344. string parsed;
  1345. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1346. EXPECT_TRUE(ret);
  1347. EXPECT_EQ(parsed, boundary);
  1348. }
  1349. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1350. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1351. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1352. string parsed;
  1353. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1354. EXPECT_FALSE(ret);
  1355. }
  1356. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1357. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1358. // is 72 characters on the wire and still valid.
  1359. const string boundary(70, 'a');
  1360. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1361. string parsed;
  1362. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1363. EXPECT_EQ(parsed, boundary);
  1364. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1365. parsed.clear();
  1366. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1367. }
  1368. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1369. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1370. // The parameter parser must not treat that '=' as the key/value separator.
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1373. "charset=UTF-8";
  1374. string parsed;
  1375. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1376. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1379. // A ';' inside the quoted-string is part of the value, not a parameter
  1380. // separator, so it must not truncate the boundary.
  1381. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1382. string parsed;
  1383. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1384. EXPECT_EQ(parsed, "a;b");
  1385. }
  1386. TEST(ParseDispositionParamsTest, QuotedValues) {
  1387. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1388. // ';' and '=' are ordinary characters inside one.
  1389. struct {
  1390. const char *value;
  1391. std::vector<std::pair<const char *, const char *>> expected;
  1392. } cases[] = {
  1393. {"name=\"file1\"; filename=\"a.txt\"",
  1394. {{"name", "file1"}, {"filename", "a.txt"}}},
  1395. // Whitespace around '=' and ';' is still trimmed
  1396. {"name=\"file2\" ;filename = \"a.html\"",
  1397. {{"name", "file2"}, {"filename", "a.html"}}},
  1398. // '=' inside the value used to leave only the text after the last one
  1399. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1400. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1401. {"name=\"x=y\"", {{"name", "x=y"}}},
  1402. // ';' inside the value used to truncate the pair and leave a bogus one
  1403. {"name=\"file3\"; filename=\"a;b.txt\"",
  1404. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1405. // An unquoted value keeps working, and so does filename*
  1406. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1407. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1408. // A parameter with no key is dropped rather than turned into one whose
  1409. // key is the value
  1410. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1411. };
  1412. for (const auto &c : cases) {
  1413. Params params;
  1414. detail::parse_disposition_params(c.value, params);
  1415. for (const auto &kv : c.expected) {
  1416. auto it = params.find(kv.first);
  1417. ASSERT_NE(it, params.end())
  1418. << "value: " << c.value << ", key: " << kv.first;
  1419. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1420. }
  1421. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1422. }
  1423. }
  1424. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1425. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1426. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1427. Server svr;
  1428. std::string field_value, file_name, file_filename;
  1429. bool has_field = false, has_file = false;
  1430. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1431. has_field = req.form.has_field("x=y");
  1432. field_value = req.form.get_field("x=y");
  1433. has_file = req.form.has_file("file1");
  1434. const auto &file = req.form.get_file("file1");
  1435. file_name = file.name;
  1436. file_filename = file.filename;
  1437. res.set_content("ok", "text/plain");
  1438. });
  1439. auto port = svr.bind_to_any_port(HOST);
  1440. thread t = thread([&] { svr.listen_after_bind(); });
  1441. auto se = detail::scope_exit([&] {
  1442. svr.stop();
  1443. t.join();
  1444. ASSERT_FALSE(svr.is_running());
  1445. });
  1446. svr.wait_until_ready();
  1447. UploadFormDataItems items = {
  1448. {"x=y", "field-value", "", ""},
  1449. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1450. };
  1451. Client cli(HOST, port);
  1452. auto res = cli.Post("/quoted", items);
  1453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1454. ASSERT_EQ(StatusCode::OK_200, res->status);
  1455. EXPECT_TRUE(has_field);
  1456. EXPECT_EQ("field-value", field_value);
  1457. EXPECT_TRUE(has_file);
  1458. EXPECT_EQ("file1", file_name);
  1459. EXPECT_EQ("a;b=report.pdf", file_filename);
  1460. }
  1461. TEST(GetHeaderValueTest, DefaultValue) {
  1462. Headers headers = {{"Dummy", "Dummy"}};
  1463. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1464. EXPECT_STREQ("text/plain", val);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValueInt) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1469. EXPECT_EQ(100ull, val);
  1470. }
  1471. TEST(GetHeaderValueTest, RegularValue) {
  1472. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1474. EXPECT_STREQ("text/html", val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, SetContent) {
  1482. Response res;
  1483. res.set_content("html", "text/html");
  1484. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1485. res.set_content("text", "text/plain");
  1486. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1487. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1488. }
  1489. TEST(GetHeaderValueTest, RegularValueInt) {
  1490. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1491. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1492. EXPECT_EQ(100ull, val);
  1493. }
  1494. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1495. Headers headers = {{"Content-Length", "x"}};
  1496. auto is_invalid_value = false;
  1497. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1498. is_invalid_value);
  1499. EXPECT_EQ(0ull, val);
  1500. EXPECT_TRUE(is_invalid_value);
  1501. }
  1502. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1503. // An all-digit value that overflows size_t must be reported as invalid, not
  1504. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1505. // a large length to a small one on 32-bit builds, leaving the framing length
  1506. // wrong while is_invalid_value stayed false.
  1507. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1508. auto is_invalid_value = false;
  1509. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1510. is_invalid_value);
  1511. EXPECT_TRUE(is_invalid_value);
  1512. // A well-formed length is unaffected.
  1513. Headers ok = {{"Content-Length", "1234"}};
  1514. is_invalid_value = false;
  1515. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1516. is_invalid_value);
  1517. EXPECT_EQ(1234ull, val);
  1518. EXPECT_FALSE(is_invalid_value);
  1519. }
  1520. TEST(GetHeaderValueTest, Range) {
  1521. {
  1522. Headers headers = {make_range_header({{1, -1}})};
  1523. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1524. EXPECT_STREQ("bytes=1-", val);
  1525. }
  1526. {
  1527. Headers headers = {make_range_header({{-1, 1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=-1", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{1, 10}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=1-10", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10, 100-", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=0-0, -1", val);
  1550. }
  1551. }
  1552. TEST(BearerTokenAuthTest, SchemeValidation) {
  1553. // A value shorter than "Bearer " must not throw from the fixed-length
  1554. // substr, and a non-Bearer scheme must not be reported as a token.
  1555. struct {
  1556. const char *value;
  1557. const char *expected;
  1558. } cases[] = {
  1559. {"x", ""},
  1560. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1561. {"Bearer abc123", "abc123"},
  1562. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1563. };
  1564. for (const auto &c : cases) {
  1565. Request req;
  1566. req.set_header("Authorization", c.value);
  1567. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1568. }
  1569. }
  1570. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1571. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1572. // to depend on the standard library (libstdc++ handed back duplicates in
  1573. // reverse insertion order, libc++ in insertion order).
  1574. Request req;
  1575. req.set_header("Accept-Encoding", "gzip");
  1576. req.set_header("Accept-Encoding", "deflate");
  1577. req.set_header("Accept-Encoding", "br");
  1578. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1579. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1580. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1581. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1582. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1583. }
  1584. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1585. Request req;
  1586. req.set_header("X-Test", "only");
  1587. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1588. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1589. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1590. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1591. }
  1592. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1593. Headers headers;
  1594. headers.emplace("Host", "example.com");
  1595. headers.emplace("Accept-Encoding", "gzip");
  1596. headers.emplace("User-Agent", "test");
  1597. headers.emplace("Accept-Encoding", "deflate");
  1598. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1599. "Accept-Encoding=deflate ",
  1600. entries_to_string(headers));
  1601. }
  1602. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1603. Headers headers = {{"Content-Type", "text/html"},
  1604. {"CONTENT-TYPE", "text/xml"}};
  1605. EXPECT_EQ(2U, headers.count("content-type"));
  1606. auto it = headers.find("content-type");
  1607. ASSERT_TRUE(it != headers.end());
  1608. EXPECT_EQ("text/html", it->second);
  1609. }
  1610. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1611. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1612. // drop only those fields and leave everything positioned between them.
  1613. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1614. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1615. auto rng = headers.equal_range("a");
  1616. headers.erase(rng.first, rng.second);
  1617. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1618. }
  1619. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1620. Headers headers = {
  1621. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1622. EXPECT_EQ(3U, headers.erase("A"));
  1623. EXPECT_EQ(0U, headers.count("A"));
  1624. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1625. }
  1626. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1627. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1628. headers.emplace_front("Host", "example.com");
  1629. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1630. entries_to_string(headers));
  1631. }
  1632. TEST(ParseHeaderValueTest, Range) {
  1633. {
  1634. Ranges ranges;
  1635. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1636. EXPECT_TRUE(ret);
  1637. EXPECT_EQ(1u, ranges.size());
  1638. EXPECT_EQ(1u, ranges[0].first);
  1639. EXPECT_EQ(-1, ranges[0].second);
  1640. }
  1641. {
  1642. Ranges ranges;
  1643. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1644. EXPECT_TRUE(ret);
  1645. EXPECT_EQ(1u, ranges.size());
  1646. EXPECT_EQ(-1, ranges[0].first);
  1647. EXPECT_EQ(1u, ranges[0].second);
  1648. }
  1649. {
  1650. Ranges ranges;
  1651. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1652. EXPECT_TRUE(ret);
  1653. EXPECT_EQ(1u, ranges.size());
  1654. EXPECT_EQ(1u, ranges[0].first);
  1655. EXPECT_EQ(10u, ranges[0].second);
  1656. }
  1657. {
  1658. Ranges ranges;
  1659. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1660. EXPECT_FALSE(ret);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(2u, ranges.size());
  1667. EXPECT_EQ(1u, ranges[0].first);
  1668. EXPECT_EQ(10u, ranges[0].second);
  1669. EXPECT_EQ(100u, ranges[1].first);
  1670. EXPECT_EQ(-1, ranges[1].second);
  1671. }
  1672. {
  1673. Ranges ranges;
  1674. auto ret =
  1675. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1676. EXPECT_TRUE(ret);
  1677. EXPECT_EQ(3u, ranges.size());
  1678. EXPECT_EQ(1u, ranges[0].first);
  1679. EXPECT_EQ(10u, ranges[0].second);
  1680. EXPECT_EQ(100u, ranges[1].first);
  1681. EXPECT_EQ(200u, ranges[1].second);
  1682. EXPECT_EQ(300u, ranges[2].first);
  1683. EXPECT_EQ(400u, ranges[2].second);
  1684. }
  1685. {
  1686. Ranges ranges;
  1687. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1688. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1689. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1690. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1700. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1701. EXPECT_FALSE(
  1702. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1703. EXPECT_TRUE(ranges.empty());
  1704. }
  1705. {
  1706. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1707. // remainder of the representation, so it stays accepted.
  1708. Ranges ranges;
  1709. auto ret =
  1710. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1711. EXPECT_TRUE(ret);
  1712. ASSERT_EQ(1u, ranges.size());
  1713. EXPECT_EQ(0, ranges[0].first);
  1714. EXPECT_EQ(-1, ranges[0].second);
  1715. }
  1716. }
  1717. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1718. Request req;
  1719. req.set_header("Accept-Encoding", "gzip");
  1720. Response res;
  1721. res.set_header("Content-Type", "text/plain");
  1722. auto ret = detail::encoding_type(req, res);
  1723. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1724. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1725. #else
  1726. EXPECT_TRUE(ret == detail::EncodingType::None);
  1727. #endif
  1728. }
  1729. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1730. Request req;
  1731. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1732. Response res;
  1733. res.set_header("Content-Type", "text/plain");
  1734. auto ret = detail::encoding_type(req, res);
  1735. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1736. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1737. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1738. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1739. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1740. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1741. #else
  1742. EXPECT_TRUE(ret == detail::EncodingType::None);
  1743. #endif
  1744. }
  1745. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1746. Request req;
  1747. req.set_header("Accept-Encoding",
  1748. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1749. Response res;
  1750. res.set_header("Content-Type", "text/plain");
  1751. auto ret = detail::encoding_type(req, res);
  1752. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1753. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1754. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1755. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1756. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1757. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1758. #else
  1759. EXPECT_TRUE(ret == detail::EncodingType::None);
  1760. #endif
  1761. }
  1762. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1763. // All supported encodings rejected with q=0 should return None
  1764. Request req;
  1765. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1766. Response res;
  1767. res.set_header("Content-Type", "text/plain");
  1768. auto ret = detail::encoding_type(req, res);
  1769. EXPECT_TRUE(ret == detail::EncodingType::None);
  1770. }
  1771. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1772. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1773. Request req;
  1774. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1775. Response res;
  1776. res.set_header("Content-Type", "text/plain");
  1777. auto ret = detail::encoding_type(req, res);
  1778. EXPECT_TRUE(ret == detail::EncodingType::None);
  1779. }
  1780. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1781. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1782. Request req;
  1783. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1784. Response res;
  1785. res.set_header("Content-Type", "text/plain");
  1786. auto ret = detail::encoding_type(req, res);
  1787. EXPECT_TRUE(ret == detail::EncodingType::None);
  1788. }
  1789. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1790. // RFC 7231: Accept-Encoding values are case-insensitive
  1791. Request req;
  1792. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1793. Response res;
  1794. res.set_header("Content-Type", "text/plain");
  1795. auto ret = detail::encoding_type(req, res);
  1796. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1797. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1798. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1799. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1800. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1801. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1802. #else
  1803. EXPECT_TRUE(ret == detail::EncodingType::None);
  1804. #endif
  1805. }
  1806. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1807. // q value should determine priority, not hardcoded order
  1808. Request req;
  1809. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1810. Response res;
  1811. res.set_header("Content-Type", "text/plain");
  1812. auto ret = detail::encoding_type(req, res);
  1813. // gzip has highest q=1.0, so it should be selected even though
  1814. // br and zstd are also supported
  1815. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1816. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1817. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1818. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1819. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1820. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1821. #else
  1822. EXPECT_TRUE(ret == detail::EncodingType::None);
  1823. #endif
  1824. }
  1825. TEST(BufferStreamTest, read) {
  1826. detail::BufferStream strm1;
  1827. Stream &strm = strm1;
  1828. EXPECT_EQ(5, strm.write("hello"));
  1829. char buf[512];
  1830. EXPECT_EQ(2, strm.read(buf, 2));
  1831. EXPECT_EQ('h', buf[0]);
  1832. EXPECT_EQ('e', buf[1]);
  1833. EXPECT_EQ(2, strm.read(buf, 2));
  1834. EXPECT_EQ('l', buf[0]);
  1835. EXPECT_EQ('l', buf[1]);
  1836. EXPECT_EQ(1, strm.read(buf, 1));
  1837. EXPECT_EQ('o', buf[0]);
  1838. EXPECT_EQ(0, strm.read(buf, 1));
  1839. }
  1840. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1841. auto host = "www.httpwatch.com";
  1842. auto ip = hosted_at(host);
  1843. EXPECT_EQ("23.96.13.243", ip);
  1844. std::vector<std::string> addrs;
  1845. hosted_at(host, addrs);
  1846. EXPECT_EQ(1u, addrs.size());
  1847. }
  1848. #if 0 // It depends on each test environment...
  1849. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1850. auto host = "www.youtube.com";
  1851. std::vector<std::string> addrs;
  1852. hosted_at(host, addrs);
  1853. EXPECT_EQ(20u, addrs.size());
  1854. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1855. EXPECT_TRUE(it != addrs.end());
  1856. }
  1857. #endif
  1858. class ChunkedEncodingTest : public ::testing::Test {
  1859. protected:
  1860. ChunkedEncodingTest()
  1861. : cli_(HOST, PORT)
  1862. #ifdef CPPHTTPLIB_SSL_ENABLED
  1863. ,
  1864. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1865. #endif
  1866. {
  1867. cli_.set_connection_timeout(2);
  1868. #ifdef CPPHTTPLIB_SSL_ENABLED
  1869. cli_.enable_server_certificate_verification(false);
  1870. #endif
  1871. }
  1872. virtual void SetUp() {
  1873. read_file("./image.jpg", image_data_);
  1874. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("Hello World!", "text/plain");
  1876. });
  1877. svr_.Get(
  1878. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1879. res.set_chunked_content_provider(
  1880. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1881. size_t remaining = image_data_.size() - offset;
  1882. if (remaining == 0) {
  1883. sink.done();
  1884. } else {
  1885. constexpr size_t CHUNK_SIZE = 1024;
  1886. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1887. sink.write(&image_data_[offset], send_size);
  1888. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1889. }
  1890. return true;
  1891. });
  1892. });
  1893. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1894. svr_.wait_until_ready();
  1895. }
  1896. virtual void TearDown() {
  1897. svr_.stop();
  1898. if (!request_threads_.empty()) {
  1899. std::this_thread::sleep_for(std::chrono::seconds(1));
  1900. for (auto &t : request_threads_) {
  1901. t.join();
  1902. }
  1903. }
  1904. t_.join();
  1905. }
  1906. #ifdef CPPHTTPLIB_SSL_ENABLED
  1907. SSLClient cli_;
  1908. SSLServer svr_;
  1909. #else
  1910. Client cli_;
  1911. Server svr_;
  1912. #endif
  1913. thread t_;
  1914. std::vector<thread> request_threads_;
  1915. std::string image_data_;
  1916. };
  1917. TEST_F(ChunkedEncodingTest, NormalGet) {
  1918. auto res = cli_.Get("/chunked");
  1919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1920. std::string out;
  1921. read_file("./image.jpg", out);
  1922. EXPECT_EQ(StatusCode::OK_200, res->status);
  1923. EXPECT_EQ(out, res->body);
  1924. }
  1925. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1926. std::string body;
  1927. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1928. body.append(data, data_length);
  1929. return true;
  1930. });
  1931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1932. std::string out;
  1933. read_file("./image.jpg", out);
  1934. EXPECT_EQ(StatusCode::OK_200, res->status);
  1935. EXPECT_EQ(out, body);
  1936. }
  1937. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1938. std::string body;
  1939. auto res = cli_.Get(
  1940. "/chunked",
  1941. [&](const Response &response) {
  1942. EXPECT_EQ(StatusCode::OK_200, response.status);
  1943. return true;
  1944. },
  1945. [&](const char *data, size_t data_length) {
  1946. body.append(data, data_length);
  1947. return true;
  1948. });
  1949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1950. std::string out;
  1951. read_file("./image.jpg", out);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. EXPECT_EQ(out, body);
  1954. }
  1955. TEST(RangeTest, FromHTTPBin_Online) {
  1956. auto host = "httpbingo.org";
  1957. auto path = std::string{"/range/32"};
  1958. #ifdef CPPHTTPLIB_SSL_ENABLED
  1959. auto port = 443;
  1960. SSLClient cli(host, port);
  1961. #else
  1962. auto port = 80;
  1963. Client cli(host, port);
  1964. #endif
  1965. cli.set_connection_timeout(5);
  1966. {
  1967. auto res = cli.Get(path);
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1970. EXPECT_EQ(StatusCode::OK_200, res->status);
  1971. }
  1972. {
  1973. Headers headers = {make_range_header({{1, -1}})};
  1974. auto res = cli.Get(path, headers);
  1975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1976. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1978. }
  1979. {
  1980. Headers headers = {make_range_header({{1, 10}})};
  1981. auto res = cli.Get(path, headers);
  1982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1983. EXPECT_EQ("bcdefghijk", res->body);
  1984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1985. }
  1986. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1987. // entire resource, while the original httpbin returned 200. Both are
  1988. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1989. {
  1990. Headers headers = {make_range_header({{0, 31}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1994. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1995. res->status == StatusCode::PartialContent_206);
  1996. }
  1997. {
  1998. Headers headers = {make_range_header({{0, -1}})};
  1999. auto res = cli.Get(path, headers);
  2000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2001. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2002. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2003. res->status == StatusCode::PartialContent_206);
  2004. }
  2005. // go-httpbin returns 206 with clamped range for over-range requests,
  2006. // while the original httpbin returned 416. Both behaviors are observed
  2007. // in real servers, so we only verify the request succeeds.
  2008. {
  2009. Headers headers = {make_range_header({{0, 32}})};
  2010. auto res = cli.Get(path, headers);
  2011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2012. }
  2013. }
  2014. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2015. auto host = "unresolvableaddress.local";
  2016. auto path = std::string{"/"};
  2017. #ifdef CPPHTTPLIB_SSL_ENABLED
  2018. auto port = 443;
  2019. SSLClient cli(host, port);
  2020. #else
  2021. auto port = 80;
  2022. Client cli(host, port);
  2023. #endif
  2024. cli.set_connection_timeout(1);
  2025. {
  2026. auto res = cli.Get(path);
  2027. ASSERT_FALSE(res);
  2028. }
  2029. std::this_thread::sleep_for(std::chrono::seconds(8));
  2030. }
  2031. #if defined(__linux__) && defined(__GLIBC__) && \
  2032. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2033. // Forward declaration: in split builds split.py strips `inline` and moves the
  2034. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2035. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2036. // against the symbol in both header-only and split builds.
  2037. namespace httplib {
  2038. namespace detail {
  2039. int getaddrinfo_with_timeout(const char *node, const char *service,
  2040. const struct addrinfo *hints,
  2041. struct addrinfo **res, time_t timeout_sec);
  2042. } // namespace detail
  2043. } // namespace httplib
  2044. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2045. //
  2046. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2047. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2048. // gai_suspend() call hits the connection timeout the function calls
  2049. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2050. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2051. // still alive and still references the now-destroyed stack frame.
  2052. //
  2053. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2054. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2055. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2056. // and runs them in a container.
  2057. namespace {
  2058. bool should_run_issue_2431_tests() {
  2059. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2060. return v && *v && std::string(v) != "0";
  2061. }
  2062. std::string unique_unresolvable_host(int n) {
  2063. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2064. // glibc still asks the configured nameserver — which is exactly the path
  2065. // we want to exercise. A unique label per call avoids the resolver cache.
  2066. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2067. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2068. std::to_string(n) + ".invalid";
  2069. }
  2070. } // namespace
  2071. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2072. if (!should_run_issue_2431_tests()) {
  2073. GTEST_SKIP()
  2074. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2075. }
  2076. for (int i = 0; i < 8; ++i) {
  2077. struct addrinfo hints;
  2078. memset(&hints, 0, sizeof(hints));
  2079. hints.ai_family = AF_UNSPEC;
  2080. hints.ai_socktype = SOCK_STREAM;
  2081. auto host = unique_unresolvable_host(i);
  2082. struct addrinfo *result = nullptr;
  2083. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2084. &result, /*timeout_sec=*/1);
  2085. if (rc == 0 && result) { freeaddrinfo(result); }
  2086. }
  2087. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2088. // stack region they still believe holds their gaicb.
  2089. std::this_thread::sleep_for(std::chrono::seconds(3));
  2090. }
  2091. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2092. if (!should_run_issue_2431_tests()) {
  2093. GTEST_SKIP()
  2094. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2095. }
  2096. std::atomic<bool> stop{false};
  2097. std::vector<std::thread> threads;
  2098. for (int t = 0; t < 8; ++t) {
  2099. threads.emplace_back([t, &stop] {
  2100. int i = 0;
  2101. while (!stop.load(std::memory_order_relaxed)) {
  2102. struct addrinfo hints;
  2103. memset(&hints, 0, sizeof(hints));
  2104. hints.ai_family = AF_UNSPEC;
  2105. hints.ai_socktype = SOCK_STREAM;
  2106. auto host = unique_unresolvable_host(t * 100000 + i++);
  2107. struct addrinfo *result = nullptr;
  2108. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2109. &result, /*timeout_sec=*/1);
  2110. if (rc == 0 && result) { freeaddrinfo(result); }
  2111. }
  2112. });
  2113. }
  2114. std::this_thread::sleep_for(std::chrono::seconds(8));
  2115. stop.store(true, std::memory_order_relaxed);
  2116. for (auto &th : threads) {
  2117. th.join();
  2118. }
  2119. std::this_thread::sleep_for(std::chrono::seconds(3));
  2120. }
  2121. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2122. if (!should_run_issue_2431_tests()) {
  2123. GTEST_SKIP()
  2124. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2125. }
  2126. std::atomic<bool> stop{false};
  2127. std::vector<std::thread> threads;
  2128. for (int t = 0; t < 8; ++t) {
  2129. threads.emplace_back([t, &stop] {
  2130. int i = 0;
  2131. while (!stop.load(std::memory_order_relaxed)) {
  2132. auto host = unique_unresolvable_host(t * 100000 + i++);
  2133. Client cli(host, 80);
  2134. cli.set_connection_timeout(1, 0);
  2135. cli.set_read_timeout(1, 0);
  2136. cli.set_write_timeout(1, 0);
  2137. (void)cli.Get("/");
  2138. }
  2139. });
  2140. }
  2141. std::this_thread::sleep_for(std::chrono::seconds(8));
  2142. stop.store(true, std::memory_order_relaxed);
  2143. for (auto &th : threads) {
  2144. th.join();
  2145. }
  2146. std::this_thread::sleep_for(std::chrono::seconds(3));
  2147. }
  2148. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2149. TEST(ConnectionErrorTest, InvalidHost) {
  2150. auto host = "-abcde.com";
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. auto port = 443;
  2153. SSLClient cli(host, port);
  2154. #else
  2155. auto port = 80;
  2156. Client cli(host, port);
  2157. #endif
  2158. cli.set_connection_timeout(std::chrono::seconds(2));
  2159. auto res = cli.Get("/");
  2160. ASSERT_TRUE(!res);
  2161. EXPECT_EQ(Error::Connection, res.error());
  2162. }
  2163. TEST(ConnectionErrorTest, InvalidHost2) {
  2164. auto host = "httpcan.org/";
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. SSLClient cli(host);
  2167. #else
  2168. Client cli(host);
  2169. #endif
  2170. cli.set_connection_timeout(std::chrono::seconds(2));
  2171. auto res = cli.Get("/");
  2172. ASSERT_TRUE(!res);
  2173. EXPECT_EQ(Error::Connection, res.error());
  2174. }
  2175. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2176. auto host = "httpcan.org/";
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. SSLClient cli(host);
  2179. #else
  2180. Client cli(host);
  2181. #endif
  2182. cli.set_connection_timeout(std::chrono::seconds(2));
  2183. auto res = cli.Get("/");
  2184. ASSERT_TRUE(!res);
  2185. stringstream s;
  2186. s << "error code: " << res.error();
  2187. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2188. }
  2189. TEST(ConnectionErrorTest, InvalidPort) {
  2190. auto host = "localhost";
  2191. auto port = 44380;
  2192. #ifdef CPPHTTPLIB_SSL_ENABLED
  2193. SSLClient cli(host, port);
  2194. #else
  2195. Client cli(host, port);
  2196. #endif
  2197. cli.set_connection_timeout(std::chrono::seconds(2));
  2198. auto res = cli.Get("/");
  2199. ASSERT_TRUE(!res);
  2200. EXPECT_TRUE(Error::Connection == res.error() ||
  2201. Error::ConnectionTimeout == res.error());
  2202. }
  2203. TEST(ConnectionErrorTest, Timeout_Online) {
  2204. auto host = "google.com";
  2205. #ifdef CPPHTTPLIB_SSL_ENABLED
  2206. auto port = 44380;
  2207. SSLClient cli(host, port);
  2208. #else
  2209. auto port = 8080;
  2210. Client cli(host, port);
  2211. #endif
  2212. cli.set_connection_timeout(std::chrono::seconds(2));
  2213. // only probe one address type so that the error reason
  2214. // correlates to the timed-out IPv4, not the unsupported
  2215. // IPv6 connection attempt
  2216. cli.set_address_family(AF_INET);
  2217. auto res = cli.Get("/");
  2218. ASSERT_TRUE(!res);
  2219. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2220. }
  2221. TEST(CancelTest, NoCancel_Online) {
  2222. auto host = "httpbingo.org";
  2223. auto path = std::string{"/range/32"};
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. auto port = 443;
  2226. SSLClient cli(host, port);
  2227. #else
  2228. auto port = 80;
  2229. Client cli(host, port);
  2230. #endif
  2231. cli.set_connection_timeout(std::chrono::seconds(5));
  2232. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2235. EXPECT_EQ(StatusCode::OK_200, res->status);
  2236. }
  2237. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2238. // Use /bytes with a large payload so that the DownloadProgress callback
  2239. // (which only fires for Content-Length responses) is invoked before the
  2240. // entire body is received, giving cancellation a chance to fire.
  2241. auto host = "httpbingo.org";
  2242. auto path = std::string{"/bytes/524288"};
  2243. #ifdef CPPHTTPLIB_SSL_ENABLED
  2244. auto port = 443;
  2245. SSLClient cli(host, port);
  2246. #else
  2247. auto port = 80;
  2248. Client cli(host, port);
  2249. #endif
  2250. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2251. cli.set_connection_timeout(std::chrono::seconds(5));
  2252. ASSERT_TRUE(!res);
  2253. EXPECT_EQ(Error::Canceled, res.error());
  2254. }
  2255. TEST(CancelTest, WithCancelLargePayload_Online) {
  2256. auto host = "httpbingo.org";
  2257. auto path = std::string{"/bytes/524288"};
  2258. #ifdef CPPHTTPLIB_SSL_ENABLED
  2259. auto port = 443;
  2260. SSLClient cli(host, port);
  2261. #else
  2262. auto port = 80;
  2263. Client cli(host, port);
  2264. #endif
  2265. cli.set_connection_timeout(std::chrono::seconds(5));
  2266. uint32_t count = 0;
  2267. auto res =
  2268. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2269. ASSERT_TRUE(!res);
  2270. EXPECT_EQ(Error::Canceled, res.error());
  2271. }
  2272. TEST(CancelTest, NoCancelPost) {
  2273. Server svr;
  2274. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2275. res.set_content("Hello World!", "text/plain");
  2276. });
  2277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2278. auto se = detail::scope_exit([&] {
  2279. svr.stop();
  2280. thread.join();
  2281. ASSERT_FALSE(svr.is_running());
  2282. });
  2283. svr.wait_until_ready();
  2284. Client cli(HOST, PORT);
  2285. cli.set_connection_timeout(std::chrono::seconds(5));
  2286. auto res =
  2287. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2288. "application/json", [](uint64_t, uint64_t) { return true; });
  2289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2290. EXPECT_EQ("Hello World!", res->body);
  2291. EXPECT_EQ(StatusCode::OK_200, res->status);
  2292. }
  2293. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2294. Server svr;
  2295. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2296. res.set_content("Hello World!", "text/plain");
  2297. });
  2298. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2299. auto se = detail::scope_exit([&] {
  2300. svr.stop();
  2301. thread.join();
  2302. ASSERT_FALSE(svr.is_running());
  2303. });
  2304. svr.wait_until_ready();
  2305. Client cli(HOST, PORT);
  2306. cli.set_connection_timeout(std::chrono::seconds(5));
  2307. auto res =
  2308. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2309. "application/json", [](uint64_t, uint64_t) { return false; });
  2310. ASSERT_TRUE(!res);
  2311. EXPECT_EQ(Error::Canceled, res.error());
  2312. }
  2313. TEST(CancelTest, WithCancelLargePayloadPost) {
  2314. Server svr;
  2315. svr.set_payload_max_length(200 * 1024 * 1024);
  2316. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2317. res.set_content(LARGE_DATA, "text/plain");
  2318. });
  2319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2320. auto se = detail::scope_exit([&] {
  2321. svr.stop();
  2322. thread.join();
  2323. ASSERT_FALSE(svr.is_running());
  2324. });
  2325. svr.wait_until_ready();
  2326. Client cli(HOST, PORT);
  2327. cli.set_payload_max_length(200 * 1024 * 1024);
  2328. cli.set_connection_timeout(std::chrono::seconds(5));
  2329. auto res =
  2330. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2331. "application/json", [](uint64_t, uint64_t) { return false; });
  2332. ASSERT_TRUE(!res);
  2333. EXPECT_EQ(Error::Canceled, res.error());
  2334. }
  2335. TEST(CancelTest, NoCancelPut) {
  2336. Server svr;
  2337. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2338. res.set_content("Hello World!", "text/plain");
  2339. });
  2340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2341. auto se = detail::scope_exit([&] {
  2342. svr.stop();
  2343. thread.join();
  2344. ASSERT_FALSE(svr.is_running());
  2345. });
  2346. svr.wait_until_ready();
  2347. Client cli(HOST, PORT);
  2348. cli.set_connection_timeout(std::chrono::seconds(5));
  2349. auto res =
  2350. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2351. "application/json", [](uint64_t, uint64_t) { return true; });
  2352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2353. EXPECT_EQ("Hello World!", res->body);
  2354. EXPECT_EQ(StatusCode::OK_200, res->status);
  2355. }
  2356. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2357. Server svr;
  2358. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2359. res.set_content("Hello World!", "text/plain");
  2360. });
  2361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2362. auto se = detail::scope_exit([&] {
  2363. svr.stop();
  2364. thread.join();
  2365. ASSERT_FALSE(svr.is_running());
  2366. });
  2367. svr.wait_until_ready();
  2368. Client cli(HOST, PORT);
  2369. cli.set_connection_timeout(std::chrono::seconds(5));
  2370. auto res =
  2371. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2372. "application/json", [](uint64_t, uint64_t) { return false; });
  2373. ASSERT_TRUE(!res);
  2374. EXPECT_EQ(Error::Canceled, res.error());
  2375. }
  2376. TEST(CancelTest, WithCancelLargePayloadPut) {
  2377. Server svr;
  2378. svr.set_payload_max_length(200 * 1024 * 1024);
  2379. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2380. res.set_content(LARGE_DATA, "text/plain");
  2381. });
  2382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2383. auto se = detail::scope_exit([&] {
  2384. svr.stop();
  2385. thread.join();
  2386. ASSERT_FALSE(svr.is_running());
  2387. });
  2388. svr.wait_until_ready();
  2389. Client cli(HOST, PORT);
  2390. cli.set_payload_max_length(200 * 1024 * 1024);
  2391. cli.set_connection_timeout(std::chrono::seconds(5));
  2392. auto res =
  2393. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2394. "application/json", [](uint64_t, uint64_t) { return false; });
  2395. ASSERT_TRUE(!res);
  2396. EXPECT_EQ(Error::Canceled, res.error());
  2397. }
  2398. TEST(CancelTest, NoCancelPatch) {
  2399. Server svr;
  2400. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2401. res.set_content("Hello World!", "text/plain");
  2402. });
  2403. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2404. auto se = detail::scope_exit([&] {
  2405. svr.stop();
  2406. thread.join();
  2407. ASSERT_FALSE(svr.is_running());
  2408. });
  2409. svr.wait_until_ready();
  2410. Client cli(HOST, PORT);
  2411. cli.set_connection_timeout(std::chrono::seconds(5));
  2412. auto res =
  2413. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2414. "application/json", [](uint64_t, uint64_t) { return true; });
  2415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2416. EXPECT_EQ("Hello World!", res->body);
  2417. EXPECT_EQ(StatusCode::OK_200, res->status);
  2418. }
  2419. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2420. Server svr;
  2421. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2422. res.set_content("Hello World!", "text/plain");
  2423. });
  2424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2425. auto se = detail::scope_exit([&] {
  2426. svr.stop();
  2427. thread.join();
  2428. ASSERT_FALSE(svr.is_running());
  2429. });
  2430. svr.wait_until_ready();
  2431. Client cli(HOST, PORT);
  2432. cli.set_connection_timeout(std::chrono::seconds(5));
  2433. auto res =
  2434. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2435. "application/json", [](uint64_t, uint64_t) { return false; });
  2436. ASSERT_TRUE(!res);
  2437. EXPECT_EQ(Error::Canceled, res.error());
  2438. }
  2439. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2440. Server svr;
  2441. svr.set_payload_max_length(200 * 1024 * 1024);
  2442. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2443. res.set_content(LARGE_DATA, "text/plain");
  2444. });
  2445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2446. auto se = detail::scope_exit([&] {
  2447. svr.stop();
  2448. thread.join();
  2449. ASSERT_FALSE(svr.is_running());
  2450. });
  2451. svr.wait_until_ready();
  2452. Client cli(HOST, PORT);
  2453. cli.set_payload_max_length(200 * 1024 * 1024);
  2454. cli.set_connection_timeout(std::chrono::seconds(5));
  2455. auto res =
  2456. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2457. "application/json", [](uint64_t, uint64_t) { return false; });
  2458. ASSERT_TRUE(!res);
  2459. EXPECT_EQ(Error::Canceled, res.error());
  2460. }
  2461. TEST(CancelTest, NoCancelDelete) {
  2462. Server svr;
  2463. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2464. res.set_content("Hello World!", "text/plain");
  2465. });
  2466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2467. auto se = detail::scope_exit([&] {
  2468. svr.stop();
  2469. thread.join();
  2470. ASSERT_FALSE(svr.is_running());
  2471. });
  2472. svr.wait_until_ready();
  2473. Client cli(HOST, PORT);
  2474. cli.set_connection_timeout(std::chrono::seconds(5));
  2475. auto res =
  2476. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2477. "application/json", [](uint64_t, uint64_t) { return true; });
  2478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2479. EXPECT_EQ("Hello World!", res->body);
  2480. EXPECT_EQ(StatusCode::OK_200, res->status);
  2481. }
  2482. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2483. Server svr;
  2484. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2485. res.set_content("Hello World!", "text/plain");
  2486. });
  2487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2488. auto se = detail::scope_exit([&] {
  2489. svr.stop();
  2490. thread.join();
  2491. ASSERT_FALSE(svr.is_running());
  2492. });
  2493. svr.wait_until_ready();
  2494. Client cli(HOST, PORT);
  2495. cli.set_connection_timeout(std::chrono::seconds(5));
  2496. auto res =
  2497. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2498. "application/json", [](uint64_t, uint64_t) { return false; });
  2499. ASSERT_TRUE(!res);
  2500. EXPECT_EQ(Error::Canceled, res.error());
  2501. }
  2502. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2503. Server svr;
  2504. svr.set_payload_max_length(200 * 1024 * 1024);
  2505. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2506. res.set_content(LARGE_DATA, "text/plain");
  2507. });
  2508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2509. auto se = detail::scope_exit([&] {
  2510. svr.stop();
  2511. thread.join();
  2512. ASSERT_FALSE(svr.is_running());
  2513. });
  2514. svr.wait_until_ready();
  2515. Client cli(HOST, PORT);
  2516. cli.set_payload_max_length(200 * 1024 * 1024);
  2517. cli.set_connection_timeout(std::chrono::seconds(5));
  2518. auto res =
  2519. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2520. "application/json", [](uint64_t, uint64_t) { return false; });
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::Canceled, res.error());
  2523. }
  2524. static std::string remove_whitespace(const std::string &input) {
  2525. std::string output;
  2526. output.reserve(input.size());
  2527. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2528. [](unsigned char c) { return !std::isspace(c); });
  2529. return output;
  2530. }
  2531. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2532. auto host = "httpbingo.org";
  2533. auto path = std::string{"/basic-auth/hello/world"};
  2534. #ifdef CPPHTTPLIB_SSL_ENABLED
  2535. auto port = 443;
  2536. SSLClient cli(host, port);
  2537. #else
  2538. auto port = 80;
  2539. Client cli(host, port);
  2540. #endif
  2541. {
  2542. auto res = cli.Get(path);
  2543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2544. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2545. }
  2546. {
  2547. auto res = cli.Get(
  2548. path, Headers{make_basic_authentication_header("hello", "world")});
  2549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2550. auto body = remove_whitespace(res->body);
  2551. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2552. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. {
  2556. cli.set_basic_auth("hello", "world");
  2557. auto res = cli.Get(path);
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. auto body = remove_whitespace(res->body);
  2560. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2561. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. }
  2564. {
  2565. cli.set_basic_auth("hello", "bad");
  2566. auto res = cli.Get(path);
  2567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2568. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2569. }
  2570. {
  2571. cli.set_basic_auth("bad", "world");
  2572. auto res = cli.Get(path);
  2573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2574. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2575. }
  2576. }
  2577. #ifdef CPPHTTPLIB_SSL_ENABLED
  2578. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2579. auto host = "httpbingo.org";
  2580. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2581. auto paths = std::vector<std::string>{
  2582. "/digest-auth/auth/hello/world/MD5",
  2583. "/digest-auth/auth/hello/world/SHA-256",
  2584. };
  2585. auto port = 443;
  2586. SSLClient cli(host, port);
  2587. {
  2588. auto res = cli.Get(unauth_path);
  2589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2590. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2591. }
  2592. {
  2593. cli.set_digest_auth("hello", "world");
  2594. for (const auto &path : paths) {
  2595. auto res = cli.Get(path.c_str());
  2596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2597. auto body = remove_whitespace(res->body);
  2598. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2599. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2600. EXPECT_EQ(StatusCode::OK_200, res->status);
  2601. }
  2602. cli.set_digest_auth("hello", "bad");
  2603. for (const auto &path : paths) {
  2604. auto res = cli.Get(path.c_str());
  2605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2606. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2607. }
  2608. }
  2609. }
  2610. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2611. // comma-separated list of challenges, and each challenge may itself carry a
  2612. // comma-separated auth-param list, so a server can legally offer Basic
  2613. // before Digest, either as two field lines or packed into one. Runs one 401
  2614. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2615. // value() joins them in receipt order) and checks that the retry carries a
  2616. // well-formed Digest Authorization header naming expected_realm.
  2617. static void
  2618. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2619. const std::string &expected_realm) {
  2620. std::atomic<int> hits{0};
  2621. Server svr;
  2622. svr.Get("/x", [&](const Request &req, Response &res) {
  2623. if (++hits == 1) {
  2624. res.status = StatusCode::Unauthorized_401;
  2625. for (const auto &challenge : challenges) {
  2626. res.set_header("WWW-Authenticate", challenge);
  2627. }
  2628. } else {
  2629. auto authorization = req.get_header_value("Authorization");
  2630. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2631. EXPECT_NE(std::string::npos,
  2632. authorization.find("realm=\"" + expected_realm + "\""));
  2633. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2634. res.set_content("ok", "text/plain");
  2635. }
  2636. });
  2637. auto port = svr.bind_to_any_port(HOST);
  2638. std::thread t([&]() { svr.listen_after_bind(); });
  2639. auto se = detail::scope_exit([&] {
  2640. svr.stop();
  2641. t.join();
  2642. });
  2643. svr.wait_until_ready();
  2644. Client cli(HOST, port);
  2645. cli.set_digest_auth("hello", "world");
  2646. auto res = cli.Get("/x");
  2647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2648. EXPECT_EQ(2, hits.load());
  2649. }
  2650. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2651. static const char *kDigestChallenge =
  2652. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2653. "algorithm=MD5";
  2654. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2655. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2656. "testrealm");
  2657. }
  2658. // Same challenge list with the schemes in the opposite order, to make sure
  2659. // the fix above didn't just special-case "Basic first".
  2660. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2661. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2662. "testrealm");
  2663. }
  2664. // A comma inside a quoted auth-param value must not be mistaken for the
  2665. // separator between two challenges (or two auth-params).
  2666. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2667. run_digest_challenge_list_test(
  2668. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2669. "algorithm=MD5"},
  2670. "test,realm");
  2671. }
  2672. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2673. // make_digest_authentication_header() dereferences both unconditionally, so
  2674. // a server sending a challenge missing either one must not be treated as
  2675. // usable -- doing so used to crash the client with std::out_of_range.
  2676. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2677. Server svr;
  2678. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2679. res.status = StatusCode::Unauthorized_401;
  2680. res.set_header("WWW-Authenticate", challenge);
  2681. });
  2682. auto port = svr.bind_to_any_port(HOST);
  2683. std::thread t([&]() { svr.listen_after_bind(); });
  2684. auto se = detail::scope_exit([&] {
  2685. svr.stop();
  2686. t.join();
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, port);
  2690. cli.set_digest_auth("hello", "world");
  2691. auto res = cli.Get("/x");
  2692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2693. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2694. }
  2695. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2696. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2697. }
  2698. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2699. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2700. }
  2701. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2702. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2703. }
  2704. #endif
  2705. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2706. auto host = "google.com";
  2707. auto another_host = "example.com";
  2708. auto wrong_ip = "0.0.0.0";
  2709. #ifdef CPPHTTPLIB_SSL_ENABLED
  2710. SSLClient cli(host);
  2711. #else
  2712. Client cli(host);
  2713. #endif
  2714. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2715. auto res = cli.Get("/");
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2718. }
  2719. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2720. auto host = "google.com";
  2721. auto wrong_ip = "0.0.0.0";
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. SSLClient cli(host);
  2724. #else
  2725. Client cli(host);
  2726. #endif
  2727. cli.set_hostname_addr_map({{host, wrong_ip}});
  2728. auto res = cli.Get("/");
  2729. ASSERT_TRUE(!res);
  2730. EXPECT_EQ(Error::Connection, res.error());
  2731. }
  2732. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2733. // A mapped value that is not an IP literal must be resolved. "localhost"
  2734. // resolves from the hosts file, so this test needs no external DNS.
  2735. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2736. auto host = "target.invalid";
  2737. Server svr;
  2738. std::string received_host;
  2739. svr.Get("/hi", [&](const Request &req, Response &res) {
  2740. received_host = req.get_header_value("Host");
  2741. res.set_content("Hello World!", "text/plain");
  2742. });
  2743. auto port = svr.bind_to_any_port(HOST);
  2744. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2745. auto se = detail::scope_exit([&] {
  2746. svr.stop();
  2747. thread.join();
  2748. ASSERT_FALSE(svr.is_running());
  2749. });
  2750. svr.wait_until_ready();
  2751. Client cli(host, port);
  2752. cli.set_hostname_addr_map({{host, HOST}});
  2753. auto res = cli.Get("/hi");
  2754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. // The mapping only redirects the connection; the identity stays host_.
  2757. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2758. }
  2759. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2760. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2761. auto host = "target.invalid";
  2762. Server svr;
  2763. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. });
  2766. auto port = svr.bind_to_any_port("127.0.0.1");
  2767. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2768. auto se = detail::scope_exit([&] {
  2769. svr.stop();
  2770. thread.join();
  2771. ASSERT_FALSE(svr.is_running());
  2772. });
  2773. svr.wait_until_ready();
  2774. Client cli(host, port);
  2775. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2776. auto res = cli.Get("/hi");
  2777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2778. EXPECT_EQ(StatusCode::OK_200, res->status);
  2779. }
  2780. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2781. // An empty mapped value must leave host_ as the connection target. Without
  2782. // that guard the empty value would become the host argument, getaddrinfo
  2783. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2784. // loopback - silently connecting somewhere the caller never asked for.
  2785. // The server listens on loopback, so such a fallback would succeed and is
  2786. // therefore observable as a failure of this test.
  2787. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2788. Server svr;
  2789. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2790. res.set_content("Hello World!", "text/plain");
  2791. });
  2792. auto port = svr.bind_to_any_port(HOST);
  2793. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2794. auto se = detail::scope_exit([&] {
  2795. svr.stop();
  2796. thread.join();
  2797. ASSERT_FALSE(svr.is_running());
  2798. });
  2799. svr.wait_until_ready();
  2800. Client cli(blackhole, port);
  2801. cli.set_hostname_addr_map({{blackhole, ""}});
  2802. cli.set_connection_timeout(1);
  2803. auto res = cli.Get("/hi");
  2804. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2805. }
  2806. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2807. auto host = "httpbingo.org";
  2808. auto path = std::string{"/absolute-redirect/3"};
  2809. #ifdef CPPHTTPLIB_SSL_ENABLED
  2810. SSLClient cli(host);
  2811. #else
  2812. Client cli(host);
  2813. #endif
  2814. cli.set_follow_location(true);
  2815. auto res = cli.Get(path);
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ(StatusCode::OK_200, res->status);
  2818. }
  2819. TEST(RedirectTest, Redirect_Online) {
  2820. auto host = "httpbingo.org";
  2821. auto path = std::string{"/redirect/3"};
  2822. #ifdef CPPHTTPLIB_SSL_ENABLED
  2823. SSLClient cli(host);
  2824. #else
  2825. Client cli(host);
  2826. #endif
  2827. cli.set_follow_location(true);
  2828. auto res = cli.Get(path);
  2829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2830. EXPECT_EQ(StatusCode::OK_200, res->status);
  2831. }
  2832. TEST(RelativeRedirectTest, Redirect_Online) {
  2833. auto host = "httpbingo.org";
  2834. auto path = std::string{"/relative-redirect/3"};
  2835. #ifdef CPPHTTPLIB_SSL_ENABLED
  2836. SSLClient cli(host);
  2837. #else
  2838. Client cli(host);
  2839. #endif
  2840. cli.set_follow_location(true);
  2841. auto res = cli.Get(path);
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. EXPECT_EQ(StatusCode::OK_200, res->status);
  2844. }
  2845. TEST(TooManyRedirectTest, Redirect_Online) {
  2846. auto host = "httpbingo.org";
  2847. auto path = std::string{"/redirect/21"};
  2848. #ifdef CPPHTTPLIB_SSL_ENABLED
  2849. SSLClient cli(host);
  2850. #else
  2851. Client cli(host);
  2852. #endif
  2853. cli.set_follow_location(true);
  2854. auto res = cli.Get(path);
  2855. ASSERT_TRUE(!res);
  2856. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2857. }
  2858. #ifdef CPPHTTPLIB_SSL_ENABLED
  2859. TEST(YahooRedirectTest, Redirect_Online) {
  2860. Client cli("yahoo.com");
  2861. auto res = cli.Get("/");
  2862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2863. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2864. cli.set_follow_location(true);
  2865. res = cli.Get("/");
  2866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2867. EXPECT_EQ(StatusCode::OK_200, res->status);
  2868. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2869. }
  2870. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2871. #define REDIR_HOST "httpbingo.org"
  2872. #define REDIR_PATH "/redirect-to"
  2873. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2874. SSLClient cli(REDIR_HOST);
  2875. cli.set_follow_location(true);
  2876. auto res =
  2877. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2882. SSLClient cli(REDIR_HOST);
  2883. cli.set_follow_location(true);
  2884. Params params;
  2885. params.emplace("url", "http://example.com");
  2886. params.emplace("status_code", "302");
  2887. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2892. SSLClient cli(REDIR_HOST);
  2893. cli.set_follow_location(true);
  2894. Params params;
  2895. params.emplace("url", "http://example.com");
  2896. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2898. EXPECT_EQ(StatusCode::OK_200, res->status);
  2899. }
  2900. TEST(UrlWithSpace, Redirect_Online) {
  2901. SSLClient cli("edge.forgecdn.net");
  2902. cli.set_follow_location(true);
  2903. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::OK_200, res->status);
  2906. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2907. }
  2908. #endif
  2909. #if !defined(_WIN32) && !defined(_WIN64)
  2910. TEST(ReceiveSignals, Signal) {
  2911. auto setupSignalHandlers = []() {
  2912. struct sigaction act;
  2913. sigemptyset(&act.sa_mask);
  2914. act.sa_flags = SA_SIGINFO;
  2915. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2916. switch (sig) {
  2917. case SIGINT:
  2918. default: break;
  2919. }
  2920. };
  2921. ::sigaction(SIGINT, &act, nullptr);
  2922. };
  2923. Server svr;
  2924. int port = 0;
  2925. auto thread = std::thread([&]() {
  2926. setupSignalHandlers();
  2927. port = svr.bind_to_any_port(HOST);
  2928. svr.listen_after_bind();
  2929. });
  2930. auto se = detail::scope_exit([&] {
  2931. svr.stop();
  2932. thread.join();
  2933. ASSERT_FALSE(svr.is_running());
  2934. });
  2935. svr.wait_until_ready();
  2936. ASSERT_TRUE(svr.is_running());
  2937. pthread_kill(thread.native_handle(), SIGINT);
  2938. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2939. ASSERT_TRUE(svr.is_running());
  2940. }
  2941. #endif
  2942. TEST(RedirectToDifferentPort, Redirect) {
  2943. Server svr1;
  2944. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2945. res.set_content("Hello World!", "text/plain");
  2946. });
  2947. int svr1_port = 0;
  2948. auto thread1 = std::thread([&]() {
  2949. svr1_port = svr1.bind_to_any_port(HOST);
  2950. svr1.listen_after_bind();
  2951. });
  2952. Server svr2;
  2953. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2954. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2955. });
  2956. int svr2_port = 0;
  2957. auto thread2 = std::thread([&]() {
  2958. svr2_port = svr2.bind_to_any_port(HOST);
  2959. svr2.listen_after_bind();
  2960. });
  2961. auto se = detail::scope_exit([&] {
  2962. svr2.stop();
  2963. thread2.join();
  2964. svr1.stop();
  2965. thread1.join();
  2966. ASSERT_FALSE(svr2.is_running());
  2967. ASSERT_FALSE(svr1.is_running());
  2968. });
  2969. svr1.wait_until_ready();
  2970. svr2.wait_until_ready();
  2971. Client cli("localhost", svr2_port);
  2972. cli.set_follow_location(true);
  2973. auto res = cli.Get("/2");
  2974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2975. EXPECT_EQ(StatusCode::OK_200, res->status);
  2976. EXPECT_EQ("Hello World!", res->body);
  2977. }
  2978. static void
  2979. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2980. Server svr1;
  2981. std::string captured_authorization;
  2982. svr1.Get("/target", [&](const Request &req, Response &res) {
  2983. captured_authorization = req.get_header_value("Authorization");
  2984. res.set_content("OK", "text/plain");
  2985. });
  2986. int svr1_port = 0;
  2987. auto thread1 = std::thread([&]() {
  2988. svr1_port = svr1.bind_to_any_port(HOST);
  2989. svr1.listen_after_bind();
  2990. });
  2991. Server svr2;
  2992. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2993. res.set_redirect(
  2994. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2995. });
  2996. int svr2_port = 0;
  2997. auto thread2 = std::thread([&]() {
  2998. svr2_port = svr2.bind_to_any_port(HOST);
  2999. svr2.listen_after_bind();
  3000. });
  3001. auto se = detail::scope_exit([&] {
  3002. svr2.stop();
  3003. thread2.join();
  3004. svr1.stop();
  3005. thread1.join();
  3006. ASSERT_FALSE(svr2.is_running());
  3007. ASSERT_FALSE(svr1.is_running());
  3008. });
  3009. svr1.wait_until_ready();
  3010. svr2.wait_until_ready();
  3011. Client cli("localhost", svr2_port);
  3012. cli.set_follow_location(true);
  3013. set_auth(cli);
  3014. auto res = cli.Get("/redir");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(StatusCode::OK_200, res->status);
  3017. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3018. EXPECT_TRUE(captured_authorization.empty());
  3019. }
  3020. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3021. TestDoNotForwardCredentialsOnRedirect(
  3022. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3023. }
  3024. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3025. TestDoNotForwardCredentialsOnRedirect(
  3026. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3027. }
  3028. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3029. Server svr1;
  3030. std::string captured_cookie;
  3031. bool target_hit = false;
  3032. svr1.Get("/target", [&](const Request &req, Response &res) {
  3033. captured_cookie = req.get_header_value("Cookie");
  3034. target_hit = true;
  3035. res.set_content("OK", "text/plain");
  3036. });
  3037. int svr1_port = 0;
  3038. auto thread1 = std::thread([&]() {
  3039. svr1_port = svr1.bind_to_any_port(HOST);
  3040. svr1.listen_after_bind();
  3041. });
  3042. Server svr2;
  3043. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3044. res.set_redirect(
  3045. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3046. });
  3047. int svr2_port = 0;
  3048. auto thread2 = std::thread([&]() {
  3049. svr2_port = svr2.bind_to_any_port(HOST);
  3050. svr2.listen_after_bind();
  3051. });
  3052. auto se = detail::scope_exit([&] {
  3053. svr2.stop();
  3054. thread2.join();
  3055. svr1.stop();
  3056. thread1.join();
  3057. ASSERT_FALSE(svr2.is_running());
  3058. ASSERT_FALSE(svr1.is_running());
  3059. });
  3060. svr1.wait_until_ready();
  3061. svr2.wait_until_ready();
  3062. Client cli("localhost", svr2_port);
  3063. cli.set_follow_location(true);
  3064. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3065. auto res = cli.Get("/redir", headers);
  3066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3067. EXPECT_EQ(StatusCode::OK_200, res->status);
  3068. EXPECT_TRUE(target_hit);
  3069. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3070. EXPECT_TRUE(captured_cookie.empty());
  3071. }
  3072. TEST(RedirectToSamePort, ForwardCookie) {
  3073. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3074. // header so that ordinary session flows keep working.
  3075. Server svr;
  3076. std::string captured_cookie;
  3077. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3078. res.set_redirect("/target", 302);
  3079. });
  3080. svr.Get("/target", [&](const Request &req, Response &res) {
  3081. captured_cookie = req.get_header_value("Cookie");
  3082. res.set_content("OK", "text/plain");
  3083. });
  3084. auto port = svr.bind_to_any_port(HOST);
  3085. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3086. auto se = detail::scope_exit([&] {
  3087. svr.stop();
  3088. thread.join();
  3089. ASSERT_FALSE(svr.is_running());
  3090. });
  3091. svr.wait_until_ready();
  3092. Client cli(HOST, port);
  3093. cli.set_follow_location(true);
  3094. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3095. auto res = cli.Get("/redir", headers);
  3096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3097. EXPECT_EQ(StatusCode::OK_200, res->status);
  3098. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3099. }
  3100. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3101. Server svr;
  3102. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3103. // Port number that overflows int — should not crash
  3104. res.set_redirect("http://localhost:99999999999999999999/target");
  3105. });
  3106. auto port = svr.bind_to_any_port(HOST);
  3107. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3108. auto se = detail::scope_exit([&] {
  3109. svr.stop();
  3110. thread.join();
  3111. ASSERT_FALSE(svr.is_running());
  3112. });
  3113. svr.wait_until_ready();
  3114. Client cli(HOST, port);
  3115. cli.set_follow_location(true);
  3116. auto res = cli.Get("/redir");
  3117. // Should fail gracefully, not crash (no valid response due to bad port)
  3118. EXPECT_FALSE(res);
  3119. }
  3120. TEST(RedirectFromPageWithContent, Redirect) {
  3121. Server svr;
  3122. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3123. res.set_content("___", "text/plain");
  3124. res.set_redirect("/2");
  3125. });
  3126. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3127. res.set_content("Hello World!", "text/plain");
  3128. });
  3129. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3130. auto se = detail::scope_exit([&] {
  3131. svr.stop();
  3132. th.join();
  3133. ASSERT_FALSE(svr.is_running());
  3134. });
  3135. svr.wait_until_ready();
  3136. {
  3137. Client cli("localhost", PORT);
  3138. cli.set_follow_location(true);
  3139. std::string body;
  3140. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3141. body.append(data, data_length);
  3142. return true;
  3143. });
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ("Hello World!", body);
  3147. }
  3148. {
  3149. Client cli("localhost", PORT);
  3150. std::string body;
  3151. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3152. body.append(data, data_length);
  3153. return true;
  3154. });
  3155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3156. EXPECT_EQ(StatusCode::Found_302, res->status);
  3157. EXPECT_EQ("___", body);
  3158. }
  3159. }
  3160. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3161. Server svr;
  3162. auto port_str = std::to_string(PORT);
  3163. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3164. auto expected_host = "[::1]:" + port_str;
  3165. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3166. res.set_content("___", "text/plain");
  3167. // res.set_redirect("/2");
  3168. res.set_redirect(redirect_url);
  3169. });
  3170. svr.Get("/2", [&](const Request &req, Response &res) {
  3171. auto host_header = req.headers.find("Host");
  3172. ASSERT_TRUE(host_header != req.headers.end());
  3173. EXPECT_EQ(expected_host, host_header->second);
  3174. res.set_content("Hello World!", "text/plain");
  3175. });
  3176. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3177. auto se = detail::scope_exit([&] {
  3178. svr.stop();
  3179. th.join();
  3180. ASSERT_FALSE(svr.is_running());
  3181. });
  3182. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3183. // actually starts anything, so the condition !svr.is_running() will
  3184. // always remain true, and the loop never stops.
  3185. // This basically counts how many milliseconds have passed since the
  3186. // call to svr.listen(), and if after 5 seconds nothing started yet
  3187. // aborts the test.
  3188. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3189. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3190. ASSERT_LT(milliseconds, 5000U);
  3191. }
  3192. {
  3193. Client cli("::1", PORT);
  3194. cli.set_follow_location(true);
  3195. std::string body;
  3196. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3197. body.append(data, data_length);
  3198. return true;
  3199. });
  3200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3201. EXPECT_EQ(StatusCode::OK_200, res->status);
  3202. EXPECT_EQ("Hello World!", body);
  3203. }
  3204. {
  3205. Client cli("::1", PORT);
  3206. std::string body;
  3207. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3208. body.append(data, data_length);
  3209. return true;
  3210. });
  3211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3212. EXPECT_EQ(StatusCode::Found_302, res->status);
  3213. EXPECT_EQ("___", body);
  3214. }
  3215. }
  3216. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3217. Server svr;
  3218. svr.Get("/foo", [](const Request &req, Response &res) {
  3219. auto a = req.params.find("a");
  3220. if (a != req.params.end()) {
  3221. res.set_content((*a).second, "text/plain");
  3222. res.status = StatusCode::OK_200;
  3223. } else {
  3224. res.status = StatusCode::BadRequest_400;
  3225. }
  3226. });
  3227. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3228. auto se = detail::scope_exit([&] {
  3229. svr.stop();
  3230. thread.join();
  3231. ASSERT_FALSE(svr.is_running());
  3232. });
  3233. svr.wait_until_ready();
  3234. {
  3235. Client cli(HOST, PORT);
  3236. cli.set_path_encode(false);
  3237. auto res = cli.Get("/foo?a=explicitly+encoded");
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::OK_200, res->status);
  3240. // This expects it back with a space, as the `+` won't have been
  3241. // url-encoded, and server-side the params get decoded turning `+`
  3242. // into spaces.
  3243. EXPECT_EQ("explicitly encoded", res->body);
  3244. }
  3245. }
  3246. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3247. // When path encoding is disabled the client must transmit the supplied
  3248. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3249. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3250. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3251. // than a space (0x20). Assert on the raw wire target to catch this.
  3252. Server svr;
  3253. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3254. svr.Get("/foo", [&](const Request &req, Response &res) {
  3255. EXPECT_EQ(expected_target, req.target);
  3256. res.status = StatusCode::OK_200;
  3257. });
  3258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3259. auto se = detail::scope_exit([&] {
  3260. svr.stop();
  3261. thread.join();
  3262. ASSERT_FALSE(svr.is_running());
  3263. });
  3264. svr.wait_until_ready();
  3265. {
  3266. Client cli(HOST, PORT);
  3267. cli.set_path_encode(false);
  3268. auto res = cli.Get(expected_target.c_str());
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. }
  3273. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3274. // `open_stream()` used to skip the path encoding that the buffered send
  3275. // path applies, so the same `path` produced different bytes in the request
  3276. // line depending on which API was used. Assert the two agree.
  3277. Server svr;
  3278. std::string target;
  3279. svr.Get(".*", [&](const Request &req, Response &res) {
  3280. target = req.target;
  3281. res.status = StatusCode::OK_200;
  3282. });
  3283. auto port = svr.bind_to_any_port(HOST);
  3284. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3285. auto se = detail::scope_exit([&] {
  3286. svr.stop();
  3287. thread.join();
  3288. ASSERT_FALSE(svr.is_running());
  3289. });
  3290. svr.wait_until_ready();
  3291. struct {
  3292. const char *path;
  3293. const char *expected;
  3294. } cases[] = {
  3295. {"/a b?x=1", "/a%20b?x=1"},
  3296. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3297. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3298. };
  3299. for (const auto &c : cases) {
  3300. Client cli(HOST, port);
  3301. target.clear();
  3302. auto res = cli.Get(c.path);
  3303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3304. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3305. auto buffered_target = target;
  3306. target.clear();
  3307. auto handle = cli.open_stream("GET", c.path);
  3308. EXPECT_TRUE(handle.is_valid())
  3309. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3310. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3311. }
  3312. }
  3313. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3314. // The `set_path_encode(false)` contract — transmit the supplied target
  3315. // verbatim — must hold for the streaming API too.
  3316. Server svr;
  3317. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3318. std::string target;
  3319. svr.Get("/foo", [&](const Request &req, Response &res) {
  3320. target = req.target;
  3321. res.status = StatusCode::OK_200;
  3322. });
  3323. auto port = svr.bind_to_any_port(HOST);
  3324. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3325. auto se = detail::scope_exit([&] {
  3326. svr.stop();
  3327. thread.join();
  3328. ASSERT_FALSE(svr.is_running());
  3329. });
  3330. svr.wait_until_ready();
  3331. {
  3332. Client cli(HOST, port);
  3333. cli.set_path_encode(false);
  3334. auto handle = cli.open_stream("GET", expected_target);
  3335. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3336. EXPECT_EQ(expected_target, target);
  3337. }
  3338. }
  3339. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3340. // With path encoding enabled a CR/LF in the target is percent-encoded
  3341. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3342. // write_request_line still backstops `set_path_encode(false)`, which is
  3343. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3344. Server svr;
  3345. // Captured before routing: the decoded path contains a newline, which a
  3346. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3347. std::string target;
  3348. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3349. target = req.target;
  3350. res.status = StatusCode::OK_200;
  3351. return Server::HandlerResponse::Handled;
  3352. });
  3353. auto port = svr.bind_to_any_port(HOST);
  3354. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3355. auto se = detail::scope_exit([&] {
  3356. svr.stop();
  3357. thread.join();
  3358. ASSERT_FALSE(svr.is_running());
  3359. });
  3360. svr.wait_until_ready();
  3361. {
  3362. Client cli(HOST, port);
  3363. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3364. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3365. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3366. }
  3367. }
  3368. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3369. // Nothing may reach the wire: a raw CR/LF target would split the request
  3370. // line and inject headers.
  3371. Server svr;
  3372. // Pre-routing so that "not called" means nothing reached the server at all,
  3373. // rather than merely failing to match a handler pattern.
  3374. auto handler_called = false;
  3375. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3376. handler_called = true;
  3377. res.status = StatusCode::OK_200;
  3378. return Server::HandlerResponse::Handled;
  3379. });
  3380. auto port = svr.bind_to_any_port(HOST);
  3381. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3382. auto se = detail::scope_exit([&] {
  3383. svr.stop();
  3384. thread.join();
  3385. ASSERT_FALSE(svr.is_running());
  3386. });
  3387. svr.wait_until_ready();
  3388. {
  3389. Client cli(HOST, port);
  3390. cli.set_path_encode(false);
  3391. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3392. EXPECT_FALSE(handle.is_valid());
  3393. EXPECT_EQ(Error::Write, handle.error);
  3394. EXPECT_FALSE(handler_called);
  3395. }
  3396. }
  3397. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3398. // Which of the two branches runs is decided by whether the query component
  3399. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3400. // an empty query and must still fall back to building one from
  3401. // `req.params`, while a non-empty query must win over `req.params`.
  3402. Server svr;
  3403. std::string target;
  3404. svr.Get("/foo", [&](const Request &req, Response &res) {
  3405. target = req.target;
  3406. res.status = StatusCode::OK_200;
  3407. });
  3408. auto port = svr.bind_to_any_port(HOST);
  3409. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3410. auto se = detail::scope_exit([&] {
  3411. svr.stop();
  3412. thread.join();
  3413. ASSERT_FALSE(svr.is_running());
  3414. });
  3415. svr.wait_until_ready();
  3416. {
  3417. // Trailing `?` -> empty query component -> `req.params` is used.
  3418. Client cli(HOST, port);
  3419. Request req;
  3420. req.method = "GET";
  3421. req.path = "/foo?";
  3422. req.params.emplace("a", "1");
  3423. target.clear();
  3424. auto res = cli.send(req);
  3425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3426. EXPECT_EQ("/foo?a=1", target);
  3427. }
  3428. {
  3429. // Non-empty query in `req.path` -> `req.params` is not appended.
  3430. Client cli(HOST, port);
  3431. Request req;
  3432. req.method = "GET";
  3433. req.path = "/foo?b=2";
  3434. req.params.emplace("a", "1");
  3435. target.clear();
  3436. auto res = cli.send(req);
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ("/foo?b=2", target);
  3439. }
  3440. }
  3441. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3442. Server svr;
  3443. svr.Get("/", [](const Request &req, Response &) {
  3444. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3445. });
  3446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3447. auto se = detail::scope_exit([&] {
  3448. svr.stop();
  3449. thread.join();
  3450. ASSERT_FALSE(svr.is_running());
  3451. });
  3452. svr.wait_until_ready();
  3453. {
  3454. Client cli(HOST, PORT);
  3455. cli.set_path_encode(false);
  3456. auto res = cli.Get("/?something=%0A");
  3457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. }
  3460. }
  3461. TEST(BindServerTest, BindDualStack) {
  3462. Server svr;
  3463. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3464. res.set_content("Hello World!", "text/plain");
  3465. });
  3466. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3467. auto se = detail::scope_exit([&] {
  3468. svr.stop();
  3469. thread.join();
  3470. ASSERT_FALSE(svr.is_running());
  3471. });
  3472. svr.wait_until_ready();
  3473. {
  3474. Client cli("127.0.0.1", PORT);
  3475. auto res = cli.Get("/1");
  3476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3477. EXPECT_EQ(StatusCode::OK_200, res->status);
  3478. EXPECT_EQ("Hello World!", res->body);
  3479. }
  3480. {
  3481. Client cli("::1", PORT);
  3482. auto res = cli.Get("/1");
  3483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3484. EXPECT_EQ(StatusCode::OK_200, res->status);
  3485. EXPECT_EQ("Hello World!", res->body);
  3486. }
  3487. }
  3488. TEST(BindServerTest, BindAndListenSeparately) {
  3489. Server svr;
  3490. int port = svr.bind_to_any_port("0.0.0.0");
  3491. ASSERT_TRUE(svr.is_valid());
  3492. ASSERT_TRUE(port > 0);
  3493. svr.stop();
  3494. }
  3495. // Reports whether anything is still listening on a loopback port. A plain
  3496. // connect() is used instead of a Client request because a socket left bound by
  3497. // mistake accepts the connection into its backlog and never answers, which
  3498. // would hang the test instead of failing it.
  3499. static bool is_loopback_port_accepting(int port) {
  3500. sockaddr_in addr{};
  3501. addr.sin_family = AF_INET;
  3502. addr.sin_port = htons(static_cast<uint16_t>(port));
  3503. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3504. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3505. EXPECT_NE(sock, INVALID_SOCKET);
  3506. if (sock == INVALID_SOCKET) { return false; }
  3507. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3508. static_cast<socklen_t>(sizeof(addr)));
  3509. detail::close_socket(sock);
  3510. return ret == 0;
  3511. }
  3512. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3513. Server svr;
  3514. auto port = svr.bind_to_any_port("127.0.0.1");
  3515. ASSERT_TRUE(port > 0);
  3516. svr.stop();
  3517. // bind_to_any_port() already called listen(2), so until stop() closed the
  3518. // descriptor the port kept accepting connections into the backlog. ASSERT
  3519. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3520. // below blocks forever in the accept loop.
  3521. ASSERT_FALSE(is_loopback_port_accepting(port));
  3522. // Nothing is left to accept on, so listen_after_bind() must report failure
  3523. // instead of returning success without ever serving.
  3524. EXPECT_FALSE(svr.listen_after_bind());
  3525. // The failed listen marks the server decommissioned, so a waiter returns
  3526. // instead of spinning forever.
  3527. svr.wait_until_ready();
  3528. }
  3529. #ifdef CPPHTTPLIB_SSL_ENABLED
  3530. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3532. CLIENT_CA_CERT_DIR);
  3533. int port = svr.bind_to_any_port("0.0.0.0");
  3534. ASSERT_TRUE(svr.is_valid());
  3535. ASSERT_TRUE(port > 0);
  3536. svr.stop();
  3537. }
  3538. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3539. // or a rejected CustomRoute() registration would not stop the server binding.
  3540. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3542. CLIENT_CA_CERT_DIR);
  3543. ASSERT_TRUE(svr.is_valid());
  3544. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3545. EXPECT_FALSE(svr.is_valid());
  3546. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3547. }
  3548. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3549. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3550. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3551. int port = svr.bind_to_any_port("0.0.0.0");
  3552. ASSERT_TRUE(svr.is_valid());
  3553. ASSERT_TRUE(port > 0);
  3554. svr.stop();
  3555. }
  3556. TEST(BindServerTest, UpdateCertsPem) {
  3557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3558. int port = svr.bind_to_any_port("0.0.0.0");
  3559. ASSERT_TRUE(svr.is_valid());
  3560. ASSERT_TRUE(port > 0);
  3561. // Read PEM files
  3562. std::string cert_pem, key_pem, ca_pem;
  3563. read_file(SERVER_CERT_FILE, cert_pem);
  3564. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3565. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3566. // Update server certificates using PEM API
  3567. ASSERT_TRUE(
  3568. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3569. ASSERT_TRUE(svr.is_valid());
  3570. svr.stop();
  3571. }
  3572. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3573. // Start server with client CA (enables client auth)
  3574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3575. ASSERT_TRUE(svr.is_valid());
  3576. bool handler_called = false;
  3577. svr.Get("/test", [&](const Request &req, Response &res) {
  3578. handler_called = true;
  3579. // Verify client certificate is present
  3580. auto cert = req.peer_cert();
  3581. EXPECT_TRUE(static_cast<bool>(cert));
  3582. res.set_content("ok", "text/plain");
  3583. });
  3584. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3585. auto se = detail::scope_exit([&] {
  3586. svr.stop();
  3587. t.join();
  3588. ASSERT_FALSE(svr.is_running());
  3589. });
  3590. svr.wait_until_ready();
  3591. // Read PEM files
  3592. std::string cert_pem, key_pem, ca_pem;
  3593. read_file(SERVER_CERT_FILE, cert_pem);
  3594. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3595. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3596. // Update server certificates and client CA using PEM API while server running
  3597. ASSERT_TRUE(
  3598. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3599. // Connect with client certificate
  3600. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3601. cli.enable_server_certificate_verification(false);
  3602. cli.set_connection_timeout(30);
  3603. auto res = cli.Get("/test");
  3604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3605. ASSERT_EQ(StatusCode::OK_200, res->status);
  3606. ASSERT_TRUE(handler_called);
  3607. EXPECT_EQ("ok", res->body);
  3608. }
  3609. #endif
  3610. TEST(ErrorHandlerTest, ContentLength) {
  3611. Server svr;
  3612. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3613. res.status = StatusCode::OK_200;
  3614. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3615. "text/html"); // <= Content-Length still 13
  3616. });
  3617. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3618. res.set_content("Hello World!\n", "text/plain");
  3619. res.status = 524;
  3620. });
  3621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3622. auto se = detail::scope_exit([&] {
  3623. svr.stop();
  3624. thread.join();
  3625. ASSERT_FALSE(svr.is_running());
  3626. });
  3627. svr.wait_until_ready();
  3628. {
  3629. Client cli(HOST, PORT);
  3630. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3632. EXPECT_EQ(StatusCode::OK_200, res->status);
  3633. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3634. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3635. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3636. }
  3637. }
  3638. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3639. TEST(ExceptionTest, WithoutExceptionHandler) {
  3640. Server svr;
  3641. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3642. throw std::runtime_error("exception...");
  3643. });
  3644. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3645. throw std::runtime_error("exception\r\n...");
  3646. });
  3647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3648. auto se = detail::scope_exit([&] {
  3649. svr.stop();
  3650. listen_thread.join();
  3651. ASSERT_FALSE(svr.is_running());
  3652. });
  3653. svr.wait_until_ready();
  3654. Client cli("localhost", PORT);
  3655. {
  3656. auto res = cli.Get("/exception");
  3657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3658. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3659. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3660. }
  3661. {
  3662. auto res = cli.Get("/unknown");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3665. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3666. }
  3667. }
  3668. TEST(ExceptionTest, WithExceptionHandler) {
  3669. Server svr;
  3670. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3671. std::exception_ptr ep) {
  3672. EXPECT_FALSE(ep == nullptr);
  3673. try {
  3674. std::rethrow_exception(ep);
  3675. } catch (std::exception &e) {
  3676. EXPECT_EQ("abc", std::string(e.what()));
  3677. } catch (...) {}
  3678. res.status = StatusCode::InternalServerError_500;
  3679. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3680. "text/html"); // <= Content-Length still 13 at this point
  3681. });
  3682. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3683. res.set_content("Hello World!\n", "text/plain");
  3684. throw std::runtime_error("abc");
  3685. });
  3686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3687. auto se = detail::scope_exit([&] {
  3688. svr.stop();
  3689. thread.join();
  3690. ASSERT_FALSE(svr.is_running());
  3691. });
  3692. svr.wait_until_ready();
  3693. for (size_t i = 0; i < 10; i++) {
  3694. Client cli(HOST, PORT);
  3695. for (size_t j = 0; j < 100; j++) {
  3696. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3698. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3699. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3700. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3701. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3702. }
  3703. cli.set_keep_alive(true);
  3704. for (size_t j = 0; j < 100; j++) {
  3705. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3708. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3709. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3710. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3711. }
  3712. }
  3713. }
  3714. TEST(ExceptionTest, AndErrorHandler) {
  3715. Server svr;
  3716. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3717. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3718. });
  3719. svr.set_exception_handler(
  3720. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3721. EXPECT_FALSE(ep == nullptr);
  3722. try {
  3723. std::rethrow_exception(ep);
  3724. } catch (std::exception &e) {
  3725. res.set_content(e.what(), "text/html");
  3726. } catch (...) {}
  3727. res.status = StatusCode::InternalServerError_500;
  3728. });
  3729. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3730. throw std::runtime_error("EXCEPTION");
  3731. });
  3732. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3733. res.set_content("ERROR", "text/html");
  3734. res.status = StatusCode::InternalServerError_500;
  3735. });
  3736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. Client cli(HOST, PORT);
  3744. {
  3745. auto res = cli.Get("/exception");
  3746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3747. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3748. EXPECT_EQ("EXCEPTION", res->body);
  3749. }
  3750. {
  3751. auto res = cli.Get("/error");
  3752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3753. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3754. EXPECT_EQ("ERROR", res->body);
  3755. }
  3756. {
  3757. auto res = cli.Get("/invalid");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3760. EXPECT_EQ("NOT_FOUND", res->body);
  3761. }
  3762. }
  3763. #endif
  3764. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3765. // process_request() wraps only routing() in a try/catch, so an exception from
  3766. // any other user callback used to unwind into the task queue - which does not
  3767. // catch - and terminate the process. Each test below runs the server on a
  3768. // single worker thread: a guard that catches the exception but still loses the
  3769. // thread would otherwise be hidden by a spare worker serving the follow-up
  3770. // request. Note that a regression here aborts the whole test binary rather
  3771. // than failing one test.
  3772. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3773. Server svr;
  3774. svr.new_task_queue = [] { return new ThreadPool(1); };
  3775. std::atomic<int> reported{0};
  3776. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3777. if (err == Error::UserCallbackException) { reported++; }
  3778. });
  3779. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3780. res.set_content_provider(
  3781. 1024, "text/plain",
  3782. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3783. sink.write("hello", 5);
  3784. throw std::runtime_error("from the content provider");
  3785. });
  3786. });
  3787. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3788. res.set_content("ok", "text/plain");
  3789. });
  3790. auto port = svr.bind_to_any_port(HOST);
  3791. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3792. auto se = detail::scope_exit([&] {
  3793. svr.stop();
  3794. listen_thread.join();
  3795. ASSERT_FALSE(svr.is_running());
  3796. });
  3797. svr.wait_until_ready();
  3798. {
  3799. Client cli(HOST, port);
  3800. cli.set_read_timeout(5, 0);
  3801. EXPECT_FALSE(cli.Get("/throw"));
  3802. }
  3803. EXPECT_TRUE(svr.is_running());
  3804. EXPECT_EQ(1, reported.load());
  3805. // A request on a fresh connection is still served.
  3806. {
  3807. Client cli(HOST, port);
  3808. auto res = cli.Get("/ok");
  3809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3810. EXPECT_EQ(StatusCode::OK_200, res->status);
  3811. EXPECT_EQ("ok", res->body);
  3812. }
  3813. }
  3814. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3815. Server svr;
  3816. svr.new_task_queue = [] { return new ThreadPool(1); };
  3817. std::atomic<bool> should_throw{true};
  3818. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3819. res.set_content("hi", "text/plain");
  3820. });
  3821. svr.set_post_routing_handler(
  3822. [&](const Request & /*req*/, Response & /*res*/) {
  3823. if (should_throw) {
  3824. throw std::runtime_error("from the post-routing handler");
  3825. }
  3826. });
  3827. auto port = svr.bind_to_any_port(HOST);
  3828. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3829. auto se = detail::scope_exit([&] {
  3830. svr.stop();
  3831. listen_thread.join();
  3832. ASSERT_FALSE(svr.is_running());
  3833. });
  3834. svr.wait_until_ready();
  3835. {
  3836. Client cli(HOST, port);
  3837. cli.set_read_timeout(5, 0);
  3838. EXPECT_FALSE(cli.Get("/hi"));
  3839. }
  3840. EXPECT_TRUE(svr.is_running());
  3841. should_throw = false;
  3842. {
  3843. Client cli(HOST, port);
  3844. auto res = cli.Get("/hi");
  3845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3846. EXPECT_EQ(StatusCode::OK_200, res->status);
  3847. EXPECT_EQ("hi", res->body);
  3848. }
  3849. }
  3850. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3851. // The guard reports the caught exception through the error logger, which is
  3852. // a user callback too. A logger that throws has to be contained as well, or
  3853. // the process would terminate from inside the catch.
  3854. Server svr;
  3855. svr.new_task_queue = [] { return new ThreadPool(1); };
  3856. std::atomic<int> reported{0};
  3857. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3858. if (err == Error::UserCallbackException) {
  3859. reported++;
  3860. throw std::runtime_error("from the error logger");
  3861. }
  3862. });
  3863. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3864. res.set_content_provider(
  3865. 1024, "text/plain",
  3866. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3867. sink.write("hello", 5);
  3868. throw std::runtime_error("from the content provider");
  3869. });
  3870. });
  3871. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3872. res.set_content("ok", "text/plain");
  3873. });
  3874. auto port = svr.bind_to_any_port(HOST);
  3875. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3876. auto se = detail::scope_exit([&] {
  3877. svr.stop();
  3878. listen_thread.join();
  3879. ASSERT_FALSE(svr.is_running());
  3880. });
  3881. svr.wait_until_ready();
  3882. {
  3883. Client cli(HOST, port);
  3884. cli.set_read_timeout(5, 0);
  3885. EXPECT_FALSE(cli.Get("/throw"));
  3886. }
  3887. EXPECT_TRUE(svr.is_running());
  3888. EXPECT_EQ(1, reported.load());
  3889. {
  3890. Client cli(HOST, port);
  3891. auto res = cli.Get("/ok");
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. EXPECT_EQ("ok", res->body);
  3895. }
  3896. }
  3897. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3898. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3899. // so the exception unwinds through the ws::WebSocket object on its way to
  3900. // the guard. None of the HTTP cases above cross that.
  3901. Server svr;
  3902. svr.new_task_queue = [] { return new ThreadPool(1); };
  3903. std::atomic<int> reported{0};
  3904. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3905. if (err == Error::UserCallbackException) { reported++; }
  3906. });
  3907. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3908. throw std::runtime_error("from the WebSocket handler");
  3909. });
  3910. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3911. res.set_content("ok", "text/plain");
  3912. });
  3913. auto port = svr.bind_to_any_port(HOST);
  3914. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3915. auto se = detail::scope_exit([&] {
  3916. svr.stop();
  3917. listen_thread.join();
  3918. ASSERT_FALSE(svr.is_running());
  3919. });
  3920. svr.wait_until_ready();
  3921. {
  3922. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3923. "/ws");
  3924. auto res = client.connect();
  3925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3926. // The server dropped the connection instead of dying.
  3927. std::string msg;
  3928. EXPECT_FALSE(client.read(msg));
  3929. client.close();
  3930. }
  3931. EXPECT_TRUE(svr.is_running());
  3932. EXPECT_EQ(1, reported.load());
  3933. {
  3934. Client cli(HOST, port);
  3935. auto res = cli.Get("/ok");
  3936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3937. EXPECT_EQ(StatusCode::OK_200, res->status);
  3938. EXPECT_EQ("ok", res->body);
  3939. }
  3940. }
  3941. #ifdef CPPHTTPLIB_SSL_ENABLED
  3942. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3943. // SSLServer::process_and_close_socket() is a separate overload with its own
  3944. // guard, so it is exercised on its own.
  3945. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3946. ASSERT_TRUE(svr.is_valid());
  3947. svr.new_task_queue = [] { return new ThreadPool(1); };
  3948. std::atomic<int> reported{0};
  3949. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3950. if (err == Error::UserCallbackException) { reported++; }
  3951. });
  3952. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3953. res.set_content_provider(
  3954. 1024, "text/plain",
  3955. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3956. sink.write("hello", 5);
  3957. throw std::runtime_error("from the content provider");
  3958. });
  3959. });
  3960. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3961. res.set_content("ok", "text/plain");
  3962. });
  3963. auto port = svr.bind_to_any_port(HOST);
  3964. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3965. auto se = detail::scope_exit([&] {
  3966. svr.stop();
  3967. listen_thread.join();
  3968. ASSERT_FALSE(svr.is_running());
  3969. });
  3970. svr.wait_until_ready();
  3971. {
  3972. SSLClient cli(HOST, port);
  3973. cli.enable_server_certificate_verification(false);
  3974. cli.set_read_timeout(5, 0);
  3975. EXPECT_FALSE(cli.Get("/throw"));
  3976. }
  3977. EXPECT_TRUE(svr.is_running());
  3978. EXPECT_EQ(1, reported.load());
  3979. {
  3980. SSLClient cli(HOST, port);
  3981. cli.enable_server_certificate_verification(false);
  3982. auto res = cli.Get("/ok");
  3983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. EXPECT_EQ("ok", res->body);
  3986. }
  3987. }
  3988. #endif
  3989. #endif
  3990. TEST(NoContentTest, ContentLength) {
  3991. Server svr;
  3992. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3993. res.status = StatusCode::NoContent_204;
  3994. });
  3995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3996. auto se = detail::scope_exit([&] {
  3997. svr.stop();
  3998. thread.join();
  3999. ASSERT_FALSE(svr.is_running());
  4000. });
  4001. svr.wait_until_ready();
  4002. {
  4003. Client cli(HOST, PORT);
  4004. auto res = cli.Get("/hi");
  4005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4006. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4007. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4008. }
  4009. }
  4010. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4011. #ifdef CPPHTTPLIB_SSL_ENABLED
  4012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4013. ASSERT_TRUE(svr.is_valid());
  4014. #else
  4015. Server svr;
  4016. #endif
  4017. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4018. if (req.path == "/routing_handler") {
  4019. res.set_header("PRE_ROUTING", "on");
  4020. res.set_content("Routing Handler", "text/plain");
  4021. return httplib::Server::HandlerResponse::Handled;
  4022. }
  4023. return httplib::Server::HandlerResponse::Unhandled;
  4024. });
  4025. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4026. res.set_content("Error", "text/html");
  4027. });
  4028. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4029. if (req.path == "/routing_handler") {
  4030. res.set_header("POST_ROUTING", "on");
  4031. }
  4032. });
  4033. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4034. res.set_content("Hello World!\n", "text/plain");
  4035. });
  4036. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4037. auto se = detail::scope_exit([&] {
  4038. svr.stop();
  4039. thread.join();
  4040. ASSERT_FALSE(svr.is_running());
  4041. });
  4042. svr.wait_until_ready();
  4043. {
  4044. #ifdef CPPHTTPLIB_SSL_ENABLED
  4045. SSLClient cli(HOST, PORT);
  4046. cli.enable_server_certificate_verification(false);
  4047. #else
  4048. Client cli(HOST, PORT);
  4049. #endif
  4050. auto res = cli.Get("/routing_handler");
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. EXPECT_EQ("Routing Handler", res->body);
  4054. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4055. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4056. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4057. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4058. }
  4059. {
  4060. #ifdef CPPHTTPLIB_SSL_ENABLED
  4061. SSLClient cli(HOST, PORT);
  4062. cli.enable_server_certificate_verification(false);
  4063. #else
  4064. Client cli(HOST, PORT);
  4065. #endif
  4066. auto res = cli.Get("/hi");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. EXPECT_EQ("Hello World!\n", res->body);
  4070. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4071. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4072. }
  4073. {
  4074. #ifdef CPPHTTPLIB_SSL_ENABLED
  4075. SSLClient cli(HOST, PORT);
  4076. cli.enable_server_certificate_verification(false);
  4077. #else
  4078. Client cli(HOST, PORT);
  4079. #endif
  4080. auto res = cli.Get("/aaa");
  4081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4082. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4083. EXPECT_EQ("Error", res->body);
  4084. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4085. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4086. }
  4087. }
  4088. TEST(RequestHandlerTest, PreRequestHandler) {
  4089. auto route_path = "/user/:user";
  4090. Server svr;
  4091. svr.Get("/hi", [](const Request &, Response &res) {
  4092. res.set_content("hi", "text/plain");
  4093. });
  4094. svr.Get(route_path, [](const Request &req, Response &res) {
  4095. res.set_content(req.path_params.at("user"), "text/plain");
  4096. });
  4097. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4098. if (req.matched_route == route_path) {
  4099. auto user = req.path_params.at("user");
  4100. if (user != "john") {
  4101. res.status = StatusCode::Forbidden_403;
  4102. res.set_content("error", "text/html");
  4103. return Server::HandlerResponse::Handled;
  4104. }
  4105. }
  4106. return Server::HandlerResponse::Unhandled;
  4107. });
  4108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4109. auto se = detail::scope_exit([&] {
  4110. svr.stop();
  4111. thread.join();
  4112. ASSERT_FALSE(svr.is_running());
  4113. });
  4114. svr.wait_until_ready();
  4115. Client cli(HOST, PORT);
  4116. {
  4117. auto res = cli.Get("/hi");
  4118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. EXPECT_EQ("hi", res->body);
  4121. }
  4122. {
  4123. auto res = cli.Get("/user/john");
  4124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::OK_200, res->status);
  4126. EXPECT_EQ("john", res->body);
  4127. }
  4128. {
  4129. auto res = cli.Get("/user/invalid-user");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4132. EXPECT_EQ("error", res->body);
  4133. }
  4134. }
  4135. // The pre-request handler must run before the request body is read, so a
  4136. // rejected request never forces the server to buffer a (potentially large)
  4137. // body. Here the posted body is larger than the payload limit: if the body
  4138. // were read first the server would answer 413, but because the pre-request
  4139. // handler runs first it answers 403 and the body is never read.
  4140. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4141. Server svr;
  4142. svr.set_payload_max_length(8);
  4143. auto handler_ran = false;
  4144. svr.Post("/reject", [&](const Request &req, Response &res) {
  4145. handler_ran = true;
  4146. res.set_content(req.body, "text/plain");
  4147. });
  4148. svr.Post("/accept", [](const Request &req, Response &res) {
  4149. res.set_content(req.body, "text/plain");
  4150. });
  4151. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4152. if (req.matched_route == "/reject") {
  4153. res.status = StatusCode::Forbidden_403;
  4154. res.set_content("denied", "text/plain");
  4155. return Server::HandlerResponse::Handled;
  4156. }
  4157. return Server::HandlerResponse::Unhandled;
  4158. });
  4159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4160. auto se = detail::scope_exit([&] {
  4161. svr.stop();
  4162. thread.join();
  4163. ASSERT_FALSE(svr.is_running());
  4164. });
  4165. svr.wait_until_ready();
  4166. Client cli(HOST, PORT);
  4167. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4168. // rejects with 403 before the body is read, so 413 is never reached.
  4169. {
  4170. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4172. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4173. EXPECT_EQ("denied", res->body);
  4174. EXPECT_FALSE(handler_ran);
  4175. }
  4176. // An approved route still reads the body and enforces the payload limit.
  4177. {
  4178. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4180. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4181. }
  4182. }
  4183. TEST(UserDataTest, BasicOperations) {
  4184. httplib::UserData ud;
  4185. // Initially empty
  4186. EXPECT_FALSE(ud.has("key"));
  4187. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4188. // set and get
  4189. ud.set("key", 42);
  4190. EXPECT_TRUE(ud.has("key"));
  4191. auto *p = ud.get<int>("key");
  4192. ASSERT_NE(nullptr, p);
  4193. EXPECT_EQ(42, *p);
  4194. // Type mismatch → nullptr
  4195. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4196. // Overwrite with different type
  4197. ud.set("key", std::string("hello"));
  4198. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4199. auto *s = ud.get<std::string>("key");
  4200. ASSERT_NE(nullptr, s);
  4201. EXPECT_EQ("hello", *s);
  4202. // erase
  4203. ud.erase("key");
  4204. EXPECT_FALSE(ud.has("key"));
  4205. // clear
  4206. ud.set("a", 1);
  4207. ud.set("b", 2);
  4208. ud.clear();
  4209. EXPECT_FALSE(ud.has("a"));
  4210. EXPECT_FALSE(ud.has("b"));
  4211. }
  4212. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4213. struct AuthCtx {
  4214. std::string user_id;
  4215. };
  4216. Server svr;
  4217. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4218. res.user_data.set("auth", AuthCtx{"alice"});
  4219. return Server::HandlerResponse::Unhandled;
  4220. });
  4221. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4222. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4223. ASSERT_NE(nullptr, ctx);
  4224. res.set_content("Hello " + ctx->user_id, "text/plain");
  4225. });
  4226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4227. auto se = detail::scope_exit([&] {
  4228. svr.stop();
  4229. thread.join();
  4230. ASSERT_FALSE(svr.is_running());
  4231. });
  4232. svr.wait_until_ready();
  4233. Client cli(HOST, PORT);
  4234. auto res = cli.Get("/me");
  4235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4236. EXPECT_EQ(StatusCode::OK_200, res->status);
  4237. EXPECT_EQ("Hello alice", res->body);
  4238. }
  4239. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4240. struct RoleCtx {
  4241. std::string role;
  4242. };
  4243. Server svr;
  4244. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4245. res.user_data.set("role", RoleCtx{"admin"});
  4246. return Server::HandlerResponse::Unhandled;
  4247. });
  4248. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4249. auto *ctx = res.user_data.get<RoleCtx>("role");
  4250. ASSERT_NE(nullptr, ctx);
  4251. res.set_content(ctx->role, "text/plain");
  4252. });
  4253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4254. auto se = detail::scope_exit([&] {
  4255. svr.stop();
  4256. thread.join();
  4257. ASSERT_FALSE(svr.is_running());
  4258. });
  4259. svr.wait_until_ready();
  4260. Client cli(HOST, PORT);
  4261. auto res = cli.Get("/role");
  4262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4263. EXPECT_EQ(StatusCode::OK_200, res->status);
  4264. EXPECT_EQ("admin", res->body);
  4265. }
  4266. TEST(InvalidFormatTest, StatusCode) {
  4267. Server svr;
  4268. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4269. res.set_content("Hello World!\n", "text/plain");
  4270. res.status = 9999; // Status should be a three-digit code...
  4271. });
  4272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4273. auto se = detail::scope_exit([&] {
  4274. svr.stop();
  4275. thread.join();
  4276. ASSERT_FALSE(svr.is_running());
  4277. });
  4278. svr.wait_until_ready();
  4279. {
  4280. Client cli(HOST, PORT);
  4281. auto res = cli.Get("/hi");
  4282. ASSERT_FALSE(res);
  4283. }
  4284. }
  4285. TEST(URLFragmentTest, WithFragment) {
  4286. Server svr;
  4287. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4288. EXPECT_TRUE(req.target == "/hi");
  4289. });
  4290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4291. auto se = detail::scope_exit([&] {
  4292. svr.stop();
  4293. thread.join();
  4294. ASSERT_FALSE(svr.is_running());
  4295. });
  4296. svr.wait_until_ready();
  4297. {
  4298. Client cli(HOST, PORT);
  4299. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4300. EXPECT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. res = cli.Get("/hi%23key1=val1=key2=val2");
  4303. EXPECT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4305. }
  4306. }
  4307. TEST(HeaderWriter, SetHeaderWriter) {
  4308. Server svr;
  4309. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4310. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4311. return detail::write_headers(strm, hdrs);
  4312. });
  4313. svr.Get("/hi", [](const Request &req, Response &res) {
  4314. auto it = req.headers.find("CustomClientHeader");
  4315. EXPECT_TRUE(it != req.headers.end());
  4316. EXPECT_EQ(it->second, "CustomClientValue");
  4317. res.set_content("Hello World!\n", "text/plain");
  4318. });
  4319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4320. auto se = detail::scope_exit([&] {
  4321. svr.stop();
  4322. thread.join();
  4323. ASSERT_FALSE(svr.is_running());
  4324. });
  4325. svr.wait_until_ready();
  4326. {
  4327. Client cli(HOST, PORT);
  4328. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4329. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4330. return detail::write_headers(strm, hdrs);
  4331. });
  4332. auto res = cli.Get("/hi");
  4333. EXPECT_TRUE(res);
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. auto it = res->headers.find("CustomServerHeader");
  4336. EXPECT_TRUE(it != res->headers.end());
  4337. EXPECT_EQ(it->second, "CustomServerValue");
  4338. }
  4339. }
  4340. class ServerTest : public ::testing::Test {
  4341. protected:
  4342. ServerTest()
  4343. : cli_(HOST, PORT)
  4344. #ifdef CPPHTTPLIB_SSL_ENABLED
  4345. ,
  4346. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4347. #endif
  4348. {
  4349. #ifdef CPPHTTPLIB_SSL_ENABLED
  4350. cli_.enable_server_certificate_verification(false);
  4351. #endif
  4352. // Allow LARGE_DATA (100MB) responses
  4353. cli_.set_payload_max_length(200 * 1024 * 1024);
  4354. }
  4355. virtual void SetUp() {
  4356. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4357. svr_.set_payload_max_length(200 * 1024 * 1024);
  4358. svr_.set_mount_point("/", "./www");
  4359. svr_.set_mount_point("/mount", "./www2");
  4360. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4361. svr_.Get("/hi",
  4362. [&](const Request & /*req*/, Response &res) {
  4363. res.set_content("Hello World!", "text/plain");
  4364. })
  4365. .Get("/file_content",
  4366. [&](const Request & /*req*/, Response &res) {
  4367. res.set_file_content("./www/dir/test.html");
  4368. })
  4369. .Get("/file_content_with_content_type",
  4370. [&](const Request & /*req*/, Response &res) {
  4371. res.set_file_content("./www/file", "text/plain");
  4372. })
  4373. .Get("/invalid_file_content",
  4374. [&](const Request & /*req*/, Response &res) {
  4375. res.set_file_content("./www/dir/invalid_file_path");
  4376. })
  4377. .Get("/http_response_splitting",
  4378. [&](const Request & /*req*/, Response &res) {
  4379. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4380. EXPECT_EQ(0U, res.headers.size());
  4381. EXPECT_FALSE(res.has_header("a"));
  4382. res.set_header("a", "1\nSet-Cookie: a=1");
  4383. EXPECT_EQ(0U, res.headers.size());
  4384. EXPECT_FALSE(res.has_header("a"));
  4385. res.set_header("a", "1\rSet-Cookie: a=1");
  4386. EXPECT_EQ(0U, res.headers.size());
  4387. EXPECT_FALSE(res.has_header("a"));
  4388. res.set_header("a\r\nb", "0");
  4389. EXPECT_EQ(0U, res.headers.size());
  4390. EXPECT_FALSE(res.has_header("a"));
  4391. res.set_header("a\rb", "0");
  4392. EXPECT_EQ(0U, res.headers.size());
  4393. EXPECT_FALSE(res.has_header("a"));
  4394. res.set_header("a\nb", "0");
  4395. EXPECT_EQ(0U, res.headers.size());
  4396. EXPECT_FALSE(res.has_header("a"));
  4397. res.set_redirect("1\r\nSet-Cookie: a=1");
  4398. EXPECT_EQ(0U, res.headers.size());
  4399. EXPECT_FALSE(res.has_header("Location"));
  4400. })
  4401. .Get("/slow",
  4402. [&](const Request & /*req*/, Response &res) {
  4403. std::this_thread::sleep_for(std::chrono::seconds(4));
  4404. res.set_content("slow", "text/plain");
  4405. })
  4406. #if 0
  4407. .Post("/slowpost",
  4408. [&](const Request & /*req*/, Response &res) {
  4409. std::this_thread::sleep_for(std::chrono::seconds(2));
  4410. res.set_content("slow", "text/plain");
  4411. })
  4412. #endif
  4413. .Get("/remote_addr",
  4414. [&](const Request &req, Response &res) {
  4415. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4416. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4417. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4418. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4419. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4420. #endif
  4421. res.set_content(req.remote_addr, "text/plain");
  4422. })
  4423. .Get("/local_addr",
  4424. [&](const Request &req, Response &res) {
  4425. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4426. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4427. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4428. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4429. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4430. #endif
  4431. auto local_addr = req.local_addr;
  4432. auto local_port = std::to_string(req.local_port);
  4433. res.set_content(local_addr.append(":").append(local_port),
  4434. "text/plain");
  4435. })
  4436. .Get("/endwith%",
  4437. [&](const Request & /*req*/, Response &res) {
  4438. res.set_content("Hello World!", "text/plain");
  4439. })
  4440. .Get("/a\\+\\+b",
  4441. [&](const Request &req, Response &res) {
  4442. ASSERT_TRUE(req.has_param("a +b"));
  4443. auto val = req.get_param_value("a +b");
  4444. res.set_content(val, "text/plain");
  4445. })
  4446. .Get("/", [&](const Request & /*req*/,
  4447. Response &res) { res.set_redirect("/hi"); })
  4448. .Post("/1",
  4449. [](const Request & /*req*/, Response &res) {
  4450. res.set_redirect("/2", StatusCode::SeeOther_303);
  4451. })
  4452. .Get("/2",
  4453. [](const Request & /*req*/, Response &res) {
  4454. res.set_content("redirected.", "text/plain");
  4455. res.status = StatusCode::OK_200;
  4456. })
  4457. .Post("/person",
  4458. [&](const Request &req, Response &res) {
  4459. if (req.has_param("name") && req.has_param("note")) {
  4460. persons_[req.get_param_value("name")] =
  4461. req.get_param_value("note");
  4462. } else {
  4463. res.status = StatusCode::BadRequest_400;
  4464. }
  4465. })
  4466. .Put("/person",
  4467. [&](const Request &req, Response &res) {
  4468. if (req.has_param("name") && req.has_param("note")) {
  4469. persons_[req.get_param_value("name")] =
  4470. req.get_param_value("note");
  4471. } else {
  4472. res.status = StatusCode::BadRequest_400;
  4473. }
  4474. })
  4475. .Get("/person/(.*)",
  4476. [&](const Request &req, Response &res) {
  4477. string name = req.matches[1];
  4478. if (persons_.find(name) != persons_.end()) {
  4479. auto note = persons_[name];
  4480. res.set_content(note, "text/plain");
  4481. } else {
  4482. res.status = StatusCode::NotFound_404;
  4483. }
  4484. })
  4485. .Delete("/person",
  4486. [&](const Request &req, Response &res) {
  4487. if (req.has_param("name")) {
  4488. string name = req.get_param_value("name");
  4489. if (persons_.find(name) != persons_.end()) {
  4490. persons_.erase(name);
  4491. res.set_content("DELETED", "text/plain");
  4492. } else {
  4493. res.status = StatusCode::NotFound_404;
  4494. }
  4495. } else {
  4496. res.status = StatusCode::BadRequest_400;
  4497. }
  4498. })
  4499. .Post("/x-www-form-urlencoded-json",
  4500. [&](const Request &req, Response &res) {
  4501. auto json = req.get_param_value("json");
  4502. ASSERT_EQ(JSON_DATA, json);
  4503. res.set_content(json, "appliation/json");
  4504. res.status = StatusCode::OK_200;
  4505. })
  4506. .Get("/streamed-chunked",
  4507. [&](const Request & /*req*/, Response &res) {
  4508. res.set_chunked_content_provider(
  4509. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4510. sink.os << "123";
  4511. sink.os << "456";
  4512. sink.os << "789";
  4513. sink.done();
  4514. return true;
  4515. });
  4516. })
  4517. .Get("/streamed-chunked-with-prohibited-trailer",
  4518. [&](const Request & /*req*/, Response &res) {
  4519. auto i = new int(0);
  4520. // Declare both a prohibited trailer (Content-Length) and an
  4521. // allowed one
  4522. res.set_header("Trailer", "Content-Length, X-Allowed");
  4523. res.set_chunked_content_provider(
  4524. "text/plain",
  4525. [i](size_t /*offset*/, DataSink &sink) {
  4526. switch (*i) {
  4527. case 0: sink.os << "123"; break;
  4528. case 1: sink.os << "456"; break;
  4529. case 2: sink.os << "789"; break;
  4530. case 3: {
  4531. sink.done_with_trailer(
  4532. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4533. } break;
  4534. }
  4535. (*i)++;
  4536. return true;
  4537. },
  4538. [i](bool success) {
  4539. EXPECT_TRUE(success);
  4540. delete i;
  4541. });
  4542. })
  4543. .Get("/streamed-chunked2",
  4544. [&](const Request & /*req*/, Response &res) {
  4545. auto i = new int(0);
  4546. res.set_chunked_content_provider(
  4547. "text/plain",
  4548. [i](size_t /*offset*/, DataSink &sink) {
  4549. switch (*i) {
  4550. case 0: sink.os << "123"; break;
  4551. case 1: sink.os << "456"; break;
  4552. case 2: sink.os << "789"; break;
  4553. case 3: sink.done(); break;
  4554. }
  4555. (*i)++;
  4556. return true;
  4557. },
  4558. [i](bool success) {
  4559. EXPECT_TRUE(success);
  4560. delete i;
  4561. });
  4562. })
  4563. .Get("/streamed-chunked-with-trailer",
  4564. [&](const Request & /*req*/, Response &res) {
  4565. auto i = new int(0);
  4566. res.set_header("Trailer", "Dummy1, Dummy2");
  4567. res.set_chunked_content_provider(
  4568. "text/plain",
  4569. [i](size_t /*offset*/, DataSink &sink) {
  4570. switch (*i) {
  4571. case 0: sink.os << "123"; break;
  4572. case 1: sink.os << "456"; break;
  4573. case 2: sink.os << "789"; break;
  4574. case 3: {
  4575. sink.done_with_trailer(
  4576. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4577. } break;
  4578. }
  4579. (*i)++;
  4580. return true;
  4581. },
  4582. [i](bool success) {
  4583. EXPECT_TRUE(success);
  4584. delete i;
  4585. });
  4586. })
  4587. .Get("/streamed",
  4588. [&](const Request & /*req*/, Response &res) {
  4589. res.set_content_provider(
  4590. 6, "text/plain",
  4591. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4592. sink.os << (offset < 3 ? "a" : "b");
  4593. return true;
  4594. });
  4595. })
  4596. .Get("/streamed-without-length",
  4597. [&](const Request & /*req*/, Response &res) {
  4598. auto data = new std::string("abcdefg");
  4599. res.set_content_provider(
  4600. "text/plain",
  4601. [data](size_t offset, DataSink &sink) {
  4602. if (offset < data->size()) {
  4603. sink.os << data->substr(offset);
  4604. }
  4605. sink.done();
  4606. return true;
  4607. },
  4608. [data](bool success) {
  4609. EXPECT_TRUE(success);
  4610. delete data;
  4611. });
  4612. })
  4613. .Get("/streamed-with-range",
  4614. [&](const Request &req, Response &res) {
  4615. auto data = new std::string("abcdefg");
  4616. // An explicit status keeps the server from picking the 206 it
  4617. // would otherwise choose for a ranged request, so the response
  4618. // is not a partial representation.
  4619. auto status = req.get_param_value("status");
  4620. if (status == "200") {
  4621. res.status = StatusCode::OK_200;
  4622. } else if (status == "403") {
  4623. res.status = StatusCode::Forbidden_403;
  4624. }
  4625. res.set_content_provider(
  4626. data->size(), "text/plain",
  4627. [data](size_t offset, size_t length, DataSink &sink) {
  4628. size_t DATA_CHUNK_SIZE = 4;
  4629. const auto &d = *data;
  4630. auto out_len =
  4631. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4632. auto ret =
  4633. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4634. EXPECT_TRUE(ret);
  4635. return true;
  4636. },
  4637. [data, &req](bool success) {
  4638. EXPECT_EQ(success, !req.has_param("error"));
  4639. delete data;
  4640. });
  4641. })
  4642. .Get("/streamed-cancel",
  4643. [&](const Request & /*req*/, Response &res) {
  4644. res.set_content_provider(
  4645. size_t(-1), "text/plain",
  4646. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4647. sink.os << "data_chunk";
  4648. return true;
  4649. });
  4650. })
  4651. .Get("/regex-with-delimiter",
  4652. [&](const Request &req, Response & /*res*/) {
  4653. ASSERT_TRUE(req.has_param("key"));
  4654. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4655. })
  4656. .Get("/with-range",
  4657. [&](const Request & /*req*/, Response &res) {
  4658. res.set_content("abcdefg", "text/plain");
  4659. })
  4660. .Get("/test-start-time",
  4661. [&](const Request &req, Response & /*res*/) {
  4662. EXPECT_NE(req.start_time_,
  4663. std::chrono::steady_clock::time_point::min());
  4664. })
  4665. .Get("/with-range-customized-response",
  4666. [&](const Request & /*req*/, Response &res) {
  4667. res.status = StatusCode::BadRequest_400;
  4668. res.set_content(JSON_DATA, "application/json");
  4669. })
  4670. .Post("/chunked",
  4671. [&](const Request &req, Response & /*res*/) {
  4672. EXPECT_EQ(req.body, "dechunked post body");
  4673. })
  4674. .Post("/large-chunked",
  4675. [&](const Request &req, Response & /*res*/) {
  4676. std::string expected(6 * 30 * 1024u, 'a');
  4677. EXPECT_EQ(req.body, expected);
  4678. })
  4679. .Post("/multipart",
  4680. [&](const Request &req, Response & /*res*/) {
  4681. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4682. req.form.get_field_count("text2") +
  4683. req.form.get_field_count("file3") +
  4684. req.form.get_field_count("file4"));
  4685. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4686. req.form.get_file_count("file2"));
  4687. ASSERT_TRUE(!req.form.has_file("???"));
  4688. ASSERT_TRUE(!req.form.has_field("???"));
  4689. ASSERT_TRUE(req.body.empty());
  4690. {
  4691. const auto &text = req.form.get_field("text1");
  4692. EXPECT_EQ("text default", text);
  4693. }
  4694. {
  4695. const auto &text = req.form.get_field("text2");
  4696. EXPECT_EQ("aωb", text);
  4697. }
  4698. {
  4699. const auto &file = req.form.get_file("file1");
  4700. EXPECT_EQ("hello.txt", file.filename);
  4701. EXPECT_EQ("text/plain", file.content_type);
  4702. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4703. }
  4704. {
  4705. const auto &file = req.form.get_file("file2");
  4706. EXPECT_EQ("world.json", file.filename);
  4707. EXPECT_EQ("application/json", file.content_type);
  4708. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4709. }
  4710. {
  4711. const auto &text = req.form.get_field("file3");
  4712. EXPECT_EQ(0u, text.size());
  4713. }
  4714. {
  4715. const auto &text = req.form.get_field("file4");
  4716. EXPECT_EQ(0u, text.size());
  4717. }
  4718. })
  4719. .Post("/multipart/multi_file_values",
  4720. [&](const Request &req, Response & /*res*/) {
  4721. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4722. req.form.get_field_count("multi_text1"));
  4723. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4724. ASSERT_TRUE(!req.form.has_file("???"));
  4725. ASSERT_TRUE(!req.form.has_field("???"));
  4726. ASSERT_TRUE(req.body.empty());
  4727. {
  4728. const auto &text = req.form.get_field("text");
  4729. EXPECT_EQ("default text", text);
  4730. }
  4731. {
  4732. const auto &text1_values = req.form.get_fields("multi_text1");
  4733. EXPECT_EQ(2u, text1_values.size());
  4734. EXPECT_EQ("aaaaa", text1_values[0]);
  4735. EXPECT_EQ("bbbbb", text1_values[1]);
  4736. }
  4737. {
  4738. const auto &file1_values = req.form.get_files("multi_file1");
  4739. EXPECT_EQ(2u, file1_values.size());
  4740. auto file1 = file1_values[0];
  4741. EXPECT_EQ(file1.filename, "hello.txt");
  4742. EXPECT_EQ(file1.content_type, "text/plain");
  4743. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4744. auto file2 = file1_values[1];
  4745. EXPECT_EQ(file2.filename, "world.json");
  4746. EXPECT_EQ(file2.content_type, "application/json");
  4747. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4748. }
  4749. })
  4750. .Post("/empty",
  4751. [&](const Request &req, Response &res) {
  4752. EXPECT_EQ(req.body, "");
  4753. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4754. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4755. res.set_content("empty", "text/plain");
  4756. })
  4757. .Post("/empty-no-content-type",
  4758. [&](const Request &req, Response &res) {
  4759. EXPECT_EQ(req.body, "");
  4760. EXPECT_FALSE(req.has_header("Content-Type"));
  4761. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4762. res.set_content("empty-no-content-type", "text/plain");
  4763. })
  4764. .Post("/path-only",
  4765. [&](const Request &req, Response &res) {
  4766. EXPECT_EQ(req.body, "");
  4767. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4768. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4769. res.set_content("path-only", "text/plain");
  4770. })
  4771. .Post("/path-headers-only",
  4772. [&](const Request &req, Response &res) {
  4773. EXPECT_EQ(req.body, "");
  4774. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4775. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4776. EXPECT_EQ("world", req.get_header_value("hello"));
  4777. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4778. res.set_content("path-headers-only", "text/plain");
  4779. })
  4780. .Post("/post-large",
  4781. [&](const Request &req, Response &res) {
  4782. EXPECT_EQ(req.body, LARGE_DATA);
  4783. res.set_content(req.body, "text/plain");
  4784. })
  4785. .Post("/post-loopback",
  4786. [&](const Request &, Response &res,
  4787. ContentReader const &content_reader) {
  4788. std::string body;
  4789. content_reader([&](const char *data, size_t data_length) {
  4790. body.append(data, data_length);
  4791. return true;
  4792. });
  4793. res.set_content(body, "text/plain");
  4794. })
  4795. .Put("/put-loopback",
  4796. [&](const Request &, Response &res,
  4797. ContentReader const &content_reader) {
  4798. std::string body;
  4799. content_reader([&](const char *data, size_t data_length) {
  4800. body.append(data, data_length);
  4801. return true;
  4802. });
  4803. res.set_content(body, "text/plain");
  4804. })
  4805. .Patch("/patch-loopback",
  4806. [&](const Request &, Response &res,
  4807. ContentReader const &content_reader) {
  4808. std::string body;
  4809. content_reader([&](const char *data, size_t data_length) {
  4810. body.append(data, data_length);
  4811. return true;
  4812. });
  4813. res.set_content(body, "text/plain");
  4814. })
  4815. .Put("/empty-no-content-type",
  4816. [&](const Request &req, Response &res) {
  4817. EXPECT_EQ(req.body, "");
  4818. EXPECT_FALSE(req.has_header("Content-Type"));
  4819. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4820. res.set_content("empty-no-content-type", "text/plain");
  4821. })
  4822. .Put("/put",
  4823. [&](const Request &req, Response &res) {
  4824. EXPECT_EQ(req.body, "PUT");
  4825. res.set_content(req.body, "text/plain");
  4826. })
  4827. .Put("/put-large",
  4828. [&](const Request &req, Response &res) {
  4829. EXPECT_EQ(req.body, LARGE_DATA);
  4830. res.set_content(req.body, "text/plain");
  4831. })
  4832. .Patch("/patch",
  4833. [&](const Request &req, Response &res) {
  4834. EXPECT_EQ(req.body, "PATCH");
  4835. res.set_content(req.body, "text/plain");
  4836. })
  4837. .Delete("/delete",
  4838. [&](const Request & /*req*/, Response &res) {
  4839. res.set_content("DELETE", "text/plain");
  4840. })
  4841. .Delete("/delete-body",
  4842. [&](const Request &req, Response &res) {
  4843. EXPECT_EQ(req.body, "content");
  4844. res.set_content(req.body, "text/plain");
  4845. })
  4846. .Options(R"(\*)",
  4847. [&](const Request & /*req*/, Response &res) {
  4848. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4849. })
  4850. .CustomRoute("PROPFIND", "/dav/:id",
  4851. [&](const Request &req, Response &res) {
  4852. res.set_header("x-body-size",
  4853. std::to_string(req.body.size()));
  4854. res.set_header("x-matched-route", req.matched_route);
  4855. res.set_header("x-dav-id", req.path_params.at("id"));
  4856. res.status = StatusCode::MultiStatus_207;
  4857. res.set_content(req.body, "application/xml");
  4858. })
  4859. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4860. [&](const Request &req, Response &res) {
  4861. res.set_header("x-dav-match", req.matches[1]);
  4862. res.status = StatusCode::MultiStatus_207;
  4863. })
  4864. .CustomRoute("MKCOL", "/dav-mkcol",
  4865. [&](const Request &req, Response &res) {
  4866. EXPECT_TRUE(req.body.empty());
  4867. res.status = StatusCode::Created_201;
  4868. })
  4869. .CustomRoute(
  4870. "REPORT", "/dav-report",
  4871. [&](const Request & /*req*/, Response &res,
  4872. const ContentReader &content_reader) {
  4873. std::string body;
  4874. content_reader([&](const char *data, size_t data_length) {
  4875. body.append(data, data_length);
  4876. return true;
  4877. });
  4878. res.set_header("x-body-size", std::to_string(body.size()));
  4879. res.status = StatusCode::MultiStatus_207;
  4880. res.set_content(body, "application/xml");
  4881. })
  4882. .Get("/request-target",
  4883. [&](const Request &req, Response & /*res*/) {
  4884. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4885. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4886. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4887. })
  4888. .Get("/long-query-value",
  4889. [&](const Request &req, Response & /*res*/) {
  4890. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4891. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4892. })
  4893. .Get("/too-long-query-value",
  4894. [&](const Request &req, Response & /*res*/) {
  4895. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4896. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4897. })
  4898. .Get("/array-param",
  4899. [&](const Request &req, Response & /*res*/) {
  4900. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4901. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4902. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4903. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4904. })
  4905. .Get("/array-param-values",
  4906. [&](const Request &req, Response & /*res*/) {
  4907. auto values = req.get_param_values("array");
  4908. EXPECT_EQ(3u, values.size());
  4909. EXPECT_EQ("value1", values[0]);
  4910. EXPECT_EQ("value2", values[1]);
  4911. EXPECT_EQ("value3", values[2]);
  4912. auto empty = req.get_param_values("nonexistent");
  4913. EXPECT_TRUE(empty.empty());
  4914. })
  4915. .Post("/validate-no-multiple-headers",
  4916. [&](const Request &req, Response & /*res*/) {
  4917. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4918. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4919. })
  4920. .Post("/content_receiver",
  4921. [&](const Request &req, Response &res,
  4922. const ContentReader &content_reader) {
  4923. if (req.is_multipart_form_data()) {
  4924. std::vector<FormData> items;
  4925. content_reader(
  4926. [&](const FormData &file) {
  4927. items.push_back(file);
  4928. return true;
  4929. },
  4930. [&](const char *data, size_t data_length) {
  4931. items.back().content.append(data, data_length);
  4932. return true;
  4933. });
  4934. EXPECT_EQ(5u, items.size());
  4935. {
  4936. const auto &file = get_file_value(items, "text1");
  4937. EXPECT_TRUE(file.filename.empty());
  4938. EXPECT_EQ("text default", file.content);
  4939. }
  4940. {
  4941. const auto &file = get_file_value(items, "text2");
  4942. EXPECT_TRUE(file.filename.empty());
  4943. EXPECT_EQ("aωb", file.content);
  4944. }
  4945. {
  4946. const auto &file = get_file_value(items, "file1");
  4947. EXPECT_EQ("hello.txt", file.filename);
  4948. EXPECT_EQ("text/plain", file.content_type);
  4949. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4950. }
  4951. {
  4952. const auto &file = get_file_value(items, "file2");
  4953. EXPECT_EQ("world.json", file.filename);
  4954. EXPECT_EQ("application/json", file.content_type);
  4955. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4956. }
  4957. {
  4958. const auto &file = get_file_value(items, "file3");
  4959. EXPECT_TRUE(file.filename.empty());
  4960. EXPECT_EQ("application/octet-stream", file.content_type);
  4961. EXPECT_EQ(0u, file.content.size());
  4962. }
  4963. } else {
  4964. std::string body;
  4965. content_reader([&](const char *data, size_t data_length) {
  4966. EXPECT_EQ(7U, data_length);
  4967. body.append(data, data_length);
  4968. return true;
  4969. });
  4970. EXPECT_EQ(body, "content");
  4971. res.set_content(body, "text/plain");
  4972. }
  4973. })
  4974. .Put("/content_receiver",
  4975. [&](const Request & /*req*/, Response &res,
  4976. const ContentReader &content_reader) {
  4977. std::string body;
  4978. content_reader([&](const char *data, size_t data_length) {
  4979. body.append(data, data_length);
  4980. return true;
  4981. });
  4982. EXPECT_EQ(body, "content");
  4983. res.set_content(body, "text/plain");
  4984. })
  4985. .Patch("/content_receiver",
  4986. [&](const Request & /*req*/, Response &res,
  4987. const ContentReader &content_reader) {
  4988. std::string body;
  4989. content_reader([&](const char *data, size_t data_length) {
  4990. body.append(data, data_length);
  4991. return true;
  4992. });
  4993. EXPECT_EQ(body, "content");
  4994. res.set_content(body, "text/plain");
  4995. })
  4996. .Post("/query-string-and-body",
  4997. [&](const Request &req, Response & /*res*/) {
  4998. ASSERT_TRUE(req.has_param("key"));
  4999. EXPECT_EQ(req.get_param_value("key"), "value");
  5000. EXPECT_EQ(req.body, "content");
  5001. })
  5002. .Get("/last-request",
  5003. [&](const Request &req, Response & /*res*/) {
  5004. EXPECT_EQ("close", req.get_header_value("Connection"));
  5005. })
  5006. .Get(R"(/redirect/(\d+))",
  5007. [&](const Request &req, Response &res) {
  5008. auto num = std::stoi(req.matches[1]) + 1;
  5009. std::string url = "/redirect/" + std::to_string(num);
  5010. res.set_redirect(url);
  5011. })
  5012. .Post("/binary",
  5013. [&](const Request &req, Response &res) {
  5014. EXPECT_EQ(4U, req.body.size());
  5015. EXPECT_EQ("application/octet-stream",
  5016. req.get_header_value("Content-Type"));
  5017. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5018. res.set_content(req.body, "application/octet-stream");
  5019. })
  5020. .Put("/binary",
  5021. [&](const Request &req, Response &res) {
  5022. EXPECT_EQ(4U, req.body.size());
  5023. EXPECT_EQ("application/octet-stream",
  5024. req.get_header_value("Content-Type"));
  5025. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5026. res.set_content(req.body, "application/octet-stream");
  5027. })
  5028. .Patch("/binary",
  5029. [&](const Request &req, Response &res) {
  5030. EXPECT_EQ(4U, req.body.size());
  5031. EXPECT_EQ("application/octet-stream",
  5032. req.get_header_value("Content-Type"));
  5033. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5034. res.set_content(req.body, "application/octet-stream");
  5035. })
  5036. .Delete("/binary",
  5037. [&](const Request &req, Response &res) {
  5038. EXPECT_EQ(4U, req.body.size());
  5039. EXPECT_EQ("application/octet-stream",
  5040. req.get_header_value("Content-Type"));
  5041. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5042. res.set_content(req.body, "application/octet-stream");
  5043. })
  5044. .Get("/issue1772",
  5045. [&](const Request & /*req*/, Response &res) {
  5046. res.status = 401;
  5047. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5048. })
  5049. .Delete("/issue609",
  5050. [](const httplib::Request &, httplib::Response &res,
  5051. const httplib::ContentReader &) {
  5052. res.set_content("ok", "text/plain");
  5053. })
  5054. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5055. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5056. .Get("/compress",
  5057. [&](const Request & /*req*/, Response &res) {
  5058. res.set_content(
  5059. "12345678901234567890123456789012345678901234567890123456789"
  5060. "01234567890123456789012345678901234567890",
  5061. "text/plain");
  5062. })
  5063. .Get("/compress-with-charset",
  5064. [&](const Request & /*req*/, Response &res) {
  5065. res.set_content(
  5066. "12345678901234567890123456789012345678901234567890123456789"
  5067. "01234567890123456789012345678901234567890",
  5068. "application/json; charset=utf-8");
  5069. })
  5070. .Get("/nocompress",
  5071. [&](const Request & /*req*/, Response &res) {
  5072. res.set_content(
  5073. "12345678901234567890123456789012345678901234567890123456789"
  5074. "01234567890123456789012345678901234567890",
  5075. "application/octet-stream");
  5076. })
  5077. .Post("/compress-multipart",
  5078. [&](const Request &req, Response & /*res*/) {
  5079. EXPECT_EQ(2u, req.form.fields.size());
  5080. ASSERT_TRUE(!req.form.has_field("???"));
  5081. {
  5082. const auto &text = req.form.get_field("key1");
  5083. EXPECT_EQ("test", text);
  5084. }
  5085. {
  5086. const auto &text = req.form.get_field("key2");
  5087. EXPECT_EQ("--abcdefg123", text);
  5088. }
  5089. })
  5090. #endif
  5091. ;
  5092. persons_["john"] = "programmer";
  5093. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5094. svr_.wait_until_ready();
  5095. }
  5096. virtual void TearDown() {
  5097. svr_.stop();
  5098. if (!request_threads_.empty()) {
  5099. std::this_thread::sleep_for(std::chrono::seconds(1));
  5100. for (auto &t : request_threads_) {
  5101. t.join();
  5102. }
  5103. }
  5104. t_.join();
  5105. }
  5106. map<string, string> persons_;
  5107. #ifdef CPPHTTPLIB_SSL_ENABLED
  5108. SSLClient cli_;
  5109. SSLServer svr_;
  5110. #else
  5111. Client cli_;
  5112. Server svr_;
  5113. #endif
  5114. thread t_;
  5115. std::vector<thread> request_threads_;
  5116. };
  5117. TEST_F(ServerTest, GetMethod200) {
  5118. auto res = cli_.Get("/hi");
  5119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5120. EXPECT_EQ("HTTP/1.1", res->version);
  5121. EXPECT_EQ(StatusCode::OK_200, res->status);
  5122. EXPECT_EQ("OK", res->reason);
  5123. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5124. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5125. EXPECT_EQ("Hello World!", res->body);
  5126. }
  5127. TEST_F(ServerTest, GetEmptyFile) {
  5128. auto res = cli_.Get("/empty_file");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5132. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5133. EXPECT_EQ("", res->body);
  5134. }
  5135. TEST_F(ServerTest, GetFileContent) {
  5136. auto res = cli_.Get("/file_content");
  5137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5140. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5141. EXPECT_EQ("test.html", res->body);
  5142. }
  5143. TEST_F(ServerTest, GetFileContentWithRange) {
  5144. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5147. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5148. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5149. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5150. EXPECT_EQ("est", res->body);
  5151. }
  5152. TEST_F(ServerTest, GetFileContentWithContentType) {
  5153. auto res = cli_.Get("/file_content_with_content_type");
  5154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5158. EXPECT_EQ("file\n", res->body);
  5159. }
  5160. TEST_F(ServerTest, GetInvalidFileContent) {
  5161. auto res = cli_.Get("/invalid_file_content");
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5164. }
  5165. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5166. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5168. EXPECT_EQ("HTTP/1.1", res->version);
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5171. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5172. EXPECT_EQ("Hello World!", res->body);
  5173. }
  5174. TEST_F(ServerTest, GetMethod302) {
  5175. auto res = cli_.Get("/");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::Found_302, res->status);
  5178. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5179. }
  5180. TEST_F(ServerTest, GetMethod302Redirect) {
  5181. cli_.set_follow_location(true);
  5182. auto res = cli_.Get("/");
  5183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. EXPECT_EQ("Hello World!", res->body);
  5186. EXPECT_EQ("/hi", res->location);
  5187. }
  5188. TEST_F(ServerTest, GetMethod404) {
  5189. auto res = cli_.Get("/invalid");
  5190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5191. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5192. }
  5193. TEST_F(ServerTest, HeadMethod200) {
  5194. auto res = cli_.Head("/hi");
  5195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5196. EXPECT_EQ(StatusCode::OK_200, res->status);
  5197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5198. EXPECT_TRUE(res->body.empty());
  5199. }
  5200. TEST_F(ServerTest, HeadMethod200Static) {
  5201. auto res = cli_.Head("/mount/dir/index.html");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5205. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5206. EXPECT_TRUE(res->body.empty());
  5207. }
  5208. TEST_F(ServerTest, HeadMethod404) {
  5209. auto res = cli_.Head("/invalid");
  5210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5212. EXPECT_TRUE(res->body.empty());
  5213. }
  5214. TEST_F(ServerTest, GetMethodPersonJohn) {
  5215. auto res = cli_.Get("/person/john");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5219. EXPECT_EQ("programmer", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostMethod1) {
  5222. auto res = cli_.Get("/person/john1");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5225. res = cli_.Post("/person", "name=john1&note=coder",
  5226. "application/x-www-form-urlencoded");
  5227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5228. ASSERT_EQ(StatusCode::OK_200, res->status);
  5229. res = cli_.Get("/person/john1");
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. ASSERT_EQ(StatusCode::OK_200, res->status);
  5232. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5233. ASSERT_EQ("coder", res->body);
  5234. }
  5235. TEST_F(ServerTest, PostMethod2) {
  5236. auto res = cli_.Get("/person/john2");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5239. Params params;
  5240. params.emplace("name", "john2");
  5241. params.emplace("note", "coder");
  5242. res = cli_.Post("/person", params);
  5243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5244. ASSERT_EQ(StatusCode::OK_200, res->status);
  5245. res = cli_.Get("/person/john2");
  5246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5247. ASSERT_EQ(StatusCode::OK_200, res->status);
  5248. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5249. ASSERT_EQ("coder", res->body);
  5250. }
  5251. TEST_F(ServerTest, PutMethod3) {
  5252. auto res = cli_.Get("/person/john3");
  5253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5254. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5255. Params params;
  5256. params.emplace("name", "john3");
  5257. params.emplace("note", "coder");
  5258. res = cli_.Put("/person", params);
  5259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5260. ASSERT_EQ(StatusCode::OK_200, res->status);
  5261. res = cli_.Get("/person/john3");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5265. ASSERT_EQ("coder", res->body);
  5266. }
  5267. TEST_F(ServerTest, DeleteMethod1) {
  5268. auto res = cli_.Get("/person/john4");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5271. Params params;
  5272. params.emplace("name", "john4");
  5273. params.emplace("note", "coder");
  5274. res = cli_.Post("/person", params);
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. ASSERT_EQ(StatusCode::OK_200, res->status);
  5277. res = cli_.Get("/person/john4");
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. ASSERT_EQ(StatusCode::OK_200, res->status);
  5280. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5281. ASSERT_EQ("coder", res->body);
  5282. Params delete_params;
  5283. delete_params.emplace("name", "john4");
  5284. res = cli_.Delete("/person", delete_params);
  5285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5286. ASSERT_EQ(StatusCode::OK_200, res->status);
  5287. ASSERT_EQ("DELETED", res->body);
  5288. res = cli_.Get("/person/john4");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5291. }
  5292. TEST_F(ServerTest, DeleteMethod2) {
  5293. auto res = cli_.Get("/person/john5");
  5294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5295. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5296. Params params;
  5297. params.emplace("name", "john5");
  5298. params.emplace("note", "developer");
  5299. res = cli_.Post("/person", params);
  5300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5301. ASSERT_EQ(StatusCode::OK_200, res->status);
  5302. res = cli_.Get("/person/john5");
  5303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5304. ASSERT_EQ(StatusCode::OK_200, res->status);
  5305. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5306. ASSERT_EQ("developer", res->body);
  5307. Params delete_params;
  5308. delete_params.emplace("name", "john5");
  5309. Headers headers;
  5310. headers.emplace("Custom-Header", "test-value");
  5311. res = cli_.Delete("/person", headers, delete_params);
  5312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5313. ASSERT_EQ(StatusCode::OK_200, res->status);
  5314. ASSERT_EQ("DELETED", res->body);
  5315. res = cli_.Get("/person/john5");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5318. }
  5319. TEST_F(ServerTest, DeleteMethod3) {
  5320. auto res = cli_.Get("/person/john6");
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5323. Params params;
  5324. params.emplace("name", "john6");
  5325. params.emplace("note", "tester");
  5326. res = cli_.Post("/person", params);
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. ASSERT_EQ(StatusCode::OK_200, res->status);
  5329. res = cli_.Get("/person/john6");
  5330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5331. ASSERT_EQ(StatusCode::OK_200, res->status);
  5332. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. ASSERT_EQ("tester", res->body);
  5334. Params delete_params;
  5335. delete_params.emplace("name", "john6");
  5336. Headers headers;
  5337. headers.emplace("Custom-Header", "test-value");
  5338. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5340. ASSERT_EQ(StatusCode::OK_200, res->status);
  5341. ASSERT_EQ("DELETED", res->body);
  5342. res = cli_.Get("/person/john6");
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5345. }
  5346. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5347. Params params;
  5348. params.emplace("json", JSON_DATA);
  5349. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5351. ASSERT_EQ(StatusCode::OK_200, res->status);
  5352. ASSERT_EQ(JSON_DATA, res->body);
  5353. }
  5354. TEST_F(ServerTest, PostEmptyContent) {
  5355. auto res = cli_.Post("/empty", "", "text/plain");
  5356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5357. ASSERT_EQ(StatusCode::OK_200, res->status);
  5358. ASSERT_EQ("empty", res->body);
  5359. }
  5360. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5361. auto res = cli_.Post("/empty-no-content-type");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. ASSERT_EQ("empty-no-content-type", res->body);
  5365. }
  5366. TEST_F(ServerTest, PostPathOnly) {
  5367. auto res = cli_.Post("/path-only");
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. ASSERT_EQ(StatusCode::OK_200, res->status);
  5370. ASSERT_EQ("path-only", res->body);
  5371. }
  5372. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5373. auto res = cli_.Post("/path-headers-only",
  5374. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. ASSERT_EQ(StatusCode::OK_200, res->status);
  5377. ASSERT_EQ("path-headers-only", res->body);
  5378. }
  5379. TEST_F(ServerTest, PostLarge) {
  5380. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5382. ASSERT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ(LARGE_DATA, res->body);
  5384. }
  5385. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5386. auto res = cli_.Put("/empty-no-content-type");
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. ASSERT_EQ(StatusCode::OK_200, res->status);
  5389. ASSERT_EQ("empty-no-content-type", res->body);
  5390. }
  5391. TEST_F(ServerTest, GetMethodDir) {
  5392. auto res = cli_.Get("/dir/");
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5396. auto body = R"(<html>
  5397. <head>
  5398. </head>
  5399. <body>
  5400. <a href="/dir/test.html">Test</a>
  5401. <a href="/hi">hi</a>
  5402. </body>
  5403. </html>
  5404. )";
  5405. EXPECT_EQ(body, res->body);
  5406. }
  5407. TEST_F(ServerTest, GetMethodDirTest) {
  5408. auto res = cli_.Get("/dir/test.html");
  5409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5410. EXPECT_EQ(StatusCode::OK_200, res->status);
  5411. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5412. EXPECT_EQ("test.html", res->body);
  5413. }
  5414. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5415. auto res = cli_.Get("/dir/../dir/test.html");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. EXPECT_EQ(StatusCode::OK_200, res->status);
  5418. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5419. EXPECT_EQ("test.html", res->body);
  5420. }
  5421. TEST_F(ServerTest, GetMethodInvalidPath) {
  5422. auto res = cli_.Get("/dir/../test.html");
  5423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5425. }
  5426. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5427. auto res = cli_.Get("/../www/dir/test.html");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5430. }
  5431. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5432. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5435. }
  5436. TEST_F(ServerTest, GetMethodDirMountTest) {
  5437. auto res = cli_.Get("/mount/dir/test.html");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::OK_200, res->status);
  5440. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5441. EXPECT_EQ("test.html", res->body);
  5442. }
  5443. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5444. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5448. EXPECT_EQ("test.html", res->body);
  5449. }
  5450. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5451. auto res = cli_.Get("/mount/dir/../test.html");
  5452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5454. }
  5455. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5456. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5459. }
  5460. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5461. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5464. }
  5465. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5466. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5469. }
  5470. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5471. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5474. }
  5475. TEST_F(ServerTest, PostMethod303) {
  5476. auto res = cli_.Post("/1", "body", "text/plain");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5479. EXPECT_EQ("/2", res->get_header_value("Location"));
  5480. }
  5481. TEST_F(ServerTest, PostMethod303Redirect) {
  5482. cli_.set_follow_location(true);
  5483. auto res = cli_.Post("/1", "body", "text/plain");
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("redirected.", res->body);
  5487. EXPECT_EQ("/2", res->location);
  5488. }
  5489. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5490. auto res = cli_.Get("/dir/test.abcde");
  5491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5494. EXPECT_EQ("abcde", res->body);
  5495. }
  5496. TEST_F(ServerTest, StaticFileRange) {
  5497. auto res =
  5498. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5500. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5501. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5503. EXPECT_EQ(true, res->has_header("Content-Range"));
  5504. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5505. EXPECT_EQ(std::string("cd"), res->body);
  5506. }
  5507. TEST_F(ServerTest, StaticFileRanges) {
  5508. auto res = cli_.Get("/dir/test.abcde",
  5509. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5512. EXPECT_TRUE(
  5513. res->get_header_value("Content-Type")
  5514. .find(
  5515. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5516. 0);
  5517. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5518. }
  5519. TEST_F(ServerTest, StaticFileRangeHead) {
  5520. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5522. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5523. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5524. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5525. EXPECT_EQ(true, res->has_header("Content-Range"));
  5526. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5527. }
  5528. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5529. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5532. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5533. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5534. EXPECT_EQ(true, res->has_header("Content-Range"));
  5535. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5536. res->get_header_value("Content-Range"));
  5537. EXPECT_EQ("LAST\n", res->body);
  5538. }
  5539. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5540. auto res =
  5541. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5543. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5544. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5545. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5546. EXPECT_EQ(true, res->has_header("Content-Range"));
  5547. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5548. }
  5549. TEST_F(ServerTest, StaticFileBigFile) {
  5550. auto res = cli_.Get("/dir/1MB.txt");
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. EXPECT_EQ(StatusCode::OK_200, res->status);
  5553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5554. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5555. }
  5556. TEST_F(ServerTest, InvalidBaseDirMount) {
  5557. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5558. }
  5559. TEST_F(ServerTest, Binary) {
  5560. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5561. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5562. "application/octet-stream");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. ASSERT_EQ(StatusCode::OK_200, res->status);
  5565. ASSERT_EQ(4U, res->body.size());
  5566. res = cli_.Put("/binary", binary.data(), binary.size(),
  5567. "application/octet-stream");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. ASSERT_EQ(StatusCode::OK_200, res->status);
  5570. ASSERT_EQ(4U, res->body.size());
  5571. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5572. "application/octet-stream");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. ASSERT_EQ(StatusCode::OK_200, res->status);
  5575. ASSERT_EQ(4U, res->body.size());
  5576. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5577. "application/octet-stream");
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. ASSERT_EQ(4U, res->body.size());
  5581. }
  5582. TEST_F(ServerTest, BinaryString) {
  5583. auto binary = std::string("\x00\x01\x02\x03", 4);
  5584. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. ASSERT_EQ(StatusCode::OK_200, res->status);
  5587. ASSERT_EQ(4U, res->body.size());
  5588. res = cli_.Put("/binary", binary, "application/octet-stream");
  5589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5590. ASSERT_EQ(StatusCode::OK_200, res->status);
  5591. ASSERT_EQ(4U, res->body.size());
  5592. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. ASSERT_EQ(StatusCode::OK_200, res->status);
  5595. ASSERT_EQ(4U, res->body.size());
  5596. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. ASSERT_EQ(StatusCode::OK_200, res->status);
  5599. ASSERT_EQ(4U, res->body.size());
  5600. }
  5601. TEST_F(ServerTest, EmptyRequest) {
  5602. auto res = cli_.Get("");
  5603. ASSERT_TRUE(!res);
  5604. EXPECT_EQ(Error::Connection, res.error());
  5605. }
  5606. TEST_F(ServerTest, LongRequest) {
  5607. std::string request;
  5608. for (size_t i = 0; i < 545; i++) {
  5609. request += "/TooLongRequest";
  5610. }
  5611. request += "OK";
  5612. auto res = cli_.Get(request.c_str());
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5615. }
  5616. TEST_F(ServerTest, TooLongRequest) {
  5617. std::string request;
  5618. for (size_t i = 0; i < 546; i++) {
  5619. request += "/TooLongRequest";
  5620. }
  5621. request += "_NG";
  5622. auto start = std::chrono::high_resolution_clock::now();
  5623. cli_.set_keep_alive(true);
  5624. auto res = cli_.Get(request.c_str());
  5625. auto end = std::chrono::high_resolution_clock::now();
  5626. auto elapsed =
  5627. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5628. .count();
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5631. EXPECT_LE(elapsed, 1000);
  5632. EXPECT_EQ("close", res->get_header_value("Connection"));
  5633. EXPECT_FALSE(cli_.is_socket_open());
  5634. }
  5635. TEST_F(ServerTest, AlmostTooLongRequest) {
  5636. // test for #2046 - URI length check shouldn't include other content on req
  5637. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5638. // leading /, space, HTTP/1.1)
  5639. std::string request =
  5640. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5641. auto res = cli_.Get(request.c_str());
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5644. }
  5645. TEST_F(ServerTest, LongHeader) {
  5646. Request req;
  5647. req.method = "GET";
  5648. req.path = "/hi";
  5649. std::string host_and_port;
  5650. host_and_port += HOST;
  5651. host_and_port += ":";
  5652. host_and_port += std::to_string(PORT);
  5653. req.headers.emplace("Host", host_and_port.c_str());
  5654. req.headers.emplace("Accept", "*/*");
  5655. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5656. req.headers.emplace(
  5657. "Header-Name",
  5658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5686. "@@@@@@@@@@@@@@@@");
  5687. auto res = std::make_shared<Response>();
  5688. auto error = Error::Success;
  5689. auto ret = cli_.send(req, *res, error);
  5690. ASSERT_TRUE(ret);
  5691. EXPECT_EQ(StatusCode::OK_200, res->status);
  5692. }
  5693. TEST_F(ServerTest, LongQueryValue) {
  5694. auto start = std::chrono::high_resolution_clock::now();
  5695. cli_.set_keep_alive(true);
  5696. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5697. auto end = std::chrono::high_resolution_clock::now();
  5698. auto elapsed =
  5699. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5700. .count();
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5703. EXPECT_LE(elapsed, 1000);
  5704. EXPECT_EQ("close", res->get_header_value("Connection"));
  5705. EXPECT_FALSE(cli_.is_socket_open());
  5706. }
  5707. TEST_F(ServerTest, TooLongQueryValue) {
  5708. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5709. ASSERT_FALSE(res);
  5710. EXPECT_EQ(Error::Read, res.error());
  5711. }
  5712. TEST_F(ServerTest, TooLongHeader) {
  5713. Request req;
  5714. req.method = "GET";
  5715. req.path = "/hi";
  5716. std::string host_and_port;
  5717. host_and_port += HOST;
  5718. host_and_port += ":";
  5719. host_and_port += std::to_string(PORT);
  5720. req.headers.emplace("Host", host_and_port.c_str());
  5721. req.headers.emplace("Accept", "*/*");
  5722. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5723. req.headers.emplace(
  5724. "Header-Name",
  5725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5753. "@@@@@@@@@@@@@@@@@");
  5754. auto res = std::make_shared<Response>();
  5755. auto error = Error::Success;
  5756. auto ret = cli_.send(req, *res, error);
  5757. ASSERT_TRUE(ret);
  5758. EXPECT_EQ(StatusCode::OK_200, res->status);
  5759. }
  5760. TEST_F(ServerTest, HeaderCountAtLimit) {
  5761. // Test with headers just under the 100 limit
  5762. httplib::Headers headers;
  5763. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5764. // This should keep us just under the 100 header limit
  5765. for (int i = 0; i < 95; i++) {
  5766. std::string name = "X-Test-Header-" + std::to_string(i);
  5767. std::string value = "value" + std::to_string(i);
  5768. headers.emplace(name, value);
  5769. }
  5770. // This should work fine as we're under the limit
  5771. auto res = cli_.Get("/hi", headers);
  5772. EXPECT_TRUE(res);
  5773. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5774. }
  5775. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5776. // Test with many headers to exceed the 100 limit
  5777. httplib::Headers headers;
  5778. // Add 150 headers to definitely exceed the 100 limit
  5779. for (int i = 0; i < 150; i++) {
  5780. std::string name = "X-Test-Header-" + std::to_string(i);
  5781. std::string value = "value" + std::to_string(i);
  5782. headers.emplace(name, value);
  5783. }
  5784. // This should fail due to exceeding header count limit
  5785. cli_.set_keep_alive(true);
  5786. auto res = cli_.Get("/hi", headers);
  5787. // The server should respond with 400 Bad Request
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5790. EXPECT_EQ("close", res->get_header_value("Connection"));
  5791. EXPECT_FALSE(cli_.is_socket_open());
  5792. }
  5793. TEST_F(ServerTest, PercentEncoding) {
  5794. auto res = cli_.Get("/e%6edwith%");
  5795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. TEST_F(ServerTest, PercentEncodingUnicode) {
  5799. auto res = cli_.Get("/e%u006edwith%");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. }
  5803. TEST_F(ServerTest, InvalidPercentEncoding) {
  5804. auto res = cli_.Get("/%endwith%");
  5805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5806. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5807. }
  5808. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5809. auto res = cli_.Get("/%uendwith%");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5812. }
  5813. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5814. auto res = cli_.Get("/hello?aaa=bbb%");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5817. }
  5818. TEST_F(ServerTest, PlusSignEncoding) {
  5819. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ("a +b", res->body);
  5823. }
  5824. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5825. // This test simulates a potential DoS attack using many headers
  5826. // to verify our security fix prevents memory exhaustion
  5827. httplib::Headers attack_headers;
  5828. // Attempt to add many headers like an attacker would (200 headers to far
  5829. // exceed limit)
  5830. for (int i = 0; i < 200; i++) {
  5831. std::string name = "X-Attack-Header-" + std::to_string(i);
  5832. std::string value = "attack_payload_" + std::to_string(i);
  5833. attack_headers.emplace(name, value);
  5834. }
  5835. // Try to POST with excessive headers
  5836. cli_.set_keep_alive(true);
  5837. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5838. // Should either fail or return 400 Bad Request due to security limit
  5839. if (res) {
  5840. // If we get a response, it should be 400 Bad Request
  5841. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5842. EXPECT_EQ("close", res->get_header_value("Connection"));
  5843. }
  5844. EXPECT_FALSE(cli_.is_socket_open());
  5845. }
  5846. TEST_F(ServerTest, MultipartFormData) {
  5847. UploadFormDataItems items = {
  5848. {"text1", "text default", "", ""},
  5849. {"text2", "aωb", "", ""},
  5850. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5851. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5852. {"file3", "", "", "application/octet-stream"},
  5853. {"file4", "", "", " application/json tmp-string "}};
  5854. auto res = cli_.Post("/multipart", items);
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. }
  5858. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5859. UploadFormDataItems items = {
  5860. {"text", "default text", "", ""},
  5861. {"multi_text1", "aaaaa", "", ""},
  5862. {"multi_text1", "bbbbb", "", ""},
  5863. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5864. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5865. "application/json"},
  5866. };
  5867. auto res = cli_.Post("/multipart/multi_file_values", items);
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. EXPECT_EQ(StatusCode::OK_200, res->status);
  5870. }
  5871. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5872. auto res = cli_.Get("/hi");
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::OK_200, res->status);
  5875. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5876. EXPECT_EQ("Hello World!", res->body);
  5877. }
  5878. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5879. Request req;
  5880. req.method = "POST";
  5881. req.path = "/chunked";
  5882. std::string host_and_port;
  5883. host_and_port += HOST;
  5884. host_and_port += ":";
  5885. host_and_port += std::to_string(PORT);
  5886. req.headers.emplace("Host", host_and_port.c_str());
  5887. req.headers.emplace("Accept", "*/*");
  5888. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5889. req.headers.emplace("Content-Type", "text/plain");
  5890. req.headers.emplace("Content-Length", "0");
  5891. req.headers.emplace(
  5892. "Transfer-Encoding",
  5893. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5894. // Client does not chunk, so make a chunked body manually.
  5895. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5896. auto res = std::make_shared<Response>();
  5897. auto error = Error::Success;
  5898. auto ret = cli_.send(req, *res, error);
  5899. ASSERT_TRUE(ret);
  5900. EXPECT_EQ(StatusCode::OK_200, res->status);
  5901. }
  5902. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5903. // rather than treat them as valid lengths.
  5904. template <typename ClientT>
  5905. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5906. Request req;
  5907. req.method = "POST";
  5908. req.path = "/chunked";
  5909. std::string host_and_port;
  5910. host_and_port += HOST;
  5911. host_and_port += ":";
  5912. host_and_port += std::to_string(PORT);
  5913. req.headers.emplace("Host", host_and_port.c_str());
  5914. req.headers.emplace("Content-Length", "0");
  5915. req.headers.emplace("Transfer-Encoding", "chunked");
  5916. req.body = body;
  5917. auto res = std::make_shared<Response>();
  5918. auto error = Error::Success;
  5919. ASSERT_TRUE(cli.send(req, *res, error));
  5920. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5921. }
  5922. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5923. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5924. }
  5925. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5926. expect_chunked_body_rejected(
  5927. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5928. }
  5929. TEST_F(ServerTest, GetStreamed2) {
  5930. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5932. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5933. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5934. EXPECT_EQ(true, res->has_header("Content-Range"));
  5935. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5936. EXPECT_EQ(std::string("ab"), res->body);
  5937. }
  5938. TEST_F(ServerTest, GetStreamed) {
  5939. auto res = cli_.Get("/streamed");
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5943. EXPECT_EQ(std::string("aaabbb"), res->body);
  5944. }
  5945. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5946. auto res = cli_.Get("/streamed-without-length",
  5947. Headers{make_range_header({{0, -1}})});
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. EXPECT_EQ(StatusCode::OK_200, res->status);
  5950. EXPECT_EQ(false, res->has_header("Content-Length"));
  5951. EXPECT_EQ(false, res->has_header("Content-Range"));
  5952. EXPECT_EQ(std::string("abcdefg"), res->body);
  5953. }
  5954. TEST_F(ServerTest, GetStreamedWithRange1) {
  5955. auto res =
  5956. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5958. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5959. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5960. EXPECT_EQ(true, res->has_header("Content-Range"));
  5961. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5962. EXPECT_EQ(std::string("def"), res->body);
  5963. }
  5964. TEST_F(ServerTest, GetStreamedWithRange2) {
  5965. auto res =
  5966. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5969. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5970. EXPECT_EQ(true, res->has_header("Content-Range"));
  5971. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5972. EXPECT_EQ(std::string("bcdefg"), res->body);
  5973. }
  5974. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5975. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5978. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5979. EXPECT_EQ(true, res->has_header("Content-Range"));
  5980. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5981. EXPECT_EQ(std::string("efg"), res->body);
  5982. }
  5983. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5984. auto res =
  5985. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5987. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5988. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5989. EXPECT_EQ(false, res->has_header("Content-Range"));
  5990. EXPECT_EQ(0U, res->body.size());
  5991. }
  5992. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5993. // Only a 206 is served as a partial representation. Under any other status
  5994. // `apply_ranges()` reported the full content length, so the body must match
  5995. // that header, and the content provider must never be asked for an offset
  5996. // outside the representation.
  5997. auto check = [&](int status, const char *range) {
  5998. auto path =
  5999. std::string("/streamed-with-range?status=") + std::to_string(status);
  6000. auto ctx = path + " Range: " + range;
  6001. auto res = cli_.Get(path, Headers{{"Range", range}});
  6002. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6003. EXPECT_EQ(status, res->status) << ctx;
  6004. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6006. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6007. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6008. };
  6009. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6010. check(403, "bytes=3-5");
  6011. // The offset is far past the representation.
  6012. check(403, "bytes=100000-100200");
  6013. // `first_pos` is still -1 here, and the bounds asserts in
  6014. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6015. check(403, "bytes=-3");
  6016. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6017. // multipart branch would have written one that is empty.
  6018. check(403, "bytes=1-2, 4-5");
  6019. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6020. // covers the whole representation.
  6021. check(200, "bytes=3-5");
  6022. check(200, "bytes=1-2, 4-5");
  6023. }
  6024. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6025. auto res =
  6026. cli_.Get("/streamed-with-range",
  6027. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6028. "92233720368547758079223372036854775807"}});
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6031. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6032. EXPECT_EQ(false, res->has_header("Content-Range"));
  6033. EXPECT_EQ(0U, res->body.size());
  6034. }
  6035. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6036. auto res = cli_.Get(
  6037. "/with-range",
  6038. Headers{{"Range",
  6039. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6040. {"Accept-Encoding", ""}});
  6041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6042. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6043. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6044. EXPECT_EQ(true, res->has_header("Content-Range"));
  6045. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6046. EXPECT_EQ(std::string("abcdefg"), res->body);
  6047. }
  6048. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6049. auto res = cli_.Get("/with-range", Headers{
  6050. {"Range", "bytes=0-"},
  6051. {"Accept-Encoding", ""},
  6052. });
  6053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6055. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6056. EXPECT_EQ(true, res->has_header("Content-Range"));
  6057. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6058. EXPECT_EQ(std::string("abcdefg"), res->body);
  6059. }
  6060. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6061. auto res = cli_.Get("/streamed-with-range",
  6062. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6065. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6066. EXPECT_EQ(false, res->has_header("Content-Range"));
  6067. EXPECT_EQ(267U, res->body.size());
  6068. // Check that both range contents are present
  6069. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6070. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6071. // Check that Content-Range headers are present for both ranges
  6072. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6073. std::string::npos);
  6074. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6075. std::string::npos);
  6076. }
  6077. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6078. Ranges ranges;
  6079. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6080. ranges.emplace_back(0, -1);
  6081. }
  6082. auto res = cli_.Get("/streamed-with-range?error",
  6083. Headers{{make_range_header(ranges)}});
  6084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6085. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6086. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6087. EXPECT_EQ(false, res->has_header("Content-Range"));
  6088. EXPECT_EQ(0U, res->body.size());
  6089. }
  6090. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6091. auto res = cli_.Get("/streamed-with-range",
  6092. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6095. EXPECT_EQ(5U, res->body.size());
  6096. // Check that overlapping ranges are coalesced into a single range
  6097. EXPECT_EQ("bcdef", res->body);
  6098. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6099. // Should be single range, not multipart
  6100. EXPECT_TRUE(res->has_header("Content-Range"));
  6101. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6102. }
  6103. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6104. auto res = cli_.Get("/streamed-with-range",
  6105. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6107. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6108. EXPECT_EQ(268U, res->body.size());
  6109. // Check that both range contents are present
  6110. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6111. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6112. // Check that Content-Range headers are present for both ranges
  6113. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6114. std::string::npos);
  6115. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6116. std::string::npos);
  6117. }
  6118. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6119. auto res = cli_.Get("/streamed-with-range",
  6120. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6123. EXPECT_EQ(269U, res->body.size());
  6124. // Check that both duplicate range contents are present
  6125. size_t first_abc = res->body.find("abc\r\n");
  6126. EXPECT_TRUE(first_abc != std::string::npos);
  6127. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6128. EXPECT_TRUE(second_abc != std::string::npos);
  6129. // Check that Content-Range headers are present for both ranges
  6130. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6131. EXPECT_TRUE(first_range != std::string::npos);
  6132. size_t second_range =
  6133. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6134. EXPECT_TRUE(second_range != std::string::npos);
  6135. }
  6136. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6137. auto res =
  6138. cli_.Get("/streamed-with-range?error",
  6139. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6142. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6143. EXPECT_EQ(false, res->has_header("Content-Range"));
  6144. EXPECT_EQ(0U, res->body.size());
  6145. }
  6146. TEST_F(ServerTest, GetStreamedEndless) {
  6147. uint64_t offset = 0;
  6148. auto res = cli_.Get("/streamed-cancel",
  6149. [&](const char * /*data*/, uint64_t data_length) {
  6150. if (offset < 100) {
  6151. offset += data_length;
  6152. return true;
  6153. }
  6154. return false;
  6155. });
  6156. ASSERT_TRUE(!res);
  6157. EXPECT_EQ(Error::Canceled, res.error());
  6158. }
  6159. TEST_F(ServerTest, ClientStop) {
  6160. std::atomic_size_t count{4};
  6161. std::vector<std::thread> threads;
  6162. for (auto i = count.load(); i != 0; --i) {
  6163. threads.emplace_back([&]() {
  6164. auto res = cli_.Get("/streamed-cancel",
  6165. [&](const char *, uint64_t) { return true; });
  6166. --count;
  6167. ASSERT_TRUE(!res);
  6168. EXPECT_TRUE(res.error() == Error::Canceled ||
  6169. res.error() == Error::Read || res.error() == Error::Write);
  6170. });
  6171. }
  6172. std::this_thread::sleep_for(std::chrono::seconds(2));
  6173. while (count != 0) {
  6174. cli_.stop();
  6175. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6176. }
  6177. for (auto &t : threads) {
  6178. t.join();
  6179. }
  6180. }
  6181. TEST_F(ServerTest, GetWithRange1) {
  6182. auto res = cli_.Get("/with-range", Headers{
  6183. make_range_header({{3, 5}}),
  6184. {"Accept-Encoding", ""},
  6185. });
  6186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6187. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6188. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6189. EXPECT_EQ(true, res->has_header("Content-Range"));
  6190. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6191. EXPECT_EQ(std::string("def"), res->body);
  6192. }
  6193. TEST_F(ServerTest, GetWithRange2) {
  6194. auto res = cli_.Get("/with-range", Headers{
  6195. make_range_header({{1, -1}}),
  6196. {"Accept-Encoding", ""},
  6197. });
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6200. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6201. EXPECT_EQ(true, res->has_header("Content-Range"));
  6202. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6203. EXPECT_EQ(std::string("bcdefg"), res->body);
  6204. }
  6205. TEST_F(ServerTest, GetWithRange3) {
  6206. auto res = cli_.Get("/with-range", Headers{
  6207. make_range_header({{0, 0}}),
  6208. {"Accept-Encoding", ""},
  6209. });
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6212. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6213. EXPECT_EQ(true, res->has_header("Content-Range"));
  6214. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6215. EXPECT_EQ(std::string("a"), res->body);
  6216. }
  6217. TEST_F(ServerTest, GetWithRange4) {
  6218. auto res = cli_.Get("/with-range", Headers{
  6219. make_range_header({{-1, 2}}),
  6220. {"Accept-Encoding", ""},
  6221. });
  6222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6223. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6224. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6225. EXPECT_EQ(true, res->has_header("Content-Range"));
  6226. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6227. EXPECT_EQ(std::string("fg"), res->body);
  6228. }
  6229. TEST_F(ServerTest, GetWithRange5) {
  6230. auto res = cli_.Get("/with-range", Headers{
  6231. make_range_header({{0, 5}}),
  6232. {"Accept-Encoding", ""},
  6233. });
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6236. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6237. EXPECT_EQ(true, res->has_header("Content-Range"));
  6238. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6239. EXPECT_EQ(std::string("abcdef"), res->body);
  6240. }
  6241. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6242. auto res =
  6243. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6245. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6246. }
  6247. TEST_F(ServerTest, GetWithRangeMultipart) {
  6248. auto res =
  6249. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6251. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6252. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6253. EXPECT_EQ(false, res->has_header("Content-Range"));
  6254. EXPECT_EQ(267U, res->body.size());
  6255. }
  6256. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6257. auto res = cli_.Get("/with-range",
  6258. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6261. }
  6262. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6263. auto res = cli_.Get("/with-range-customized-response",
  6264. Headers{{make_range_header({{1, 2}})}});
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6267. EXPECT_EQ(true, res->has_header("Content-Length"));
  6268. EXPECT_EQ(false, res->has_header("Content-Range"));
  6269. EXPECT_EQ(JSON_DATA, res->body);
  6270. }
  6271. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6272. auto res = cli_.Get("/with-range-customized-response",
  6273. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6276. EXPECT_EQ(true, res->has_header("Content-Length"));
  6277. EXPECT_EQ(false, res->has_header("Content-Range"));
  6278. EXPECT_EQ(JSON_DATA, res->body);
  6279. }
  6280. TEST_F(ServerTest, Issue1772) {
  6281. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6283. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6284. }
  6285. TEST_F(ServerTest, Issue609) {
  6286. auto res = cli_.Delete("/issue609");
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. EXPECT_EQ(StatusCode::OK_200, res->status);
  6289. EXPECT_EQ(std::string("ok"), res->body);
  6290. }
  6291. TEST_F(ServerTest, GetStreamedChunked) {
  6292. auto res = cli_.Get("/streamed-chunked");
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. EXPECT_EQ(StatusCode::OK_200, res->status);
  6295. EXPECT_EQ(std::string("123456789"), res->body);
  6296. }
  6297. TEST_F(ServerTest, GetStreamedChunked2) {
  6298. auto res = cli_.Get("/streamed-chunked2");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. EXPECT_EQ(StatusCode::OK_200, res->status);
  6301. EXPECT_EQ(std::string("123456789"), res->body);
  6302. }
  6303. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6304. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. EXPECT_EQ(std::string("123456789"), res->body);
  6308. EXPECT_TRUE(res->has_header("Trailer"));
  6309. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6310. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6311. // Trailers are now stored separately from headers (security fix)
  6312. EXPECT_EQ(2U, res->trailers.size());
  6313. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6314. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6315. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6316. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6317. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6318. // Verify trailers are NOT in headers (security verification)
  6319. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6320. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6321. }
  6322. TEST_F(ServerTest, LargeChunkedPost) {
  6323. Request req;
  6324. req.method = "POST";
  6325. req.path = "/large-chunked";
  6326. std::string host_and_port;
  6327. host_and_port += HOST;
  6328. host_and_port += ":";
  6329. host_and_port += std::to_string(PORT);
  6330. req.headers.emplace("Host", host_and_port.c_str());
  6331. req.headers.emplace("Accept", "*/*");
  6332. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6333. req.headers.emplace("Content-Type", "text/plain");
  6334. req.headers.emplace("Content-Length", "0");
  6335. req.headers.emplace("Transfer-Encoding", "chunked");
  6336. std::string long_string(30 * 1024u, 'a');
  6337. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6338. // Attempt to make a large enough post to exceed OS buffers, to test that
  6339. // the server handles short reads if the full chunk data isn't available.
  6340. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6341. auto res = std::make_shared<Response>();
  6342. auto error = Error::Success;
  6343. auto ret = cli_.send(req, *res, error);
  6344. ASSERT_TRUE(ret);
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. }
  6347. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6348. auto res = cli_.Get("/remote_addr");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6352. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6353. }
  6354. TEST_F(ServerTest, GetMethodLocalAddr) {
  6355. auto res = cli_.Get("/local_addr");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::OK_200, res->status);
  6358. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6359. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6360. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6361. }
  6362. TEST_F(ServerTest, HTTPResponseSplitting) {
  6363. auto res = cli_.Get("/http_response_splitting");
  6364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6365. EXPECT_EQ(StatusCode::OK_200, res->status);
  6366. }
  6367. TEST_F(ServerTest, SlowRequest) {
  6368. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6369. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6370. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6371. }
  6372. #if 0
  6373. TEST_F(ServerTest, SlowPost) {
  6374. char buffer[64 * 1024];
  6375. memset(buffer, 0x42, sizeof(buffer));
  6376. auto res = cli_.Post(
  6377. "/slowpost", 64 * 1024 * 1024,
  6378. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6379. auto ret = sink.write(buffer, sizeof(buffer));
  6380. EXPECT_TRUE(ret);
  6381. return true;
  6382. },
  6383. "text/plain");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::OK_200, res->status);
  6386. }
  6387. TEST_F(ServerTest, SlowPostFail) {
  6388. char buffer[64 * 1024];
  6389. memset(buffer, 0x42, sizeof(buffer));
  6390. cli_.set_write_timeout(std::chrono::seconds(0));
  6391. auto res = cli_.Post(
  6392. "/slowpost", 64 * 1024 * 1024,
  6393. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6394. sink.write(buffer, sizeof(buffer));
  6395. return true;
  6396. },
  6397. "text/plain");
  6398. ASSERT_TRUE(!res);
  6399. EXPECT_EQ(Error::Write, res.error());
  6400. }
  6401. #endif
  6402. TEST_F(ServerTest, Put) {
  6403. auto res = cli_.Put("/put", "PUT", "text/plain");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. EXPECT_EQ(StatusCode::OK_200, res->status);
  6406. EXPECT_EQ("PUT", res->body);
  6407. }
  6408. TEST_F(ServerTest, PutWithContentProvider) {
  6409. auto res = cli_.Put(
  6410. "/put", 3,
  6411. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6412. sink.os << "PUT";
  6413. return true;
  6414. },
  6415. "text/plain");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::OK_200, res->status);
  6418. EXPECT_EQ("PUT", res->body);
  6419. }
  6420. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6421. auto res = cli_.Post(
  6422. "/post", 42,
  6423. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6424. return false;
  6425. },
  6426. "text/plain");
  6427. ASSERT_TRUE(!res);
  6428. EXPECT_EQ(Error::Canceled, res.error());
  6429. }
  6430. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6431. auto res = cli_.Put(
  6432. "/put",
  6433. [](size_t /*offset*/, DataSink &sink) {
  6434. sink.os << "PUT";
  6435. sink.done();
  6436. return true;
  6437. },
  6438. "text/plain");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::OK_200, res->status);
  6441. EXPECT_EQ("PUT", res->body);
  6442. }
  6443. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6444. auto res = cli_.Post(
  6445. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6446. "text/plain");
  6447. ASSERT_TRUE(!res);
  6448. EXPECT_EQ(Error::Canceled, res.error());
  6449. }
  6450. TEST_F(ServerTest, PostLoopBack) {
  6451. std::string body;
  6452. auto res = cli_.Post(
  6453. "/post-loopback", 9,
  6454. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6455. EXPECT_EQ(9u, length);
  6456. sink.write("123", 3);
  6457. sink.write("456", 3);
  6458. sink.write("789", 3);
  6459. return true;
  6460. },
  6461. "text/plain",
  6462. [&body](const char *data, size_t data_length) {
  6463. body.append(data, data_length);
  6464. return true;
  6465. });
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::OK_200, res->status);
  6468. EXPECT_EQ("123456789", body);
  6469. }
  6470. TEST_F(ServerTest, PutLoopBack) {
  6471. std::string body;
  6472. auto res = cli_.Put(
  6473. "/put-loopback", 9,
  6474. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6475. EXPECT_EQ(9u, length);
  6476. sink.write("123", 3);
  6477. sink.write("456", 3);
  6478. sink.write("789", 3);
  6479. return true;
  6480. },
  6481. "text/plain",
  6482. [&body](const char *data, size_t data_length) {
  6483. body.append(data, data_length);
  6484. return true;
  6485. });
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. EXPECT_EQ(StatusCode::OK_200, res->status);
  6488. EXPECT_EQ("123456789", body);
  6489. }
  6490. TEST_F(ServerTest, PatchLoopBack) {
  6491. std::string body;
  6492. auto res = cli_.Patch(
  6493. "/patch-loopback", 9,
  6494. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6495. EXPECT_EQ(9u, length);
  6496. sink.write("123", 3);
  6497. sink.write("456", 3);
  6498. sink.write("789", 3);
  6499. return true;
  6500. },
  6501. "text/plain",
  6502. [&body](const char *data, size_t data_length) {
  6503. body.append(data, data_length);
  6504. return true;
  6505. });
  6506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6507. EXPECT_EQ(StatusCode::OK_200, res->status);
  6508. EXPECT_EQ("123456789", body);
  6509. }
  6510. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6511. std::string body;
  6512. auto res = cli_.Post(
  6513. "/post-loopback",
  6514. [](size_t /*offset*/, DataSink &sink) {
  6515. sink.write("123", 3);
  6516. sink.write("456", 3);
  6517. sink.write("789", 3);
  6518. sink.done();
  6519. return true;
  6520. },
  6521. "text/plain",
  6522. [&body](const char *data, size_t data_length) {
  6523. body.append(data, data_length);
  6524. return true;
  6525. });
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(StatusCode::OK_200, res->status);
  6528. EXPECT_EQ("123456789", body);
  6529. }
  6530. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6531. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6532. cli_.set_compress(true);
  6533. auto res = cli_.Put(
  6534. "/put", 3,
  6535. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6536. sink.os << "PUT";
  6537. return true;
  6538. },
  6539. "text/plain");
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. EXPECT_EQ("PUT", res->body);
  6543. }
  6544. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6545. cli_.set_compress(true);
  6546. auto res = cli_.Post(
  6547. "/post", 42,
  6548. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6549. return false;
  6550. },
  6551. "text/plain");
  6552. ASSERT_TRUE(!res);
  6553. EXPECT_EQ(Error::Canceled, res.error());
  6554. }
  6555. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6556. cli_.set_compress(true);
  6557. auto res = cli_.Put(
  6558. "/put",
  6559. [](size_t /*offset*/, DataSink &sink) {
  6560. sink.os << "PUT";
  6561. sink.done();
  6562. return true;
  6563. },
  6564. "text/plain");
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_EQ(StatusCode::OK_200, res->status);
  6567. EXPECT_EQ("PUT", res->body);
  6568. }
  6569. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6570. cli_.set_compress(true);
  6571. auto res = cli_.Post(
  6572. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6573. "text/plain");
  6574. ASSERT_TRUE(!res);
  6575. EXPECT_EQ(Error::Canceled, res.error());
  6576. }
  6577. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6578. cli_.set_compress(true);
  6579. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6581. EXPECT_EQ(StatusCode::OK_200, res->status);
  6582. EXPECT_EQ(LARGE_DATA, res->body);
  6583. }
  6584. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6585. #ifdef CPPHTTPLIB_SSL_ENABLED
  6586. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6587. Client cli(s.c_str());
  6588. cli.enable_server_certificate_verification(false);
  6589. #else
  6590. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6591. Client cli(s.c_str());
  6592. #endif
  6593. cli.set_compress(true);
  6594. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ(LARGE_DATA, res->body);
  6598. // The compressed size should be less than a 10th of the original. May vary
  6599. // depending on the zlib library.
  6600. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6601. static_cast<uint64_t>(10 * 1024 * 1024));
  6602. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6603. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6604. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6605. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6606. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6607. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6608. #endif
  6609. }
  6610. TEST_F(ServerTest, PutContentWithDeflate) {
  6611. cli_.set_compress(false);
  6612. Headers headers;
  6613. headers.emplace("Content-Encoding", "deflate");
  6614. // PUT in deflate format:
  6615. auto res = cli_.Put("/put", headers,
  6616. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. EXPECT_EQ("PUT", res->body);
  6620. }
  6621. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6622. Headers headers;
  6623. headers.emplace("Accept-Encoding", "gzip, deflate");
  6624. auto res = cli_.Get("/streamed-chunked", headers);
  6625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6626. EXPECT_EQ(StatusCode::OK_200, res->status);
  6627. EXPECT_EQ(std::string("123456789"), res->body);
  6628. }
  6629. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6630. Headers headers;
  6631. headers.emplace("Accept-Encoding", "gzip, deflate");
  6632. auto res = cli_.Get("/streamed-chunked2", headers);
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ(std::string("123456789"), res->body);
  6636. }
  6637. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6638. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6640. EXPECT_EQ(StatusCode::OK_200, res->status);
  6641. }
  6642. TEST(GzipDecompressor, ChunkedDecompression) {
  6643. std::string data;
  6644. for (size_t i = 0; i < 32 * 1024; ++i) {
  6645. data.push_back(static_cast<char>('a' + i % 26));
  6646. }
  6647. std::string compressed_data;
  6648. {
  6649. httplib::detail::gzip_compressor compressor;
  6650. bool result = compressor.compress(
  6651. data.data(), data.size(),
  6652. /*last=*/true,
  6653. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6654. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6655. compressed_data_size);
  6656. return true;
  6657. });
  6658. ASSERT_TRUE(result);
  6659. }
  6660. std::string decompressed_data;
  6661. {
  6662. httplib::detail::gzip_decompressor decompressor;
  6663. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6664. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6665. size_t chunk_size = 130;
  6666. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6667. chunk_begin += chunk_size) {
  6668. size_t current_chunk_size =
  6669. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6670. bool result = decompressor.decompress(
  6671. compressed_data.data() + chunk_begin, current_chunk_size,
  6672. [&](const char *decompressed_data_chunk,
  6673. size_t decompressed_data_chunk_size) {
  6674. decompressed_data.insert(decompressed_data.size(),
  6675. decompressed_data_chunk,
  6676. decompressed_data_chunk_size);
  6677. return true;
  6678. });
  6679. ASSERT_TRUE(result);
  6680. }
  6681. }
  6682. ASSERT_EQ(data, decompressed_data);
  6683. }
  6684. TEST(GzipDecompressor, DeflateDecompression) {
  6685. std::string original_text = "Raw deflate without gzip";
  6686. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6687. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6688. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6689. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6690. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6691. std::string decompressed_data;
  6692. {
  6693. httplib::detail::gzip_decompressor decompressor;
  6694. bool result = decompressor.decompress(
  6695. compressed_data.data(), compressed_data.size(),
  6696. [&](const char *decompressed_data_chunk,
  6697. size_t decompressed_data_chunk_size) {
  6698. decompressed_data.insert(decompressed_data.size(),
  6699. decompressed_data_chunk,
  6700. decompressed_data_chunk_size);
  6701. return true;
  6702. });
  6703. ASSERT_TRUE(result);
  6704. }
  6705. ASSERT_EQ(original_text, decompressed_data);
  6706. }
  6707. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6708. std::string original_text = "Raw deflate without gzip";
  6709. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6710. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6711. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6712. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6713. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6714. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6715. std::string decompressed_data;
  6716. {
  6717. httplib::detail::gzip_decompressor decompressor;
  6718. bool result = decompressor.decompress(
  6719. compressed_data.data(), compressed_data.size(),
  6720. [&](const char *decompressed_data_chunk,
  6721. size_t decompressed_data_chunk_size) {
  6722. decompressed_data.insert(decompressed_data.size(),
  6723. decompressed_data_chunk,
  6724. decompressed_data_chunk_size);
  6725. return true;
  6726. });
  6727. ASSERT_TRUE(result);
  6728. }
  6729. ASSERT_EQ(original_text, decompressed_data);
  6730. }
  6731. #endif
  6732. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6733. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6734. Headers headers;
  6735. headers.emplace("Accept-Encoding", "br");
  6736. auto res = cli_.Get("/streamed-chunked", headers);
  6737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6738. EXPECT_EQ(StatusCode::OK_200, res->status);
  6739. EXPECT_EQ(std::string("123456789"), res->body);
  6740. }
  6741. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6742. Headers headers;
  6743. headers.emplace("Accept-Encoding", "br");
  6744. auto res = cli_.Get("/streamed-chunked2", headers);
  6745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6746. EXPECT_EQ(StatusCode::OK_200, res->status);
  6747. EXPECT_EQ(std::string("123456789"), res->body);
  6748. }
  6749. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6750. cli_.set_compress(true);
  6751. auto res = cli_.Put(
  6752. "/put", 3,
  6753. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6754. sink.os << "PUT";
  6755. return true;
  6756. },
  6757. "text/plain");
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. EXPECT_EQ("PUT", res->body);
  6761. }
  6762. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6763. cli_.set_compress(true);
  6764. auto res = cli_.Put(
  6765. "/put",
  6766. [](size_t /*offset*/, DataSink &sink) {
  6767. sink.os << "PUT";
  6768. sink.done();
  6769. return true;
  6770. },
  6771. "text/plain");
  6772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6773. EXPECT_EQ(StatusCode::OK_200, res->status);
  6774. EXPECT_EQ("PUT", res->body);
  6775. }
  6776. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6777. cli_.set_compress(true);
  6778. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ(LARGE_DATA, res->body);
  6782. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6783. }
  6784. #endif
  6785. TEST_F(ServerTest, Patch) {
  6786. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6788. EXPECT_EQ(StatusCode::OK_200, res->status);
  6789. EXPECT_EQ("PATCH", res->body);
  6790. }
  6791. TEST_F(ServerTest, Delete) {
  6792. auto res = cli_.Delete("/delete");
  6793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6794. EXPECT_EQ(StatusCode::OK_200, res->status);
  6795. EXPECT_EQ("DELETE", res->body);
  6796. }
  6797. TEST_F(ServerTest, DeleteContentReceiver) {
  6798. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6800. EXPECT_EQ(StatusCode::OK_200, res->status);
  6801. EXPECT_EQ("content", res->body);
  6802. }
  6803. TEST_F(ServerTest, Options) {
  6804. auto res = cli_.Options("*");
  6805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6806. EXPECT_EQ(StatusCode::OK_200, res->status);
  6807. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6808. EXPECT_TRUE(res->body.empty());
  6809. }
  6810. TEST_F(ServerTest, URL) {
  6811. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. }
  6815. TEST_F(ServerTest, ArrayParam) {
  6816. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6818. EXPECT_EQ(StatusCode::OK_200, res->status);
  6819. }
  6820. TEST_F(ServerTest, ArrayParamValues) {
  6821. auto res =
  6822. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6824. EXPECT_EQ(StatusCode::OK_200, res->status);
  6825. }
  6826. TEST_F(ServerTest, NoMultipleHeaders) {
  6827. Headers headers = {{"Content-Length", "5"}};
  6828. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6829. "text/plain");
  6830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6831. EXPECT_EQ(StatusCode::OK_200, res->status);
  6832. }
  6833. TEST_F(ServerTest, PostContentReceiver) {
  6834. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6836. ASSERT_EQ(StatusCode::OK_200, res->status);
  6837. ASSERT_EQ("content", res->body);
  6838. }
  6839. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6840. UploadFormDataItems items = {
  6841. {"text1", "text default", "", ""},
  6842. {"text2", "aωb", "", ""},
  6843. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6844. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6845. {"file3", "", "", "application/octet-stream"},
  6846. };
  6847. auto res = cli_.Post("/content_receiver", items);
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. }
  6851. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6852. UploadFormDataItems items = {
  6853. {"text1", "text default", "", ""},
  6854. {"text2", "aωb", "", ""},
  6855. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6856. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6857. {"file3", "", "", "application/octet-stream"},
  6858. };
  6859. auto boundary = std::string("+++++");
  6860. std::string body;
  6861. for (const auto &item : items) {
  6862. body += "--" + boundary + "\r\n";
  6863. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6864. if (!item.filename.empty()) {
  6865. body += "; filename=\"" + item.filename + "\"";
  6866. }
  6867. body += "\r\n";
  6868. if (!item.content_type.empty()) {
  6869. body += "Content-Type: " + item.content_type + "\r\n";
  6870. }
  6871. body += "\r\n";
  6872. body += item.content + "\r\n";
  6873. }
  6874. body += "--" + boundary + "--\r\n";
  6875. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6876. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. EXPECT_EQ(StatusCode::OK_200, res->status);
  6879. }
  6880. TEST(MultipartFormDataTest, FieldEscaping) {
  6881. Server svr;
  6882. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6883. const ContentReader &content_reader) {
  6884. ASSERT_TRUE(req.is_multipart_form_data());
  6885. std::vector<FormData> received;
  6886. content_reader(
  6887. [&](const FormData &file) {
  6888. received.push_back(file);
  6889. return true;
  6890. },
  6891. [&](const char *data, size_t data_length) {
  6892. received.back().content.append(data, data_length);
  6893. return true;
  6894. });
  6895. // '"', CR and LF in names and filenames are escaped following the
  6896. // WHATWG HTML standard, so each part still parses as a single part
  6897. // with no injected headers. Content types get CR/LF escaped too,
  6898. // while '"' (legal there, e.g. quoted charset) is preserved.
  6899. ASSERT_EQ(4U, received.size());
  6900. EXPECT_EQ("na%22me", received[0].name);
  6901. EXPECT_EQ("quoted name", received[0].content);
  6902. EXPECT_EQ("file", received[1].name);
  6903. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6904. received[1].filename);
  6905. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6906. EXPECT_EQ("injected", received[1].content);
  6907. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6908. EXPECT_EQ("my%22file.txt", received[2].filename);
  6909. EXPECT_EQ("cr lf name", received[2].content);
  6910. EXPECT_EQ("typed", received[3].name);
  6911. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6912. received[3].content_type);
  6913. EXPECT_EQ("typed content", received[3].content);
  6914. });
  6915. auto port = svr.bind_to_any_port("localhost");
  6916. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6917. auto se = detail::scope_exit([&] {
  6918. svr.stop();
  6919. t.join();
  6920. ASSERT_FALSE(svr.is_running());
  6921. });
  6922. svr.wait_until_ready();
  6923. Client cli("localhost", port);
  6924. UploadFormDataItems items = {
  6925. {"na\"me", "quoted name", "", ""},
  6926. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6927. "application/octet-stream"},
  6928. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6929. {"typed", "typed content", "",
  6930. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6931. };
  6932. auto res = cli.Post("/post", items);
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. }
  6936. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6937. const UploadFormDataItems items = {
  6938. {"name1", "Content 1", "", ""},
  6939. {"name2", "Content 2", "file2.txt", "text/plain"},
  6940. };
  6941. Server svr;
  6942. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6943. const ContentReader &content_reader) {
  6944. ASSERT_TRUE(req.is_multipart_form_data());
  6945. std::vector<FormData> received;
  6946. content_reader(
  6947. [&](const FormData &file) {
  6948. received.push_back(file);
  6949. return true;
  6950. },
  6951. [&](const char *data, size_t data_length) {
  6952. received.back().content.append(data, data_length);
  6953. return true;
  6954. });
  6955. ASSERT_EQ(2U, received.size());
  6956. EXPECT_EQ("name1", received[0].name);
  6957. EXPECT_EQ("Content 1", received[0].content);
  6958. EXPECT_EQ("name2", received[1].name);
  6959. EXPECT_EQ("Content 2", received[1].content);
  6960. EXPECT_EQ("file2.txt", received[1].filename);
  6961. EXPECT_EQ("text/plain", received[1].content_type);
  6962. });
  6963. auto port = svr.bind_to_any_port("localhost");
  6964. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6965. auto se = detail::scope_exit([&] {
  6966. svr.stop();
  6967. t.join();
  6968. ASSERT_FALSE(svr.is_running());
  6969. });
  6970. svr.wait_until_ready();
  6971. Client cli("localhost", port);
  6972. // Whole-body serialization with a generated boundary
  6973. {
  6974. MultipartFormDataWriter writer;
  6975. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6976. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6977. writer.content_type());
  6978. auto body = writer.serialize(items);
  6979. EXPECT_EQ(body.size(), writer.content_length(items));
  6980. auto res = cli.Post("/post", body, writer.content_type());
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::OK_200, res->status);
  6983. }
  6984. // Per-part framing with a custom boundary via a content provider
  6985. {
  6986. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6987. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6988. MultipartFormDataWriter writer("custom-boundary_123");
  6989. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6990. std::string body;
  6991. for (const auto &item : items) {
  6992. body += writer.item_begin(item);
  6993. body += item.content;
  6994. body += MultipartFormDataWriter::item_end();
  6995. }
  6996. body += writer.finish();
  6997. EXPECT_EQ(body.size(), writer.content_length(items));
  6998. auto res = cli.Post(
  6999. "/post", body.size(),
  7000. [&](size_t offset, size_t length, DataSink &sink) {
  7001. sink.write(body.data() + offset, length);
  7002. return true;
  7003. },
  7004. writer.content_type());
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. EXPECT_EQ(StatusCode::OK_200, res->status);
  7007. }
  7008. }
  7009. TEST_F(ServerTest, PostContentReceiverGzip) {
  7010. cli_.set_compress(true);
  7011. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. ASSERT_EQ(StatusCode::OK_200, res->status);
  7014. ASSERT_EQ("content", res->body);
  7015. }
  7016. TEST_F(ServerTest, PutContentReceiver) {
  7017. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7019. ASSERT_EQ(StatusCode::OK_200, res->status);
  7020. ASSERT_EQ("content", res->body);
  7021. }
  7022. TEST_F(ServerTest, PatchContentReceiver) {
  7023. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. ASSERT_EQ(StatusCode::OK_200, res->status);
  7026. ASSERT_EQ("content", res->body);
  7027. }
  7028. template <typename ClientType>
  7029. void TestWithHeadersAndContentReceiver(
  7030. ClientType &cli,
  7031. std::function<Result(ClientType &, const std::string &, const Headers &,
  7032. const std::string &, const std::string &,
  7033. ContentReceiver, DownloadProgress)>
  7034. request_func) {
  7035. Headers headers;
  7036. headers.emplace("X-Custom-Header", "test-value");
  7037. std::string received_body;
  7038. auto res = request_func(
  7039. cli, "/content_receiver", headers, "content", "application/json",
  7040. [&](const char *data, size_t data_length) {
  7041. received_body.append(data, data_length);
  7042. return true;
  7043. },
  7044. nullptr);
  7045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7046. EXPECT_EQ(StatusCode::OK_200, res->status);
  7047. EXPECT_EQ("content", received_body);
  7048. }
  7049. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7050. #ifdef CPPHTTPLIB_SSL_ENABLED
  7051. using ClientT = SSLClient;
  7052. #else
  7053. using ClientT = Client;
  7054. #endif
  7055. TestWithHeadersAndContentReceiver<ClientT>(
  7056. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7057. const std::string &body, const std::string &content_type,
  7058. ContentReceiver receiver, DownloadProgress progress) {
  7059. return cli.Post(path, headers, body, content_type, receiver, progress);
  7060. });
  7061. }
  7062. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7063. #ifdef CPPHTTPLIB_SSL_ENABLED
  7064. using ClientT = SSLClient;
  7065. #else
  7066. using ClientT = Client;
  7067. #endif
  7068. TestWithHeadersAndContentReceiver<ClientT>(
  7069. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7070. const std::string &body, const std::string &content_type,
  7071. ContentReceiver receiver, DownloadProgress progress) {
  7072. return cli.Put(path, headers, body, content_type, receiver, progress);
  7073. });
  7074. }
  7075. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7076. #ifdef CPPHTTPLIB_SSL_ENABLED
  7077. using ClientT = SSLClient;
  7078. #else
  7079. using ClientT = Client;
  7080. #endif
  7081. TestWithHeadersAndContentReceiver<ClientT>(
  7082. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7083. const std::string &body, const std::string &content_type,
  7084. ContentReceiver receiver, DownloadProgress progress) {
  7085. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7086. });
  7087. }
  7088. template <typename ClientType>
  7089. void TestWithHeadersAndContentReceiverWithProgress(
  7090. ClientType &cli,
  7091. std::function<Result(ClientType &, const std::string &, const Headers &,
  7092. const std::string &, const std::string &,
  7093. ContentReceiver, DownloadProgress)>
  7094. request_func) {
  7095. Headers headers;
  7096. headers.emplace("X-Test-Header", "progress-test");
  7097. std::string received_body;
  7098. auto progress_called = false;
  7099. auto res = request_func(
  7100. cli, "/content_receiver", headers, "content", "text/plain",
  7101. [&](const char *data, size_t data_length) {
  7102. received_body.append(data, data_length);
  7103. return true;
  7104. },
  7105. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7106. progress_called = true;
  7107. return true;
  7108. });
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::OK_200, res->status);
  7111. EXPECT_EQ("content", received_body);
  7112. EXPECT_TRUE(progress_called);
  7113. }
  7114. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7115. #ifdef CPPHTTPLIB_SSL_ENABLED
  7116. using ClientT = SSLClient;
  7117. #else
  7118. using ClientT = Client;
  7119. #endif
  7120. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7121. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7122. const std::string &body, const std::string &content_type,
  7123. ContentReceiver receiver, DownloadProgress progress) {
  7124. return cli.Post(path, headers, body, content_type, receiver, progress);
  7125. });
  7126. }
  7127. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7128. #ifdef CPPHTTPLIB_SSL_ENABLED
  7129. using ClientT = SSLClient;
  7130. #else
  7131. using ClientT = Client;
  7132. #endif
  7133. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7134. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7135. const std::string &body, const std::string &content_type,
  7136. ContentReceiver receiver, DownloadProgress progress) {
  7137. return cli.Put(path, headers, body, content_type, receiver, progress);
  7138. });
  7139. }
  7140. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7141. #ifdef CPPHTTPLIB_SSL_ENABLED
  7142. using ClientT = SSLClient;
  7143. #else
  7144. using ClientT = Client;
  7145. #endif
  7146. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7147. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7148. const std::string &body, const std::string &content_type,
  7149. ContentReceiver receiver, DownloadProgress progress) {
  7150. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7151. });
  7152. }
  7153. template <typename ClientType>
  7154. void TestWithHeadersAndContentReceiverError(
  7155. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7156. const Headers &, const std::string &,
  7157. const std::string &, ContentReceiver)>
  7158. request_func) {
  7159. Headers headers;
  7160. headers.emplace("X-Error-Test", "true");
  7161. std::string received_body;
  7162. auto receiver_failed = false;
  7163. auto res =
  7164. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7165. [&](const char *data, size_t data_length) {
  7166. received_body.append(data, data_length);
  7167. receiver_failed = true;
  7168. return false;
  7169. });
  7170. ASSERT_FALSE(res);
  7171. EXPECT_TRUE(receiver_failed);
  7172. }
  7173. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7174. #ifdef CPPHTTPLIB_SSL_ENABLED
  7175. using ClientT = SSLClient;
  7176. #else
  7177. using ClientT = Client;
  7178. #endif
  7179. TestWithHeadersAndContentReceiverError<ClientT>(
  7180. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7181. const std::string &body, const std::string &content_type,
  7182. ContentReceiver receiver) {
  7183. return cli.Post(path, headers, body, content_type, receiver);
  7184. });
  7185. }
  7186. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7187. #ifdef CPPHTTPLIB_SSL_ENABLED
  7188. using ClientT = SSLClient;
  7189. #else
  7190. using ClientT = Client;
  7191. #endif
  7192. TestWithHeadersAndContentReceiverError<ClientT>(
  7193. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7194. const std::string &body, const std::string &content_type,
  7195. ContentReceiver receiver) {
  7196. return cli.Put(path, headers, body, content_type, receiver);
  7197. });
  7198. }
  7199. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7200. #ifdef CPPHTTPLIB_SSL_ENABLED
  7201. using ClientT = SSLClient;
  7202. #else
  7203. using ClientT = Client;
  7204. #endif
  7205. TestWithHeadersAndContentReceiverError<ClientT>(
  7206. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7207. const std::string &body, const std::string &content_type,
  7208. ContentReceiver receiver) {
  7209. return cli.Patch(path, headers, body, content_type, receiver);
  7210. });
  7211. }
  7212. TEST_F(ServerTest, PostQueryStringAndBody) {
  7213. auto res =
  7214. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7216. ASSERT_EQ(StatusCode::OK_200, res->status);
  7217. }
  7218. TEST_F(ServerTest, HTTP2Magic) {
  7219. Request req;
  7220. req.method = "PRI";
  7221. req.path = "*";
  7222. req.body = "SM";
  7223. auto res = std::make_shared<Response>();
  7224. auto error = Error::Success;
  7225. auto ret = cli_.send(req, *res, error);
  7226. ASSERT_TRUE(ret);
  7227. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7228. }
  7229. TEST_F(ServerTest, KeepAlive) {
  7230. auto res = cli_.Get("/hi");
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::OK_200, res->status);
  7233. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7234. EXPECT_EQ("Hello World!", res->body);
  7235. res = cli_.Get("/hi");
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. EXPECT_EQ(StatusCode::OK_200, res->status);
  7238. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7239. EXPECT_EQ("Hello World!", res->body);
  7240. res = cli_.Get("/hi");
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::OK_200, res->status);
  7243. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7244. EXPECT_EQ("Hello World!", res->body);
  7245. res = cli_.Get("/not-exist");
  7246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7247. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7248. res = cli_.Post("/empty", "", "text/plain");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7252. EXPECT_EQ("empty", res->body);
  7253. EXPECT_EQ("close", res->get_header_value("Connection"));
  7254. res = cli_.Post(
  7255. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7256. "text/plain");
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::OK_200, res->status);
  7259. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7260. EXPECT_EQ("empty", res->body);
  7261. cli_.set_keep_alive(false);
  7262. res = cli_.Get("/last-request");
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ("close", res->get_header_value("Connection"));
  7266. }
  7267. TEST_F(ServerTest, TooManyRedirect) {
  7268. cli_.set_follow_location(true);
  7269. auto res = cli_.Get("/redirect/0");
  7270. ASSERT_TRUE(!res);
  7271. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7272. }
  7273. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7274. Request req;
  7275. req.method = "FOOBAR";
  7276. req.path = "/hi";
  7277. cli_.set_keep_alive(true);
  7278. auto res = cli_.send(req);
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7281. EXPECT_EQ("close", res->get_header_value("Connection"));
  7282. EXPECT_FALSE(cli_.is_socket_open());
  7283. }
  7284. TEST_F(ServerTest, CustomRouteReadsBody) {
  7285. const std::string xml =
  7286. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7287. Request req;
  7288. req.method = "PROPFIND";
  7289. req.path = "/dav/dir";
  7290. req.set_header("Depth", "1");
  7291. req.body = xml;
  7292. auto res = cli_.send(req);
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7295. EXPECT_EQ(xml, res->body);
  7296. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7297. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7298. }
  7299. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7300. Request req;
  7301. req.method = "PROPFIND";
  7302. req.path = "/dav/42";
  7303. auto res = cli_.send(req);
  7304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7305. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7306. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7307. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7308. }
  7309. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7310. Request req;
  7311. req.method = "PROPFIND";
  7312. req.path = "/dav-re/123";
  7313. auto res = cli_.send(req);
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7316. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7317. }
  7318. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7319. Request req;
  7320. req.method = "MKCOL";
  7321. req.path = "/dav-mkcol";
  7322. auto res = cli_.send(req);
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::Created_201, res->status);
  7325. }
  7326. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7327. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7328. Request req;
  7329. req.method = "REPORT";
  7330. req.path = "/dav-report";
  7331. req.body = xml;
  7332. auto res = cli_.send(req);
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7335. EXPECT_EQ(xml, res->body);
  7336. }
  7337. // A content reader route must fire even when the request carries no body,
  7338. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7339. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7340. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7341. Request req;
  7342. req.method = "REPORT";
  7343. req.path = "/dav-report";
  7344. auto res = cli_.send(req);
  7345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7346. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7347. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7348. }
  7349. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7350. Request req;
  7351. req.method = "PROPFIND";
  7352. req.path = "/not-dav";
  7353. auto res = cli_.send(req);
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7356. }
  7357. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7358. Request req;
  7359. req.method = "UNLOCK";
  7360. req.path = "/dav/dir";
  7361. cli_.set_keep_alive(true);
  7362. auto res = cli_.send(req);
  7363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7364. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7365. EXPECT_EQ("close", res->get_header_value("Connection"));
  7366. EXPECT_FALSE(cli_.is_socket_open());
  7367. }
  7368. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7369. // The mount point serves this path, but only for GET and HEAD.
  7370. auto get_res = cli_.Get("/dir/index.html");
  7371. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7372. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7373. Request req;
  7374. req.method = "PROPFIND";
  7375. req.path = "/dir/index.html";
  7376. auto res = cli_.send(req);
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7379. }
  7380. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7381. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7382. cli_.set_keep_alive(true);
  7383. for (auto i = 0; i < 2; i++) {
  7384. Request req;
  7385. req.method = "PROPFIND";
  7386. req.path = "/dav/dir";
  7387. req.body = xml;
  7388. auto res = cli_.send(req);
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7391. EXPECT_EQ(xml, res->body);
  7392. EXPECT_TRUE(cli_.is_socket_open());
  7393. }
  7394. // A built-in method must still be served on the same connection.
  7395. cli_.set_keep_alive(false);
  7396. auto res = cli_.Get("/hi");
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. EXPECT_EQ("close", res->get_header_value("Connection"));
  7400. }
  7401. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7402. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7403. Request req;
  7404. req.method = "PROPFIND";
  7405. req.path = "/dav/dir";
  7406. req.set_header("Expect", "100-continue");
  7407. req.body = xml;
  7408. auto res = cli_.send(req);
  7409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7410. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7411. EXPECT_EQ(xml, res->body);
  7412. }
  7413. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7414. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7415. TEST_F(ServerTest, Gzip) {
  7416. Headers headers;
  7417. headers.emplace("Accept-Encoding", "gzip, deflate");
  7418. auto res = cli_.Get("/compress", headers);
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7422. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7423. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7424. "7890123456789012345678901234567890",
  7425. res->body);
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. }
  7428. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7429. Headers headers;
  7430. headers.emplace("Accept-Encoding", "gzip, deflate");
  7431. auto res = cli_.Get("/compress-with-charset", headers);
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7434. EXPECT_EQ("application/json; charset=utf-8",
  7435. res->get_header_value("Content-Type"));
  7436. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7437. "7890123456789012345678901234567890",
  7438. res->body);
  7439. EXPECT_EQ(StatusCode::OK_200, res->status);
  7440. }
  7441. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7442. Headers headers;
  7443. headers.emplace("Accept-Encoding", "");
  7444. auto res = cli_.Get("/compress", headers);
  7445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7446. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7447. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7448. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7449. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7450. "7890123456789012345678901234567890",
  7451. res->body);
  7452. EXPECT_EQ(StatusCode::OK_200, res->status);
  7453. }
  7454. TEST_F(ServerTest, GzipWithContentReceiver) {
  7455. Headers headers;
  7456. headers.emplace("Accept-Encoding", "gzip, deflate");
  7457. std::string body;
  7458. auto res = cli_.Get("/compress", headers,
  7459. [&](const char *data, uint64_t data_length) {
  7460. EXPECT_EQ(100U, data_length);
  7461. body.append(data, data_length);
  7462. return true;
  7463. });
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7467. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7468. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7469. "7890123456789012345678901234567890",
  7470. body);
  7471. EXPECT_EQ(StatusCode::OK_200, res->status);
  7472. }
  7473. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7474. Headers headers;
  7475. headers.emplace("Accept-Encoding", "gzip, deflate");
  7476. cli_.set_decompress(false);
  7477. auto res = cli_.Get("/compress", headers);
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7480. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7481. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7482. EXPECT_EQ(33U, res->body.size());
  7483. EXPECT_EQ(StatusCode::OK_200, res->status);
  7484. }
  7485. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7486. Headers headers;
  7487. headers.emplace("Accept-Encoding", "");
  7488. std::string body;
  7489. auto res = cli_.Get("/compress", headers,
  7490. [&](const char *data, uint64_t data_length) {
  7491. EXPECT_EQ(100U, data_length);
  7492. body.append(data, data_length);
  7493. return true;
  7494. });
  7495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7496. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7497. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7498. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7499. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7500. "7890123456789012345678901234567890",
  7501. body);
  7502. EXPECT_EQ(StatusCode::OK_200, res->status);
  7503. }
  7504. TEST_F(ServerTest, NoGzip) {
  7505. Headers headers;
  7506. headers.emplace("Accept-Encoding", "gzip, deflate");
  7507. auto res = cli_.Get("/nocompress", headers);
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7510. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7511. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7512. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7513. "7890123456789012345678901234567890",
  7514. res->body);
  7515. EXPECT_EQ(StatusCode::OK_200, res->status);
  7516. }
  7517. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7518. Headers headers;
  7519. headers.emplace("Accept-Encoding", "gzip, deflate");
  7520. std::string body;
  7521. auto res = cli_.Get("/nocompress", headers,
  7522. [&](const char *data, uint64_t data_length) {
  7523. EXPECT_EQ(100U, data_length);
  7524. body.append(data, data_length);
  7525. return true;
  7526. });
  7527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7528. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7529. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7530. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7531. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7532. "7890123456789012345678901234567890",
  7533. body);
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. }
  7536. TEST_F(ServerTest, MultipartFormDataGzip) {
  7537. UploadFormDataItems items = {
  7538. {"key1", "test", "", ""},
  7539. {"key2", "--abcdefg123", "", ""},
  7540. };
  7541. cli_.set_compress(true);
  7542. auto res = cli_.Post("/compress-multipart", items);
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::OK_200, res->status);
  7545. }
  7546. #endif
  7547. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7548. // Static file compression is opt-in, so these run their own server rather than
  7549. // flipping it on for the shared ServerTest fixture, which would silently
  7550. // rewrite what every other static file test is asserting.
  7551. class StaticFileCompressionTest : public ::testing::Test {
  7552. protected:
  7553. void TearDown() override {
  7554. if (t_.joinable()) {
  7555. svr_.stop();
  7556. t_.join();
  7557. }
  7558. }
  7559. int start(const std::function<void(Server &)> &configure = nullptr) {
  7560. // Serves the same tree as a directory of build-time compressed assets
  7561. // would be served: the mount point names the coding the files are already
  7562. // stored in. Registered before "/" so it is the one that matches.
  7563. svr_.set_mount_point("/pre-encoded", "./www",
  7564. {{"Content-Encoding", "gzip"}});
  7565. svr_.set_mount_point("/", "./www");
  7566. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7567. res.set_file_content("./www/dir/index.html", "text/html");
  7568. });
  7569. svr_.Get("/pre-encoded-file-content",
  7570. [](const Request & /*req*/, Response &res) {
  7571. res.set_header("Content-Encoding", "gzip");
  7572. res.set_file_content("./www/dir/index.html", "text/html");
  7573. });
  7574. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7575. res.set_content_provider(
  7576. 6, "text/plain",
  7577. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7578. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7579. return true;
  7580. });
  7581. });
  7582. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7583. res.set_content_provider(
  7584. 1000, "text/plain",
  7585. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7586. if (offset < 100) {
  7587. std::string data(100, 'A');
  7588. sink.write(data.data(), data.size());
  7589. return true;
  7590. }
  7591. std::this_thread::sleep_for(std::chrono::seconds(2));
  7592. std::string data(900, 'B');
  7593. sink.write(data.data(), data.size());
  7594. return true;
  7595. });
  7596. });
  7597. if (configure) { configure(svr_); }
  7598. auto port = svr_.bind_to_any_port(HOST);
  7599. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7600. svr_.wait_until_ready();
  7601. return port;
  7602. }
  7603. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7604. // Every file under ./www except 1MB.txt is smaller than the default
  7605. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7606. // it out of the way.
  7607. static void enable_without_floor(Server &svr) {
  7608. svr.set_static_file_compression(true);
  7609. svr.set_static_file_compression_min_length(0);
  7610. }
  7611. Server svr_;
  7612. std::thread t_;
  7613. };
  7614. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7615. auto port = start();
  7616. Client cli(HOST, port);
  7617. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7619. EXPECT_EQ(StatusCode::OK_200, res->status);
  7620. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7621. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7622. EXPECT_EQ(1048576U, res->body.size());
  7623. }
  7624. TEST_F(StaticFileCompressionTest, MountPoint) {
  7625. auto port = start(enable);
  7626. Client cli(HOST, port);
  7627. cli.set_decompress(false);
  7628. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_EQ(StatusCode::OK_200, res->status);
  7631. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7632. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7633. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7634. // The response stays self-delimiting: a length, not a chunked body.
  7635. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7636. EXPECT_EQ(std::to_string(res->body.size()),
  7637. res->get_header_value("Content-Length"));
  7638. EXPECT_LT(res->body.size(), 1048576U);
  7639. EXPECT_FALSE(res->body.empty());
  7640. }
  7641. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7642. auto port = start(enable);
  7643. Client cli(HOST, port);
  7644. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7646. EXPECT_EQ(StatusCode::OK_200, res->status);
  7647. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7648. EXPECT_EQ(1048576U, res->body.size());
  7649. }
  7650. TEST_F(StaticFileCompressionTest, FileContent) {
  7651. auto port = start(enable_without_floor);
  7652. Client cli(HOST, port);
  7653. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7655. EXPECT_EQ(StatusCode::OK_200, res->status);
  7656. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7657. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7658. EXPECT_EQ(104U, res->body.size());
  7659. }
  7660. // A handler that serves an already-encoded file names the coding itself. The
  7661. // file-backed path decided its coding from Accept-Encoding and the content
  7662. // type alone, so it compressed the stored bytes a second time and appended a
  7663. // second Content-Encoding field line.
  7664. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7665. auto port = start(enable_without_floor);
  7666. Client cli(HOST, port);
  7667. cli.set_decompress(false);
  7668. auto res = cli.Get("/pre-encoded-file-content",
  7669. Headers{{"Accept-Encoding", "gzip"}});
  7670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7671. EXPECT_EQ(StatusCode::OK_200, res->status);
  7672. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7673. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7674. // Vary belongs to a coding the server chose, and it chose none here.
  7675. EXPECT_FALSE(res->has_header("Vary"));
  7676. // The file travels exactly as it is stored on disk.
  7677. EXPECT_EQ(104U, res->body.size());
  7678. }
  7679. // The 1MB file clears the default floor, so this one runs the configuration a
  7680. // deployment would actually have.
  7681. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7682. auto port = start(enable);
  7683. Client cli(HOST, port);
  7684. cli.set_decompress(false);
  7685. auto res =
  7686. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7690. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7691. EXPECT_FALSE(res->has_header("Vary"));
  7692. EXPECT_EQ(1048576U, res->body.size());
  7693. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7694. }
  7695. TEST_F(StaticFileCompressionTest, Head) {
  7696. auto port = start(enable);
  7697. Client cli(HOST, port);
  7698. cli.set_decompress(false);
  7699. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7700. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7701. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7703. EXPECT_EQ(StatusCode::OK_200, res->status);
  7704. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7705. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7706. // HEAD still reports the size a GET would return.
  7707. EXPECT_EQ(get->get_header_value("Content-Length"),
  7708. res->get_header_value("Content-Length"));
  7709. EXPECT_TRUE(res->body.empty());
  7710. }
  7711. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7712. auto port = start(enable);
  7713. Client cli(HOST, port);
  7714. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7715. {"Accept-Encoding", "gzip"}});
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7718. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7719. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7720. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7721. EXPECT_EQ("cd", res->body);
  7722. }
  7723. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7724. auto port = start(enable);
  7725. Client cli(HOST, port);
  7726. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7730. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7731. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7732. }
  7733. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7734. auto port = start(enable);
  7735. Client cli(HOST, port);
  7736. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7740. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7741. EXPECT_TRUE(res->body.empty());
  7742. }
  7743. TEST_F(StaticFileCompressionTest, MinLength) {
  7744. auto port = start(enable);
  7745. Client cli(HOST, port);
  7746. // 104 bytes, well under the default floor. Compressing it would add the
  7747. // gzip header and trailer to a body that already fits in one packet.
  7748. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::OK_200, res->status);
  7751. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7752. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7753. }
  7754. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7755. auto port = start([](Server &svr) {
  7756. svr.set_static_file_compression(true);
  7757. svr.set_static_file_compression_min_length(1);
  7758. });
  7759. Client cli(HOST, port);
  7760. cli.set_decompress(false);
  7761. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7763. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7764. // A 9-byte file comes back larger than it went in, because gzip's header and
  7765. // trailer outweigh anything deflate can save. That is the end of the range
  7766. // the floor exists to keep out.
  7767. EXPECT_GT(res->body.size(), 9U);
  7768. }
  7769. TEST_F(StaticFileCompressionTest, MaxLength) {
  7770. auto port = start([](Server &svr) {
  7771. svr.set_static_file_compression(true);
  7772. svr.set_static_file_compression_min_length(0);
  7773. svr.set_static_file_compression_max_length(1024);
  7774. });
  7775. Client cli(HOST, port);
  7776. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7777. // defines `small` as a macro on Windows.
  7778. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7779. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7780. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7781. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7782. // Under it: compressed.
  7783. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7784. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7785. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7786. }
  7787. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7788. auto port = start(enable_without_floor);
  7789. Client cli(HOST, port);
  7790. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7791. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7792. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7793. auto identity_etag = identity->get_header_value("ETag");
  7794. ASSERT_FALSE(identity_etag.empty());
  7795. auto gzipped =
  7796. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7797. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7798. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7799. auto gzip_etag = gzipped->get_header_value("ETag");
  7800. ASSERT_FALSE(gzip_etag.empty());
  7801. // Two representations, two validators.
  7802. EXPECT_NE(identity_etag, gzip_etag);
  7803. // Each one revalidates against the request that would produce it...
  7804. auto fresh =
  7805. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7806. {"If-None-Match", gzip_etag}});
  7807. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7808. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7809. auto fresh_identity =
  7810. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7811. {"If-None-Match", identity_etag}});
  7812. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7813. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7814. // ...and not against the other representation.
  7815. auto crossed =
  7816. cli.Get("/dir/index.html",
  7817. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7818. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7819. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7820. }
  7821. // The opt-in covers responses the server reads off disk itself. A caller's own
  7822. // known-length provider keeps its Content-Length and, more importantly, keeps
  7823. // delivering incrementally: routing it through a compressor would hold every
  7824. // write back until zlib's window filled.
  7825. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7826. auto port = start(enable);
  7827. Client cli(HOST, port);
  7828. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::OK_200, res->status);
  7831. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7832. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7833. EXPECT_EQ("aaabbb", res->body);
  7834. }
  7835. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7836. auto port = start(enable);
  7837. Client cli(HOST, port);
  7838. cli.set_read_timeout(1, 0);
  7839. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7840. Headers{{"Accept-Encoding", "gzip"}});
  7841. ASSERT_TRUE(handle.is_valid());
  7842. // The provider writes 100 bytes and then stalls for longer than the read
  7843. // timeout. Those first bytes have to arrive anyway: run the response through
  7844. // a compressor and zlib holds them until its window fills, so the read would
  7845. // come back empty instead.
  7846. char buf[256];
  7847. auto n = handle.read(buf, sizeof(buf));
  7848. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7849. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7850. }
  7851. #endif
  7852. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7853. TEST_F(ServerTest, Brotli) {
  7854. Headers headers;
  7855. headers.emplace("Accept-Encoding", "br");
  7856. auto res = cli_.Get("/compress", headers);
  7857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7858. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7860. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7861. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7862. "7890123456789012345678901234567890",
  7863. res->body);
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. }
  7866. #endif
  7867. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7868. TEST_F(ServerTest, Zstd) {
  7869. Headers headers;
  7870. headers.emplace("Accept-Encoding", "zstd");
  7871. auto res = cli_.Get("/compress", headers);
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7874. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7875. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7876. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7877. "7890123456789012345678901234567890",
  7878. res->body);
  7879. EXPECT_EQ(StatusCode::OK_200, res->status);
  7880. }
  7881. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7882. Headers headers;
  7883. headers.emplace("Accept-Encoding", "");
  7884. auto res = cli_.Get("/compress", headers);
  7885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7886. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7888. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7889. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7890. "7890123456789012345678901234567890",
  7891. res->body);
  7892. EXPECT_EQ(StatusCode::OK_200, res->status);
  7893. }
  7894. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7895. Headers headers;
  7896. headers.emplace("Accept-Encoding", "zstd");
  7897. std::string body;
  7898. auto res = cli_.Get("/compress", headers,
  7899. [&](const char *data, uint64_t data_length) {
  7900. EXPECT_EQ(100U, data_length);
  7901. body.append(data, data_length);
  7902. return true;
  7903. });
  7904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7905. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7907. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7908. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7909. "7890123456789012345678901234567890",
  7910. body);
  7911. EXPECT_EQ(StatusCode::OK_200, res->status);
  7912. }
  7913. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7914. Headers headers;
  7915. headers.emplace("Accept-Encoding", "zstd");
  7916. cli_.set_decompress(false);
  7917. auto res = cli_.Get("/compress", headers);
  7918. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7919. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7920. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7921. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7923. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7924. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7925. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. ASSERT_EQ(26U, res->body.size());
  7928. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7929. 0);
  7930. }
  7931. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7932. Headers headers;
  7933. headers.emplace("Accept-Encoding", "");
  7934. std::string body;
  7935. auto res = cli_.Get("/compress", headers,
  7936. [&](const char *data, uint64_t data_length) {
  7937. EXPECT_EQ(100U, data_length);
  7938. body.append(data, data_length);
  7939. return true;
  7940. });
  7941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7942. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7944. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7946. "7890123456789012345678901234567890",
  7947. body);
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. }
  7950. TEST_F(ServerTest, NoZstd) {
  7951. Headers headers;
  7952. headers.emplace("Accept-Encoding", "zstd");
  7953. auto res = cli_.Get("/nocompress", headers);
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7956. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7957. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7958. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7959. "7890123456789012345678901234567890",
  7960. res->body);
  7961. EXPECT_EQ(StatusCode::OK_200, res->status);
  7962. }
  7963. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7964. Headers headers;
  7965. headers.emplace("Accept-Encoding", "zstd");
  7966. std::string body;
  7967. auto res = cli_.Get("/nocompress", headers,
  7968. [&](const char *data, uint64_t data_length) {
  7969. EXPECT_EQ(100U, data_length);
  7970. body.append(data, data_length);
  7971. return true;
  7972. });
  7973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7974. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7975. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7976. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7977. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7978. "7890123456789012345678901234567890",
  7979. body);
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. }
  7982. // TODO: How to enable zstd ??
  7983. TEST_F(ServerTest, MultipartFormDataZstd) {
  7984. UploadFormDataItems items = {
  7985. {"key1", "test", "", ""},
  7986. {"key2", "--abcdefg123", "", ""},
  7987. };
  7988. Headers headers;
  7989. headers.emplace("Accept-Encoding", "zstd");
  7990. cli_.set_compress(true);
  7991. auto res = cli_.Post("/compress-multipart", headers, items);
  7992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7993. EXPECT_EQ(StatusCode::OK_200, res->status);
  7994. }
  7995. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7996. Headers headers;
  7997. headers.emplace("Accept-Encoding", "zstd");
  7998. cli_.set_compress(true);
  7999. auto res = cli_.Put(
  8000. "/put", headers, 3,
  8001. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8002. sink.os << "PUT";
  8003. return true;
  8004. },
  8005. "text/plain");
  8006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8007. EXPECT_EQ(StatusCode::OK_200, res->status);
  8008. EXPECT_EQ("PUT", res->body);
  8009. }
  8010. // Pre-compression logging tests
  8011. TEST_F(ServerTest, PreCompressionLogging) {
  8012. // Test data for compression (matches the actual /compress endpoint content)
  8013. const std::string test_content =
  8014. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8015. "3456789012345678901234567890";
  8016. // Variables to capture logging data
  8017. std::string pre_compression_body;
  8018. std::string pre_compression_content_type;
  8019. std::string pre_compression_content_encoding;
  8020. std::string post_compression_body;
  8021. std::string post_compression_content_type;
  8022. std::string post_compression_content_encoding;
  8023. // Set up pre-compression logger
  8024. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8025. const Response &res) {
  8026. pre_compression_body = res.body;
  8027. pre_compression_content_type = res.get_header_value("Content-Type");
  8028. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8029. });
  8030. // Set up post-compression logger
  8031. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8032. post_compression_body = res.body;
  8033. post_compression_content_type = res.get_header_value("Content-Type");
  8034. post_compression_content_encoding =
  8035. res.get_header_value("Content-Encoding");
  8036. });
  8037. // Test with gzip compression
  8038. Headers headers;
  8039. headers.emplace("Accept-Encoding", "gzip");
  8040. auto res = cli_.Get("/compress", headers);
  8041. // Verify response was compressed
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8045. // Verify pre-compression logger captured uncompressed content
  8046. EXPECT_EQ(test_content, pre_compression_body);
  8047. EXPECT_EQ("text/plain", pre_compression_content_type);
  8048. EXPECT_TRUE(pre_compression_content_encoding
  8049. .empty()); // No encoding header before compression
  8050. // Verify post-compression logger captured compressed content
  8051. EXPECT_NE(test_content,
  8052. post_compression_body); // Should be different after compression
  8053. EXPECT_EQ("text/plain", post_compression_content_type);
  8054. EXPECT_EQ("gzip", post_compression_content_encoding);
  8055. // Verify compressed content is smaller
  8056. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8057. }
  8058. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8059. const std::string test_content =
  8060. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8061. "3456789012345678901234567890";
  8062. std::string pre_compression_body;
  8063. std::string post_compression_body;
  8064. svr_.set_pre_compression_logger(
  8065. [&](const Request & /*req*/, const Response &res) {
  8066. pre_compression_body = res.body;
  8067. });
  8068. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8069. post_compression_body = res.body;
  8070. });
  8071. Headers headers;
  8072. headers.emplace("Accept-Encoding", "br");
  8073. auto res = cli_.Get("/compress", headers);
  8074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8075. EXPECT_EQ(StatusCode::OK_200, res->status);
  8076. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8077. // Verify pre-compression content is uncompressed
  8078. EXPECT_EQ(test_content, pre_compression_body);
  8079. // Verify post-compression content is compressed
  8080. EXPECT_NE(test_content, post_compression_body);
  8081. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8082. }
  8083. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8084. const std::string test_content =
  8085. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8086. "3456789012345678901234567890";
  8087. std::string pre_compression_body;
  8088. std::string post_compression_body;
  8089. svr_.set_pre_compression_logger(
  8090. [&](const Request & /*req*/, const Response &res) {
  8091. pre_compression_body = res.body;
  8092. });
  8093. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8094. post_compression_body = res.body;
  8095. });
  8096. // Request without compression (use /nocompress endpoint)
  8097. Headers headers;
  8098. auto res = cli_.Get("/nocompress", headers);
  8099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8100. EXPECT_EQ(StatusCode::OK_200, res->status);
  8101. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8102. // Pre-compression logger should not be called when no compression is applied
  8103. EXPECT_TRUE(
  8104. pre_compression_body.empty()); // Pre-compression logger not called
  8105. EXPECT_EQ(
  8106. test_content,
  8107. post_compression_body); // Post-compression logger captures final content
  8108. }
  8109. TEST_F(ServerTest, LoggerSeesContentLength) {
  8110. size_t logged_content_length = 0;
  8111. std::string logged_content_length_header;
  8112. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8113. logged_content_length = res.content_length_;
  8114. logged_content_length_header = res.get_header_value("Content-Length");
  8115. });
  8116. auto res = cli_.Get("/nocompress");
  8117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8118. EXPECT_EQ(StatusCode::OK_200, res->status);
  8119. EXPECT_EQ(res->body.size(), logged_content_length);
  8120. EXPECT_EQ(std::to_string(logged_content_length),
  8121. logged_content_length_header);
  8122. }
  8123. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8124. const std::string test_content =
  8125. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8126. "3456789012345678901234567890";
  8127. std::string pre_compression_body;
  8128. bool pre_logger_called = false;
  8129. // Set only pre-compression logger
  8130. svr_.set_pre_compression_logger(
  8131. [&](const Request & /*req*/, const Response &res) {
  8132. pre_compression_body = res.body;
  8133. pre_logger_called = true;
  8134. });
  8135. Headers headers;
  8136. headers.emplace("Accept-Encoding", "gzip");
  8137. auto res = cli_.Get("/compress", headers);
  8138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8139. EXPECT_EQ(StatusCode::OK_200, res->status);
  8140. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8141. // Verify pre-compression logger was called
  8142. EXPECT_TRUE(pre_logger_called);
  8143. EXPECT_EQ(test_content, pre_compression_body);
  8144. }
  8145. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8146. {
  8147. // Test with Expect: 100-continue header - success case
  8148. // Server returns 100 Continue, client sends body, server returns 200 OK
  8149. Request req;
  8150. req.method = "POST";
  8151. req.path = "/post-large";
  8152. req.set_header("Expect", "100-continue");
  8153. req.body = LARGE_DATA;
  8154. Response res;
  8155. auto error = Error::Success;
  8156. cli_.set_keep_alive(true);
  8157. auto ret = cli_.send(req, res, error);
  8158. EXPECT_TRUE(ret);
  8159. EXPECT_EQ(StatusCode::OK_200, res.status);
  8160. EXPECT_EQ(LARGE_DATA, res.body);
  8161. }
  8162. {
  8163. // Test with Expect: 100-continue header - error case
  8164. // Client should not send the body when server returns an error
  8165. Request req;
  8166. req.method = "POST";
  8167. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8168. req.set_header("Expect", "100-continue");
  8169. req.body = LARGE_DATA;
  8170. Response res;
  8171. auto error = Error::Success;
  8172. auto start = std::chrono::high_resolution_clock::now();
  8173. cli_.set_keep_alive(true);
  8174. auto ret = cli_.send(req, res, error);
  8175. auto end = std::chrono::high_resolution_clock::now();
  8176. auto elapsed =
  8177. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8178. .count();
  8179. // With Expect: 100-continue, request completes successfully but with error
  8180. EXPECT_TRUE(ret);
  8181. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8182. EXPECT_EQ("close", res.get_header_value("Connection"));
  8183. EXPECT_FALSE(cli_.is_socket_open());
  8184. EXPECT_LE(elapsed, 2000);
  8185. }
  8186. {
  8187. // Send an extra GET request to ensure error recovery without hanging
  8188. Request req;
  8189. req.method = "GET";
  8190. req.path = "/hi";
  8191. auto start = std::chrono::high_resolution_clock::now();
  8192. auto res = cli_.send(req);
  8193. auto end = std::chrono::high_resolution_clock::now();
  8194. auto elapsed =
  8195. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8196. .count();
  8197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8198. EXPECT_EQ(StatusCode::OK_200, res->status);
  8199. EXPECT_EQ("Hello World!", res->body);
  8200. EXPECT_LE(elapsed, 500);
  8201. }
  8202. }
  8203. TEST(ZstdDecompressor, ChunkedDecompression) {
  8204. std::string data;
  8205. for (size_t i = 0; i < 32 * 1024; ++i) {
  8206. data.push_back(static_cast<char>('a' + i % 26));
  8207. }
  8208. std::string compressed_data;
  8209. {
  8210. httplib::detail::zstd_compressor compressor;
  8211. bool result = compressor.compress(
  8212. data.data(), data.size(),
  8213. /*last=*/true,
  8214. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8215. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8216. compressed_data_size);
  8217. return true;
  8218. });
  8219. ASSERT_TRUE(result);
  8220. }
  8221. std::string decompressed_data;
  8222. {
  8223. httplib::detail::zstd_decompressor decompressor;
  8224. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8225. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8226. size_t chunk_size = 130;
  8227. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8228. chunk_begin += chunk_size) {
  8229. size_t current_chunk_size =
  8230. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8231. bool result = decompressor.decompress(
  8232. compressed_data.data() + chunk_begin, current_chunk_size,
  8233. [&](const char *decompressed_data_chunk,
  8234. size_t decompressed_data_chunk_size) {
  8235. decompressed_data.insert(decompressed_data.size(),
  8236. decompressed_data_chunk,
  8237. decompressed_data_chunk_size);
  8238. return true;
  8239. });
  8240. ASSERT_TRUE(result);
  8241. }
  8242. }
  8243. ASSERT_EQ(data, decompressed_data);
  8244. }
  8245. TEST(ZstdDecompressor, Decompress) {
  8246. std::string original_text = "Compressed with ZSTD";
  8247. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8248. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8249. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8250. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8251. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8252. std::string decompressed_data;
  8253. {
  8254. httplib::detail::zstd_decompressor decompressor;
  8255. bool result = decompressor.decompress(
  8256. compressed_data.data(), compressed_data.size(),
  8257. [&](const char *decompressed_data_chunk,
  8258. size_t decompressed_data_chunk_size) {
  8259. decompressed_data.insert(decompressed_data.size(),
  8260. decompressed_data_chunk,
  8261. decompressed_data_chunk_size);
  8262. return true;
  8263. });
  8264. ASSERT_TRUE(result);
  8265. }
  8266. ASSERT_EQ(original_text, decompressed_data);
  8267. }
  8268. #endif
  8269. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8270. // separate chunks so that the server sees each part in its own read(). Used to
  8271. // place a read boundary at a specific offset of a request body.
  8272. static bool send_request_in_parts(time_t read_timeout_sec,
  8273. const std::vector<std::string> &parts,
  8274. std::string *resp = nullptr,
  8275. int port = PORT) {
  8276. auto error = Error::Success;
  8277. auto client_sock = detail::create_client_socket(
  8278. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8279. /*connection_timeout_sec=*/5, 0,
  8280. /*read_timeout_sec=*/5, 0,
  8281. /*write_timeout_sec=*/5, 0, std::string(), error);
  8282. if (client_sock == INVALID_SOCKET) { return false; }
  8283. auto ret = detail::process_client_socket(
  8284. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8285. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8286. for (size_t i = 0; i < parts.size(); i++) {
  8287. const auto &part = parts[i];
  8288. if (part.size() !=
  8289. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8290. return false;
  8291. }
  8292. if (i + 1 < parts.size()) {
  8293. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8294. }
  8295. }
  8296. char buf[512];
  8297. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8298. while (line_reader.getline()) {
  8299. if (resp) { *resp += line_reader.ptr(); }
  8300. }
  8301. return true;
  8302. });
  8303. detail::close_socket(client_sock);
  8304. return ret;
  8305. }
  8306. // Sends a raw request to a server listening at HOST:PORT.
  8307. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8308. std::string *resp = nullptr, int port = PORT) {
  8309. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8310. }
  8311. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8312. Server svr;
  8313. std::string header_value;
  8314. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8315. header_value = req.get_header_value("foo");
  8316. res.set_content("ok", "text/plain");
  8317. });
  8318. thread t = thread([&] { svr.listen(HOST, PORT); });
  8319. auto se = detail::scope_exit([&] {
  8320. svr.stop();
  8321. t.join();
  8322. ASSERT_FALSE(svr.is_running());
  8323. });
  8324. svr.wait_until_ready();
  8325. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8326. // like characters are not treated the same - use vertical tab and escape.
  8327. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8328. "foo: \t \v bar \x1B\t \r\n"
  8329. "Connection: close\r\n"
  8330. "\r\n";
  8331. std::string res;
  8332. ASSERT_TRUE(send_request(5, req, &res));
  8333. EXPECT_EQ(header_value, "");
  8334. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8335. }
  8336. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8337. Server svr;
  8338. std::string received;
  8339. svr.Get("/order", [&](const Request &req, Response &res) {
  8340. received = entries_to_string(req.headers);
  8341. res.set_content("ok", "text/plain");
  8342. });
  8343. auto port = svr.bind_to_any_port(HOST);
  8344. thread t = thread([&] { svr.listen_after_bind(); });
  8345. auto se = detail::scope_exit([&] {
  8346. svr.stop();
  8347. t.join();
  8348. ASSERT_FALSE(svr.is_running());
  8349. });
  8350. svr.wait_until_ready();
  8351. const std::string req = "GET /order HTTP/1.1\r\n"
  8352. "X-First: 1\r\n"
  8353. "X-Dup: a\r\n"
  8354. "X-Second: 2\r\n"
  8355. "X-Dup: b\r\n"
  8356. "Connection: close\r\n"
  8357. "\r\n";
  8358. std::string res;
  8359. ASSERT_TRUE(send_request(5, req, &res, port));
  8360. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8361. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8362. }
  8363. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8364. Server svr;
  8365. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8366. res.set_header("Set-Cookie", "first=1");
  8367. res.set_header("X-Between", "y");
  8368. res.set_header("Set-Cookie", "second=2");
  8369. res.set_content("ok", "text/plain");
  8370. });
  8371. auto port = svr.bind_to_any_port(HOST);
  8372. thread t = thread([&] { svr.listen_after_bind(); });
  8373. auto se = detail::scope_exit([&] {
  8374. svr.stop();
  8375. t.join();
  8376. ASSERT_FALSE(svr.is_running());
  8377. });
  8378. svr.wait_until_ready();
  8379. Client cli(HOST, port);
  8380. auto res = cli.Get("/cookies");
  8381. ASSERT_TRUE(res);
  8382. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8383. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8384. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8385. }
  8386. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8387. Server svr;
  8388. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8389. auto i = new int(0);
  8390. res.set_header("Trailer", "X-Safe, X-Reflected");
  8391. res.set_chunked_content_provider(
  8392. "text/plain",
  8393. [i](size_t /*offset*/, DataSink &sink) {
  8394. if (*i == 0) {
  8395. sink.os << "body";
  8396. } else {
  8397. Headers trailer;
  8398. // A valid trailer that must survive.
  8399. trailer.emplace("X-Safe", "safe");
  8400. // Attacker-controlled value carrying CR/LF (response splitting).
  8401. trailer.emplace("X-Reflected",
  8402. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8403. // Attacker-controlled name carrying CR/LF.
  8404. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8405. sink.done_with_trailer(trailer);
  8406. }
  8407. (*i)++;
  8408. return true;
  8409. },
  8410. [i](bool /*success*/) { delete i; });
  8411. });
  8412. thread t = thread([&] { svr.listen(HOST, PORT); });
  8413. auto se = detail::scope_exit([&] {
  8414. svr.stop();
  8415. t.join();
  8416. ASSERT_FALSE(svr.is_running());
  8417. });
  8418. svr.wait_until_ready();
  8419. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8420. "Host: " + HOST +
  8421. "\r\n"
  8422. "Connection: close\r\n"
  8423. "\r\n";
  8424. std::string res;
  8425. ASSERT_TRUE(send_request(5, req, &res));
  8426. // The injected fields must not appear anywhere in the raw response.
  8427. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8428. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8429. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8430. // Invalid trailers are dropped entirely, matching set_header().
  8431. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8432. // The valid trailer still passes through.
  8433. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8434. }
  8435. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8436. Server svr;
  8437. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8438. // res.headers is a public field an application can populate directly,
  8439. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8440. // A valid header that must survive.
  8441. res.headers.emplace("X-Safe", "safe");
  8442. // Attacker-controlled value carrying CR/LF (response splitting).
  8443. res.headers.emplace("X-Reflected",
  8444. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8445. // Attacker-controlled name carrying CR/LF.
  8446. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8447. res.set_content("body", "text/plain");
  8448. });
  8449. thread t = thread([&] { svr.listen(HOST, PORT); });
  8450. auto se = detail::scope_exit([&] {
  8451. svr.stop();
  8452. t.join();
  8453. ASSERT_FALSE(svr.is_running());
  8454. });
  8455. svr.wait_until_ready();
  8456. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8457. "Host: " + HOST +
  8458. "\r\n"
  8459. "Connection: close\r\n"
  8460. "\r\n";
  8461. std::string res;
  8462. ASSERT_TRUE(send_request(5, req, &res));
  8463. // The injected fields must not appear anywhere in the raw response.
  8464. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8465. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8466. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8467. // Invalid headers are dropped entirely, matching set_header().
  8468. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8469. // The valid header still passes through.
  8470. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8471. }
  8472. // Forward declaration: in split builds split.py strips `inline` and moves the
  8473. // definition into httplib.cc, so detail::write_request_line is not visible from
  8474. // the public httplib.h. Re-declaring it here lets the tests link against the
  8475. // symbol in both header-only and split builds.
  8476. namespace httplib {
  8477. namespace detail {
  8478. ssize_t write_request_line(Stream &strm, const std::string &method,
  8479. const std::string &path);
  8480. } // namespace detail
  8481. } // namespace httplib
  8482. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8483. // A well-formed target is written verbatim.
  8484. {
  8485. detail::BufferStream strm;
  8486. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8487. EXPECT_GT(n, 0);
  8488. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8489. }
  8490. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8491. // otherwise it splits the request line and injects a header or a whole
  8492. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8493. // when path encoding is disabled.
  8494. const std::string evil_targets[] = {
  8495. "/a\r\nInjected: pwned",
  8496. "/a\rInjected",
  8497. "/a\nInjected",
  8498. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8499. };
  8500. for (const auto &evil : evil_targets) {
  8501. detail::BufferStream strm;
  8502. auto n = detail::write_request_line(strm, "GET", evil);
  8503. EXPECT_LT(n, 0);
  8504. EXPECT_TRUE(strm.get_buffer().empty());
  8505. }
  8506. }
  8507. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8508. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8509. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8510. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8511. // client must fail cleanly with Error::Write instead of putting a
  8512. // request-line-less, header-injecting request on the wire.
  8513. Server svr;
  8514. svr.Get("/a", [](const Request &, Response &res) {
  8515. res.set_content("ok", "text/plain");
  8516. });
  8517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8518. auto se = detail::scope_exit([&] {
  8519. svr.stop();
  8520. thread.join();
  8521. ASSERT_FALSE(svr.is_running());
  8522. });
  8523. svr.wait_until_ready();
  8524. {
  8525. Client cli(HOST, PORT);
  8526. cli.set_path_encode(false);
  8527. // The request is rejected before anything is written, so the connection
  8528. // stays silent and the subsequent response read would otherwise block for
  8529. // the full default read timeout. Shorten it -- the assertion is on the
  8530. // error, not the timeout.
  8531. cli.set_read_timeout(1, 0);
  8532. auto res = cli.Get("/a\r\nInjected: pwned");
  8533. EXPECT_FALSE(res);
  8534. EXPECT_EQ(Error::Write, res.error());
  8535. }
  8536. }
  8537. // Sends a raw request and verifies that there isn't a crash or exception.
  8538. static void test_raw_request(const std::string &req,
  8539. std::string *out = nullptr) {
  8540. Server svr;
  8541. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8542. res.set_content("ok", "text/plain");
  8543. });
  8544. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8545. res.set_content("ok", "text/plain");
  8546. });
  8547. svr.Get("/header_field_value_check",
  8548. [&](const Request & /*req*/, Response &res) {
  8549. res.set_content("ok", "text/plain");
  8550. });
  8551. svr.CustomRoute("PROPFIND", "/dav",
  8552. [&](const Request & /*req*/, Response &res) {
  8553. res.status = StatusCode::MultiStatus_207;
  8554. });
  8555. // Server read timeout must be longer than the client read timeout for the
  8556. // bug to reproduce, probably to force the server to process a request
  8557. // without a trailing blank line.
  8558. const time_t client_read_timeout_sec = 1;
  8559. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8560. bool listen_thread_ok = false;
  8561. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8562. auto se = detail::scope_exit([&] {
  8563. svr.stop();
  8564. t.join();
  8565. ASSERT_FALSE(svr.is_running());
  8566. EXPECT_TRUE(listen_thread_ok);
  8567. });
  8568. svr.wait_until_ready();
  8569. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8570. }
  8571. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8572. // A certain header line causes an exception if the header property is parsed
  8573. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8574. test_raw_request(
  8575. "GET /hi HTTP/1.1\r\n"
  8576. " : "
  8577. " "
  8578. " ");
  8579. }
  8580. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8581. // A certain header line causes an exception if the header property *name* is
  8582. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8583. // greedy matcher and requires backtracking when there are a lot of ":"
  8584. // characters.
  8585. // This occurs with libc++ but not libstdc++.
  8586. test_raw_request(
  8587. "GET /hi HTTP/1.1\r\n"
  8588. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8589. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8590. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8591. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8592. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8593. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8594. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8595. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8596. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8597. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8598. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8599. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8600. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8601. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8602. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8603. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8604. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8605. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8606. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8607. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8608. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8609. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8610. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8611. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8612. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8613. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8614. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8615. "&&&%%%");
  8616. }
  8617. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8618. // Make sure this doesn't crash the server.
  8619. // In a previous version of the header line regex, the "\r" rendered the line
  8620. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8621. // a new position where the leading white space ended and the field value
  8622. // began.
  8623. // The crash occurs with libc++ but not libstdc++.
  8624. test_raw_request("GET /hi HTTP/1.1\r\n"
  8625. "a:" +
  8626. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8627. "\r\n"
  8628. "\r\n");
  8629. }
  8630. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8631. std::string out;
  8632. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8633. "Content-Type: text/plain\r\n"
  8634. "Transfer-Encoding: chunked\r\n"
  8635. "\r\n"
  8636. "nothex\r\n",
  8637. &out);
  8638. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8639. }
  8640. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8641. std::string out;
  8642. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8643. "Content-Type: text/plain\r\n"
  8644. "Transfer-Encoding: chunked\r\n"
  8645. "\r\n"
  8646. "3\r\n"
  8647. "xyz\r\n"
  8648. "NaN\r\n",
  8649. &out);
  8650. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8651. }
  8652. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8653. std::string out;
  8654. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8655. "Content-Type: text/plain\r\n"
  8656. "Transfer-Encoding: chunked\r\n"
  8657. "\r\n"
  8658. // Length is too large for 64 bits.
  8659. "1ffffffffffffffff\r\n"
  8660. "xyz\r\n",
  8661. &out);
  8662. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8663. }
  8664. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8665. test_raw_request("GET /hi HTTP/1.1\r\n"
  8666. "Content-Type: text/plain\r\n\r");
  8667. }
  8668. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8669. std::string out;
  8670. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8671. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8672. }
  8673. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8674. Server svr;
  8675. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8676. EXPECT_TRUE(!req.remote_addr.empty());
  8677. });
  8678. thread t = thread([&] { svr.listen(HOST, PORT); });
  8679. auto se = detail::scope_exit([&] {
  8680. svr.stop();
  8681. t.join();
  8682. ASSERT_FALSE(svr.is_running());
  8683. });
  8684. svr.wait_until_ready();
  8685. // Send an invalid request line to trigger Bad Request
  8686. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8687. std::string out;
  8688. ASSERT_TRUE(send_request(5, bad_req, &out));
  8689. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8690. }
  8691. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8692. // answered right away rather than blocking on a read that waits for EOF.
  8693. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8694. std::string out;
  8695. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8696. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8697. }
  8698. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8699. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8700. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8701. for (const auto *method : methods) {
  8702. Server svr;
  8703. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8704. EXPECT_FALSE(svr.is_valid()) << method;
  8705. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8706. }
  8707. }
  8708. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8709. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8710. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8711. for (const auto *method : methods) {
  8712. Server svr;
  8713. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8714. EXPECT_FALSE(svr.is_valid()) << method;
  8715. }
  8716. }
  8717. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8718. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8719. "COPY", "MOVE", "LOCK",
  8720. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8721. Server svr;
  8722. for (const auto *method : methods) {
  8723. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8724. }
  8725. EXPECT_TRUE(svr.is_valid());
  8726. }
  8727. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8728. Server svr;
  8729. svr.CustomRoute("POST", "/x",
  8730. [](const Request &, Response &, const ContentReader &) {});
  8731. EXPECT_FALSE(svr.is_valid());
  8732. }
  8733. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8734. Server svr;
  8735. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8736. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8737. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8738. EXPECT_FALSE(svr.is_valid());
  8739. }
  8740. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8741. Server svr;
  8742. auto captured = Error::Success;
  8743. svr.set_error_logger(
  8744. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8745. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8746. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8747. }
  8748. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8749. std::string out;
  8750. std::string request(
  8751. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8752. test_raw_request(request, &out);
  8753. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8754. }
  8755. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8756. std::string out;
  8757. std::string request(
  8758. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8759. test_raw_request(request, &out);
  8760. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8761. }
  8762. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8763. std::string out;
  8764. std::string request(
  8765. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8766. test_raw_request(request, &out);
  8767. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8768. }
  8769. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8770. std::string out;
  8771. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8772. "Test: \r\n\r\n",
  8773. &out);
  8774. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8775. }
  8776. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8777. Server svr;
  8778. std::string x_custom;
  8779. std::string cookie;
  8780. std::string xff;
  8781. std::string x_unicode;
  8782. std::string x_iis;
  8783. svr.Get("/check", [&](const Request &req, Response &res) {
  8784. x_custom = req.get_header_value("X-Custom");
  8785. cookie = req.get_header_value("Cookie");
  8786. xff = req.get_header_value("X-Forwarded-For");
  8787. x_unicode = req.get_header_value("X-Unicode");
  8788. x_iis = req.get_header_value("X-IIS");
  8789. res.set_content("ok", "text/plain");
  8790. });
  8791. thread t = thread([&] { svr.listen(HOST, PORT); });
  8792. auto se = detail::scope_exit([&] {
  8793. svr.stop();
  8794. t.join();
  8795. ASSERT_FALSE(svr.is_running());
  8796. });
  8797. svr.wait_until_ready();
  8798. const std::string req = "GET /check HTTP/1.1\r\n"
  8799. "Host: localhost\r\n"
  8800. "X-Custom: a%0D%0AInjected: b\r\n"
  8801. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8802. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8803. "X-Unicode: %E3%81%82\r\n"
  8804. "X-IIS: %u00E9\r\n"
  8805. "Connection: close\r\n"
  8806. "\r\n";
  8807. std::string res;
  8808. ASSERT_TRUE(send_request(5, req, &res));
  8809. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8810. // Every value must be returned verbatim (wire form), with no decoding.
  8811. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8812. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8813. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8814. EXPECT_EQ("%E3%81%82", x_unicode);
  8815. EXPECT_EQ("%u00E9", x_iis);
  8816. }
  8817. // Applications that previously relied on automatic percent-decoding can
  8818. // reproduce the old behavior by explicitly calling decode_path_component()
  8819. // or, for RFC 3986 conformance, decode_uri_component().
  8820. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8821. Server svr;
  8822. std::string decoded;
  8823. svr.Get("/check", [&](const Request &req, Response &res) {
  8824. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8825. res.set_content("ok", "text/plain");
  8826. });
  8827. thread t = thread([&] { svr.listen(HOST, PORT); });
  8828. auto se = detail::scope_exit([&] {
  8829. svr.stop();
  8830. t.join();
  8831. ASSERT_FALSE(svr.is_running());
  8832. });
  8833. svr.wait_until_ready();
  8834. const std::string req = "GET /check HTTP/1.1\r\n"
  8835. "Host: localhost\r\n"
  8836. "X-Custom: hello%20world\r\n"
  8837. "Connection: close\r\n"
  8838. "\r\n";
  8839. std::string res;
  8840. ASSERT_TRUE(send_request(5, req, &res));
  8841. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8842. EXPECT_EQ("hello world", decoded);
  8843. }
  8844. // Regression test for #2033. Browsers send Referer values that include
  8845. // percent-encoded characters such as %0A inside the URL. Decoding the
  8846. // header value would either trip the post-decode CR/LF/NUL guard (the
  8847. // original bug, returning 400) or, after that guard was relaxed, silently
  8848. // store a literal LF — both unacceptable. The wire form must round-trip.
  8849. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8850. Server svr;
  8851. std::string referer;
  8852. svr.Get("/check", [&](const Request &req, Response &res) {
  8853. referer = req.get_header_value("Referer");
  8854. res.set_content("ok", "text/plain");
  8855. });
  8856. thread t = thread([&] { svr.listen(HOST, PORT); });
  8857. auto se = detail::scope_exit([&] {
  8858. svr.stop();
  8859. t.join();
  8860. ASSERT_FALSE(svr.is_running());
  8861. });
  8862. svr.wait_until_ready();
  8863. const std::string req = "GET /check HTTP/1.1\r\n"
  8864. "Host: localhost\r\n"
  8865. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8866. "Connection: close\r\n"
  8867. "\r\n";
  8868. std::string res;
  8869. ASSERT_TRUE(send_request(5, req, &res));
  8870. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8871. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8872. }
  8873. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8874. Server svr;
  8875. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8876. res.set_header("Cache-Control", "no-cache");
  8877. res.set_chunked_content_provider(
  8878. "text/event-stream", [](size_t offset, DataSink &sink) {
  8879. std::string s = "data:";
  8880. s += std::to_string(offset);
  8881. s += "\n\n";
  8882. auto ret = sink.write(s.data(), s.size());
  8883. EXPECT_TRUE(ret);
  8884. std::this_thread::sleep_for(std::chrono::seconds(1));
  8885. return true;
  8886. });
  8887. });
  8888. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8889. svr.wait_until_ready();
  8890. Client client(HOST, PORT);
  8891. const Headers headers = {{"Accept", "text/event-stream"}};
  8892. auto get_thread = std::thread([&client, &headers]() {
  8893. auto res = client.Get(
  8894. "/events", headers,
  8895. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8896. });
  8897. auto se = detail::scope_exit([&] {
  8898. svr.stop();
  8899. get_thread.join();
  8900. listen_thread.join();
  8901. ASSERT_FALSE(svr.is_running());
  8902. });
  8903. // Give GET time to get a few messages.
  8904. std::this_thread::sleep_for(std::chrono::seconds(2));
  8905. }
  8906. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8907. httplib::Server svr;
  8908. svr.Post("/hi",
  8909. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8910. res.status = StatusCode::OK_200;
  8911. });
  8912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8913. svr.wait_until_ready();
  8914. Client cli(HOST, PORT);
  8915. auto res = cli.Post("/hi", "data", "text/plain");
  8916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8917. EXPECT_EQ(StatusCode::OK_200, res->status);
  8918. svr.stop();
  8919. thread.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. res = cli.Post("/hi", "data", "text/plain");
  8922. ASSERT_FALSE(res);
  8923. }
  8924. TEST(ServerStopTest, ListenFailure) {
  8925. Server svr;
  8926. auto t = thread([&]() {
  8927. auto ret = svr.listen("????", PORT);
  8928. EXPECT_FALSE(ret);
  8929. });
  8930. svr.wait_until_ready();
  8931. svr.stop();
  8932. t.join();
  8933. }
  8934. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8935. TEST(ServerStopTest, Decommision) {
  8936. Server svr;
  8937. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8938. for (int i = 0; i < 4; i++) {
  8939. auto is_even = !(i % 2);
  8940. std::thread t{[&] {
  8941. try {
  8942. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8943. if (is_even) {
  8944. throw std::runtime_error("Some thing that happens to go wrong.");
  8945. }
  8946. svr.listen(HOST, PORT);
  8947. } catch (...) { svr.decommission(); }
  8948. }};
  8949. svr.wait_until_ready();
  8950. // Server is up
  8951. {
  8952. Client cli(HOST, PORT);
  8953. auto res = cli.Get("/hi");
  8954. if (is_even) {
  8955. EXPECT_FALSE(res);
  8956. } else {
  8957. EXPECT_TRUE(res);
  8958. EXPECT_EQ("hi...", res->body);
  8959. }
  8960. }
  8961. svr.stop();
  8962. t.join();
  8963. // Server is down...
  8964. {
  8965. Client cli(HOST, PORT);
  8966. auto res = cli.Get("/hi");
  8967. EXPECT_FALSE(res);
  8968. }
  8969. }
  8970. }
  8971. #endif
  8972. // Helper function for string body upload progress tests
  8973. template <typename SetupHandler, typename ClientCall>
  8974. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8975. ClientCall &&client_call,
  8976. const string &body) {
  8977. Server svr;
  8978. setup_handler(svr);
  8979. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8980. auto se = detail::scope_exit([&] {
  8981. svr.stop();
  8982. t.join();
  8983. });
  8984. svr.wait_until_ready();
  8985. Client cli(HOST, PORT);
  8986. vector<uint64_t> progress_values;
  8987. bool progress_called = false;
  8988. auto res =
  8989. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8990. progress_values.push_back(current);
  8991. progress_called = true;
  8992. return true;
  8993. });
  8994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8995. EXPECT_EQ(200, res->status);
  8996. EXPECT_TRUE(progress_called);
  8997. }
  8998. TEST(UploadProgressTest, PostStringBodyBasic) {
  8999. TestStringBodyUploadProgress(
  9000. [](Server &svr) {
  9001. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9002. res.set_content("received", "text/plain");
  9003. });
  9004. },
  9005. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9006. return cli.Post("/test", body, "text/plain", progress_callback);
  9007. },
  9008. "test data for upload progress");
  9009. }
  9010. TEST(UploadProgressTest, PutStringBodyBasic) {
  9011. TestStringBodyUploadProgress(
  9012. [](Server &svr) {
  9013. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9014. res.set_content("put received", "text/plain");
  9015. });
  9016. },
  9017. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9018. return cli.Put("/test", body, "text/plain", progress_callback);
  9019. },
  9020. "put test data for upload progress");
  9021. }
  9022. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9023. TestStringBodyUploadProgress(
  9024. [](Server &svr) {
  9025. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9026. res.set_content("patch received", "text/plain");
  9027. });
  9028. },
  9029. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9030. return cli.Patch("/test", body, "text/plain", progress_callback);
  9031. },
  9032. "patch test data for upload progress");
  9033. }
  9034. // Helper function for content provider upload progress tests
  9035. template <typename SetupHandler, typename ClientCall>
  9036. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9037. ClientCall &&client_call) {
  9038. Server svr;
  9039. setup_handler(svr);
  9040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9041. auto se = detail::scope_exit([&] {
  9042. svr.stop();
  9043. t.join();
  9044. });
  9045. svr.wait_until_ready();
  9046. Client cli(HOST, PORT);
  9047. vector<uint64_t> progress_values;
  9048. auto res =
  9049. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9050. progress_values.push_back(current);
  9051. return true;
  9052. });
  9053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9054. EXPECT_EQ(200, res->status);
  9055. EXPECT_FALSE(progress_values.empty());
  9056. }
  9057. TEST(UploadProgressTest, PostContentProviderProgress) {
  9058. TestContentProviderUploadProgress(
  9059. [](Server &svr) {
  9060. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9061. res.set_content("provider received", "text/plain");
  9062. });
  9063. },
  9064. [](Client &cli, UploadProgress progress_callback) {
  9065. return cli.Post(
  9066. "/test", 10,
  9067. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9068. sink.os << "test data";
  9069. return true;
  9070. },
  9071. "text/plain", progress_callback);
  9072. });
  9073. }
  9074. // Helper function for multipart upload progress tests
  9075. template <typename SetupHandler, typename ClientCall>
  9076. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9077. ClientCall &&client_call,
  9078. const string &endpoint) {
  9079. Server svr;
  9080. setup_handler(svr);
  9081. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9082. auto se = detail::scope_exit([&] {
  9083. svr.stop();
  9084. t.join();
  9085. });
  9086. svr.wait_until_ready();
  9087. Client cli(HOST, PORT);
  9088. vector<uint64_t> progress_values;
  9089. UploadFormDataItems items = {
  9090. {"field1", "value1", "", ""},
  9091. {"field2", "longer value for progress tracking test", "", ""},
  9092. {"file1", "file content data for upload progress", "test.txt",
  9093. "text/plain"}};
  9094. auto res = client_call(cli, endpoint, items,
  9095. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9096. progress_values.push_back(current);
  9097. return true;
  9098. });
  9099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9100. EXPECT_EQ(200, res->status);
  9101. EXPECT_FALSE(progress_values.empty());
  9102. }
  9103. TEST(UploadProgressTest, PostMultipartProgress) {
  9104. TestMultipartUploadProgress(
  9105. [](Server &svr) {
  9106. svr.Post("/multipart", [](const Request &req, Response &res) {
  9107. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9108. res.set_content("multipart received", "text/plain");
  9109. });
  9110. },
  9111. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9112. UploadProgress progress_callback) {
  9113. return cli.Post(endpoint, items, progress_callback);
  9114. },
  9115. "/multipart");
  9116. }
  9117. // Helper function for basic download progress tests
  9118. template <typename SetupHandler, typename ClientCall>
  9119. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9120. ClientCall &&client_call, const string &endpoint,
  9121. size_t expected_content_size) {
  9122. Server svr;
  9123. setup_handler(svr);
  9124. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9125. auto se = detail::scope_exit([&] {
  9126. svr.stop();
  9127. t.join();
  9128. });
  9129. svr.wait_until_ready();
  9130. Client cli(HOST, PORT);
  9131. vector<uint64_t> progress_values;
  9132. auto res = client_call(cli, endpoint,
  9133. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9134. progress_values.push_back(current);
  9135. return true;
  9136. });
  9137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9138. EXPECT_EQ(200, res->status);
  9139. EXPECT_FALSE(progress_values.empty());
  9140. EXPECT_EQ(expected_content_size, res->body.size());
  9141. }
  9142. TEST(DownloadProgressTest, GetBasic) {
  9143. TestBasicDownloadProgress(
  9144. [](Server &svr) {
  9145. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9146. string content(1000, 'D');
  9147. res.set_content(content, "text/plain");
  9148. });
  9149. },
  9150. [](Client &cli, const string &endpoint,
  9151. DownloadProgress progress_callback) {
  9152. return cli.Get(endpoint, progress_callback);
  9153. },
  9154. "/download", 1000u);
  9155. }
  9156. // Helper function for content receiver download progress tests
  9157. template <typename SetupHandler, typename ClientCall>
  9158. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9159. ClientCall &&client_call,
  9160. const string &endpoint,
  9161. size_t expected_content_size) {
  9162. Server svr;
  9163. setup_handler(svr);
  9164. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9165. auto se = detail::scope_exit([&] {
  9166. svr.stop();
  9167. t.join();
  9168. });
  9169. svr.wait_until_ready();
  9170. Client cli(HOST, PORT);
  9171. vector<uint64_t> progress_values;
  9172. string received_body;
  9173. auto res = client_call(
  9174. cli, endpoint,
  9175. [&](const char *data, size_t data_length) -> bool {
  9176. received_body.append(data, data_length);
  9177. return true;
  9178. },
  9179. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9180. progress_values.push_back(current);
  9181. return true;
  9182. });
  9183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9184. EXPECT_EQ(200, res->status);
  9185. EXPECT_FALSE(progress_values.empty());
  9186. EXPECT_EQ(expected_content_size, received_body.size());
  9187. EXPECT_TRUE(res->body.empty());
  9188. }
  9189. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9190. TestContentReceiverDownloadProgress(
  9191. [](Server &svr) {
  9192. svr.Get("/download-receiver",
  9193. [](const Request & /*req*/, Response &res) {
  9194. string content(2000, 'R');
  9195. res.set_content(content, "text/plain");
  9196. });
  9197. },
  9198. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9199. DownloadProgress progress_callback) {
  9200. return cli.Get(endpoint, content_receiver, progress_callback);
  9201. },
  9202. "/download-receiver", 2000u);
  9203. }
  9204. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9205. // A provider reaching a pass with nothing to hand over - an empty buffer
  9206. // popped off a queue, say - must not be taken to mean the body is finished.
  9207. // It used to end the loop with the terminating chunk unwritten while the
  9208. // server still considered the response complete, so the peer waited for an
  9209. // end that never arrived.
  9210. Server svr;
  9211. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9212. auto step = std::make_shared<int>(0);
  9213. res.set_chunked_content_provider("text/plain",
  9214. [step](size_t /*offset*/, DataSink &sink) {
  9215. switch ((*step)++) {
  9216. case 0: sink.write("", 0); break;
  9217. case 1: sink.write("hello", 5); break;
  9218. default: sink.done(); break;
  9219. }
  9220. return true;
  9221. });
  9222. });
  9223. auto port = svr.bind_to_any_port(HOST);
  9224. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9225. auto listen_se = detail::scope_exit([&] {
  9226. svr.stop();
  9227. listen_thread.join();
  9228. ASSERT_FALSE(svr.is_running());
  9229. });
  9230. svr.wait_until_ready();
  9231. Client cli(HOST, port);
  9232. // Without the fix the body is never terminated, so bound the wait rather
  9233. // than letting the test hang on the default read timeout.
  9234. cli.set_read_timeout(5, 0);
  9235. auto res = cli.Get("/stream");
  9236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9237. EXPECT_EQ(StatusCode::OK_200, res->status);
  9238. EXPECT_EQ("hello", res->body);
  9239. }
  9240. TEST(StreamingTest, NoContentLengthStreaming) {
  9241. Server svr;
  9242. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9243. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9244. if (offset < 6) {
  9245. sink.os << (offset < 3 ? "a" : "b");
  9246. } else {
  9247. sink.done();
  9248. }
  9249. return true;
  9250. });
  9251. });
  9252. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9253. auto listen_se = detail::scope_exit([&] {
  9254. svr.stop();
  9255. listen_thread.join();
  9256. ASSERT_FALSE(svr.is_running());
  9257. });
  9258. svr.wait_until_ready();
  9259. Client client(HOST, PORT);
  9260. auto get_thread = std::thread([&client]() {
  9261. std::string s;
  9262. auto res =
  9263. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9264. s += std::string(data, len);
  9265. return true;
  9266. });
  9267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9268. EXPECT_EQ(StatusCode::OK_200, res->status);
  9269. EXPECT_EQ("aaabbb", s);
  9270. });
  9271. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9272. // Give GET time to get a few messages.
  9273. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9274. }
  9275. TEST(MountTest, Unmount) {
  9276. Server svr;
  9277. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9278. auto se = detail::scope_exit([&] {
  9279. svr.stop();
  9280. listen_thread.join();
  9281. ASSERT_FALSE(svr.is_running());
  9282. });
  9283. svr.wait_until_ready();
  9284. Client cli("localhost", PORT);
  9285. svr.set_mount_point("/mount2", "./www2");
  9286. auto res = cli.Get("/");
  9287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9288. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9289. res = cli.Get("/mount2/dir/test.html");
  9290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9291. EXPECT_EQ(StatusCode::OK_200, res->status);
  9292. svr.set_mount_point("/", "./www");
  9293. res = cli.Get("/dir/");
  9294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9295. EXPECT_EQ(StatusCode::OK_200, res->status);
  9296. svr.remove_mount_point("/");
  9297. res = cli.Get("/dir/");
  9298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9300. svr.remove_mount_point("/mount2");
  9301. res = cli.Get("/mount2/dir/test.html");
  9302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9304. }
  9305. TEST(MountTest, PathSegmentBoundary) {
  9306. Server svr;
  9307. svr.set_mount_point("/mount2", "./www2");
  9308. svr.set_mount_point("/", "./www");
  9309. auto port = svr.bind_to_any_port(HOST);
  9310. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9311. auto se = detail::scope_exit([&] {
  9312. svr.stop();
  9313. listen_thread.join();
  9314. ASSERT_FALSE(svr.is_running());
  9315. });
  9316. svr.wait_until_ready();
  9317. Client cli(HOST, port);
  9318. auto res = cli.Get("/mount2/dir/test.html");
  9319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9320. EXPECT_EQ(StatusCode::OK_200, res->status);
  9321. // "/mount2" must not match part-way through a path segment.
  9322. res = cli.Get("/mount2dir/test.html");
  9323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9324. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9325. // A mount point ending in '/' keeps matching every path below it.
  9326. res = cli.Get("/dir/test.html");
  9327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9328. EXPECT_EQ(StatusCode::OK_200, res->status);
  9329. }
  9330. TEST(MountTest, Redicect) {
  9331. Server svr;
  9332. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9333. auto se = detail::scope_exit([&] {
  9334. svr.stop();
  9335. listen_thread.join();
  9336. ASSERT_FALSE(svr.is_running());
  9337. });
  9338. svr.set_mount_point("/", "./www");
  9339. svr.wait_until_ready();
  9340. Client cli("localhost", PORT);
  9341. auto res = cli.Get("/dir/");
  9342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9343. EXPECT_EQ(StatusCode::OK_200, res->status);
  9344. res = cli.Get("/dir");
  9345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9346. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9347. res = cli.Get("/file");
  9348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9349. EXPECT_EQ(StatusCode::OK_200, res->status);
  9350. res = cli.Get("/file/");
  9351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9353. cli.set_follow_location(true);
  9354. res = cli.Get("/dir");
  9355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9356. EXPECT_EQ(StatusCode::OK_200, res->status);
  9357. }
  9358. TEST(MountTest, MultibytesPathName) {
  9359. Server svr;
  9360. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9361. auto se = detail::scope_exit([&] {
  9362. svr.stop();
  9363. listen_thread.join();
  9364. ASSERT_FALSE(svr.is_running());
  9365. });
  9366. svr.set_mount_point("/", "./www");
  9367. svr.wait_until_ready();
  9368. Client cli("localhost", PORT);
  9369. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9371. EXPECT_EQ(StatusCode::OK_200, res->status);
  9372. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9373. }
  9374. #ifdef _WIN32
  9375. // Issue #2435: mmap::open() must succeed even when another handle holds
  9376. // the file open for writing (e.g. an active log file).
  9377. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9378. const char *path = "mmap_concurrent_writer_test.txt";
  9379. const char *content = "hello";
  9380. {
  9381. std::ofstream f(path, std::ios::binary);
  9382. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9383. }
  9384. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9385. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9386. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9387. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9388. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9389. detail::mmap m(path);
  9390. ASSERT_TRUE(m.is_open());
  9391. EXPECT_EQ(strlen(content), m.size());
  9392. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9393. }
  9394. #endif
  9395. #ifndef _WIN32
  9396. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9397. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9398. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9399. TEST(MmapTest, FailedMappingIsNotOpen) {
  9400. const char *path = "./mmap_failed_mapping_test_dir";
  9401. ASSERT_EQ(0, ::mkdir(path, 0755));
  9402. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9403. detail::mmap m(path);
  9404. EXPECT_FALSE(m.is_open());
  9405. EXPECT_EQ(0U, m.size());
  9406. EXPECT_NE(static_cast<const void *>(m.data()),
  9407. static_cast<const void *>(MAP_FAILED));
  9408. }
  9409. #endif
  9410. TEST(KeepAliveTest, ReadTimeout) {
  9411. Server svr;
  9412. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9413. std::this_thread::sleep_for(std::chrono::seconds(2));
  9414. res.set_content("a", "text/plain");
  9415. });
  9416. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9417. res.set_content("b", "text/plain");
  9418. });
  9419. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9420. auto se = detail::scope_exit([&] {
  9421. svr.stop();
  9422. listen_thread.join();
  9423. ASSERT_FALSE(svr.is_running());
  9424. });
  9425. svr.wait_until_ready();
  9426. Client cli("localhost", PORT);
  9427. cli.set_keep_alive(true);
  9428. cli.set_read_timeout(std::chrono::seconds(1));
  9429. auto resa = cli.Get("/a");
  9430. ASSERT_FALSE(resa);
  9431. EXPECT_EQ(Error::Read, resa.error());
  9432. auto resb = cli.Get("/b");
  9433. ASSERT_TRUE(resb);
  9434. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9435. EXPECT_EQ("b", resb->body);
  9436. }
  9437. TEST(KeepAliveTest, MaxCount) {
  9438. size_t keep_alive_max_count = 3;
  9439. Server svr;
  9440. svr.set_keep_alive_max_count(keep_alive_max_count);
  9441. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9442. res.set_content("Hello World!", "text/plain");
  9443. });
  9444. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9445. auto se = detail::scope_exit([&] {
  9446. svr.stop();
  9447. listen_thread.join();
  9448. ASSERT_FALSE(svr.is_running());
  9449. });
  9450. svr.wait_until_ready();
  9451. Client cli(HOST, PORT);
  9452. cli.set_keep_alive(true);
  9453. for (size_t i = 0; i < 5; i++) {
  9454. auto result = cli.Get("/hi");
  9455. ASSERT_TRUE(result);
  9456. EXPECT_EQ(StatusCode::OK_200, result->status);
  9457. if (i == keep_alive_max_count - 1) {
  9458. EXPECT_EQ("close", result->get_header_value("Connection"));
  9459. } else {
  9460. EXPECT_FALSE(result->has_header("Connection"));
  9461. }
  9462. }
  9463. }
  9464. TEST(KeepAliveTest, Issue1041) {
  9465. Server svr;
  9466. svr.set_keep_alive_timeout(3);
  9467. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9468. res.set_content("Hello World!", "text/plain");
  9469. });
  9470. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9471. auto se = detail::scope_exit([&] {
  9472. svr.stop();
  9473. listen_thread.join();
  9474. ASSERT_FALSE(svr.is_running());
  9475. });
  9476. svr.wait_until_ready();
  9477. Client cli(HOST, PORT);
  9478. cli.set_keep_alive(true);
  9479. auto result = cli.Get("/hi");
  9480. ASSERT_TRUE(result);
  9481. EXPECT_EQ(StatusCode::OK_200, result->status);
  9482. std::this_thread::sleep_for(std::chrono::seconds(5));
  9483. result = cli.Get("/hi");
  9484. ASSERT_TRUE(result);
  9485. EXPECT_EQ(StatusCode::OK_200, result->status);
  9486. }
  9487. TEST(KeepAliveTest, Issue1959) {
  9488. Server svr;
  9489. svr.set_keep_alive_timeout(5);
  9490. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9491. res.set_content("a", "text/plain");
  9492. });
  9493. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9494. auto se = detail::scope_exit([&] {
  9495. if (!svr.is_running()) return;
  9496. svr.stop();
  9497. listen_thread.join();
  9498. ASSERT_FALSE(svr.is_running());
  9499. });
  9500. svr.wait_until_ready();
  9501. Client cli("localhost", PORT);
  9502. cli.set_keep_alive(true);
  9503. using namespace std::chrono;
  9504. auto start = steady_clock::now();
  9505. cli.Get("/a");
  9506. svr.stop();
  9507. listen_thread.join();
  9508. auto end = steady_clock::now();
  9509. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9510. EXPECT_LT(elapsed, 5000);
  9511. }
  9512. #ifdef CPPHTTPLIB_SSL_ENABLED
  9513. TEST(KeepAliveTest, SSLClientReconnection) {
  9514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9515. ASSERT_TRUE(svr.is_valid());
  9516. svr.set_keep_alive_timeout(1);
  9517. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9518. res.set_content("Hello World!", "text/plain");
  9519. });
  9520. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9521. auto se = detail::scope_exit([&] {
  9522. svr.stop();
  9523. listen_thread.join();
  9524. ASSERT_FALSE(svr.is_running());
  9525. });
  9526. svr.wait_until_ready();
  9527. SSLClient cli(HOST, PORT);
  9528. cli.enable_server_certificate_verification(false);
  9529. cli.set_keep_alive(true);
  9530. auto result = cli.Get("/hi");
  9531. ASSERT_TRUE(result);
  9532. EXPECT_EQ(StatusCode::OK_200, result->status);
  9533. result = cli.Get("/hi");
  9534. ASSERT_TRUE(result);
  9535. EXPECT_EQ(StatusCode::OK_200, result->status);
  9536. std::this_thread::sleep_for(std::chrono::seconds(2));
  9537. // Recoonect
  9538. result = cli.Get("/hi");
  9539. ASSERT_TRUE(result);
  9540. EXPECT_EQ(StatusCode::OK_200, result->status);
  9541. result = cli.Get("/hi");
  9542. ASSERT_TRUE(result);
  9543. EXPECT_EQ(StatusCode::OK_200, result->status);
  9544. }
  9545. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9547. ASSERT_TRUE(svr.is_valid());
  9548. svr.set_keep_alive_timeout(1);
  9549. std::string content = "reconnect";
  9550. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9551. res.set_content("Hello World!", "text/plain");
  9552. });
  9553. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9554. auto se = detail::scope_exit([&] {
  9555. svr.stop();
  9556. listen_thread.join();
  9557. ASSERT_FALSE(svr.is_running());
  9558. });
  9559. svr.wait_until_ready();
  9560. SSLClient cli(HOST, PORT);
  9561. cli.enable_server_certificate_verification(false);
  9562. cli.set_keep_alive(true);
  9563. auto result = cli.Post(
  9564. "/hi", content.size(),
  9565. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9566. sink.write(content.c_str(), content.size());
  9567. return true;
  9568. },
  9569. "text/plain");
  9570. ASSERT_TRUE(result);
  9571. EXPECT_EQ(200, result->status);
  9572. std::this_thread::sleep_for(std::chrono::seconds(2));
  9573. // Recoonect
  9574. result = cli.Post(
  9575. "/hi", content.size(),
  9576. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9577. sink.write(content.c_str(), content.size());
  9578. return true;
  9579. },
  9580. "text/plain");
  9581. ASSERT_TRUE(result);
  9582. EXPECT_EQ(200, result->status);
  9583. result = cli.Post(
  9584. "/hi", content.size(),
  9585. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9586. sink.write(content.c_str(), content.size());
  9587. return true;
  9588. },
  9589. "text/plain");
  9590. ASSERT_TRUE(result);
  9591. EXPECT_EQ(200, result->status);
  9592. }
  9593. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9594. using namespace httplib::tls;
  9595. {
  9596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9597. ASSERT_TRUE(svr.is_valid());
  9598. svr.Get("/sni", [&](const Request &req, Response &res) {
  9599. std::string expected = req.sni();
  9600. EXPECT_EQ(expected, req.get_param_value("expected"));
  9601. res.set_content("ok", "text/plain");
  9602. });
  9603. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9604. auto se = detail::scope_exit([&] {
  9605. svr.stop();
  9606. listen_thread.join();
  9607. ASSERT_FALSE(svr.is_running());
  9608. });
  9609. svr.wait_until_ready();
  9610. {
  9611. SSLClient cli("localhost", PORT);
  9612. cli.enable_server_certificate_verification(false);
  9613. auto res = cli.Get("/sni?expected=localhost");
  9614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9615. }
  9616. {
  9617. SSLClient cli("::1", PORT);
  9618. cli.enable_server_certificate_verification(false);
  9619. auto res = cli.Get("/sni?expected=");
  9620. // NOTE: This may fail if the server is listening on IPv4 only
  9621. // (e.g., when localhost resolves to 127.0.0.1 only)
  9622. if (res) {
  9623. EXPECT_EQ(StatusCode::OK_200, res->status);
  9624. } else {
  9625. EXPECT_EQ(Error::Connection, res.error());
  9626. }
  9627. }
  9628. }
  9629. }
  9630. #endif
  9631. TEST(ClientProblemDetectionTest, ContentProvider) {
  9632. Server svr;
  9633. size_t content_length = 1024 * 1024;
  9634. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9635. res.set_content_provider(
  9636. content_length, "text/plain",
  9637. [&](size_t offset, size_t length, DataSink &sink) {
  9638. auto out_len = std::min(length, static_cast<size_t>(1024));
  9639. std::string out(out_len, '@');
  9640. sink.write(out.data(), out_len);
  9641. return offset < 4096;
  9642. },
  9643. [](bool success) { ASSERT_FALSE(success); });
  9644. });
  9645. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9646. res.set_content_provider(
  9647. 0, "text/plain",
  9648. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9649. EXPECT_TRUE(false);
  9650. return true;
  9651. },
  9652. [](bool success) { ASSERT_FALSE(success); });
  9653. });
  9654. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9655. auto se = detail::scope_exit([&] {
  9656. svr.stop();
  9657. listen_thread.join();
  9658. ASSERT_FALSE(svr.is_running());
  9659. });
  9660. svr.wait_until_ready();
  9661. Client cli("localhost", PORT);
  9662. {
  9663. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9664. size_t /*data_length*/) { return false; });
  9665. ASSERT_FALSE(res);
  9666. }
  9667. {
  9668. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9669. size_t /*data_length*/) { return false; });
  9670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9671. }
  9672. }
  9673. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9674. // A provider that reports success without writing anything and without
  9675. // calling done() used to be handed the same offset and length again on every
  9676. // pass, so it spun for as long as the peer stayed connected.
  9677. Server svr;
  9678. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9679. res.set_content("ok", "text/plain");
  9680. });
  9681. auto port = svr.bind_to_any_port(HOST);
  9682. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9683. auto se = detail::scope_exit([&] {
  9684. svr.stop();
  9685. listen_thread.join();
  9686. ASSERT_FALSE(svr.is_running());
  9687. });
  9688. svr.wait_until_ready();
  9689. std::atomic<int> call_count{0};
  9690. Client cli(HOST, port);
  9691. auto res = cli.Post(
  9692. "/", 1024,
  9693. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9694. // Give up after enough passes to show the spin, so that losing the
  9695. // check below fails this test instead of hanging it.
  9696. return ++call_count < 100;
  9697. },
  9698. "text/plain");
  9699. ASSERT_FALSE(res);
  9700. EXPECT_EQ(Error::Write, res.error());
  9701. EXPECT_EQ(1, call_count.load());
  9702. }
  9703. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9704. // A writer only has to assign `write`. The other three used to be left as
  9705. // empty std::functions, so a provider calling one threw
  9706. // std::bad_function_call out of the thread running it and took the whole
  9707. // process down.
  9708. DataSink sink;
  9709. std::string written;
  9710. sink.write = [&](const char *data, size_t data_len) {
  9711. written.append(data, data_len);
  9712. return true;
  9713. };
  9714. EXPECT_TRUE(sink.is_writable());
  9715. sink.done();
  9716. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9717. EXPECT_TRUE(written.empty());
  9718. }
  9719. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9720. // A sink that cannot carry trailers still has to finish.
  9721. DataSink sink;
  9722. auto done_count = 0;
  9723. sink.done = [&]() { done_count++; };
  9724. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9725. EXPECT_EQ(1, done_count);
  9726. }
  9727. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9728. Server svr;
  9729. const std::string body(4096, 'x');
  9730. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9731. res.set_content_provider(body.size(), "text/plain",
  9732. [&](size_t offset, size_t length, DataSink &sink) {
  9733. sink.write(body.data() + offset, length);
  9734. sink.done();
  9735. return true;
  9736. });
  9737. });
  9738. auto port = svr.bind_to_any_port(HOST);
  9739. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9740. auto se = detail::scope_exit([&] {
  9741. svr.stop();
  9742. listen_thread.join();
  9743. ASSERT_FALSE(svr.is_running());
  9744. });
  9745. svr.wait_until_ready();
  9746. Client cli(HOST, port);
  9747. auto res = cli.Get("/");
  9748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9749. EXPECT_EQ(StatusCode::OK_200, res->status);
  9750. EXPECT_EQ(body, res->body);
  9751. }
  9752. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9753. Server svr;
  9754. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9755. res.set_content_provider(
  9756. 1024, "text/plain",
  9757. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9758. sink.write("hello", 5);
  9759. sink.done(); // short of the 1024 bytes the response promised
  9760. return true;
  9761. });
  9762. });
  9763. auto port = svr.bind_to_any_port(HOST);
  9764. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9765. auto se = detail::scope_exit([&] {
  9766. svr.stop();
  9767. listen_thread.join();
  9768. ASSERT_FALSE(svr.is_running());
  9769. });
  9770. svr.wait_until_ready();
  9771. Client cli(HOST, port);
  9772. cli.set_read_timeout(5, 0);
  9773. // The response is short of its Content-Length, so the client cannot read a
  9774. // complete body. What matters is that this returns at all: a no-op done()
  9775. // would leave the writer looping over a provider that never makes progress.
  9776. auto res = cli.Get("/");
  9777. EXPECT_FALSE(res);
  9778. }
  9779. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9780. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9781. // The compressed path builds the whole body before connecting, so this
  9782. // fails client-side and never reaches a server.
  9783. Client cli(HOST, PORT);
  9784. cli.set_compress(true);
  9785. auto res = cli.Post(
  9786. "/", 1024,
  9787. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9788. sink.write("hello", 5);
  9789. sink.done(); // short of the 1024 bytes the request announced
  9790. return true;
  9791. },
  9792. "text/plain");
  9793. ASSERT_FALSE(res);
  9794. EXPECT_EQ(Error::Write, res.error());
  9795. }
  9796. #endif
  9797. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9798. Server svr;
  9799. svr.set_error_handler([](Request const &, Response &res) -> void {
  9800. res.set_chunked_content_provider(
  9801. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9802. sink.os << "hello";
  9803. sink.os << "world";
  9804. sink.done();
  9805. return true;
  9806. });
  9807. });
  9808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9809. auto se = detail::scope_exit([&] {
  9810. svr.stop();
  9811. listen_thread.join();
  9812. ASSERT_FALSE(svr.is_running());
  9813. });
  9814. svr.wait_until_ready();
  9815. Client cli("localhost", PORT);
  9816. auto res = cli.Get("/");
  9817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9818. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9819. EXPECT_EQ("helloworld", res->body);
  9820. }
  9821. TEST(LongPollingTest, ClientCloseDetection) {
  9822. Server svr;
  9823. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9824. res.set_chunked_content_provider(
  9825. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9826. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9827. sink.os << "hello";
  9828. auto count = 10;
  9829. while (count > 0 && sink.is_writable()) {
  9830. this_thread::sleep_for(chrono::milliseconds(10));
  9831. count--;
  9832. }
  9833. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9834. return true;
  9835. });
  9836. });
  9837. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9838. auto se = detail::scope_exit([&] {
  9839. svr.stop();
  9840. listen_thread.join();
  9841. ASSERT_FALSE(svr.is_running());
  9842. });
  9843. svr.wait_until_ready();
  9844. Client cli("localhost", PORT);
  9845. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9846. EXPECT_EQ("hello", string(data, data_length));
  9847. return false; // close the socket immediately.
  9848. });
  9849. ASSERT_FALSE(res);
  9850. }
  9851. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9852. Server svr;
  9853. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9854. res.set_chunked_content_provider(
  9855. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9856. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9857. sink.os << "hello";
  9858. EXPECT_TRUE(sink.os.good());
  9859. // Wait for the client to close the connection
  9860. auto count = 10;
  9861. while (count > 0 && sink.is_writable()) {
  9862. this_thread::sleep_for(chrono::milliseconds(10));
  9863. count--;
  9864. }
  9865. // After client disconnect, write repeatedly until the socket
  9866. // write actually fails (small writes may be absorbed by the
  9867. // kernel buffer)
  9868. std::string chunk(1024, 'x');
  9869. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9870. sink.os << chunk;
  9871. }
  9872. EXPECT_TRUE(sink.os.fail());
  9873. return true;
  9874. });
  9875. });
  9876. auto port = svr.bind_to_any_port("localhost");
  9877. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9878. auto se = detail::scope_exit([&] {
  9879. svr.stop();
  9880. listen_thread.join();
  9881. ASSERT_FALSE(svr.is_running());
  9882. });
  9883. svr.wait_until_ready();
  9884. Client cli("localhost", port);
  9885. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9886. EXPECT_EQ("hello", string(data, data_length));
  9887. return false; // close the socket immediately.
  9888. });
  9889. ASSERT_FALSE(res);
  9890. }
  9891. TEST(GetWithParametersTest, GetWithParameters) {
  9892. Server svr;
  9893. svr.Get("/", [&](const Request &req, Response &) {
  9894. EXPECT_EQ("world", req.get_param_value("hello"));
  9895. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9896. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9897. });
  9898. svr.Get("/params", [&](const Request &req, Response &) {
  9899. EXPECT_EQ("world", req.get_param_value("hello"));
  9900. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9901. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9902. });
  9903. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9904. EXPECT_EQ("resource-id", req.matches[1]);
  9905. EXPECT_EQ("foo", req.get_param_value("param1"));
  9906. EXPECT_EQ("bar", req.get_param_value("param2"));
  9907. });
  9908. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9909. EXPECT_EQ("user-id", req.path_params.at("id"));
  9910. EXPECT_EQ("foo", req.get_param_value("param1"));
  9911. EXPECT_EQ("bar", req.get_param_value("param2"));
  9912. });
  9913. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9914. auto se = detail::scope_exit([&] {
  9915. svr.stop();
  9916. listen_thread.join();
  9917. ASSERT_FALSE(svr.is_running());
  9918. });
  9919. svr.wait_until_ready();
  9920. {
  9921. Client cli(HOST, PORT);
  9922. Params params;
  9923. params.emplace("hello", "world");
  9924. params.emplace("hello2", "world2");
  9925. params.emplace("hello3", "world3");
  9926. auto res = cli.Get("/", params, Headers{});
  9927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9928. EXPECT_EQ(StatusCode::OK_200, res->status);
  9929. }
  9930. {
  9931. Client cli(HOST, PORT);
  9932. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9934. EXPECT_EQ(StatusCode::OK_200, res->status);
  9935. }
  9936. {
  9937. Client cli(HOST, PORT);
  9938. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9940. EXPECT_EQ(StatusCode::OK_200, res->status);
  9941. }
  9942. {
  9943. Client cli(HOST, PORT);
  9944. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9946. EXPECT_EQ(StatusCode::OK_200, res->status);
  9947. }
  9948. }
  9949. TEST(GetWithParametersTest, GetWithParameters2) {
  9950. Server svr;
  9951. svr.Get("/", [&](const Request &req, Response &res) {
  9952. auto text = req.get_param_value("hello");
  9953. res.set_content(text, "text/plain");
  9954. });
  9955. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9956. auto se = detail::scope_exit([&] {
  9957. svr.stop();
  9958. listen_thread.join();
  9959. ASSERT_FALSE(svr.is_running());
  9960. });
  9961. svr.wait_until_ready();
  9962. Client cli("localhost", PORT);
  9963. Params params;
  9964. params.emplace("hello", "world");
  9965. std::string body;
  9966. auto res = cli.Get("/", params, Headers{},
  9967. [&](const char *data, size_t data_length) {
  9968. body.append(data, data_length);
  9969. return true;
  9970. });
  9971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9972. EXPECT_EQ(StatusCode::OK_200, res->status);
  9973. EXPECT_EQ("world", body);
  9974. }
  9975. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9976. Server svr;
  9977. svr.Get("/search", [&](const Request &req, Response &res) {
  9978. auto q = req.get_param_value("q");
  9979. res.set_content(q, "text/plain");
  9980. });
  9981. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9982. auto se = detail::scope_exit([&] {
  9983. svr.stop();
  9984. listen_thread.join();
  9985. ASSERT_FALSE(svr.is_running());
  9986. });
  9987. svr.wait_until_ready();
  9988. Client cli("localhost", PORT);
  9989. // Verify that Get(path, params) works without requiring Headers argument
  9990. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9992. EXPECT_EQ(StatusCode::OK_200, res->status);
  9993. EXPECT_EQ("cpp-httplib", res->body);
  9994. }
  9995. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9996. auto host = "httpbingo.org";
  9997. auto path = std::string{"/range/32"};
  9998. #ifdef CPPHTTPLIB_SSL_ENABLED
  9999. SSLClient cli(host);
  10000. #else
  10001. Client cli(host);
  10002. #endif
  10003. cli.set_default_headers({make_range_header({{1, 10}})});
  10004. cli.set_connection_timeout(5);
  10005. {
  10006. auto res = cli.Get(path);
  10007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10008. EXPECT_EQ("bcdefghijk", res->body);
  10009. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10010. }
  10011. {
  10012. auto res = cli.Get(path);
  10013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10014. EXPECT_EQ("bcdefghijk", res->body);
  10015. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10016. }
  10017. }
  10018. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10019. Server svr;
  10020. svr.set_default_headers({{"Hello", "World"}});
  10021. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10022. res.set_content("ok", "text/plain");
  10023. });
  10024. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10025. auto se = detail::scope_exit([&] {
  10026. svr.stop();
  10027. listen_thread.join();
  10028. ASSERT_FALSE(svr.is_running());
  10029. });
  10030. svr.wait_until_ready();
  10031. Client cli("localhost", PORT);
  10032. auto res = cli.Get("/");
  10033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10034. EXPECT_EQ(StatusCode::OK_200, res->status);
  10035. EXPECT_EQ("ok", res->body);
  10036. EXPECT_EQ("World", res->get_header_value("Hello"));
  10037. }
  10038. #ifdef CPPHTTPLIB_SSL_ENABLED
  10039. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10041. ASSERT_TRUE(svr.is_valid());
  10042. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10043. std::this_thread::sleep_for(std::chrono::seconds(2));
  10044. res.set_content("a", "text/plain");
  10045. });
  10046. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10047. res.set_content("b", "text/plain");
  10048. });
  10049. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10050. auto se = detail::scope_exit([&] {
  10051. svr.stop();
  10052. listen_thread.join();
  10053. ASSERT_FALSE(svr.is_running());
  10054. });
  10055. svr.wait_until_ready();
  10056. SSLClient cli("localhost", PORT);
  10057. cli.enable_server_certificate_verification(false);
  10058. cli.set_keep_alive(true);
  10059. cli.set_read_timeout(std::chrono::seconds(1));
  10060. auto resa = cli.Get("/a");
  10061. ASSERT_TRUE(!resa);
  10062. EXPECT_EQ(Error::Read, resa.error());
  10063. auto resb = cli.Get("/b");
  10064. ASSERT_TRUE(resb);
  10065. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10066. EXPECT_EQ("b", resb->body);
  10067. }
  10068. // Closing an idle keep-alive connection sends close_notify and returns. The
  10069. // server must not wait for the client's close_notify: an idle client never
  10070. // sends one, so the worker would be held until the read timeout expires, and
  10071. // stop() would wait for it.
  10072. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10074. ASSERT_TRUE(svr.is_valid());
  10075. svr.set_keep_alive_timeout(1);
  10076. svr.set_read_timeout(10, 0);
  10077. svr.Get("/", [](const Request &, Response &res) {
  10078. res.set_content("ok", "text/plain");
  10079. });
  10080. auto port = svr.bind_to_any_port(HOST);
  10081. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10082. auto se = detail::scope_exit([&] {
  10083. if (listen_thread.joinable()) {
  10084. svr.stop();
  10085. listen_thread.join();
  10086. }
  10087. });
  10088. svr.wait_until_ready();
  10089. SSLClient cli(HOST, port);
  10090. cli.enable_server_certificate_verification(false);
  10091. cli.set_keep_alive(true);
  10092. auto res = cli.Get("/");
  10093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10094. EXPECT_EQ(StatusCode::OK_200, res->status);
  10095. // Stay idle past the keep-alive timeout so the server closes the connection.
  10096. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10097. auto start = std::chrono::steady_clock::now();
  10098. svr.stop();
  10099. listen_thread.join();
  10100. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10101. std::chrono::steady_clock::now() - start)
  10102. .count();
  10103. EXPECT_LT(elapsed, 3000);
  10104. }
  10105. #endif
  10106. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10107. protected:
  10108. ServerTestWithAI_PASSIVE()
  10109. : cli_(HOST, PORT)
  10110. #ifdef CPPHTTPLIB_SSL_ENABLED
  10111. ,
  10112. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10113. #endif
  10114. {
  10115. #ifdef CPPHTTPLIB_SSL_ENABLED
  10116. cli_.enable_server_certificate_verification(false);
  10117. #endif
  10118. }
  10119. virtual void SetUp() {
  10120. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10121. res.set_content("Hello World!", "text/plain");
  10122. });
  10123. t_ = thread(
  10124. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10125. svr_.wait_until_ready();
  10126. }
  10127. virtual void TearDown() {
  10128. svr_.stop();
  10129. t_.join();
  10130. }
  10131. #ifdef CPPHTTPLIB_SSL_ENABLED
  10132. SSLClient cli_;
  10133. SSLServer svr_;
  10134. #else
  10135. Client cli_;
  10136. Server svr_;
  10137. #endif
  10138. thread t_;
  10139. };
  10140. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10141. auto res = cli_.Get("/hi");
  10142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10143. EXPECT_EQ(StatusCode::OK_200, res->status);
  10144. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10145. EXPECT_EQ("Hello World!", res->body);
  10146. }
  10147. class ServerUpDownTest : public ::testing::Test {
  10148. protected:
  10149. ServerUpDownTest() : cli_(HOST, PORT) {}
  10150. virtual void SetUp() {
  10151. t_ = thread([&]() {
  10152. svr_.bind_to_any_port(HOST);
  10153. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10154. ASSERT_TRUE(svr_.listen_after_bind());
  10155. });
  10156. svr_.wait_until_ready();
  10157. }
  10158. virtual void TearDown() {
  10159. svr_.stop();
  10160. t_.join();
  10161. }
  10162. Client cli_;
  10163. Server svr_;
  10164. thread t_;
  10165. };
  10166. TEST_F(ServerUpDownTest, QuickStartStop) {
  10167. // Should not crash, especially when run with
  10168. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10169. }
  10170. class PayloadMaxLengthTest : public ::testing::Test {
  10171. protected:
  10172. PayloadMaxLengthTest()
  10173. : cli_(HOST, PORT)
  10174. #ifdef CPPHTTPLIB_SSL_ENABLED
  10175. ,
  10176. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10177. #endif
  10178. {
  10179. #ifdef CPPHTTPLIB_SSL_ENABLED
  10180. cli_.enable_server_certificate_verification(false);
  10181. #endif
  10182. }
  10183. virtual void SetUp() {
  10184. svr_.set_payload_max_length(8);
  10185. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10186. res.set_content("test", "text/plain");
  10187. });
  10188. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10189. svr_.wait_until_ready();
  10190. }
  10191. virtual void TearDown() {
  10192. svr_.stop();
  10193. t_.join();
  10194. }
  10195. #ifdef CPPHTTPLIB_SSL_ENABLED
  10196. SSLClient cli_;
  10197. SSLServer svr_;
  10198. #else
  10199. Client cli_;
  10200. Server svr_;
  10201. #endif
  10202. thread t_;
  10203. };
  10204. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10205. auto res = cli_.Post("/test", "123456789", "text/plain");
  10206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10207. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10208. res = cli_.Post("/test", "12345678", "text/plain");
  10209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10210. EXPECT_EQ(StatusCode::OK_200, res->status);
  10211. }
  10212. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10213. // Test chunked encoding with payload exceeding the 8-byte limit
  10214. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10215. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10217. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10218. }
  10219. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10220. // Test chunked encoding with payload within the 8-byte limit
  10221. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10222. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10224. EXPECT_EQ(StatusCode::OK_200, res->status);
  10225. }
  10226. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10227. // Test using send_request to send chunked data exceeding payload limit
  10228. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10229. "Host: " +
  10230. std::string(HOST) + ":" + std::to_string(PORT) +
  10231. "\r\n"
  10232. "Transfer-Encoding: chunked\r\n"
  10233. "Connection: close\r\n"
  10234. "\r\n"
  10235. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10236. "0123456789\r\n"
  10237. "0\r\n" // End chunk
  10238. "\r\n";
  10239. std::string response;
  10240. bool result = send_request(1, chunked_request, &response);
  10241. if (!result) {
  10242. // If send_request fails, it might be because the server closed the
  10243. // connection due to payload limit enforcement, which is acceptable
  10244. SUCCEED()
  10245. << "Server rejected oversized chunked request (connection closed)";
  10246. } else {
  10247. // If we got a response, check if it's an error response or connection was
  10248. // closed early Short response length indicates connection was closed due to
  10249. // payload limit
  10250. if (response.length() <= 10) {
  10251. SUCCEED() << "Server closed connection for oversized chunked request";
  10252. } else {
  10253. // Check for error status codes
  10254. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10255. response.find("Payload Too Large") != std::string::npos ||
  10256. response.find("400") != std::string::npos);
  10257. }
  10258. }
  10259. }
  10260. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10261. // Test request without Content-Length header exceeding payload limit
  10262. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10263. "Host: " +
  10264. std::string(HOST) + ":" +
  10265. std::to_string(PORT) +
  10266. "\r\n"
  10267. "Connection: close\r\n"
  10268. "\r\n";
  10269. // Add payload exceeding the 8-byte limit
  10270. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10271. request_without_content_length += large_payload;
  10272. std::string response;
  10273. bool result = send_request(1, request_without_content_length, &response);
  10274. if (!result) {
  10275. // If send_request fails, server likely closed connection due to payload
  10276. // limit
  10277. SUCCEED() << "Server rejected oversized request without Content-Length "
  10278. "(connection closed)";
  10279. } else {
  10280. // Check if server responded with error or closed connection early
  10281. if (response.length() <= 10) {
  10282. SUCCEED() << "Server closed connection for oversized request without "
  10283. "Content-Length";
  10284. } else {
  10285. // Check for error status codes
  10286. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10287. response.find("Payload Too Large") != std::string::npos ||
  10288. response.find("400") != std::string::npos);
  10289. }
  10290. }
  10291. }
  10292. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10293. // Test request without Content-Length header within payload limit
  10294. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10295. "Host: " +
  10296. std::string(HOST) + ":" +
  10297. std::to_string(PORT) +
  10298. "\r\n"
  10299. "Connection: close\r\n"
  10300. "\r\n";
  10301. // Add payload within the 8-byte limit
  10302. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10303. request_without_content_length += small_payload;
  10304. std::string response;
  10305. bool result = send_request(1, request_without_content_length, &response);
  10306. // For requests without Content-Length, the server may have different behavior
  10307. // The key is that it should not reject due to payload limit for small
  10308. // payloads
  10309. if (result) {
  10310. // Check for any HTTP response (success or error, but not connection closed)
  10311. if (response.length() > 10) {
  10312. SUCCEED()
  10313. << "Server processed request without Content-Length within limit";
  10314. } else {
  10315. // Short response might indicate connection closed, which is acceptable
  10316. SUCCEED() << "Server closed connection for request without "
  10317. "Content-Length (acceptable behavior)";
  10318. }
  10319. } else {
  10320. // Connection failure might be due to protocol requirements
  10321. SUCCEED() << "Connection issue with request without Content-Length "
  10322. "(environment-specific)";
  10323. }
  10324. }
  10325. class LargePayloadMaxLengthTest : public ::testing::Test {
  10326. protected:
  10327. LargePayloadMaxLengthTest()
  10328. : cli_(HOST, PORT)
  10329. #ifdef CPPHTTPLIB_SSL_ENABLED
  10330. ,
  10331. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10332. #endif
  10333. {
  10334. #ifdef CPPHTTPLIB_SSL_ENABLED
  10335. cli_.enable_server_certificate_verification(false);
  10336. #endif
  10337. }
  10338. virtual void SetUp() {
  10339. // Set 10MB payload limit
  10340. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10341. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10342. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10343. res.set_content("Large payload test", "text/plain");
  10344. });
  10345. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10346. svr_.wait_until_ready();
  10347. }
  10348. virtual void TearDown() {
  10349. svr_.stop();
  10350. t_.join();
  10351. }
  10352. #ifdef CPPHTTPLIB_SSL_ENABLED
  10353. SSLClient cli_;
  10354. SSLServer svr_;
  10355. #else
  10356. Client cli_;
  10357. Server svr_;
  10358. #endif
  10359. thread t_;
  10360. };
  10361. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10362. // Test chunked encoding with payload within 10MB limit
  10363. std::string medium_payload(5 * 1024 * 1024,
  10364. 'A'); // 5MB payload, within 10MB limit
  10365. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10367. EXPECT_EQ(StatusCode::OK_200, res->status);
  10368. }
  10369. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10370. // Test chunked encoding with payload exceeding 10MB limit
  10371. std::string large_payload(12 * 1024 * 1024,
  10372. 'B'); // 12MB payload, exceeds 10MB limit
  10373. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10374. // Server may either return 413 or close the connection
  10375. if (res) {
  10376. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10377. } else {
  10378. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10379. }
  10380. }
  10381. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10382. // Test request without Content-Length header within 10MB limit
  10383. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10384. "Host: " +
  10385. std::string(HOST) + ":" +
  10386. std::to_string(PORT) +
  10387. "\r\n"
  10388. "Connection: close\r\n"
  10389. "\r\n";
  10390. // Add 1MB payload (within 10MB limit)
  10391. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10392. request_without_content_length += medium_payload;
  10393. std::string response;
  10394. bool result = send_request(5, request_without_content_length, &response);
  10395. if (result) {
  10396. // Should get a proper HTTP response for payloads within limit
  10397. if (response.length() > 10) {
  10398. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10399. "10MB limit";
  10400. } else {
  10401. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10402. "Content-Length)";
  10403. }
  10404. } else {
  10405. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10406. }
  10407. }
  10408. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10409. // Test request without Content-Length header exceeding 10MB limit
  10410. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10411. "Host: " +
  10412. std::string(HOST) + ":" +
  10413. std::to_string(PORT) +
  10414. "\r\n"
  10415. "Connection: close\r\n"
  10416. "\r\n";
  10417. // Add 12MB payload (exceeds 10MB limit)
  10418. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10419. request_without_content_length += large_payload;
  10420. std::string response;
  10421. bool result = send_request(10, request_without_content_length, &response);
  10422. if (!result) {
  10423. // Server should close connection due to payload limit
  10424. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10425. "(connection closed)";
  10426. } else {
  10427. // Check for error response
  10428. if (response.length() <= 10) {
  10429. SUCCEED()
  10430. << "Server closed connection for 12MB request exceeding 10MB limit";
  10431. } else {
  10432. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10433. response.find("Payload Too Large") != std::string::npos ||
  10434. response.find("400") != std::string::npos);
  10435. }
  10436. }
  10437. }
  10438. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10439. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10440. // path.
  10441. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10442. Server svr;
  10443. const size_t LIMIT = 64 * 1024; // 64KB
  10444. svr.set_payload_max_length(LIMIT);
  10445. size_t total = 0;
  10446. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10447. const ContentReader &content_reader) {
  10448. content_reader([&](const char * /*data*/, size_t len) {
  10449. total += len;
  10450. return true;
  10451. });
  10452. res.status = 200;
  10453. res.set_content("stream_ok", "text/plain");
  10454. });
  10455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10456. auto se = detail::scope_exit([&] {
  10457. svr.stop();
  10458. thread.join();
  10459. ASSERT_FALSE(svr.is_running());
  10460. });
  10461. svr.wait_until_ready();
  10462. // Prepare 256KB raw data and gzip-compress it
  10463. std::string raw(256 * 1024, 'A');
  10464. std::string gz;
  10465. {
  10466. z_stream zs{};
  10467. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10468. Z_DEFAULT_STRATEGY);
  10469. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10470. zs.avail_in = static_cast<uInt>(raw.size());
  10471. char outbuf[4096];
  10472. int ret;
  10473. do {
  10474. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10475. zs.avail_out = sizeof(outbuf);
  10476. ret = deflate(&zs, Z_FINISH);
  10477. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10478. } while (ret != Z_STREAM_END);
  10479. deflateEnd(&zs);
  10480. }
  10481. Client cli(HOST, PORT);
  10482. cli.set_connection_timeout(std::chrono::seconds(5));
  10483. Headers headers = {{"Content-Encoding", "gzip"}};
  10484. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10485. "application/octet-stream");
  10486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10487. // Server must reject oversized decompressed payloads with 413.
  10488. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10489. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10490. EXPECT_LE(total, LIMIT);
  10491. }
  10492. #ifndef CPPHTTPLIB_SSL_ENABLED
  10493. // For a request with neither Content-Length nor Transfer-Encoding, the
  10494. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10495. // compressed wire bytes straight to the ContentReader without ever routing
  10496. // them through the decompressor, so payload_max_length_ only bounded the
  10497. // compressed size on the wire, not the decompressed size.
  10498. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10499. Server svr;
  10500. const size_t LIMIT = 64 * 1024; // 64KB
  10501. svr.set_payload_max_length(LIMIT);
  10502. size_t total = 0;
  10503. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10504. const ContentReader &content_reader) {
  10505. content_reader([&](const char * /*data*/, size_t len) {
  10506. total += len;
  10507. return true;
  10508. });
  10509. res.status = 200;
  10510. res.set_content("stream_ok", "text/plain");
  10511. });
  10512. auto port = svr.bind_to_any_port(HOST);
  10513. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10514. auto se = detail::scope_exit([&] {
  10515. svr.stop();
  10516. thread.join();
  10517. ASSERT_FALSE(svr.is_running());
  10518. });
  10519. svr.wait_until_ready();
  10520. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10521. // StreamingGzipDecompression test above.
  10522. std::string raw(256 * 1024, 'A');
  10523. std::string gz;
  10524. {
  10525. httplib::detail::gzip_compressor compressor;
  10526. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10527. [&](const char *chunk, size_t len) {
  10528. gz.append(chunk, len);
  10529. return true;
  10530. });
  10531. ASSERT_TRUE(result);
  10532. }
  10533. // Send the gzip body over raw TCP with neither Content-Length nor
  10534. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10535. // kicks in.
  10536. std::string req = "POST /stream HTTP/1.1\r\n"
  10537. "Host: " +
  10538. std::string(HOST) + ":" + std::to_string(port) +
  10539. "\r\n"
  10540. "Content-Encoding: gzip\r\n"
  10541. "Connection: close\r\n"
  10542. "\r\n" +
  10543. gz;
  10544. std::string response;
  10545. ASSERT_TRUE(send_request(5, req, &response, port));
  10546. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10547. EXPECT_LE(total, LIMIT);
  10548. }
  10549. #endif
  10550. #endif
  10551. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10552. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10553. // the payload must be passed through untouched instead of being rejected.
  10554. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10555. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10556. Server svr;
  10557. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10558. res.set_content(body, "image/jpeg");
  10559. res.set_header("Content-Encoding", "UTF-8");
  10560. });
  10561. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10562. res.set_content(body, "image/jpeg");
  10563. res.set_header("Content-Encoding", "identity");
  10564. });
  10565. svr.Post("/echo", [](const Request &req, Response &res) {
  10566. res.set_content(req.body, "image/jpeg");
  10567. });
  10568. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10569. auto se = detail::scope_exit([&] {
  10570. svr.stop();
  10571. t.join();
  10572. ASSERT_FALSE(svr.is_running());
  10573. });
  10574. svr.wait_until_ready();
  10575. Client cli(HOST, PORT);
  10576. {
  10577. auto res = cli.Get("/image");
  10578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10579. EXPECT_EQ(StatusCode::OK_200, res->status);
  10580. EXPECT_EQ(body, res->body);
  10581. }
  10582. {
  10583. auto res = cli.Get("/identity");
  10584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10585. EXPECT_EQ(StatusCode::OK_200, res->status);
  10586. EXPECT_EQ(body, res->body);
  10587. }
  10588. {
  10589. // The same applies to a request body reaching the server.
  10590. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10591. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10593. EXPECT_EQ(StatusCode::OK_200, res->status);
  10594. EXPECT_EQ(body, res->body);
  10595. }
  10596. }
  10597. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10598. // gzip-encoded response even when the build has no zlib support.
  10599. static const char GZIPPED_HELLO_WORLD[] = {
  10600. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10601. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10602. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10603. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10604. // A content coding is a whole token, not something the field value merely
  10605. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10606. // as "fibre" look like Brotli, and turned a multi-coding value like
  10607. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10608. // it was never meant to see.
  10609. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10610. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10611. Server svr;
  10612. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10613. res.set_content(body, "image/jpeg");
  10614. res.set_header("Content-Encoding", "fibre");
  10615. });
  10616. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10617. res.set_content(body, "image/jpeg");
  10618. res.set_header("Content-Encoding", "gzip, br");
  10619. });
  10620. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10621. res.set_content(body, "image/jpeg");
  10622. res.set_header("Content-Encoding", "x-zstd-ish");
  10623. });
  10624. auto port = svr.bind_to_any_port(HOST);
  10625. thread t = thread([&]() { svr.listen_after_bind(); });
  10626. auto se = detail::scope_exit([&] {
  10627. svr.stop();
  10628. t.join();
  10629. ASSERT_FALSE(svr.is_running());
  10630. });
  10631. svr.wait_until_ready();
  10632. Client cli(HOST, port);
  10633. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10634. auto res = cli.Get(path);
  10635. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10636. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10637. // Not a coding we recognize, so the payload comes back untouched
  10638. EXPECT_EQ(body, res->body) << path;
  10639. }
  10640. }
  10641. // A content coding cpp-httplib recognizes but was not built with must be
  10642. // reported as such. Handing the still-compressed payload back to the caller
  10643. // would silently corrupt it.
  10644. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10645. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10646. Server svr;
  10647. // "image/jpeg" keeps the server from applying a content coding of its own,
  10648. // so the hand-crafted Content-Encoding below survives.
  10649. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10650. res.set_content(gzipped, "image/jpeg");
  10651. res.set_header("Content-Encoding", "gzip");
  10652. });
  10653. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10654. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10655. res.set_content(gzipped, "image/jpeg");
  10656. res.set_header("Content-Encoding", "GZIP");
  10657. });
  10658. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10659. auto se = detail::scope_exit([&] {
  10660. svr.stop();
  10661. t.join();
  10662. ASSERT_FALSE(svr.is_running());
  10663. });
  10664. svr.wait_until_ready();
  10665. Client cli(HOST, PORT);
  10666. {
  10667. auto res = cli.Get("/gzipped");
  10668. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10670. EXPECT_EQ("Hello World!", res->body);
  10671. #else
  10672. ASSERT_FALSE(res);
  10673. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10674. #endif
  10675. }
  10676. {
  10677. // open_stream() must behave the same way.
  10678. auto handle = cli.open_stream("GET", "/gzipped");
  10679. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10680. ASSERT_TRUE(handle.is_valid());
  10681. std::string received;
  10682. char buf[256];
  10683. ssize_t n;
  10684. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10685. received.append(buf, static_cast<size_t>(n));
  10686. }
  10687. EXPECT_EQ("Hello World!", received);
  10688. #else
  10689. EXPECT_FALSE(handle.is_valid());
  10690. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10691. #endif
  10692. }
  10693. {
  10694. // A differently-cased coding must not be mistaken for an unknown one, or
  10695. // the body would be handed back still compressed.
  10696. auto res = cli.Get("/gzipped-uppercase");
  10697. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10699. EXPECT_EQ("Hello World!", res->body);
  10700. #else
  10701. ASSERT_FALSE(res);
  10702. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10703. #endif
  10704. }
  10705. }
  10706. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10707. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10708. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10709. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10710. // body a second time and appending a second Content-Encoding field line, so
  10711. // clients that decode one coding per listed value handed back raw gzip bytes.
  10712. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10713. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10714. Server svr;
  10715. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10716. // keeps the server from applying a coding of its own.
  10717. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10718. res.set_content(gzipped, "text/plain");
  10719. res.set_header("Content-Encoding", "gzip");
  10720. });
  10721. auto port = svr.bind_to_any_port(HOST);
  10722. thread t = thread([&]() { svr.listen_after_bind(); });
  10723. auto se = detail::scope_exit([&] {
  10724. svr.stop();
  10725. t.join();
  10726. ASSERT_FALSE(svr.is_running());
  10727. });
  10728. svr.wait_until_ready();
  10729. Client cli(HOST, port);
  10730. Headers headers = {{"Accept-Encoding", "gzip"}};
  10731. auto res = cli.Get("/pre-gzipped", headers);
  10732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10733. EXPECT_EQ(StatusCode::OK_200, res->status);
  10734. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10735. EXPECT_EQ("Hello World!", res->body);
  10736. }
  10737. // A chunked provider settles its coding where the headers are written and
  10738. // reuses it at write time. Both ends of that have to hold: a handler's own
  10739. // Content-Encoding suppresses the coding, and a response without one is still
  10740. // compressed as it always was.
  10741. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10742. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10743. const std::string plain = "Hello World! Hello World! Hello World!";
  10744. Server svr;
  10745. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10746. res.set_header("Content-Encoding", "gzip");
  10747. res.set_chunked_content_provider(
  10748. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10749. sink.write(gzipped.data(), gzipped.size());
  10750. sink.done();
  10751. return true;
  10752. });
  10753. });
  10754. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10755. res.set_chunked_content_provider(
  10756. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10757. sink.write(plain.data(), plain.size());
  10758. sink.done();
  10759. return true;
  10760. });
  10761. });
  10762. auto port = svr.bind_to_any_port(HOST);
  10763. thread t = thread([&]() { svr.listen_after_bind(); });
  10764. auto se = detail::scope_exit([&] {
  10765. svr.stop();
  10766. t.join();
  10767. ASSERT_FALSE(svr.is_running());
  10768. });
  10769. svr.wait_until_ready();
  10770. Client cli(HOST, port);
  10771. Headers headers = {{"Accept-Encoding", "gzip"}};
  10772. {
  10773. auto res = cli.Get("/pre-gzipped", headers);
  10774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10775. EXPECT_EQ(StatusCode::OK_200, res->status);
  10776. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10777. EXPECT_EQ("Hello World!", res->body);
  10778. }
  10779. {
  10780. auto res = cli.Get("/negotiated", headers);
  10781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10782. EXPECT_EQ(StatusCode::OK_200, res->status);
  10783. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10784. EXPECT_EQ(plain, res->body);
  10785. }
  10786. }
  10787. #endif
  10788. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10789. // the same message as the comma-joined one, so both have to be read the same
  10790. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10791. // single gzip coding, and a body the sender says was encoded twice was handed
  10792. // back after one pass, still compressed but presented as decoded.
  10793. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10794. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10795. Server svr;
  10796. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10797. res.set_content(body, "image/jpeg");
  10798. res.headers.emplace("Content-Encoding", "gzip");
  10799. res.headers.emplace("Content-Encoding", "gzip");
  10800. });
  10801. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10802. res.set_content(body, "image/jpeg");
  10803. res.set_header("Content-Encoding", "gzip, gzip");
  10804. });
  10805. auto port = svr.bind_to_any_port(HOST);
  10806. thread t = thread([&]() { svr.listen_after_bind(); });
  10807. auto se = detail::scope_exit([&] {
  10808. svr.stop();
  10809. t.join();
  10810. ASSERT_FALSE(svr.is_running());
  10811. });
  10812. svr.wait_until_ready();
  10813. Client cli(HOST, port);
  10814. // Two codings is not something cpp-httplib decodes, so both representations
  10815. // take the pass-through path rather than one of them being gunzipped once.
  10816. for (const char *path : {"/split", "/joined"}) {
  10817. auto res = cli.Get(path);
  10818. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10819. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10820. EXPECT_EQ(body, res->body) << path;
  10821. }
  10822. }
  10823. // Regression test for DoS vulnerability: a malicious server sending a response
  10824. // without Content-Length header must not cause unbounded memory consumption on
  10825. // the client side. The client should stop reading after a reasonable limit,
  10826. // similar to the server-side set_payload_max_length protection.
  10827. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10828. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10829. #ifndef _WIN32
  10830. signal(SIGPIPE, SIG_IGN);
  10831. #endif
  10832. auto server_thread = std::thread([] {
  10833. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10834. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10835. default_socket_options(srv);
  10836. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10837. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10838. sockaddr_in addr{};
  10839. addr.sin_family = AF_INET;
  10840. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10841. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10842. int opt = 1;
  10843. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10844. #ifdef _WIN32
  10845. reinterpret_cast<const char *>(&opt),
  10846. #else
  10847. &opt,
  10848. #endif
  10849. sizeof(opt));
  10850. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10851. ::listen(srv, 1);
  10852. sockaddr_in cli_addr{};
  10853. socklen_t cli_len = sizeof(cli_addr);
  10854. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10855. if (cli != INVALID_SOCKET) {
  10856. char buf[4096];
  10857. ::recv(cli, buf, sizeof(buf), 0);
  10858. // Malicious response: no Content-Length, no chunked encoding
  10859. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10860. "Connection: close\r\n"
  10861. "\r\n";
  10862. ::send(cli,
  10863. #ifdef _WIN32
  10864. static_cast<const char *>(response_header.c_str()),
  10865. static_cast<int>(response_header.size()),
  10866. #else
  10867. response_header.c_str(), response_header.size(),
  10868. #endif
  10869. 0);
  10870. // Send 10MB of data
  10871. std::string chunk(64 * 1024, 'A');
  10872. size_t total_sent = 0;
  10873. while (total_sent < MALICIOUS_DATA_SIZE) {
  10874. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10875. auto sent = ::send(cli,
  10876. #ifdef _WIN32
  10877. static_cast<const char *>(chunk.c_str()),
  10878. static_cast<int>(to_send),
  10879. #else
  10880. chunk.c_str(), to_send,
  10881. #endif
  10882. 0);
  10883. if (sent <= 0) break;
  10884. total_sent += static_cast<size_t>(sent);
  10885. }
  10886. detail::close_socket(cli);
  10887. }
  10888. detail::close_socket(srv);
  10889. });
  10890. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10891. size_t total_read = 0;
  10892. {
  10893. Client cli("127.0.0.1", PORT + 2);
  10894. cli.set_read_timeout(5, 0);
  10895. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10896. auto stream = cli.open_stream("GET", "/malicious");
  10897. ASSERT_TRUE(stream.is_valid());
  10898. char buffer[64 * 1024];
  10899. ssize_t n;
  10900. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10901. total_read += static_cast<size_t>(n);
  10902. }
  10903. } // StreamHandle and Client destroyed here, closing the socket
  10904. server_thread.join();
  10905. // With set_payload_max_length, the client must stop reading before consuming
  10906. // all 10MB. The read loop should be cut off at or near the configured limit.
  10907. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10908. << "Client read " << total_read << " bytes, exceeding the configured "
  10909. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10910. }
  10911. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10912. // the entire response body without truncation.
  10913. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10914. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10915. #ifndef _WIN32
  10916. signal(SIGPIPE, SIG_IGN);
  10917. #endif
  10918. auto server_thread = std::thread([] {
  10919. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10920. default_socket_options(srv);
  10921. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10922. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10923. sockaddr_in addr{};
  10924. addr.sin_family = AF_INET;
  10925. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10926. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10927. int opt = 1;
  10928. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10929. #ifdef _WIN32
  10930. reinterpret_cast<const char *>(&opt),
  10931. #else
  10932. &opt,
  10933. #endif
  10934. sizeof(opt));
  10935. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10936. ::listen(srv, 1);
  10937. sockaddr_in cli_addr{};
  10938. socklen_t cli_len = sizeof(cli_addr);
  10939. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10940. if (cli != INVALID_SOCKET) {
  10941. char buf[4096];
  10942. ::recv(cli, buf, sizeof(buf), 0);
  10943. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10944. "Connection: close\r\n"
  10945. "\r\n";
  10946. ::send(cli,
  10947. #ifdef _WIN32
  10948. static_cast<const char *>(response_header.c_str()),
  10949. static_cast<int>(response_header.size()),
  10950. #else
  10951. response_header.c_str(), response_header.size(),
  10952. #endif
  10953. 0);
  10954. std::string chunk(64 * 1024, 'A');
  10955. size_t total_sent = 0;
  10956. while (total_sent < DATA_SIZE) {
  10957. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10958. auto sent = ::send(cli,
  10959. #ifdef _WIN32
  10960. static_cast<const char *>(chunk.c_str()),
  10961. static_cast<int>(to_send),
  10962. #else
  10963. chunk.c_str(), to_send,
  10964. #endif
  10965. 0);
  10966. if (sent <= 0) break;
  10967. total_sent += static_cast<size_t>(sent);
  10968. }
  10969. #ifdef _WIN32
  10970. ::shutdown(cli, SD_SEND);
  10971. #else
  10972. ::shutdown(cli, SHUT_WR);
  10973. #endif
  10974. // Drain until the client closes its end, ensuring all data is delivered
  10975. char drain[1024];
  10976. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10977. detail::close_socket(cli);
  10978. }
  10979. detail::close_socket(srv);
  10980. });
  10981. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10982. size_t total_read = 0;
  10983. {
  10984. Client cli("127.0.0.1", PORT + 2);
  10985. cli.set_read_timeout(5, 0);
  10986. cli.set_payload_max_length(0); // 0 means no limit
  10987. auto stream = cli.open_stream("GET", "/data");
  10988. ASSERT_TRUE(stream.is_valid());
  10989. char buffer[64 * 1024];
  10990. ssize_t n;
  10991. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10992. total_read += static_cast<size_t>(n);
  10993. }
  10994. }
  10995. server_thread.join();
  10996. EXPECT_EQ(total_read, DATA_SIZE)
  10997. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10998. << " bytes without truncation, but only read " << total_read << " bytes.";
  10999. }
  11000. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11001. // enormous Content-Length must not cause the client to pre-allocate a huge
  11002. // response body buffer. The reservation is capped at payload_max_length_, and
  11003. // the read itself fails when the body exceeds the limit.
  11004. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11005. #ifndef _WIN32
  11006. signal(SIGPIPE, SIG_IGN);
  11007. #endif
  11008. auto server_thread = std::thread([] {
  11009. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11010. default_socket_options(srv);
  11011. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11013. sockaddr_in addr{};
  11014. addr.sin_family = AF_INET;
  11015. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11016. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11017. int opt = 1;
  11018. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11019. #ifdef _WIN32
  11020. reinterpret_cast<const char *>(&opt),
  11021. #else
  11022. &opt,
  11023. #endif
  11024. sizeof(opt));
  11025. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11026. ::listen(srv, 1);
  11027. sockaddr_in cli_addr{};
  11028. socklen_t cli_len = sizeof(cli_addr);
  11029. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11030. if (cli != INVALID_SOCKET) {
  11031. char buf[4096];
  11032. ::recv(cli, buf, sizeof(buf), 0);
  11033. // Malicious response: claim a 20GB body but send only a tiny payload.
  11034. std::string response = "HTTP/1.1 200 OK\r\n"
  11035. "Content-Length: 20000000000\r\n"
  11036. "\r\n"
  11037. "abc";
  11038. ::send(cli,
  11039. #ifdef _WIN32
  11040. static_cast<const char *>(response.c_str()),
  11041. static_cast<int>(response.size()),
  11042. #else
  11043. response.c_str(), response.size(),
  11044. #endif
  11045. 0);
  11046. detail::close_socket(cli);
  11047. }
  11048. detail::close_socket(srv);
  11049. });
  11050. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11051. {
  11052. Client cli("127.0.0.1", PORT + 2);
  11053. cli.set_read_timeout(5, 0);
  11054. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11055. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11056. // (server claims more bytes than payload_max_length permits), but it must
  11057. // not exhaust memory before getting there.
  11058. auto res = cli.Get("/malicious");
  11059. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11060. }
  11061. server_thread.join();
  11062. }
  11063. // Verify that content_receiver bypasses the default payload_max_length,
  11064. // allowing streaming downloads larger than 100MB without requiring an explicit
  11065. // set_payload_max_length call.
  11066. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11067. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11068. #ifndef _WIN32
  11069. signal(SIGPIPE, SIG_IGN);
  11070. #endif
  11071. auto server_thread = std::thread([] {
  11072. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11073. default_socket_options(srv);
  11074. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11075. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11076. sockaddr_in addr{};
  11077. addr.sin_family = AF_INET;
  11078. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11079. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11080. int opt = 1;
  11081. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11082. #ifdef _WIN32
  11083. reinterpret_cast<const char *>(&opt),
  11084. #else
  11085. &opt,
  11086. #endif
  11087. sizeof(opt));
  11088. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11089. ::listen(srv, 1);
  11090. sockaddr_in cli_addr{};
  11091. socklen_t cli_len = sizeof(cli_addr);
  11092. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11093. if (cli != INVALID_SOCKET) {
  11094. char buf[4096];
  11095. ::recv(cli, buf, sizeof(buf), 0);
  11096. // Response with Content-Length larger than default 100MB limit
  11097. auto content_length = std::to_string(DATA_SIZE);
  11098. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11099. "Content-Length: " +
  11100. content_length +
  11101. "\r\n"
  11102. "Connection: close\r\n"
  11103. "\r\n";
  11104. ::send(cli,
  11105. #ifdef _WIN32
  11106. static_cast<const char *>(response_header.c_str()),
  11107. static_cast<int>(response_header.size()),
  11108. #else
  11109. response_header.c_str(), response_header.size(),
  11110. #endif
  11111. 0);
  11112. std::string chunk(64 * 1024, 'A');
  11113. size_t total_sent = 0;
  11114. while (total_sent < DATA_SIZE) {
  11115. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11116. auto sent = ::send(cli,
  11117. #ifdef _WIN32
  11118. static_cast<const char *>(chunk.c_str()),
  11119. static_cast<int>(to_send),
  11120. #else
  11121. chunk.c_str(), to_send,
  11122. #endif
  11123. 0);
  11124. if (sent <= 0) break;
  11125. total_sent += static_cast<size_t>(sent);
  11126. }
  11127. detail::close_socket(cli);
  11128. }
  11129. detail::close_socket(srv);
  11130. });
  11131. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11132. size_t total_received = 0;
  11133. {
  11134. Client cli("127.0.0.1", PORT + 2);
  11135. cli.set_read_timeout(10, 0);
  11136. // Do NOT call set_payload_max_length — use the default 100MB limit
  11137. auto res =
  11138. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11139. total_received += data_length;
  11140. return true;
  11141. });
  11142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11143. EXPECT_EQ(StatusCode::OK_200, res->status);
  11144. }
  11145. server_thread.join();
  11146. EXPECT_EQ(total_received, DATA_SIZE)
  11147. << "With content_receiver, the client should read all " << DATA_SIZE
  11148. << " bytes despite the default 100MB payload_max_length, but only read "
  11149. << total_received << " bytes.";
  11150. }
  11151. // Verify that an explicit set_payload_max_length smaller than the response is
  11152. // enforced even when a content_receiver is used.
  11153. TEST(ClientVulnerabilityTest,
  11154. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11155. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11156. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11157. #ifndef _WIN32
  11158. signal(SIGPIPE, SIG_IGN);
  11159. #endif
  11160. auto server_thread = std::thread([] {
  11161. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11162. default_socket_options(srv);
  11163. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11164. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11165. sockaddr_in addr{};
  11166. addr.sin_family = AF_INET;
  11167. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11168. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11169. int opt = 1;
  11170. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11171. #ifdef _WIN32
  11172. reinterpret_cast<const char *>(&opt),
  11173. #else
  11174. &opt,
  11175. #endif
  11176. sizeof(opt));
  11177. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11178. ::listen(srv, 1);
  11179. sockaddr_in cli_addr{};
  11180. socklen_t cli_len = sizeof(cli_addr);
  11181. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11182. if (cli != INVALID_SOCKET) {
  11183. char buf[4096];
  11184. ::recv(cli, buf, sizeof(buf), 0);
  11185. auto content_length = std::to_string(DATA_SIZE);
  11186. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11187. "Content-Length: " +
  11188. content_length +
  11189. "\r\n"
  11190. "Connection: close\r\n"
  11191. "\r\n";
  11192. ::send(cli,
  11193. #ifdef _WIN32
  11194. static_cast<const char *>(response_header.c_str()),
  11195. static_cast<int>(response_header.size()),
  11196. #else
  11197. response_header.c_str(), response_header.size(),
  11198. #endif
  11199. 0);
  11200. std::string chunk(64 * 1024, 'A');
  11201. size_t total_sent = 0;
  11202. while (total_sent < DATA_SIZE) {
  11203. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11204. auto sent = ::send(cli,
  11205. #ifdef _WIN32
  11206. static_cast<const char *>(chunk.c_str()),
  11207. static_cast<int>(to_send),
  11208. #else
  11209. chunk.c_str(), to_send,
  11210. #endif
  11211. 0);
  11212. if (sent <= 0) break;
  11213. total_sent += static_cast<size_t>(sent);
  11214. }
  11215. detail::close_socket(cli);
  11216. }
  11217. detail::close_socket(srv);
  11218. });
  11219. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11220. size_t total_received = 0;
  11221. {
  11222. Client cli("127.0.0.1", PORT + 2);
  11223. cli.set_read_timeout(10, 0);
  11224. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11225. auto res =
  11226. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11227. total_received += data_length;
  11228. return true;
  11229. });
  11230. // Should fail because 200MB exceeds the explicit 150MB limit
  11231. EXPECT_FALSE(res);
  11232. }
  11233. server_thread.join();
  11234. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11235. << "Client with content_receiver should respect the explicit "
  11236. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11237. << total_received << " bytes.";
  11238. }
  11239. // Verify that an explicit set_payload_max_length larger than the response
  11240. // allows the content_receiver to read all data successfully.
  11241. TEST(ClientVulnerabilityTest,
  11242. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11243. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11244. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11245. #ifndef _WIN32
  11246. signal(SIGPIPE, SIG_IGN);
  11247. #endif
  11248. auto server_thread = std::thread([] {
  11249. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11250. default_socket_options(srv);
  11251. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11252. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11253. sockaddr_in addr{};
  11254. addr.sin_family = AF_INET;
  11255. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11256. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11257. int opt = 1;
  11258. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11259. #ifdef _WIN32
  11260. reinterpret_cast<const char *>(&opt),
  11261. #else
  11262. &opt,
  11263. #endif
  11264. sizeof(opt));
  11265. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11266. ::listen(srv, 1);
  11267. sockaddr_in cli_addr{};
  11268. socklen_t cli_len = sizeof(cli_addr);
  11269. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11270. if (cli != INVALID_SOCKET) {
  11271. char buf[4096];
  11272. ::recv(cli, buf, sizeof(buf), 0);
  11273. auto content_length = std::to_string(DATA_SIZE);
  11274. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11275. "Content-Length: " +
  11276. content_length +
  11277. "\r\n"
  11278. "Connection: close\r\n"
  11279. "\r\n";
  11280. ::send(cli,
  11281. #ifdef _WIN32
  11282. static_cast<const char *>(response_header.c_str()),
  11283. static_cast<int>(response_header.size()),
  11284. #else
  11285. response_header.c_str(), response_header.size(),
  11286. #endif
  11287. 0);
  11288. std::string chunk(64 * 1024, 'A');
  11289. size_t total_sent = 0;
  11290. while (total_sent < DATA_SIZE) {
  11291. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11292. auto sent = ::send(cli,
  11293. #ifdef _WIN32
  11294. static_cast<const char *>(chunk.c_str()),
  11295. static_cast<int>(to_send),
  11296. #else
  11297. chunk.c_str(), to_send,
  11298. #endif
  11299. 0);
  11300. if (sent <= 0) break;
  11301. total_sent += static_cast<size_t>(sent);
  11302. }
  11303. #ifdef _WIN32
  11304. ::shutdown(cli, SD_SEND);
  11305. #else
  11306. ::shutdown(cli, SHUT_WR);
  11307. #endif
  11308. char drain[1024];
  11309. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11310. detail::close_socket(cli);
  11311. }
  11312. detail::close_socket(srv);
  11313. });
  11314. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11315. size_t total_received = 0;
  11316. {
  11317. Client cli("127.0.0.1", PORT + 2);
  11318. cli.set_read_timeout(10, 0);
  11319. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11320. auto res =
  11321. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11322. total_received += data_length;
  11323. return true;
  11324. });
  11325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11326. EXPECT_EQ(StatusCode::OK_200, res->status);
  11327. }
  11328. server_thread.join();
  11329. EXPECT_EQ(total_received, DATA_SIZE)
  11330. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11331. << " bytes (larger than " << DATA_SIZE
  11332. << " bytes response), content_receiver should read all data, but only "
  11333. "read "
  11334. << total_received << " bytes.";
  11335. }
  11336. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11337. // Regression test for "zip bomb" attack on the client side: a malicious server
  11338. // sends a small gzip-compressed response that decompresses to a huge payload.
  11339. // The client must enforce payload_max_length on the decompressed size.
  11340. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11341. constexpr size_t DECOMPRESSED_SIZE =
  11342. 10 * 1024 * 1024; // 10MB after decompression
  11343. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11344. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11345. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11346. std::string compressed;
  11347. {
  11348. httplib::detail::gzip_compressor compressor;
  11349. bool ok =
  11350. compressor.compress(uncompressed.data(), uncompressed.size(),
  11351. /*last=*/true, [&](const char *buf, size_t len) {
  11352. compressed.append(buf, len);
  11353. return true;
  11354. });
  11355. ASSERT_TRUE(ok);
  11356. }
  11357. // Sanity: compressed data should be much smaller than the decompressed size
  11358. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11359. #ifndef _WIN32
  11360. signal(SIGPIPE, SIG_IGN);
  11361. #endif
  11362. // Set up the listening socket in the main thread so the server is guaranteed
  11363. // to be ready before the client connects (eliminates race condition).
  11364. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11365. default_socket_options(srv);
  11366. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11367. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11368. sockaddr_in addr{};
  11369. addr.sin_family = AF_INET;
  11370. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11371. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11372. int opt = 1;
  11373. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11374. #ifdef _WIN32
  11375. reinterpret_cast<const char *>(&opt),
  11376. #else
  11377. &opt,
  11378. #endif
  11379. sizeof(opt));
  11380. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11381. ASSERT_EQ(0, ::listen(srv, 1));
  11382. auto server_thread = std::thread([&compressed, srv] {
  11383. sockaddr_in cli_addr{};
  11384. socklen_t cli_len = sizeof(cli_addr);
  11385. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11386. if (cli != INVALID_SOCKET) {
  11387. // Read the full HTTP request (until \r\n\r\n)
  11388. char buf[4096];
  11389. size_t total = 0;
  11390. while (total < sizeof(buf)) {
  11391. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11392. if (n <= 0) break;
  11393. total += static_cast<size_t>(n);
  11394. // Check for end of headers
  11395. if (total >= 4) {
  11396. std::string req(buf, total);
  11397. if (req.find("\r\n\r\n") != std::string::npos) break;
  11398. }
  11399. }
  11400. // Malicious response: gzip-compressed body, no Content-Length
  11401. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11402. "Content-Encoding: gzip\r\n"
  11403. "Connection: close\r\n"
  11404. "\r\n";
  11405. ::send(cli,
  11406. #ifdef _WIN32
  11407. static_cast<const char *>(response_header.c_str()),
  11408. static_cast<int>(response_header.size()),
  11409. #else
  11410. response_header.c_str(), response_header.size(),
  11411. #endif
  11412. 0);
  11413. // Send the compressed payload (small on the wire, huge when decompressed)
  11414. size_t total_sent = 0;
  11415. while (total_sent < compressed.size()) {
  11416. auto to_send = std::min(compressed.size() - total_sent,
  11417. static_cast<size_t>(64 * 1024));
  11418. auto sent =
  11419. ::send(cli,
  11420. #ifdef _WIN32
  11421. static_cast<const char *>(compressed.c_str() + total_sent),
  11422. static_cast<int>(to_send),
  11423. #else
  11424. compressed.c_str() + total_sent, to_send,
  11425. #endif
  11426. 0);
  11427. if (sent <= 0) break;
  11428. total_sent += static_cast<size_t>(sent);
  11429. }
  11430. detail::close_socket(cli);
  11431. }
  11432. });
  11433. auto se = detail::scope_exit([&] {
  11434. detail::close_socket(srv);
  11435. server_thread.join();
  11436. });
  11437. size_t total_decompressed = 0;
  11438. {
  11439. Client cli("127.0.0.1", PORT + 3);
  11440. cli.set_read_timeout(5, 0);
  11441. cli.set_decompress(true);
  11442. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11443. auto stream = cli.open_stream("GET", "/zipbomb");
  11444. ASSERT_TRUE(stream.is_valid());
  11445. char buffer[64 * 1024];
  11446. ssize_t n;
  11447. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11448. total_decompressed += static_cast<size_t>(n);
  11449. }
  11450. }
  11451. // The decompressed size must be capped by payload_max_length. Without
  11452. // protection, the client would decompress the full 10MB from a tiny
  11453. // compressed payload, enabling a zip bomb DoS attack.
  11454. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11455. << "Client decompressed " << total_decompressed
  11456. << " bytes from a gzip response. The decompressed size should be "
  11457. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11458. }
  11459. #endif
  11460. TEST(HostAndPortPropertiesTest, NoSSL) {
  11461. httplib::Client cli("www.google.com", 1234);
  11462. ASSERT_EQ("www.google.com", cli.host());
  11463. ASSERT_EQ(1234, cli.port());
  11464. }
  11465. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11466. httplib::Client cli("www.google.com:1234");
  11467. ASSERT_EQ("www.google.com", cli.host());
  11468. ASSERT_EQ(1234, cli.port());
  11469. }
  11470. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11471. // Port number that overflows int — should not crash, client becomes invalid
  11472. httplib::Client cli("http://www.google.com:99999999999999999999");
  11473. ASSERT_FALSE(cli.is_valid());
  11474. }
  11475. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11476. // Port 99999 exceeds valid range (1-65535) — should not crash
  11477. httplib::Client cli("http://www.google.com:99999");
  11478. ASSERT_FALSE(cli.is_valid());
  11479. }
  11480. #ifdef CPPHTTPLIB_SSL_ENABLED
  11481. TEST(HostAndPortPropertiesTest, SSL) {
  11482. httplib::SSLClient cli("www.google.com");
  11483. ASSERT_EQ("www.google.com", cli.host());
  11484. ASSERT_EQ(443, cli.port());
  11485. }
  11486. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11487. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11488. std::string cert;
  11489. read_file(CA_CERT_FILE, cert);
  11490. httplib::SSLClient httplib_client("www.google.com");
  11491. // Load CA store first time
  11492. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11493. // Load CA store second time (update)
  11494. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11495. // Verify client is still valid and can make connections
  11496. httplib_client.enable_server_certificate_verification(true);
  11497. auto res = httplib_client.Get("/");
  11498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11499. // Google may return 200 or 301 depending on various factors
  11500. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11501. res->status == StatusCode::MovedPermanently_301);
  11502. }
  11503. TEST(SSLClientTest, ServerNameIndication_Online) {
  11504. auto host = "httpbingo.org";
  11505. auto path = std::string{"/get"};
  11506. SSLClient cli(host, 443);
  11507. auto res = cli.Get(path);
  11508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11509. ASSERT_EQ(StatusCode::OK_200, res->status);
  11510. }
  11511. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11512. // Use a site that will cause SSL verification failure due to self-signed cert
  11513. SSLClient cli("self-signed.badssl.com", 443);
  11514. cli.enable_server_certificate_verification(true);
  11515. auto res = cli.Get("/");
  11516. ASSERT_TRUE(!res);
  11517. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11518. // Verify backend error is captured for SSLServerVerification
  11519. // This occurs when certificate verification fails
  11520. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11521. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11522. EXPECT_NE(0UL, res.ssl_backend_error());
  11523. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11524. // For OpenSSL, ssl_error is 0 for verification errors
  11525. EXPECT_EQ(0, res.ssl_error());
  11526. #if !defined(_WIN32) || \
  11527. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11528. // On non-Windows or when Windows Schannel is disabled, the error comes
  11529. // from OpenSSL's verification
  11530. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11531. res.ssl_backend_error());
  11532. #endif
  11533. #endif
  11534. }
  11535. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11536. // Use a site where hostname doesn't match the certificate
  11537. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11538. SSLClient cli("wrong.host.badssl.com", 443);
  11539. cli.enable_server_certificate_verification(true);
  11540. cli.enable_server_hostname_verification(true);
  11541. auto res = cli.Get("/");
  11542. ASSERT_TRUE(!res);
  11543. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11544. // Verify backend error is captured for hostname verification failure
  11545. EXPECT_NE(0UL, res.ssl_backend_error());
  11546. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11547. // For OpenSSL, ssl_error is 0 for verification errors
  11548. EXPECT_EQ(0, res.ssl_error());
  11549. #if !defined(_WIN32) || \
  11550. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11551. // On non-Windows or when Windows Schannel is disabled, the error comes
  11552. // from OpenSSL's hostname verification
  11553. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11554. res.ssl_backend_error());
  11555. #endif
  11556. #endif
  11557. }
  11558. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11559. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11560. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11561. SSLClient cli("www.google.com", 443);
  11562. cli.enable_server_certificate_verification(true);
  11563. auto res = cli.Get("/");
  11564. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11565. }
  11566. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11567. SSLClient cli("www.google.com", 443);
  11568. cli.enable_server_certificate_verification(true);
  11569. cli.enable_windows_certificate_verification(false);
  11570. auto res = cli.Get("/");
  11571. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11572. }
  11573. #endif
  11574. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11575. Client cli("https://google.com");
  11576. auto res = cli.Get("/");
  11577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11578. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11579. }
  11580. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11581. SSLClient cli("google.com");
  11582. cli.set_ca_cert_path(CA_CERT_FILE);
  11583. auto res = cli.Get("/");
  11584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11585. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11586. }
  11587. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11588. SSLClient cli("google.com");
  11589. cli.enable_server_certificate_verification(true);
  11590. cli.set_ca_cert_path("hello");
  11591. auto res = cli.Get("/");
  11592. ASSERT_TRUE(!res);
  11593. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11594. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11595. // should be set
  11596. EXPECT_EQ(0, res.ssl_error());
  11597. // Verify backend error is captured for SSLLoadingCerts
  11598. // This error occurs when loading CA certificates fails
  11599. EXPECT_NE(0UL, res.ssl_backend_error());
  11600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11601. // OpenSSL specific error codes:
  11602. // > openssl errstr 0x80000002
  11603. // error:80000002:system library::No such file or directory
  11604. // > openssl errstr 0xA000126
  11605. // error:0A000126:SSL routines::unexpected eof while reading
  11606. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11607. res.ssl_backend_error() == 0xA000126);
  11608. #endif
  11609. }
  11610. TEST(SSLClientTest, ServerCertificateVerification4) {
  11611. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11612. ASSERT_TRUE(svr.is_valid());
  11613. svr.Get("/test", [&](const Request &, Response &res) {
  11614. res.set_content("test", "text/plain");
  11615. svr.stop();
  11616. ASSERT_TRUE(true);
  11617. });
  11618. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11619. auto se = detail::scope_exit([&] {
  11620. t.join();
  11621. ASSERT_FALSE(svr.is_running());
  11622. });
  11623. svr.wait_until_ready();
  11624. SSLClient cli("127.0.0.1", PORT);
  11625. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11626. cli.enable_server_certificate_verification(true);
  11627. cli.set_connection_timeout(30);
  11628. auto res = cli.Get("/test");
  11629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11630. ASSERT_EQ(StatusCode::OK_200, res->status);
  11631. }
  11632. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11633. std::string cert;
  11634. read_file(CA_CERT_FILE, cert);
  11635. SSLClient cli("google.com");
  11636. cli.load_ca_cert_store(cert.data(), cert.size());
  11637. const auto res = cli.Get("/");
  11638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11639. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11640. }
  11641. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11642. // clang-format off
  11643. static constexpr char cert[] =
  11644. "GlobalSign Root CA\n"
  11645. "==================\n"
  11646. "-----BEGIN CERTIFICATE-----\n"
  11647. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11648. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11649. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11650. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11651. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11652. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11653. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11654. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11655. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11656. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11657. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11658. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11659. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11660. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11661. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11662. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11663. "-----END CERTIFICATE-----\n";
  11664. // clang-format on
  11665. SSLClient cli("google.com");
  11666. cli.load_ca_cert_store(cert, sizeof(cert));
  11667. const auto res = cli.Get("/");
  11668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11669. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11670. }
  11671. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11672. SSLClient cli("www.youtube.com");
  11673. cli.set_ca_cert_path(CA_CERT_FILE);
  11674. cli.enable_server_certificate_verification(true);
  11675. cli.set_follow_location(true);
  11676. auto res = cli.Get("/");
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. ASSERT_EQ(StatusCode::OK_200, res->status);
  11679. }
  11680. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11681. SSLClient cli("wWw.YouTube.Com");
  11682. cli.set_ca_cert_path(CA_CERT_FILE);
  11683. cli.enable_server_certificate_verification(true);
  11684. cli.enable_server_hostname_verification(true);
  11685. cli.set_follow_location(true);
  11686. auto res = cli.Get("/");
  11687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11688. ASSERT_EQ(StatusCode::OK_200, res->status);
  11689. }
  11690. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11691. SSLClient cli("gOoGlE.COm");
  11692. cli.enable_server_certificate_verification(true);
  11693. cli.enable_server_hostname_verification(true);
  11694. cli.set_follow_location(true);
  11695. auto res = cli.Get("/");
  11696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11697. ASSERT_EQ(StatusCode::OK_200, res->status);
  11698. }
  11699. TEST(SSLClientTest, Issue2004_Online) {
  11700. Client client("https://google.com");
  11701. client.set_follow_location(true);
  11702. auto res = client.Get("/");
  11703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11704. ASSERT_EQ(StatusCode::OK_200, res->status);
  11705. auto body = res->body;
  11706. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11707. }
  11708. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11709. // Create SSLClient with invalid cert/key to make is_valid() return false
  11710. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11711. "nonexistent_key.pem");
  11712. // is_valid() should be false due to cert loading failure
  11713. ASSERT_FALSE(cli.is_valid());
  11714. auto res = cli.Get("/");
  11715. ASSERT_FALSE(res);
  11716. EXPECT_EQ(Error::SSLConnection, res.error());
  11717. }
  11718. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11719. // Test for Issue #2251: SSL error not properly reported when client cert
  11720. // and key paths are swapped or mismatched
  11721. // This simulates the scenario where user accidentally swaps the cert and key
  11722. // files
  11723. // Using client cert file as private key and vice versa (completely wrong)
  11724. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11725. // Should fail validation due to cert/key mismatch
  11726. ASSERT_FALSE(cli.is_valid());
  11727. // Attempt to make a request should fail with proper error
  11728. auto res = cli.Get("/");
  11729. ASSERT_FALSE(res);
  11730. EXPECT_EQ(Error::SSLConnection, res.error());
  11731. // SSL error should be recorded in the Result object (this is the key fix for
  11732. // Issue #2251)
  11733. auto backend_error = res.ssl_backend_error();
  11734. EXPECT_NE(0u, backend_error);
  11735. }
  11736. // Tests cert/key mismatch detection at the TLS context level
  11737. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11738. // Test that using mismatched cert/key causes connection failure.
  11739. // We verify this at the SSLClient level rather than through internal
  11740. // TLS API functions.
  11741. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11742. cli.enable_server_certificate_verification(false);
  11743. cli.set_connection_timeout(2);
  11744. // The mismatch should cause a connection or handshake error
  11745. auto res = cli.Get("/test");
  11746. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11747. // Either way, the request should fail
  11748. EXPECT_FALSE(res);
  11749. }
  11750. #endif
  11751. #if 0
  11752. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11753. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11754. ASSERT_TRUE(cli != nullptr);
  11755. cli->set_address_family(AF_INET6);
  11756. cli->set_interface("en0");
  11757. auto res = cli->Get("/get");
  11758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11759. ASSERT_EQ(StatusCode::OK_200, res->status);
  11760. }
  11761. #endif
  11762. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11763. #ifdef CPPHTTPLIB_SSL_ENABLED
  11764. void ClientCertPresent(
  11765. const std::string &client_cert_file,
  11766. const std::string &client_private_key_file,
  11767. const std::string &client_encrypted_private_key_pass = std::string()) {
  11768. using namespace httplib::tls;
  11769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11770. CLIENT_CA_CERT_DIR);
  11771. ASSERT_TRUE(svr.is_valid());
  11772. svr.Get("/test", [&](const Request &req, Response &res) {
  11773. res.set_content("test", "text/plain");
  11774. auto cert = req.peer_cert();
  11775. ASSERT_TRUE(static_cast<bool>(cert));
  11776. std::string common_name = cert.subject_cn();
  11777. EXPECT_EQ("Common Name", common_name);
  11778. });
  11779. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11780. auto se = detail::scope_exit([&] {
  11781. svr.stop();
  11782. t.join();
  11783. ASSERT_FALSE(svr.is_running());
  11784. });
  11785. svr.wait_until_ready();
  11786. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11787. client_encrypted_private_key_pass);
  11788. cli.enable_server_certificate_verification(false);
  11789. cli.set_connection_timeout(30);
  11790. auto res = cli.Get("/test");
  11791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11792. ASSERT_EQ(StatusCode::OK_200, res->status);
  11793. }
  11794. TEST(SSLClientServerTest, ClientCertPresent) {
  11795. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11796. }
  11797. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11798. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11799. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11800. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11801. }
  11802. // PEM memory-based constructor tests (works with all TLS backends)
  11803. void PemMemoryClientCertPresent(
  11804. const std::string &client_cert_file,
  11805. const std::string &client_private_key_file,
  11806. const std::string &client_encrypted_private_key_pass = std::string()) {
  11807. // Read PEM files into memory
  11808. std::string server_cert_pem, server_key_pem;
  11809. std::string client_ca_pem;
  11810. std::string client_cert_pem, client_key_pem;
  11811. read_file(SERVER_CERT_FILE, server_cert_pem);
  11812. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11813. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11814. read_file(client_cert_file, client_cert_pem);
  11815. read_file(client_private_key_file, client_key_pem);
  11816. // Create server with PEM memory
  11817. SSLServer::PemMemory server_pem = {
  11818. server_cert_pem.c_str(),
  11819. server_cert_pem.size(),
  11820. server_key_pem.c_str(),
  11821. server_key_pem.size(),
  11822. client_ca_pem.c_str(),
  11823. client_ca_pem.size(),
  11824. nullptr // no password for server key
  11825. };
  11826. SSLServer svr(server_pem);
  11827. ASSERT_TRUE(svr.is_valid());
  11828. svr.Get("/test", [&](const Request &, Response &res) {
  11829. res.set_content("test", "text/plain");
  11830. });
  11831. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11832. auto se = detail::scope_exit([&] {
  11833. svr.stop();
  11834. t.join();
  11835. ASSERT_FALSE(svr.is_running());
  11836. });
  11837. svr.wait_until_ready();
  11838. // Create client with PEM memory
  11839. const char *password = client_encrypted_private_key_pass.empty()
  11840. ? nullptr
  11841. : client_encrypted_private_key_pass.c_str();
  11842. SSLClient::PemMemory client_pem = {
  11843. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11844. client_key_pem.size(), password};
  11845. SSLClient cli(HOST, PORT, client_pem);
  11846. cli.enable_server_certificate_verification(false);
  11847. cli.set_connection_timeout(30);
  11848. auto res = cli.Get("/test");
  11849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11850. ASSERT_EQ(StatusCode::OK_200, res->status);
  11851. }
  11852. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11853. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11854. }
  11855. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11856. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11857. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11858. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11859. }
  11860. TEST(SSLClientServerTest, ClientCertMissing) {
  11861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11862. CLIENT_CA_CERT_DIR);
  11863. ASSERT_TRUE(svr.is_valid());
  11864. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11865. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11866. auto se = detail::scope_exit([&] {
  11867. svr.stop();
  11868. t.join();
  11869. ASSERT_FALSE(svr.is_running());
  11870. });
  11871. svr.wait_until_ready();
  11872. SSLClient cli(HOST, PORT);
  11873. cli.set_connection_timeout(30);
  11874. auto res = cli.Get("/test");
  11875. ASSERT_TRUE(!res);
  11876. // When client cert is missing and server requires it, connection fails
  11877. // Error type depends on backend implementation
  11878. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11879. res.error() == Error::SSLConnection);
  11880. // Verify backend error is captured
  11881. // Note: This test may have different error codes depending on the exact
  11882. // verification failure
  11883. EXPECT_NE(0UL, res.ssl_backend_error());
  11884. }
  11885. TEST(SSLClientServerTest, TrustDirOptional) {
  11886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11887. ASSERT_TRUE(svr.is_valid());
  11888. svr.Get("/test", [&](const Request &, Response &res) {
  11889. res.set_content("test", "text/plain");
  11890. });
  11891. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11892. auto se = detail::scope_exit([&] {
  11893. svr.stop();
  11894. t.join();
  11895. ASSERT_FALSE(svr.is_running());
  11896. });
  11897. svr.wait_until_ready();
  11898. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11899. cli.enable_server_certificate_verification(false);
  11900. cli.set_connection_timeout(30);
  11901. auto res = cli.Get("/test");
  11902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11903. ASSERT_EQ(StatusCode::OK_200, res->status);
  11904. }
  11905. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11906. class NoListenSSLServer : public SSLServer {
  11907. public:
  11908. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11909. const char *client_ca_cert_file_path,
  11910. const char *client_ca_cert_dir_path = nullptr)
  11911. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11912. client_ca_cert_dir_path),
  11913. stop_(false) {}
  11914. std::atomic_bool stop_;
  11915. private:
  11916. bool process_and_close_socket(socket_t /*sock*/) override {
  11917. // Don't create SSL context
  11918. while (!stop_.load()) {
  11919. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11920. }
  11921. return true;
  11922. }
  11923. };
  11924. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11925. CLIENT_CA_CERT_FILE);
  11926. ASSERT_TRUE(svr.is_valid());
  11927. svr.Get("/test", [&](const Request &, Response &res) {
  11928. res.set_content("test", "text/plain");
  11929. });
  11930. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11931. auto se = detail::scope_exit([&] {
  11932. svr.stop_ = true;
  11933. svr.stop();
  11934. t.join();
  11935. ASSERT_FALSE(svr.is_running());
  11936. });
  11937. svr.wait_until_ready();
  11938. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11939. cli.enable_server_certificate_verification(false);
  11940. cli.set_connection_timeout(1);
  11941. auto res = cli.Get("/test");
  11942. ASSERT_TRUE(!res);
  11943. EXPECT_EQ(Error::SSLConnection, res.error());
  11944. // Timeout results in WantRead error code (maps to backend-specific value)
  11945. EXPECT_NE(0, res.ssl_error());
  11946. }
  11947. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11948. // Test SSLServer with client certificate verification using the standard
  11949. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11951. CLIENT_CA_CERT_DIR);
  11952. ASSERT_TRUE(svr.is_valid());
  11953. svr.Get("/test", [&](const Request &req, Response &res) {
  11954. res.set_content("test", "text/plain");
  11955. auto cert = req.peer_cert();
  11956. ASSERT_TRUE(static_cast<bool>(cert));
  11957. auto common_name = cert.subject_cn();
  11958. EXPECT_EQ("Common Name", common_name);
  11959. });
  11960. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11961. auto se = detail::scope_exit([&] {
  11962. svr.stop();
  11963. t.join();
  11964. ASSERT_FALSE(svr.is_running());
  11965. });
  11966. svr.wait_until_ready();
  11967. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11968. cli.enable_server_certificate_verification(false);
  11969. cli.set_connection_timeout(30);
  11970. auto res = cli.Get("/test");
  11971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11972. ASSERT_EQ(StatusCode::OK_200, res->status);
  11973. }
  11974. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11975. // Verifies that wildcard matching and exact matching work consistently
  11976. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11977. using namespace httplib::tls;
  11978. // We need a running server to test against
  11979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11980. ASSERT_TRUE(svr.is_valid());
  11981. svr.Get("/test", [](const Request &, Response &res) {
  11982. res.set_content("ok", "text/plain");
  11983. });
  11984. thread t([&]() { svr.listen(HOST, PORT); });
  11985. auto se = detail::scope_exit([&] {
  11986. svr.stop();
  11987. t.join();
  11988. });
  11989. svr.wait_until_ready();
  11990. bool verify_callback_called = false;
  11991. bool verify_result_wrong = false;
  11992. SSLClient cli(HOST, PORT);
  11993. cli.enable_server_certificate_verification(true);
  11994. cli.set_ca_cert_path(CA_CERT_FILE);
  11995. cli.set_connection_timeout(5);
  11996. // Note: Test certificate has CN="Common Name", not "localhost"
  11997. bool verify_result_cn = false;
  11998. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11999. verify_callback_called = true;
  12000. if (!ctx.cert) return false;
  12001. // Test 1: "Common Name" should match (our test server cert CN)
  12002. verify_result_cn = ctx.check_hostname("Common Name");
  12003. // Test 2: wrong hostname should not match
  12004. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12005. return true; // Accept for the purpose of this test
  12006. });
  12007. auto res = cli.Get("/test");
  12008. // The request may succeed or fail depending on cert configuration
  12009. // but the callback should have been called
  12010. ASSERT_TRUE(verify_callback_called)
  12011. << "Verify callback should have been called";
  12012. // CN="Common Name" should match our test certificate
  12013. //
  12014. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12015. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12016. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12017. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12018. // <openssl/base.h>, which is included transitively when
  12019. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12020. #if defined(OPENSSL_IS_BORINGSSL)
  12021. EXPECT_FALSE(verify_result_cn)
  12022. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12023. #else
  12024. EXPECT_TRUE(verify_result_cn)
  12025. << "verify_hostname should match 'Common Name' (certificate CN)";
  12026. #endif
  12027. // Wrong hostname should not match
  12028. EXPECT_FALSE(verify_result_wrong)
  12029. << "verify_hostname should not match 'wronghost.example.com'";
  12030. }
  12031. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12032. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12033. // X509_check_ip behavior and must hold for every backend.
  12034. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12035. using namespace httplib::tls;
  12036. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12037. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12038. ASSERT_TRUE(svr.is_valid());
  12039. svr.Get("/test", [](const Request &, Response &res) {
  12040. res.set_content("ok", "text/plain");
  12041. });
  12042. thread t([&]() { svr.listen(HOST, PORT); });
  12043. auto se = detail::scope_exit([&] {
  12044. svr.stop();
  12045. t.join();
  12046. });
  12047. svr.wait_until_ready();
  12048. bool verify_callback_called = false;
  12049. bool ip_matched_via_cn = true;
  12050. SSLClient cli(HOST, PORT);
  12051. cli.enable_server_certificate_verification(true);
  12052. cli.set_ca_cert_path(CA_CERT_FILE);
  12053. cli.set_connection_timeout(5);
  12054. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12055. verify_callback_called = true;
  12056. if (!ctx.cert) return false;
  12057. // The IP appears only in the CN, so it must NOT be accepted.
  12058. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12059. return true; // Accept for the purpose of this test
  12060. });
  12061. cli.Get("/test");
  12062. ASSERT_TRUE(verify_callback_called)
  12063. << "Verify callback should have been called";
  12064. EXPECT_FALSE(ip_matched_via_cn)
  12065. << "An IP host must not be authenticated via the certificate CN";
  12066. }
  12067. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12068. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12069. using namespace httplib::tls;
  12070. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12071. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12072. ASSERT_TRUE(svr.is_valid());
  12073. svr.Get("/test", [](const Request &, Response &res) {
  12074. res.set_content("ok", "text/plain");
  12075. });
  12076. thread t([&]() { svr.listen(HOST, PORT); });
  12077. auto se = detail::scope_exit([&] {
  12078. svr.stop();
  12079. t.join();
  12080. });
  12081. svr.wait_until_ready();
  12082. bool verify_callback_called = false;
  12083. bool san_matched = false;
  12084. bool wrong_ipv6_matched = true;
  12085. bool cn_ipv6_matched = true;
  12086. SSLClient cli(HOST, PORT);
  12087. cli.enable_server_certificate_verification(true);
  12088. cli.set_ca_cert_path(CA_CERT_FILE);
  12089. cli.set_connection_timeout(5);
  12090. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12091. verify_callback_called = true;
  12092. if (!ctx.cert) return false;
  12093. // Matches the IPv6 iPAddress SAN.
  12094. san_matched = ctx.check_hostname("2001:db8::1");
  12095. // A different IPv6 address must not match.
  12096. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12097. // "::1" lives only in the CN, so it must not be accepted.
  12098. cn_ipv6_matched = ctx.check_hostname("::1");
  12099. return true; // Accept for the purpose of this test
  12100. });
  12101. cli.Get("/test");
  12102. ASSERT_TRUE(verify_callback_called)
  12103. << "Verify callback should have been called";
  12104. EXPECT_TRUE(san_matched)
  12105. << "verify_hostname should match an IPv6 iPAddress SAN";
  12106. EXPECT_FALSE(wrong_ipv6_matched)
  12107. << "verify_hostname should not match a non-matching IPv6 address";
  12108. EXPECT_FALSE(cn_ipv6_matched)
  12109. << "An IPv6 host must not be authenticated via the certificate CN";
  12110. }
  12111. #endif
  12112. // mbedTLS-specific callback constructor test
  12113. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12114. #ifdef CPPHTTPLIB_SSL_ENABLED
  12115. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12116. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12117. ASSERT_TRUE(svr.is_valid());
  12118. // Set up a handler to verify client certificate is present
  12119. bool client_cert_verified = false;
  12120. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12121. // Verify that client certificate was provided
  12122. client_cert_verified = true;
  12123. res.set_content("success", "text/plain");
  12124. });
  12125. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12126. auto se = detail::scope_exit([&] {
  12127. svr.stop();
  12128. t.join();
  12129. ASSERT_FALSE(svr.is_running());
  12130. });
  12131. svr.wait_until_ready();
  12132. // Client with certificate
  12133. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12134. cli.enable_server_certificate_verification(false);
  12135. cli.set_connection_timeout(30);
  12136. auto res = cli.Get("/test");
  12137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12138. ASSERT_EQ(StatusCode::OK_200, res->status);
  12139. ASSERT_TRUE(client_cert_verified);
  12140. EXPECT_EQ("success", res->body);
  12141. }
  12142. #endif
  12143. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12144. // backends
  12145. #ifdef CPPHTTPLIB_SSL_ENABLED
  12146. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12147. using namespace httplib::tls;
  12148. // Test that when client CA cert file is provided,
  12149. // the server properly requests and validates client certificates
  12150. // Create a server with client authentication
  12151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12152. ASSERT_TRUE(svr.is_valid());
  12153. bool handler_called = false;
  12154. svr.Get("/test", [&](const Request &req, Response &res) {
  12155. handler_called = true;
  12156. // Verify that a client certificate was provided
  12157. auto cert = req.peer_cert();
  12158. ASSERT_TRUE(static_cast<bool>(cert));
  12159. // Get the issuer name
  12160. std::string issuer_str = cert.issuer_name();
  12161. ASSERT_FALSE(issuer_str.empty());
  12162. // The client certificate should be issued by our test CA
  12163. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12164. res.set_content("authenticated", "text/plain");
  12165. });
  12166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12167. auto se = detail::scope_exit([&] {
  12168. svr.stop();
  12169. t.join();
  12170. ASSERT_FALSE(svr.is_running());
  12171. });
  12172. svr.wait_until_ready();
  12173. // Connect with a client certificate issued by the CA
  12174. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12175. cli.enable_server_certificate_verification(false);
  12176. cli.set_connection_timeout(30);
  12177. auto res = cli.Get("/test");
  12178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12179. ASSERT_EQ(StatusCode::OK_200, res->status);
  12180. ASSERT_TRUE(handler_called);
  12181. EXPECT_EQ("authenticated", res->body);
  12182. }
  12183. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12184. using namespace httplib::tls;
  12185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12186. ASSERT_TRUE(svr.is_valid());
  12187. svr.Get("/test", [](const Request &, Response &res) {
  12188. res.set_content("ok", "text/plain");
  12189. });
  12190. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12191. auto se = detail::scope_exit([&] {
  12192. svr.stop();
  12193. t.join();
  12194. });
  12195. svr.wait_until_ready();
  12196. SSLClient cli(HOST, PORT);
  12197. cli.enable_server_certificate_verification(false);
  12198. cli.set_connection_timeout(30);
  12199. bool cert_checked = false;
  12200. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12201. if (ctx.cert) {
  12202. auto sans = ctx.sans();
  12203. // Test certificate may or may not have SANs - just verify the API
  12204. // works If SANs exist, verify the types are valid
  12205. for (const auto &san : sans) {
  12206. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12207. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12208. san.type == SanType::OTHER);
  12209. EXPECT_FALSE(san.value.empty());
  12210. }
  12211. cert_checked = true;
  12212. }
  12213. return true;
  12214. });
  12215. auto res = cli.Get("/test");
  12216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12217. EXPECT_TRUE(cert_checked);
  12218. }
  12219. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12220. using namespace httplib::tls;
  12221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12222. ASSERT_TRUE(svr.is_valid());
  12223. svr.Get("/test", [](const Request &, Response &res) {
  12224. res.set_content("ok", "text/plain");
  12225. });
  12226. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12227. auto se = detail::scope_exit([&] {
  12228. svr.stop();
  12229. t.join();
  12230. });
  12231. svr.wait_until_ready();
  12232. SSLClient cli(HOST, PORT);
  12233. cli.enable_server_certificate_verification(false);
  12234. cli.set_connection_timeout(30);
  12235. bool validity_checked = false;
  12236. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12237. if (ctx.cert) {
  12238. time_t not_before = 0, not_after = 0;
  12239. bool result = ctx.validity(not_before, not_after);
  12240. EXPECT_TRUE(result);
  12241. // Verify that not_before < now < not_after for a valid cert
  12242. time_t now = time(nullptr);
  12243. EXPECT_LT(not_before, now);
  12244. EXPECT_GT(not_after, now);
  12245. validity_checked = true;
  12246. }
  12247. return true;
  12248. });
  12249. auto res = cli.Get("/test");
  12250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12251. EXPECT_TRUE(validity_checked);
  12252. }
  12253. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12254. using namespace httplib::tls;
  12255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12256. ASSERT_TRUE(svr.is_valid());
  12257. svr.Get("/test", [](const Request &, Response &res) {
  12258. res.set_content("ok", "text/plain");
  12259. });
  12260. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12261. auto se = detail::scope_exit([&] {
  12262. svr.stop();
  12263. t.join();
  12264. });
  12265. svr.wait_until_ready();
  12266. SSLClient cli(HOST, PORT);
  12267. cli.enable_server_certificate_verification(false);
  12268. cli.set_connection_timeout(30);
  12269. bool serial_checked = false;
  12270. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12271. if (ctx.cert) {
  12272. std::string serial = ctx.serial();
  12273. EXPECT_FALSE(serial.empty());
  12274. // Serial should be a hex string
  12275. for (char c : serial) {
  12276. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12277. (c >= 'a' && c <= 'f'));
  12278. }
  12279. serial_checked = true;
  12280. }
  12281. return true;
  12282. });
  12283. auto res = cli.Get("/test");
  12284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12285. EXPECT_TRUE(serial_checked);
  12286. }
  12287. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12288. // Test 1: Valid CA file - no error should be recorded
  12289. {
  12290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12291. CLIENT_CA_CERT_FILE);
  12292. ASSERT_TRUE(svr.is_valid());
  12293. // With valid setup, last_ssl_error should be 0
  12294. EXPECT_EQ(0, svr.ssl_last_error());
  12295. }
  12296. // Test 2: Invalid CA file content
  12297. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12298. {
  12299. // Create a temporary file with completely invalid content
  12300. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12301. {
  12302. std::ofstream ofs(temp_invalid_ca);
  12303. ofs << "This is not a certificate file at all\n";
  12304. ofs << "Just plain text content\n";
  12305. }
  12306. // Create server with invalid CA file
  12307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12308. // Clean up temporary file
  12309. std::remove(temp_invalid_ca);
  12310. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12311. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12312. // Note: SSL_CTX_load_verify_locations typically fails first,
  12313. // but our error handling code path is still exercised
  12314. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12315. }
  12316. }
  12317. TEST(VerifyCallbackTest, VerifyContextFields) {
  12318. using namespace httplib::tls;
  12319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12320. ASSERT_TRUE(svr.is_valid());
  12321. svr.Get("/test", [](const Request &, Response &res) {
  12322. res.set_content("ok", "text/plain");
  12323. });
  12324. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12325. auto se = detail::scope_exit([&] {
  12326. svr.stop();
  12327. t.join();
  12328. });
  12329. svr.wait_until_ready();
  12330. SSLClient cli(HOST, PORT);
  12331. cli.enable_server_certificate_verification(false);
  12332. cli.set_connection_timeout(30);
  12333. int callback_count = 0;
  12334. bool saw_leaf_cert = false;
  12335. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12336. if (ctx.cert) {
  12337. callback_count++;
  12338. // We should see at least one certificate (the leaf)
  12339. std::string cn = ctx.subject_cn();
  12340. if (!cn.empty()) { saw_leaf_cert = true; }
  12341. // Verify context fields are populated
  12342. EXPECT_NE(ctx.session, nullptr);
  12343. EXPECT_GE(ctx.depth, 0);
  12344. }
  12345. return true;
  12346. });
  12347. auto res = cli.Get("/test");
  12348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12349. EXPECT_GT(callback_count, 0);
  12350. EXPECT_TRUE(saw_leaf_cert);
  12351. }
  12352. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12353. using httplib::tls::TlsError;
  12354. // Test that verify_error_to_string returns empty for success
  12355. std::string success_str = TlsError::verify_error_to_string(0);
  12356. EXPECT_TRUE(success_str.empty());
  12357. // Test that verify_error_to_string returns non-empty for error codes
  12358. // Using a common error code (certificate expired)
  12359. std::string error_str =
  12360. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12361. EXPECT_FALSE(error_str.empty());
  12362. }
  12363. TEST(SessionVerifierTest, CertificateAccepted) {
  12364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12365. ASSERT_TRUE(svr.is_valid());
  12366. svr.Get("/test", [](const Request &, Response &res) {
  12367. res.set_content("ok", "text/plain");
  12368. });
  12369. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12370. auto se = detail::scope_exit([&] {
  12371. svr.stop();
  12372. t.join();
  12373. });
  12374. svr.wait_until_ready();
  12375. SSLClient cli(HOST, PORT);
  12376. cli.enable_server_certificate_verification(false);
  12377. cli.set_connection_timeout(30);
  12378. bool callback_called = false;
  12379. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12380. EXPECT_NE(session, nullptr);
  12381. callback_called = true;
  12382. return SSLVerifierResponse::CertificateAccepted;
  12383. });
  12384. auto res = cli.Get("/test");
  12385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12386. EXPECT_EQ(200, res->status);
  12387. EXPECT_TRUE(callback_called);
  12388. }
  12389. TEST(SessionVerifierTest, CertificateRejected) {
  12390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12391. ASSERT_TRUE(svr.is_valid());
  12392. svr.Get("/test", [](const Request &, Response &res) {
  12393. res.set_content("ok", "text/plain");
  12394. });
  12395. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12396. auto se = detail::scope_exit([&] {
  12397. svr.stop();
  12398. t.join();
  12399. });
  12400. svr.wait_until_ready();
  12401. SSLClient cli(HOST, PORT);
  12402. cli.enable_server_certificate_verification(false);
  12403. cli.set_connection_timeout(30);
  12404. bool callback_called = false;
  12405. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12406. EXPECT_NE(session, nullptr);
  12407. callback_called = true;
  12408. return SSLVerifierResponse::CertificateRejected;
  12409. });
  12410. auto res = cli.Get("/test");
  12411. EXPECT_FALSE(res);
  12412. EXPECT_TRUE(callback_called);
  12413. }
  12414. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12416. ASSERT_TRUE(svr.is_valid());
  12417. svr.Get("/test", [](const Request &, Response &res) {
  12418. res.set_content("ok", "text/plain");
  12419. });
  12420. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12421. auto se = detail::scope_exit([&] {
  12422. svr.stop();
  12423. t.join();
  12424. });
  12425. svr.wait_until_ready();
  12426. // NoDecisionMade with verification disabled should succeed (no default check)
  12427. SSLClient cli(HOST, PORT);
  12428. cli.enable_server_certificate_verification(false);
  12429. cli.set_connection_timeout(30);
  12430. bool callback_called = false;
  12431. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12432. EXPECT_NE(session, nullptr);
  12433. callback_called = true;
  12434. return SSLVerifierResponse::NoDecisionMade;
  12435. });
  12436. auto res = cli.Get("/test");
  12437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12438. EXPECT_EQ(200, res->status);
  12439. EXPECT_TRUE(callback_called);
  12440. }
  12441. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12443. ASSERT_TRUE(svr.is_valid());
  12444. svr.Get("/test", [](const Request &, Response &res) {
  12445. res.set_content("ok", "text/plain");
  12446. });
  12447. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12448. auto se = detail::scope_exit([&] {
  12449. svr.stop();
  12450. t.join();
  12451. });
  12452. svr.wait_until_ready();
  12453. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12454. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12455. // so we only check that the request fails, not whether the callback was
  12456. // called.
  12457. SSLClient cli(HOST, PORT);
  12458. cli.enable_server_certificate_verification(true);
  12459. cli.set_connection_timeout(30);
  12460. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12461. EXPECT_NE(session, nullptr);
  12462. return SSLVerifierResponse::NoDecisionMade;
  12463. });
  12464. auto res = cli.Get("/test");
  12465. EXPECT_FALSE(res);
  12466. }
  12467. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12468. // Test SSL server using PemMemory constructor with client CA certificates
  12469. // Read PEM files
  12470. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12471. read_file(SERVER_CERT_FILE, server_cert_pem);
  12472. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12473. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12474. // Create SSLServer with PemMemory constructor including client CA
  12475. SSLServer::PemMemory server_pem = {
  12476. server_cert_pem.c_str(),
  12477. server_cert_pem.size(),
  12478. server_key_pem.c_str(),
  12479. server_key_pem.size(),
  12480. client_ca_pem.c_str(),
  12481. client_ca_pem.size(),
  12482. nullptr // no password for server key
  12483. };
  12484. SSLServer svr(server_pem);
  12485. ASSERT_TRUE(svr.is_valid());
  12486. // No SSL error should be recorded for valid setup
  12487. EXPECT_EQ(0, svr.ssl_last_error());
  12488. // Set up server endpoints
  12489. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12490. res.set_content("ok", "text/plain");
  12491. });
  12492. // Start server in a thread
  12493. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12494. svr.wait_until_ready();
  12495. // Connect with client certificate (using constructor with paths)
  12496. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12497. cli.enable_server_certificate_verification(false);
  12498. auto res = cli.Get("/test-pem-ca");
  12499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12500. EXPECT_EQ(200, res->status);
  12501. EXPECT_EQ("ok", res->body);
  12502. svr.stop();
  12503. server_thread.join();
  12504. }
  12505. #endif
  12506. #ifdef _WIN32
  12507. TEST(CleanupTest, WSACleanup) {
  12508. int ret = WSACleanup();
  12509. ASSERT_EQ(0, ret);
  12510. }
  12511. #endif
  12512. #ifndef CPPHTTPLIB_SSL_ENABLED
  12513. TEST(NoSSLSupport, SimpleInterface) {
  12514. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12515. }
  12516. #endif
  12517. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12518. TEST(InvalidScheme, SimpleInterface) {
  12519. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12520. }
  12521. #endif
  12522. TEST(NoScheme, SimpleInterface) {
  12523. Client cli("yahoo.com:80");
  12524. ASSERT_TRUE(cli.is_valid());
  12525. }
  12526. TEST(SendAPI, SimpleInterface_Online) {
  12527. Client cli("http://yahoo.com");
  12528. Request req;
  12529. req.method = "GET";
  12530. req.path = "/";
  12531. auto res = cli.send(req);
  12532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12533. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12534. }
  12535. TEST(SendAPI, WithParamsInRequest) {
  12536. Server svr;
  12537. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12538. EXPECT_TRUE(req.has_param("test"));
  12539. EXPECT_EQ("test_value", req.get_param_value("test"));
  12540. });
  12541. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12542. auto se = detail::scope_exit([&] {
  12543. svr.stop();
  12544. t.join();
  12545. ASSERT_FALSE(svr.is_running());
  12546. });
  12547. svr.wait_until_ready();
  12548. Client cli(HOST, PORT);
  12549. {
  12550. Request req;
  12551. req.method = "GET";
  12552. req.path = "/";
  12553. req.params.emplace("test", "test_value");
  12554. auto res = cli.send(req);
  12555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12556. }
  12557. {
  12558. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12560. }
  12561. }
  12562. TEST(ClientImplMethods, GetSocketTest) {
  12563. httplib::Server svr;
  12564. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12565. res.status = StatusCode::OK_200;
  12566. });
  12567. auto port = svr.bind_to_any_port("127.0.0.1");
  12568. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12569. auto se = detail::scope_exit([&] {
  12570. svr.stop();
  12571. thread.join();
  12572. ASSERT_FALSE(svr.is_running());
  12573. });
  12574. svr.wait_until_ready();
  12575. {
  12576. httplib::Client cli("127.0.0.1", port);
  12577. cli.set_keep_alive(true);
  12578. // Use the behavior of cpp-httplib of opening the connection
  12579. // only when the first request happens. If that changes,
  12580. // this test would be obsolete.
  12581. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12582. // This also implicitly tests the server. But other tests would fail much
  12583. // earlier than this one to be considered.
  12584. auto res = cli.Get("/");
  12585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12586. EXPECT_EQ(StatusCode::OK_200, res->status);
  12587. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12588. }
  12589. }
  12590. #ifdef CPPHTTPLIB_SSL_ENABLED
  12591. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12592. Client cli("http://yahoo.com");
  12593. auto res = cli.Get("/");
  12594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12595. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12596. cli.set_follow_location(true);
  12597. res = cli.Get("/");
  12598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12599. EXPECT_EQ(StatusCode::OK_200, res->status);
  12600. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12601. }
  12602. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12603. Client cli("https://yahoo.com");
  12604. auto res = cli.Get("/");
  12605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12606. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12607. cli.set_follow_location(true);
  12608. res = cli.Get("/");
  12609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12610. EXPECT_EQ(StatusCode::OK_200, res->status);
  12611. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12612. }
  12613. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12614. Client cli("https://yahoo.com");
  12615. auto res = cli.Get("/");
  12616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12617. ASSERT_FALSE(!res);
  12618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12619. ASSERT_FALSE(res == nullptr);
  12620. ASSERT_TRUE(res != nullptr);
  12621. EXPECT_EQ(Error::Success, res.error());
  12622. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12623. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12624. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12625. cli.set_follow_location(true);
  12626. res = cli.Get("/");
  12627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12628. EXPECT_EQ(Error::Success, res.error());
  12629. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12630. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12631. EXPECT_EQ(StatusCode::OK_200, res->status);
  12632. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12633. }
  12634. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12635. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12636. Client cli("https://cdnjs.cloudflare.com");
  12637. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12638. Headers{{"Accept-Encoding", "br"}});
  12639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12640. EXPECT_EQ(StatusCode::OK_200, res->status);
  12641. EXPECT_EQ(287630U, res->body.size());
  12642. EXPECT_EQ("application/javascript; charset=utf-8",
  12643. res->get_header_value("Content-Type"));
  12644. }
  12645. #endif
  12646. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12647. #undef REDIR_HOST // Silence compiler warning
  12648. #define REDIR_HOST "https://httpbingo.org"
  12649. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12650. Client cli(REDIR_HOST);
  12651. cli.set_follow_location(true);
  12652. auto res =
  12653. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12655. EXPECT_EQ(StatusCode::OK_200, res->status);
  12656. }
  12657. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12658. Client cli(REDIR_HOST);
  12659. cli.set_follow_location(true);
  12660. Params params;
  12661. params.emplace("url", "http://example.com");
  12662. params.emplace("status_code", "302");
  12663. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12665. EXPECT_EQ(StatusCode::OK_200, res->status);
  12666. }
  12667. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12668. Client cli(REDIR_HOST);
  12669. cli.set_follow_location(true);
  12670. Params params;
  12671. params.emplace("url", "http://example.com");
  12672. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12674. EXPECT_EQ(StatusCode::OK_200, res->status);
  12675. }
  12676. TEST(HttpToHttpsRedirectTest, CertFile) {
  12677. auto ssl_port = PORT + 1;
  12678. Server svr;
  12679. ASSERT_TRUE(svr.is_valid());
  12680. svr.Get("/index", [&](const Request &, Response &res) {
  12681. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12682. "/index");
  12683. svr.stop();
  12684. });
  12685. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12686. ASSERT_TRUE(ssl_svr.is_valid());
  12687. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12688. res.set_content("test", "text/plain");
  12689. ssl_svr.stop();
  12690. });
  12691. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12692. thread t2 =
  12693. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12694. auto se = detail::scope_exit([&] {
  12695. t2.join();
  12696. t.join();
  12697. ASSERT_FALSE(svr.is_running());
  12698. });
  12699. svr.wait_until_ready();
  12700. ssl_svr.wait_until_ready();
  12701. Client cli("127.0.0.1", PORT);
  12702. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12703. cli.enable_server_certificate_verification(true);
  12704. cli.set_follow_location(true);
  12705. cli.set_connection_timeout(30);
  12706. auto res = cli.Get("/index");
  12707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12708. ASSERT_EQ(StatusCode::OK_200, res->status);
  12709. }
  12710. TEST(SSLClientRedirectTest, CertFile) {
  12711. auto ssl_port = PORT + 1;
  12712. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12713. ASSERT_TRUE(ssl_svr1.is_valid());
  12714. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12715. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12716. "/index");
  12717. ssl_svr1.stop();
  12718. });
  12719. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12720. ASSERT_TRUE(ssl_svr2.is_valid());
  12721. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12722. res.set_content("test", "text/plain");
  12723. ssl_svr2.stop();
  12724. });
  12725. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12726. thread t2 =
  12727. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12728. auto se = detail::scope_exit([&] {
  12729. t2.join();
  12730. t.join();
  12731. ASSERT_FALSE(ssl_svr1.is_running());
  12732. });
  12733. ssl_svr1.wait_until_ready();
  12734. ssl_svr2.wait_until_ready();
  12735. SSLClient cli("127.0.0.1", PORT);
  12736. std::string cert;
  12737. read_file(SERVER_CERT2_FILE, cert);
  12738. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12739. cli.enable_server_certificate_verification(true);
  12740. cli.set_follow_location(true);
  12741. cli.set_connection_timeout(30);
  12742. auto res = cli.Get("/index");
  12743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12744. ASSERT_EQ(StatusCode::OK_200, res->status);
  12745. }
  12746. #endif
  12747. #ifdef CPPHTTPLIB_SSL_ENABLED
  12748. // Test that set_ca_cert_store() skips system certs (consistent with
  12749. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12750. // should be trusted - system certs should NOT be loaded.
  12751. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12752. // Load a specific cert that is NOT a system CA cert
  12753. std::string cert;
  12754. read_file(SERVER_CERT2_FILE, cert);
  12755. SSLClient cli("google.com");
  12756. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12757. cli.enable_server_certificate_verification(true);
  12758. // This should FAIL because:
  12759. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12760. // 2. System certs should NOT be loaded when custom store is set
  12761. // If system certs WERE loaded, this would succeed
  12762. auto res = cli.Get("/");
  12763. ASSERT_FALSE(res);
  12764. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12765. }
  12766. // Same as above, but through the native store handle path. Regression test:
  12767. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12768. // merged system certs into the user-provided store.
  12769. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12770. std::string cert;
  12771. read_file(SERVER_CERT2_FILE, cert);
  12772. SSLClient cli("google.com");
  12773. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12774. cli.enable_server_certificate_verification(true);
  12775. auto res = cli.Get("/");
  12776. ASSERT_FALSE(res);
  12777. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12778. }
  12779. // A custom store set via the native handle must still verify a server whose
  12780. // cert it does contain.
  12781. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12782. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12783. ASSERT_TRUE(svr.is_valid());
  12784. svr.Get("/test", [&](const Request &, Response &res) {
  12785. res.set_content("test", "text/plain");
  12786. });
  12787. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12788. auto se = detail::scope_exit([&] {
  12789. svr.stop();
  12790. t.join();
  12791. ASSERT_FALSE(svr.is_running());
  12792. });
  12793. svr.wait_until_ready();
  12794. SSLClient cli("127.0.0.1", PORT);
  12795. std::string cert;
  12796. read_file(SERVER_CERT2_FILE, cert);
  12797. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12798. cli.enable_server_certificate_verification(true);
  12799. cli.set_connection_timeout(30);
  12800. auto res = cli.Get("/test");
  12801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12802. ASSERT_EQ(StatusCode::OK_200, res->status);
  12803. }
  12804. // CA certs loaded through the universal Client must be transferred to the
  12805. // client created internally for following an HTTPS redirect. Regression test:
  12806. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12807. // the CA data for redirect transfer.
  12808. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12809. auto ssl_port = PORT + 1;
  12810. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12811. ASSERT_TRUE(ssl_svr1.is_valid());
  12812. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12813. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12814. "/index");
  12815. });
  12816. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12817. ASSERT_TRUE(ssl_svr2.is_valid());
  12818. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12819. res.set_content("test", "text/plain");
  12820. });
  12821. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12822. thread t2 =
  12823. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12824. auto se = detail::scope_exit([&] {
  12825. ssl_svr2.stop();
  12826. ssl_svr1.stop();
  12827. t2.join();
  12828. t.join();
  12829. ASSERT_FALSE(ssl_svr1.is_running());
  12830. });
  12831. ssl_svr1.wait_until_ready();
  12832. ssl_svr2.wait_until_ready();
  12833. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12834. std::string cert;
  12835. read_file(SERVER_CERT2_FILE, cert);
  12836. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12837. cli.enable_server_certificate_verification(true);
  12838. cli.set_follow_location(true);
  12839. cli.set_connection_timeout(30);
  12840. auto res = cli.Get("/index");
  12841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12842. ASSERT_EQ(StatusCode::OK_200, res->status);
  12843. }
  12844. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12845. // so a host signed by a system CA verifies even though a custom CA is set
  12846. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12847. std::string cert;
  12848. read_file(SERVER_CERT2_FILE, cert);
  12849. SSLClient cli("google.com");
  12850. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12851. cli.enable_system_ca(true);
  12852. cli.enable_server_certificate_verification(true);
  12853. auto res = cli.Get("/");
  12854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12855. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12856. }
  12857. // The custom CA remains effective when combined with the system CA
  12858. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12859. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12860. ASSERT_TRUE(svr.is_valid());
  12861. svr.Get("/test", [&](const Request &, Response &res) {
  12862. res.set_content("test", "text/plain");
  12863. });
  12864. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12865. auto se = detail::scope_exit([&] {
  12866. svr.stop();
  12867. t.join();
  12868. ASSERT_FALSE(svr.is_running());
  12869. });
  12870. svr.wait_until_ready();
  12871. SSLClient cli("127.0.0.1", PORT);
  12872. std::string cert;
  12873. read_file(SERVER_CERT2_FILE, cert);
  12874. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12875. cli.enable_system_ca(true);
  12876. cli.enable_server_certificate_verification(true);
  12877. cli.set_connection_timeout(30);
  12878. auto res = cli.Get("/test");
  12879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12880. ASSERT_EQ(StatusCode::OK_200, res->status);
  12881. }
  12882. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12883. // skip chain verification entirely (only the certificate identity was
  12884. // checked), so a server presenting an untrusted certificate with a matching
  12885. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12886. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12887. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12888. ASSERT_TRUE(svr.is_valid());
  12889. svr.Get("/test", [&](const Request &, Response &res) {
  12890. res.set_content("test", "text/plain");
  12891. });
  12892. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12893. auto se = detail::scope_exit([&] {
  12894. svr.stop();
  12895. t.join();
  12896. ASSERT_FALSE(svr.is_running());
  12897. });
  12898. svr.wait_until_ready();
  12899. SSLClient cli("127.0.0.1", PORT);
  12900. std::string cert;
  12901. // A trusted CA that did not sign the server certificate. The server cert
  12902. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12903. // this connection.
  12904. read_file(CLIENT_CA_CERT_FILE, cert);
  12905. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12906. cli.enable_server_certificate_verification(true);
  12907. cli.set_connection_timeout(30);
  12908. auto res = cli.Get("/test");
  12909. ASSERT_FALSE(res);
  12910. }
  12911. // enable_system_ca(false) prevents system CA loading entirely
  12912. TEST(SSLClientTest, DisableSystemCa_Online) {
  12913. SSLClient cli("google.com");
  12914. cli.enable_system_ca(false);
  12915. cli.enable_server_certificate_verification(true);
  12916. auto res = cli.Get("/");
  12917. ASSERT_FALSE(res);
  12918. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12919. // itself when the CA chain is empty
  12920. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12921. res.error() == Error::SSLConnection);
  12922. }
  12923. // The universal Client forwards enable_system_ca()
  12924. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12925. std::string cert;
  12926. read_file(SERVER_CERT2_FILE, cert);
  12927. Client cli("https://google.com");
  12928. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12929. cli.enable_system_ca(true);
  12930. cli.enable_server_certificate_verification(true);
  12931. auto res = cli.Get("/");
  12932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12933. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12934. }
  12935. // The system CA policy must carry over to the client created internally for
  12936. // following a cross-host HTTPS redirect
  12937. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12938. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12939. ASSERT_TRUE(svr.is_valid());
  12940. svr.Get("/index", [&](const Request &, Response &res) {
  12941. res.set_redirect("https://www.google.com/");
  12942. });
  12943. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12944. auto se = detail::scope_exit([&] {
  12945. svr.stop();
  12946. t.join();
  12947. ASSERT_FALSE(svr.is_running());
  12948. });
  12949. svr.wait_until_ready();
  12950. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12951. std::string cert;
  12952. read_file(SERVER_CERT2_FILE, cert);
  12953. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12954. cli.enable_system_ca(true);
  12955. cli.enable_server_certificate_verification(true);
  12956. cli.set_follow_location(true);
  12957. cli.set_connection_timeout(30);
  12958. // Receiving any response proves the redirect client completed the TLS
  12959. // handshake with a system-CA-signed host
  12960. auto res = cli.Get("/index");
  12961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12962. }
  12963. TEST(MultipartFormDataTest, LargeData) {
  12964. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12965. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12966. const ContentReader &content_reader) {
  12967. if (req.is_multipart_form_data()) {
  12968. std::vector<FormData> items;
  12969. content_reader(
  12970. [&](const FormData &file) {
  12971. items.push_back(file);
  12972. return true;
  12973. },
  12974. [&](const char *data, size_t data_length) {
  12975. items.back().content.append(data, data_length);
  12976. return true;
  12977. });
  12978. EXPECT_TRUE(std::string(items[0].name) == "document");
  12979. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12980. EXPECT_TRUE(items[0].filename == "2MB_data");
  12981. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12982. EXPECT_TRUE(items[1].name == "hello");
  12983. EXPECT_TRUE(items[1].content == "world");
  12984. EXPECT_TRUE(items[1].filename == "");
  12985. EXPECT_TRUE(items[1].content_type == "");
  12986. } else {
  12987. std::string body;
  12988. content_reader([&](const char *data, size_t data_length) {
  12989. body.append(data, data_length);
  12990. return true;
  12991. });
  12992. }
  12993. });
  12994. auto port = svr.bind_to_any_port(HOST);
  12995. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12996. auto se = detail::scope_exit([&] {
  12997. svr.stop();
  12998. t.join();
  12999. ASSERT_FALSE(svr.is_running());
  13000. });
  13001. svr.wait_until_ready();
  13002. {
  13003. std::string data(1024 * 1024 * 2, '.');
  13004. std::stringstream buffer;
  13005. buffer << data;
  13006. SSLClient cli(HOST, port);
  13007. cli.enable_server_certificate_verification(false);
  13008. UploadFormDataItems items{
  13009. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13010. {"hello", "world", "", ""},
  13011. };
  13012. auto res = cli.Post("/post", items);
  13013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13014. ASSERT_EQ(StatusCode::OK_200, res->status);
  13015. }
  13016. }
  13017. TEST(MultipartFormDataTest, DataProviderItems) {
  13018. std::random_device seed_gen;
  13019. std::mt19937 random(seed_gen());
  13020. std::string rand1;
  13021. rand1.resize(1000);
  13022. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13023. std::string rand2;
  13024. rand2.resize(3000);
  13025. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13027. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13028. const ContentReader &content_reader) {
  13029. ASSERT_FALSE(req.is_multipart_form_data());
  13030. std::string body;
  13031. content_reader([&](const char *data, size_t data_length) {
  13032. body.append(data, data_length);
  13033. return true;
  13034. });
  13035. EXPECT_EQ(body, "");
  13036. });
  13037. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13038. const ContentReader &content_reader) {
  13039. ASSERT_TRUE(req.is_multipart_form_data());
  13040. std::vector<FormData> items;
  13041. content_reader(
  13042. [&](const FormData &file) {
  13043. items.push_back(file);
  13044. return true;
  13045. },
  13046. [&](const char *data, size_t data_length) {
  13047. items.back().content.append(data, data_length);
  13048. return true;
  13049. });
  13050. ASSERT_TRUE(items.size() == 2);
  13051. EXPECT_EQ(std::string(items[0].name), "name1");
  13052. EXPECT_EQ(items[0].content, "Testing123");
  13053. EXPECT_EQ(items[0].filename, "filename1");
  13054. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13055. EXPECT_EQ(items[1].name, "name2");
  13056. EXPECT_EQ(items[1].content, "Testing456");
  13057. EXPECT_EQ(items[1].filename, "");
  13058. EXPECT_EQ(items[1].content_type, "");
  13059. });
  13060. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13061. const ContentReader &content_reader) {
  13062. ASSERT_TRUE(req.is_multipart_form_data());
  13063. std::vector<FormData> items;
  13064. content_reader(
  13065. [&](const FormData &file) {
  13066. items.push_back(file);
  13067. return true;
  13068. },
  13069. [&](const char *data, size_t data_length) {
  13070. items.back().content.append(data, data_length);
  13071. return true;
  13072. });
  13073. ASSERT_TRUE(items.size() == 2);
  13074. EXPECT_EQ(items[0].name, "name3");
  13075. EXPECT_EQ(items[0].content, rand1);
  13076. EXPECT_EQ(items[0].filename, "filename3");
  13077. EXPECT_EQ(items[0].content_type, "");
  13078. EXPECT_EQ(items[1].name, "name4");
  13079. EXPECT_EQ(items[1].content, rand2);
  13080. EXPECT_EQ(items[1].filename, "filename4");
  13081. EXPECT_EQ(items[1].content_type, "");
  13082. });
  13083. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13084. const ContentReader &content_reader) {
  13085. ASSERT_TRUE(req.is_multipart_form_data());
  13086. std::vector<FormData> items;
  13087. content_reader(
  13088. [&](const FormData &file) {
  13089. items.push_back(file);
  13090. return true;
  13091. },
  13092. [&](const char *data, size_t data_length) {
  13093. items.back().content.append(data, data_length);
  13094. return true;
  13095. });
  13096. ASSERT_TRUE(items.size() == 4);
  13097. EXPECT_EQ(std::string(items[0].name), "name1");
  13098. EXPECT_EQ(items[0].content, "Testing123");
  13099. EXPECT_EQ(items[0].filename, "filename1");
  13100. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13101. EXPECT_EQ(items[1].name, "name2");
  13102. EXPECT_EQ(items[1].content, "Testing456");
  13103. EXPECT_EQ(items[1].filename, "");
  13104. EXPECT_EQ(items[1].content_type, "");
  13105. EXPECT_EQ(items[2].name, "name3");
  13106. EXPECT_EQ(items[2].content, rand1);
  13107. EXPECT_EQ(items[2].filename, "filename3");
  13108. EXPECT_EQ(items[2].content_type, "");
  13109. EXPECT_EQ(items[3].name, "name4");
  13110. EXPECT_EQ(items[3].content, rand2);
  13111. EXPECT_EQ(items[3].filename, "filename4");
  13112. EXPECT_EQ(items[3].content_type, "");
  13113. });
  13114. auto port = svr.bind_to_any_port("localhost");
  13115. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13116. auto se = detail::scope_exit([&] {
  13117. svr.stop();
  13118. t.join();
  13119. ASSERT_FALSE(svr.is_running());
  13120. });
  13121. svr.wait_until_ready();
  13122. {
  13123. SSLClient cli("localhost", port);
  13124. cli.enable_server_certificate_verification(false);
  13125. UploadFormDataItems items{
  13126. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13127. {"name2", "Testing456", "", ""}, // not a file
  13128. };
  13129. {
  13130. auto res = cli.Post("/post-none", {}, {}, {});
  13131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13132. ASSERT_EQ(StatusCode::OK_200, res->status);
  13133. }
  13134. FormDataProviderItems providers;
  13135. {
  13136. auto res =
  13137. cli.Post("/post-items", {}, items, providers); // empty providers
  13138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13139. ASSERT_EQ(StatusCode::OK_200, res->status);
  13140. }
  13141. providers.push_back({"name3",
  13142. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13143. // test the offset is given correctly at each step
  13144. if (!offset)
  13145. sink.os.write(rand1.data(), 30);
  13146. else if (offset == 30)
  13147. sink.os.write(rand1.data() + 30, 300);
  13148. else if (offset == 330)
  13149. sink.os.write(rand1.data() + 330, 670);
  13150. else if (offset == rand1.size())
  13151. sink.done();
  13152. return true;
  13153. },
  13154. "filename3",
  13155. {}});
  13156. providers.push_back({"name4",
  13157. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13158. // test the offset is given correctly at each step
  13159. if (!offset)
  13160. sink.os.write(rand2.data(), 2000);
  13161. else if (offset == 2000)
  13162. sink.os.write(rand2.data() + 2000, 1);
  13163. else if (offset == 2001)
  13164. sink.os.write(rand2.data() + 2001, 999);
  13165. else if (offset == rand2.size())
  13166. sink.done();
  13167. return true;
  13168. },
  13169. "filename4",
  13170. {}});
  13171. {
  13172. auto res = cli.Post("/post-providers", {}, {}, providers);
  13173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13174. ASSERT_EQ(StatusCode::OK_200, res->status);
  13175. }
  13176. {
  13177. auto res = cli.Post("/post-both", {}, items, providers);
  13178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13179. ASSERT_EQ(StatusCode::OK_200, res->status);
  13180. }
  13181. }
  13182. }
  13183. TEST(MultipartFormDataTest, BadHeader) {
  13184. Server svr;
  13185. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13186. res.set_content("ok", "text/plain");
  13187. });
  13188. thread t = thread([&] { svr.listen(HOST, PORT); });
  13189. auto se = detail::scope_exit([&] {
  13190. svr.stop();
  13191. t.join();
  13192. ASSERT_FALSE(svr.is_running());
  13193. });
  13194. svr.wait_until_ready();
  13195. const std::string body =
  13196. "This is the preamble. It is to be ignored, though it\r\n"
  13197. "is a handy place for composition agents to include an\r\n"
  13198. "explanatory note to non-MIME conformant readers.\r\n"
  13199. "\r\n"
  13200. "\r\n"
  13201. "--simple boundary\r\n"
  13202. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13203. ": BAD...\r\n"
  13204. "\r\n"
  13205. "value1\r\n"
  13206. "--simple boundary\r\n"
  13207. "Content-Disposition: form-data; name=\"field2\"; "
  13208. "filename=\"example.txt\"\r\n"
  13209. "\r\n"
  13210. "value2\r\n"
  13211. "--simple boundary--\r\n"
  13212. "This is the epilogue. It is also to be ignored.\r\n";
  13213. std::string content_type =
  13214. R"(multipart/form-data; boundary="simple boundary")";
  13215. Client cli(HOST, PORT);
  13216. auto res = cli.Post("/post", body, content_type.c_str());
  13217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13218. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13219. }
  13220. TEST(MultipartFormDataTest, WithPreamble) {
  13221. Server svr;
  13222. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13223. res.set_content("ok", "text/plain");
  13224. });
  13225. thread t = thread([&] { svr.listen(HOST, PORT); });
  13226. auto se = detail::scope_exit([&] {
  13227. svr.stop();
  13228. t.join();
  13229. ASSERT_FALSE(svr.is_running());
  13230. });
  13231. svr.wait_until_ready();
  13232. const std::string body =
  13233. "This is the preamble. It is to be ignored, though it\r\n"
  13234. "is a handy place for composition agents to include an\r\n"
  13235. "explanatory note to non-MIME conformant readers.\r\n"
  13236. "\r\n"
  13237. "\r\n"
  13238. "--simple boundary\r\n"
  13239. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13240. "\r\n"
  13241. "value1\r\n"
  13242. "--simple boundary\r\n"
  13243. "Content-Disposition: form-data; name=\"field2\"; "
  13244. "filename=\"example.txt\"\r\n"
  13245. "\r\n"
  13246. "value2\r\n"
  13247. "--simple boundary--\r\n"
  13248. "This is the epilogue. It is also to be ignored.\r\n";
  13249. std::string content_type =
  13250. R"(multipart/form-data; boundary="simple boundary")";
  13251. Client cli(HOST, PORT);
  13252. auto res = cli.Post("/post", body, content_type.c_str());
  13253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13254. EXPECT_EQ(StatusCode::OK_200, res->status);
  13255. }
  13256. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13257. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13258. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13259. const ContentReader &content_reader) {
  13260. if (req.is_multipart_form_data()) {
  13261. std::vector<FormData> items;
  13262. content_reader(
  13263. [&](const FormData &file) {
  13264. items.push_back(file);
  13265. return true;
  13266. },
  13267. [&](const char *data, size_t data_length) {
  13268. items.back().content.append(data, data_length);
  13269. return true;
  13270. });
  13271. EXPECT_TRUE(std::string(items[0].name) == "document");
  13272. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13273. EXPECT_TRUE(items[0].filename == "2MB_data");
  13274. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13275. EXPECT_TRUE(items[1].name == "hello");
  13276. EXPECT_TRUE(items[1].content == "world");
  13277. EXPECT_TRUE(items[1].filename == "");
  13278. EXPECT_TRUE(items[1].content_type == "");
  13279. } else {
  13280. std::string body;
  13281. content_reader([&](const char *data, size_t data_length) {
  13282. body.append(data, data_length);
  13283. return true;
  13284. });
  13285. }
  13286. });
  13287. auto port = svr.bind_to_any_port("localhost");
  13288. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13289. auto se = detail::scope_exit([&] {
  13290. svr.stop();
  13291. t.join();
  13292. ASSERT_FALSE(svr.is_running());
  13293. });
  13294. svr.wait_until_ready();
  13295. {
  13296. std::string data(1024 * 1024 * 2, '.');
  13297. std::stringstream buffer;
  13298. buffer << data;
  13299. SSLClient cli("localhost", port);
  13300. cli.enable_server_certificate_verification(false);
  13301. UploadFormDataItems items{
  13302. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13303. {"hello", "world", "", ""},
  13304. };
  13305. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13307. ASSERT_EQ(StatusCode::OK_200, res->status);
  13308. }
  13309. }
  13310. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13311. std::string data(1024 * 1024 * 2, '&');
  13312. std::stringstream buffer;
  13313. buffer << data;
  13314. Client cli("https://localhost:8080");
  13315. UploadFormDataItems items{
  13316. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13317. {"hello", "world", "", ""},
  13318. };
  13319. for (const char &c : " \t\r\n") {
  13320. auto res =
  13321. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13322. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13323. ASSERT_FALSE(res);
  13324. }
  13325. }
  13326. TEST(MultipartFormDataTest, PutFormData) {
  13327. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13328. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13329. const ContentReader &content_reader) {
  13330. if (req.is_multipart_form_data()) {
  13331. std::vector<FormData> items;
  13332. content_reader(
  13333. [&](const FormData &file) {
  13334. items.push_back(file);
  13335. return true;
  13336. },
  13337. [&](const char *data, size_t data_length) {
  13338. items.back().content.append(data, data_length);
  13339. return true;
  13340. });
  13341. EXPECT_TRUE(std::string(items[0].name) == "document");
  13342. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13343. EXPECT_TRUE(items[0].filename == "2MB_data");
  13344. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13345. EXPECT_TRUE(items[1].name == "hello");
  13346. EXPECT_TRUE(items[1].content == "world");
  13347. EXPECT_TRUE(items[1].filename == "");
  13348. EXPECT_TRUE(items[1].content_type == "");
  13349. } else {
  13350. std::string body;
  13351. content_reader([&](const char *data, size_t data_length) {
  13352. body.append(data, data_length);
  13353. return true;
  13354. });
  13355. }
  13356. });
  13357. auto port = svr.bind_to_any_port("localhost");
  13358. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13359. auto se = detail::scope_exit([&] {
  13360. svr.stop();
  13361. t.join();
  13362. ASSERT_FALSE(svr.is_running());
  13363. });
  13364. svr.wait_until_ready();
  13365. {
  13366. std::string data(1024 * 1024 * 2, '&');
  13367. std::stringstream buffer;
  13368. buffer << data;
  13369. SSLClient cli("localhost", port);
  13370. cli.enable_server_certificate_verification(false);
  13371. UploadFormDataItems items{
  13372. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13373. {"hello", "world", "", ""},
  13374. };
  13375. auto res = cli.Put("/put", items);
  13376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13377. ASSERT_EQ(StatusCode::OK_200, res->status);
  13378. }
  13379. }
  13380. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13381. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13382. svr.Put("/put_customboundary",
  13383. [&](const Request &req, const Response & /*res*/,
  13384. const ContentReader &content_reader) {
  13385. if (req.is_multipart_form_data()) {
  13386. std::vector<FormData> items;
  13387. content_reader(
  13388. [&](const FormData &file) {
  13389. items.push_back(file);
  13390. return true;
  13391. },
  13392. [&](const char *data, size_t data_length) {
  13393. items.back().content.append(data, data_length);
  13394. return true;
  13395. });
  13396. EXPECT_TRUE(std::string(items[0].name) == "document");
  13397. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13398. EXPECT_TRUE(items[0].filename == "2MB_data");
  13399. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13400. EXPECT_TRUE(items[1].name == "hello");
  13401. EXPECT_TRUE(items[1].content == "world");
  13402. EXPECT_TRUE(items[1].filename == "");
  13403. EXPECT_TRUE(items[1].content_type == "");
  13404. } else {
  13405. std::string body;
  13406. content_reader([&](const char *data, size_t data_length) {
  13407. body.append(data, data_length);
  13408. return true;
  13409. });
  13410. }
  13411. });
  13412. auto port = svr.bind_to_any_port("localhost");
  13413. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13414. auto se = detail::scope_exit([&] {
  13415. svr.stop();
  13416. t.join();
  13417. ASSERT_FALSE(svr.is_running());
  13418. });
  13419. svr.wait_until_ready();
  13420. {
  13421. std::string data(1024 * 1024 * 2, '&');
  13422. std::stringstream buffer;
  13423. buffer << data;
  13424. SSLClient cli("localhost", port);
  13425. cli.enable_server_certificate_verification(false);
  13426. UploadFormDataItems items{
  13427. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13428. {"hello", "world", "", ""},
  13429. };
  13430. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13432. ASSERT_EQ(StatusCode::OK_200, res->status);
  13433. }
  13434. }
  13435. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13436. std::string data(1024 * 1024 * 2, '&');
  13437. std::stringstream buffer;
  13438. buffer << data;
  13439. Client cli("https://localhost:8080");
  13440. cli.enable_server_certificate_verification(false);
  13441. UploadFormDataItems items{
  13442. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13443. {"hello", "world", "", ""},
  13444. };
  13445. for (const char &c : " \t\r\n") {
  13446. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13447. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13448. ASSERT_FALSE(res);
  13449. }
  13450. }
  13451. TEST(MultipartFormDataTest, AlternateFilename) {
  13452. auto handled = false;
  13453. Server svr;
  13454. svr.Post("/test", [&](const Request &req, Response &res) {
  13455. ASSERT_EQ(2u, req.form.files.size());
  13456. ASSERT_EQ(1u, req.form.fields.size());
  13457. // Test files
  13458. const auto &file1 = req.form.get_file("file1");
  13459. ASSERT_EQ("file1", file1.name);
  13460. ASSERT_EQ("A.txt", file1.filename);
  13461. ASSERT_EQ("text/plain", file1.content_type);
  13462. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13463. const auto &file2 = req.form.get_file("file2");
  13464. ASSERT_EQ("file2", file2.name);
  13465. ASSERT_EQ("a.html", file2.filename);
  13466. ASSERT_EQ("text/html", file2.content_type);
  13467. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13468. file2.content);
  13469. // Test text field
  13470. const auto &text = req.form.get_field("text");
  13471. ASSERT_EQ("text default", text);
  13472. res.set_content("ok", "text/plain");
  13473. handled = true;
  13474. });
  13475. thread t = thread([&] { svr.listen(HOST, PORT); });
  13476. auto se = detail::scope_exit([&] {
  13477. svr.stop();
  13478. t.join();
  13479. ASSERT_FALSE(svr.is_running());
  13480. ASSERT_TRUE(handled);
  13481. });
  13482. svr.wait_until_ready();
  13483. auto req = "POST /test HTTP/1.1\r\n"
  13484. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13485. "Content-Length: 399\r\n"
  13486. "\r\n"
  13487. "----------\r\n"
  13488. "Content-Disposition: form-data; name=\"text\"\r\n"
  13489. "\r\n"
  13490. "text default\r\n"
  13491. "----------\r\n"
  13492. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13493. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13494. "Content-Type: text/plain\r\n"
  13495. "\r\n"
  13496. "Content of a.txt.\r\n"
  13497. "\r\n"
  13498. "----------\r\n"
  13499. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13500. "\"a.html\"\r\n"
  13501. "Content-Type: text/html\r\n"
  13502. "\r\n"
  13503. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13504. "\r\n"
  13505. "------------\r\n";
  13506. ASSERT_TRUE(send_request(1, req));
  13507. }
  13508. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13509. auto handled = false;
  13510. Server svr;
  13511. svr.Post("/test", [&](const Request &req, Response &res) {
  13512. // Case-insensitive "utf-8''" prefix with a long value
  13513. const auto &file = req.form.get_file("file1");
  13514. ASSERT_EQ("file1", file.name);
  13515. // 8000 chars exercises both the Content-Disposition parser and the
  13516. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13517. // Prior to the fix, std::regex_match on this header would cause O(N)
  13518. // stack recursion in libstdc++, leading to SIGSEGV.
  13519. std::string expected_filename(8000, 'A');
  13520. ASSERT_EQ(expected_filename, file.filename);
  13521. res.set_content("ok", "text/plain");
  13522. handled = true;
  13523. });
  13524. thread t = thread([&] { svr.listen(HOST, PORT); });
  13525. auto se = detail::scope_exit([&] {
  13526. svr.stop();
  13527. t.join();
  13528. ASSERT_FALSE(svr.is_running());
  13529. ASSERT_TRUE(handled);
  13530. });
  13531. svr.wait_until_ready();
  13532. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13533. // Regression test for GHSA-qq6v-r583-3h69
  13534. std::string long_filename(8000, 'A');
  13535. std::string body = "----------\r\n"
  13536. "Content-Disposition: form-data; name=\"file1\"; "
  13537. "filename*=\"Utf-8''" +
  13538. long_filename +
  13539. "\"\r\n"
  13540. "\r\n"
  13541. "hello\r\n"
  13542. "------------\r\n";
  13543. auto req = "POST /test HTTP/1.1\r\n"
  13544. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13545. "Content-Length: " +
  13546. std::to_string(body.size()) + "\r\n\r\n" + body;
  13547. ASSERT_TRUE(send_request(1, req));
  13548. }
  13549. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13550. auto handled = false;
  13551. Server svr;
  13552. svr.Post("/test", [&](const Request &req, Response &) {
  13553. ASSERT_EQ(2u, req.form.fields.size());
  13554. const auto &text1 = req.form.get_field("text1");
  13555. ASSERT_EQ("text1", text1);
  13556. const auto &text2 = req.form.get_field("text2");
  13557. ASSERT_EQ("text2", text2);
  13558. handled = true;
  13559. });
  13560. thread t = thread([&] { svr.listen(HOST, PORT); });
  13561. auto se = detail::scope_exit([&] {
  13562. svr.stop();
  13563. t.join();
  13564. ASSERT_FALSE(svr.is_running());
  13565. ASSERT_TRUE(handled);
  13566. });
  13567. svr.wait_until_ready();
  13568. auto req = "POST /test HTTP/1.1\r\n"
  13569. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13570. "Content-Length: 146\r\n"
  13571. "\r\n----------\r\n"
  13572. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13573. "\r\n"
  13574. "text1"
  13575. "\r\n----------\r\n"
  13576. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13577. "\r\n"
  13578. "text2"
  13579. "\r\n------------";
  13580. std::string response;
  13581. ASSERT_TRUE(send_request(1, req, &response));
  13582. ASSERT_EQ("200", response.substr(9, 3));
  13583. }
  13584. TEST(MultipartFormDataTest, ContentLength) {
  13585. auto handled = false;
  13586. Server svr;
  13587. svr.Post("/test", [&](const Request &req, Response &) {
  13588. ASSERT_EQ(2u, req.form.fields.size());
  13589. const auto &text1 = req.form.get_field("text1");
  13590. ASSERT_EQ("text1", text1);
  13591. const auto &text2 = req.form.get_field("text2");
  13592. ASSERT_EQ("text2", text2);
  13593. handled = true;
  13594. });
  13595. thread t = thread([&] { svr.listen(HOST, PORT); });
  13596. auto se = detail::scope_exit([&] {
  13597. svr.stop();
  13598. t.join();
  13599. ASSERT_FALSE(svr.is_running());
  13600. ASSERT_TRUE(handled);
  13601. });
  13602. svr.wait_until_ready();
  13603. auto req = "POST /test HTTP/1.1\r\n"
  13604. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13605. "Content-Length: 167\r\n"
  13606. "\r\n----------\r\n"
  13607. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13608. "Content-Length: 5\r\n"
  13609. "\r\n"
  13610. "text1"
  13611. "\r\n----------\r\n"
  13612. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13613. "\r\n"
  13614. "text2"
  13615. "\r\n------------\r\n";
  13616. std::string response;
  13617. ASSERT_TRUE(send_request(1, req, &response));
  13618. ASSERT_EQ("200", response.substr(9, 3));
  13619. }
  13620. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13621. auto handled = false;
  13622. Server svr;
  13623. svr.Post("/test", [&](const Request &req, Response &) {
  13624. ASSERT_EQ(2u, req.form.fields.size());
  13625. const auto &text1 = req.form.get_field("text1");
  13626. ASSERT_EQ("text1", text1);
  13627. // TODO: Add header access for text fields if needed
  13628. const auto &text2 = req.form.get_field("text2");
  13629. ASSERT_EQ("text2", text2);
  13630. // TODO: Header access for text fields needs to be implemented
  13631. // auto &headers = it->second.headers;
  13632. // ASSERT_EQ(3U, headers.size());
  13633. // auto custom_header = headers.find("x-whatever");
  13634. // ASSERT_TRUE(custom_header != headers.end());
  13635. // ASSERT_NE("customvalue", custom_header->second);
  13636. // ASSERT_EQ("CustomValue", custom_header->second);
  13637. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13638. handled = true;
  13639. });
  13640. thread t = thread([&] { svr.listen(HOST, PORT); });
  13641. auto se = detail::scope_exit([&] {
  13642. svr.stop();
  13643. t.join();
  13644. ASSERT_FALSE(svr.is_running());
  13645. ASSERT_TRUE(handled);
  13646. });
  13647. svr.wait_until_ready();
  13648. auto req = "POST /test HTTP/1.1\r\n"
  13649. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13650. "Content-Length: 232\r\n"
  13651. "\r\n----------\r\n"
  13652. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13653. "Content-Length: 5\r\n"
  13654. "X-Test: 1\r\n"
  13655. "\r\n"
  13656. "text1"
  13657. "\r\n----------\r\n"
  13658. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13659. "Content-Type: text/plain\r\n"
  13660. "X-Whatever: CustomValue\r\n"
  13661. "\r\n"
  13662. "text2"
  13663. "\r\n------------\r\n"
  13664. "That should be disregarded. Not even read";
  13665. std::string response;
  13666. ASSERT_TRUE(send_request(1, req, &response));
  13667. ASSERT_EQ("200", response.substr(9, 3));
  13668. }
  13669. TEST(MultipartFormDataTest, LargeHeader) {
  13670. auto handled = false;
  13671. Server svr;
  13672. svr.Post("/test", [&](const Request &req, Response &) {
  13673. ASSERT_EQ(1u, req.form.fields.size());
  13674. const auto &text = req.form.get_field("name1");
  13675. ASSERT_EQ("text1", text);
  13676. handled = true;
  13677. });
  13678. thread t = thread([&] { svr.listen(HOST, PORT); });
  13679. auto se = detail::scope_exit([&] {
  13680. svr.stop();
  13681. t.join();
  13682. ASSERT_FALSE(svr.is_running());
  13683. ASSERT_TRUE(handled);
  13684. });
  13685. svr.wait_until_ready();
  13686. auto boundary = std::string("cpp-httplib-multipart-data");
  13687. std::string content = "--" + boundary +
  13688. "\r\n"
  13689. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13690. "\r\n"
  13691. "text1\r\n"
  13692. "--" +
  13693. boundary + "--\r\n";
  13694. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13695. "Content-Type: multipart/form-data;boundary=" +
  13696. boundary +
  13697. "\r\n"
  13698. "Content-Length: " +
  13699. std::to_string(content.size()) +
  13700. "\r\n"
  13701. "Dummy-Header: ";
  13702. std::string header_suffix = "\r\n"
  13703. "\r\n";
  13704. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13705. size_t header_dummy_size =
  13706. read_buff_size -
  13707. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13708. auto header_dummy = std::string(header_dummy_size, '@');
  13709. auto req = header_prefix + header_dummy + header_suffix + content;
  13710. std::string response;
  13711. ASSERT_TRUE(send_request(1, req, &response));
  13712. ASSERT_EQ("200", response.substr(9, 3));
  13713. }
  13714. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13715. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13716. // (not chunked Transfer-Encoding) after the streaming refactor.
  13717. auto handled = false;
  13718. Server svr;
  13719. svr.Post("/upload", [&](const Request &req, Response &res) {
  13720. auto cl_it = req.headers.find("Content-Length");
  13721. EXPECT_TRUE(cl_it != req.headers.end());
  13722. auto te_it = req.headers.find("Transfer-Encoding");
  13723. EXPECT_TRUE(te_it == req.headers.end());
  13724. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13725. res.set_content("ok", "text/plain");
  13726. handled = true;
  13727. });
  13728. auto port = svr.bind_to_any_port(HOST);
  13729. auto t = thread([&] { svr.listen_after_bind(); });
  13730. auto se = detail::scope_exit([&] {
  13731. svr.stop();
  13732. t.join();
  13733. ASSERT_FALSE(svr.is_running());
  13734. ASSERT_TRUE(handled);
  13735. });
  13736. svr.wait_until_ready();
  13737. UploadFormDataItems items = {
  13738. {"field1", "hello", "", "text/plain"},
  13739. {"file1", "world", "test.txt", "application/octet-stream"},
  13740. };
  13741. Client cli(HOST, port);
  13742. auto res = cli.Post("/upload", {}, items);
  13743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13744. EXPECT_EQ(StatusCode::OK_200, res->status);
  13745. }
  13746. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13747. // Verify that make_multipart_content_provider coalesces many small segments
  13748. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13749. constexpr size_t kItemCount = 1000;
  13750. UploadFormDataItems items;
  13751. items.reserve(kItemCount);
  13752. for (size_t i = 0; i < kItemCount; i++) {
  13753. items.push_back(
  13754. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13755. }
  13756. const std::string boundary = "----test-boundary";
  13757. auto content_length = detail::get_multipart_content_length(items, boundary);
  13758. auto provider = detail::make_multipart_content_provider(items, boundary);
  13759. // Drive the provider the same way write_content_with_progress does
  13760. size_t write_count = 0;
  13761. size_t total_bytes = 0;
  13762. DataSink sink;
  13763. size_t offset = 0;
  13764. sink.write = [&](const char *d, size_t l) -> bool {
  13765. (void)d;
  13766. write_count++;
  13767. total_bytes += l;
  13768. offset += l;
  13769. return true;
  13770. };
  13771. sink.is_writable = []() -> bool { return true; };
  13772. while (offset < content_length) {
  13773. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13774. }
  13775. EXPECT_EQ(content_length, total_bytes);
  13776. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13777. // With buffering into 64KB blocks, write_count should be much smaller.
  13778. auto segment_count = 3 * kItemCount + 1;
  13779. EXPECT_LT(write_count, segment_count / 10);
  13780. }
  13781. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13782. // Integration test: send many UploadFormDataItems and verify the server
  13783. // receives all of them correctly (#2410).
  13784. constexpr size_t kItemCount = 500;
  13785. auto handled = false;
  13786. Server svr;
  13787. svr.Post("/upload", [&](const Request &req, Response &res) {
  13788. EXPECT_EQ(kItemCount, req.form.fields.size());
  13789. for (size_t i = 0; i < kItemCount; i++) {
  13790. auto key = "field" + std::to_string(i);
  13791. auto val = "value" + std::to_string(i);
  13792. auto it = req.form.fields.find(key);
  13793. if (it != req.form.fields.end()) {
  13794. EXPECT_EQ(val, it->second.content);
  13795. } else {
  13796. ADD_FAILURE() << "Missing field: " << key;
  13797. }
  13798. }
  13799. res.set_content("ok", "text/plain");
  13800. handled = true;
  13801. });
  13802. auto port = svr.bind_to_any_port(HOST);
  13803. auto t = thread([&] { svr.listen_after_bind(); });
  13804. auto se = detail::scope_exit([&] {
  13805. svr.stop();
  13806. t.join();
  13807. ASSERT_FALSE(svr.is_running());
  13808. ASSERT_TRUE(handled);
  13809. });
  13810. svr.wait_until_ready();
  13811. UploadFormDataItems items;
  13812. items.reserve(kItemCount);
  13813. for (size_t i = 0; i < kItemCount; i++) {
  13814. items.push_back(
  13815. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13816. }
  13817. Client cli(HOST, port);
  13818. auto res = cli.Post("/upload", items);
  13819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13820. EXPECT_EQ(StatusCode::OK_200, res->status);
  13821. }
  13822. TEST(MultipartFormDataTest, MakeFileProvider) {
  13823. // Verify make_file_provider sends a file's contents correctly.
  13824. const std::string file_content(4096, 'Z');
  13825. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13826. {
  13827. std::ofstream ofs(tmp_path, std::ios::binary);
  13828. ofs.write(file_content.data(),
  13829. static_cast<std::streamsize>(file_content.size()));
  13830. }
  13831. auto handled = false;
  13832. Server svr;
  13833. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13834. const ContentReader &content_reader) {
  13835. ASSERT_TRUE(req.is_multipart_form_data());
  13836. std::vector<FormData> items;
  13837. content_reader(
  13838. [&](const FormData &file) {
  13839. items.push_back(file);
  13840. return true;
  13841. },
  13842. [&](const char *data, size_t data_length) {
  13843. items.back().content.append(data, data_length);
  13844. return true;
  13845. });
  13846. ASSERT_EQ(1u, items.size());
  13847. EXPECT_EQ("myfile", items[0].name);
  13848. EXPECT_EQ("data.bin", items[0].filename);
  13849. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13850. EXPECT_EQ(file_content, items[0].content);
  13851. handled = true;
  13852. });
  13853. auto port = svr.bind_to_any_port(HOST);
  13854. auto t = thread([&] { svr.listen_after_bind(); });
  13855. auto se = detail::scope_exit([&] {
  13856. svr.stop();
  13857. t.join();
  13858. ASSERT_FALSE(svr.is_running());
  13859. ASSERT_TRUE(handled);
  13860. std::remove(tmp_path.c_str());
  13861. });
  13862. svr.wait_until_ready();
  13863. FormDataProviderItems providers;
  13864. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13865. "application/octet-stream"));
  13866. Client cli(HOST, port);
  13867. auto res = cli.Post("/upload", {}, {}, providers);
  13868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13869. EXPECT_EQ(StatusCode::OK_200, res->status);
  13870. }
  13871. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13872. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13873. // (100) headers is rejected with a 400 Bad Request response.
  13874. Server svr;
  13875. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13876. res.set_content("ok", "text/plain");
  13877. });
  13878. thread t = thread([&] { svr.listen(HOST, PORT); });
  13879. auto se = detail::scope_exit([&] {
  13880. svr.stop();
  13881. t.join();
  13882. ASSERT_FALSE(svr.is_running());
  13883. });
  13884. svr.wait_until_ready();
  13885. // Build a multipart part with 101 custom headers (exceeding
  13886. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13887. std::stringstream body;
  13888. body << "--simpleboundary\r\n"
  13889. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13890. for (int i = 0; i < 101; i++) {
  13891. body << "X-Custom-Header-" << i << ": value\r\n";
  13892. }
  13893. body << "\r\n"
  13894. << "value1\r\n"
  13895. << "--simpleboundary--\r\n";
  13896. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13897. Client cli(HOST, PORT);
  13898. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13900. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13901. }
  13902. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13903. // A body that never contains the declared boundary must not be accumulated
  13904. // while the parser waits for it. Buffering it would also make every read
  13905. // rescan everything seen so far, which is quadratic in the body size.
  13906. Server svr;
  13907. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13908. res.set_content("ok", "text/plain");
  13909. });
  13910. auto port = svr.bind_to_any_port(HOST);
  13911. thread t = thread([&] { svr.listen_after_bind(); });
  13912. auto se = detail::scope_exit([&] {
  13913. svr.stop();
  13914. t.join();
  13915. ASSERT_FALSE(svr.is_running());
  13916. });
  13917. svr.wait_until_ready();
  13918. Client cli(HOST, port);
  13919. cli.set_read_timeout(60, 0);
  13920. cli.set_write_timeout(60, 0);
  13921. // '-' is the worst case: it matches the first character of the boundary, so
  13922. // every position has to be checked against it.
  13923. auto post_dashes = [&](size_t size) {
  13924. const std::string body(size, '-');
  13925. auto start = std::chrono::steady_clock::now();
  13926. auto res =
  13927. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13928. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13929. std::chrono::steady_clock::now() - start)
  13930. .count();
  13931. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13932. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13933. return ms;
  13934. };
  13935. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13936. // Windows.
  13937. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13938. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13939. // Comparing the two sizes rather than checking an absolute duration keeps
  13940. // this meaningful across build types and CI load, both of which move the
  13941. // absolute numbers by more than an order of magnitude. Four times the bytes
  13942. // costs about four times the time when parsing is linear, and about sixteen
  13943. // times when the body is buffered and rescanned.
  13944. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13945. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13946. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13947. << "ms, which suggests the body is being buffered and rescanned";
  13948. }
  13949. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13950. // A boundary can only be followed by CRLF or by "--", so anything else is
  13951. // malformed no matter what comes next. The parser must say so right away
  13952. // instead of buffering the rest of the declared body.
  13953. Server svr;
  13954. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13955. res.set_content("ok", "text/plain");
  13956. });
  13957. auto port = svr.bind_to_any_port(HOST);
  13958. thread t = thread([&] { svr.listen_after_bind(); });
  13959. auto se = detail::scope_exit([&] {
  13960. svr.stop();
  13961. t.join();
  13962. ASSERT_FALSE(svr.is_running());
  13963. });
  13964. svr.wait_until_ready();
  13965. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13966. // buffers instead of failing would still be waiting for the remaining bytes.
  13967. const std::string body = "--zzzz\r\n"
  13968. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13969. "\r\n"
  13970. "text1"
  13971. "\r\n--zzzzXX";
  13972. const std::string req = "POST /post HTTP/1.1\r\n"
  13973. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13974. "Content-Length: 1048576\r\n"
  13975. "\r\n" +
  13976. body;
  13977. std::string response;
  13978. ASSERT_TRUE(send_request(3, req, &response, port));
  13979. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13980. EXPECT_EQ("400", response.substr(9, 3));
  13981. }
  13982. // Posts a multipart body split into two writes, so that the server sees the
  13983. // split at whatever offset the caller chose, and expects the single "text1"
  13984. // field to come through.
  13985. static void expect_split_multipart_ok(const std::string &body1,
  13986. const std::string &body2) {
  13987. auto handled = false;
  13988. Server svr;
  13989. svr.Post("/post", [&](const Request &req, Response &) {
  13990. EXPECT_EQ(1u, req.form.fields.size());
  13991. EXPECT_EQ("text1", req.form.get_field("text1"));
  13992. handled = true;
  13993. });
  13994. auto port = svr.bind_to_any_port(HOST);
  13995. thread t = thread([&] { svr.listen_after_bind(); });
  13996. auto se = detail::scope_exit([&] {
  13997. svr.stop();
  13998. t.join();
  13999. ASSERT_FALSE(svr.is_running());
  14000. ASSERT_TRUE(handled);
  14001. });
  14002. svr.wait_until_ready();
  14003. // "Connection: close" makes the server close once it has answered, so the
  14004. // response drain ends immediately instead of idling until the read timeout.
  14005. const std::string head =
  14006. "POST /post HTTP/1.1\r\n"
  14007. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14008. "Connection: close\r\n"
  14009. "Content-Length: " +
  14010. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14011. std::string response;
  14012. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14013. ASSERT_GE(response.size(), 12u) << "no response";
  14014. EXPECT_EQ("200", response.substr(9, 3));
  14015. }
  14016. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14017. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14018. // ignored, including when it does not arrive in the same read as the
  14019. // close-delimiter itself.
  14020. expect_split_multipart_ok("--zzzz\r\n"
  14021. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14022. "\r\n"
  14023. "text1"
  14024. "\r\n--zzzz--",
  14025. "\r\nthis epilogue must be ignored\r\n");
  14026. }
  14027. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14028. // The initial boundary may be preceded by a preamble of any length and may
  14029. // straddle a read boundary. Discarding data while waiting for it must not
  14030. // throw away a partial boundary sitting at the end of the buffer.
  14031. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14032. "zz\r\n"
  14033. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14034. "\r\n"
  14035. "text1"
  14036. "\r\n--zzzz--\r\n");
  14037. }
  14038. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14039. // The received boundary was only checked for being non-empty, so it could be
  14040. // as long as a header is allowed to be. The parser scans the body for
  14041. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14042. // costs a nearly full comparison at nearly every position, making the
  14043. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14044. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14045. Server svr;
  14046. svr.Post("/post", [](const Request &req, Response &res) {
  14047. EXPECT_EQ(1u, req.form.fields.size());
  14048. EXPECT_EQ("text1", req.form.get_field("text1"));
  14049. res.set_content("ok", "text/plain");
  14050. });
  14051. auto port = svr.bind_to_any_port(HOST);
  14052. thread t = thread([&] { svr.listen_after_bind(); });
  14053. auto se = detail::scope_exit([&] {
  14054. svr.stop();
  14055. t.join();
  14056. ASSERT_FALSE(svr.is_running());
  14057. });
  14058. svr.wait_until_ready();
  14059. Client cli(HOST, port);
  14060. auto post_with_boundary_of_length = [&](size_t len) {
  14061. const std::string boundary(len, 'a');
  14062. const std::string body =
  14063. "--" + boundary +
  14064. "\r\n"
  14065. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14066. "\r\n"
  14067. "text1"
  14068. "\r\n--" +
  14069. boundary + "--\r\n";
  14070. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14071. };
  14072. auto res = post_with_boundary_of_length(70);
  14073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14074. EXPECT_EQ(StatusCode::OK_200, res->status);
  14075. res = post_with_boundary_of_length(71);
  14076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14077. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14078. }
  14079. TEST(MakeFileBodyTest, Basic) {
  14080. const std::string file_content(4096, 'Z');
  14081. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14082. {
  14083. std::ofstream ofs(tmp_path, std::ios::binary);
  14084. ofs.write(file_content.data(),
  14085. static_cast<std::streamsize>(file_content.size()));
  14086. }
  14087. auto handled = false;
  14088. Server svr;
  14089. svr.Post("/upload", [&](const Request &req, Response &res) {
  14090. EXPECT_EQ(file_content, req.body);
  14091. handled = true;
  14092. res.status = StatusCode::OK_200;
  14093. });
  14094. auto port = svr.bind_to_any_port(HOST);
  14095. auto t = thread([&] { svr.listen_after_bind(); });
  14096. auto se = detail::scope_exit([&] {
  14097. svr.stop();
  14098. t.join();
  14099. ASSERT_FALSE(svr.is_running());
  14100. ASSERT_TRUE(handled);
  14101. std::remove(tmp_path.c_str());
  14102. });
  14103. svr.wait_until_ready();
  14104. auto fb = make_file_body(tmp_path);
  14105. ASSERT_GT(fb.first, 0u);
  14106. Client cli(HOST, port);
  14107. auto res =
  14108. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14110. EXPECT_EQ(StatusCode::OK_200, res->status);
  14111. }
  14112. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14113. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14114. {
  14115. std::ofstream ofs(path, std::ios::binary);
  14116. const std::string content(100, 'A');
  14117. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14118. }
  14119. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14120. auto body = make_file_body(path);
  14121. ASSERT_EQ(100u, body.first);
  14122. ASSERT_TRUE(static_cast<bool>(body.second));
  14123. // Rewritten shorter after its length was measured - and, on a server, after
  14124. // that length has already gone out as Content-Length.
  14125. {
  14126. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14127. const std::string content(10, 'A');
  14128. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14129. }
  14130. std::string written;
  14131. DataSink sink;
  14132. sink.write = [&](const char *d, size_t l) {
  14133. written.append(d, l);
  14134. return true;
  14135. };
  14136. // The provider has to report failure. write_content_with_progress() advances
  14137. // its offset only by what was written, so a provider that returns true
  14138. // without completing the length it promised is called again straight away,
  14139. // and again.
  14140. EXPECT_FALSE(body.second(0, body.first, sink));
  14141. EXPECT_EQ(std::string(10, 'A'), written);
  14142. }
  14143. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14144. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14145. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14146. {
  14147. std::ofstream ofs(path, std::ios::binary);
  14148. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14149. }
  14150. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14151. auto body = make_file_body(path);
  14152. ASSERT_EQ(content.size(), body.first);
  14153. ASSERT_TRUE(static_cast<bool>(body.second));
  14154. std::string written;
  14155. DataSink sink;
  14156. sink.write = [&](const char *d, size_t l) {
  14157. written.append(d, l);
  14158. return true;
  14159. };
  14160. EXPECT_TRUE(body.second(0, body.first, sink));
  14161. EXPECT_EQ(content, written);
  14162. }
  14163. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14164. static constexpr unsigned int number_of_tasks{1000000};
  14165. std::atomic_uint count{0};
  14166. std::unique_ptr<TaskQueue> task_queue{
  14167. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14168. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14169. auto queued = task_queue->enqueue(
  14170. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14171. EXPECT_TRUE(queued);
  14172. }
  14173. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14174. task_queue->shutdown();
  14175. #else
  14176. EXPECT_NO_THROW(task_queue->shutdown());
  14177. #endif
  14178. EXPECT_EQ(number_of_tasks, count.load());
  14179. }
  14180. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14181. static constexpr unsigned int number_of_tasks{1000000};
  14182. static constexpr unsigned int qlimit{2};
  14183. unsigned int queued_count{0};
  14184. std::atomic_uint count{0};
  14185. std::unique_ptr<TaskQueue> task_queue{
  14186. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14187. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14188. if (task_queue->enqueue(
  14189. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14190. queued_count++;
  14191. }
  14192. }
  14193. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14194. task_queue->shutdown();
  14195. #else
  14196. EXPECT_NO_THROW(task_queue->shutdown());
  14197. #endif
  14198. EXPECT_EQ(queued_count, count.load());
  14199. EXPECT_TRUE(queued_count <= number_of_tasks);
  14200. EXPECT_TRUE(queued_count >= qlimit);
  14201. }
  14202. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14203. // Use a short idle timeout so a dynamic thread spawns, times out and
  14204. // exits during the test, and the pool keeps working afterwards.
  14205. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14206. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14207. /*idle_timeout_sec=*/1}};
  14208. std::atomic_uint count{0};
  14209. std::condition_variable cv;
  14210. std::mutex mtx;
  14211. bool release = false;
  14212. // Block the base thread so the second task spawns a dynamic thread.
  14213. EXPECT_TRUE(task_queue->enqueue([&] {
  14214. std::unique_lock<std::mutex> lock(mtx);
  14215. while (!release) {
  14216. cv.wait(lock);
  14217. }
  14218. count++;
  14219. }));
  14220. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14221. // Let the dynamic thread finish its task and exceed the idle timeout.
  14222. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14223. {
  14224. std::unique_lock<std::mutex> lock(mtx);
  14225. release = true;
  14226. }
  14227. cv.notify_all();
  14228. // The pool must still accept and run tasks after the dynamic thread exited.
  14229. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14230. task_queue->shutdown();
  14231. EXPECT_EQ(3u, count.load());
  14232. }
  14233. TEST(TaskQueueTest, MaxQueuedRequests) {
  14234. static constexpr unsigned int qlimit{3};
  14235. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14236. std::condition_variable sem_cv;
  14237. std::mutex sem_mtx;
  14238. int credits = 0;
  14239. bool queued;
  14240. /* Fill up the queue with tasks that will block until we give them credits to
  14241. * complete. */
  14242. for (unsigned int n = 0; n <= qlimit;) {
  14243. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14244. std::unique_lock<std::mutex> lock(sem_mtx);
  14245. while (credits <= 0) {
  14246. sem_cv.wait(lock);
  14247. }
  14248. /* Consume the credit and signal the test code if they are all gone. */
  14249. if (--credits == 0) { sem_cv.notify_one(); }
  14250. });
  14251. if (n < qlimit) {
  14252. /* The first qlimit enqueues must succeed. */
  14253. EXPECT_TRUE(queued);
  14254. } else {
  14255. /* The last one will succeed only when the worker thread
  14256. * starts and dequeues the first blocking task. Although
  14257. * not necessary for the correctness of this test, we sleep for
  14258. * a short while to avoid busy waiting. */
  14259. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14260. }
  14261. if (queued) { n++; }
  14262. }
  14263. /* Further enqueues must fail since the queue is full. */
  14264. for (auto i = 0; i < 4; i++) {
  14265. queued = task_queue->enqueue([] {});
  14266. EXPECT_FALSE(queued);
  14267. }
  14268. /* Give the credits to allow the previous tasks to complete. */
  14269. {
  14270. std::unique_lock<std::mutex> lock(sem_mtx);
  14271. credits += qlimit + 1;
  14272. }
  14273. sem_cv.notify_all();
  14274. /* Wait for all the credits to be consumed. */
  14275. {
  14276. std::unique_lock<std::mutex> lock(sem_mtx);
  14277. while (credits > 0) {
  14278. sem_cv.wait(lock);
  14279. }
  14280. }
  14281. /* Check that we are able again to enqueue at least qlimit tasks. */
  14282. for (unsigned int i = 0; i < qlimit; i++) {
  14283. queued = task_queue->enqueue([] {});
  14284. EXPECT_TRUE(queued);
  14285. }
  14286. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14287. task_queue->shutdown();
  14288. #else
  14289. EXPECT_NO_THROW(task_queue->shutdown());
  14290. #endif
  14291. }
  14292. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14293. Server svr;
  14294. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14295. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14296. });
  14297. svr.Get("/hello", [](const Request &req, Response &res) {
  14298. res.set_content(req.get_param_value("key"), "text/plain");
  14299. });
  14300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14301. auto se = detail::scope_exit([&] {
  14302. svr.stop();
  14303. thread.join();
  14304. ASSERT_FALSE(svr.is_running());
  14305. });
  14306. svr.wait_until_ready();
  14307. {
  14308. Client cli(HOST, PORT);
  14309. cli.set_follow_location(true);
  14310. auto res = cli.Get("/");
  14311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14312. EXPECT_EQ(StatusCode::OK_200, res->status);
  14313. EXPECT_EQ("val&key2=val2", res->body);
  14314. }
  14315. }
  14316. #endif
  14317. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14318. Server svr;
  14319. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14320. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14321. });
  14322. svr.Get("/hello", [](const Request &req, Response &res) {
  14323. res.set_content(req.get_param_value("key"), "text/plain");
  14324. });
  14325. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14326. auto se = detail::scope_exit([&] {
  14327. svr.stop();
  14328. thread.join();
  14329. ASSERT_FALSE(svr.is_running());
  14330. });
  14331. svr.wait_until_ready();
  14332. {
  14333. Client cli(HOST, PORT);
  14334. cli.set_follow_location(true);
  14335. auto res = cli.Get("/");
  14336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14337. EXPECT_EQ(StatusCode::OK_200, res->status);
  14338. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14339. }
  14340. }
  14341. TEST(RedirectTest, RedirectWithPlusInPath) {
  14342. Server svr;
  14343. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14344. res.set_redirect("/a+b");
  14345. });
  14346. // Route pattern uses regex; escape + as \\+
  14347. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14348. res.set_content(req.path, "text/plain");
  14349. });
  14350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14351. auto se = detail::scope_exit([&] {
  14352. svr.stop();
  14353. thread.join();
  14354. ASSERT_FALSE(svr.is_running());
  14355. });
  14356. svr.wait_until_ready();
  14357. {
  14358. Client cli(HOST, PORT);
  14359. cli.set_follow_location(true);
  14360. auto res = cli.Get("/");
  14361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14362. EXPECT_EQ(StatusCode::OK_200, res->status);
  14363. EXPECT_EQ("/a+b", res->body);
  14364. }
  14365. }
  14366. #ifdef CPPHTTPLIB_SSL_ENABLED
  14367. TEST(RedirectTest, Issue2185_Online) {
  14368. SSLClient client("github.com");
  14369. client.set_follow_location(true);
  14370. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14371. "Coollab-Windows.zip");
  14372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14373. EXPECT_EQ(StatusCode::OK_200, res->status);
  14374. EXPECT_EQ(9920427U, res->body.size());
  14375. }
  14376. #endif
  14377. TEST(VulnerabilityTest, CRLFInjection) {
  14378. Server svr;
  14379. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14380. res.set_content("Hello 1", "text/plain");
  14381. });
  14382. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14383. res.set_content("Hello 2", "text/plain");
  14384. });
  14385. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14386. res.set_content("Hello 3", "text/plain");
  14387. });
  14388. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14389. res.set_content("Hello 4", "text/plain");
  14390. });
  14391. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14392. for (const auto &x : req.headers) {
  14393. auto key = x.first;
  14394. EXPECT_STRNE("evil", key.c_str());
  14395. }
  14396. });
  14397. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14398. auto se = detail::scope_exit([&] {
  14399. svr.stop();
  14400. thread.join();
  14401. ASSERT_FALSE(svr.is_running());
  14402. });
  14403. svr.wait_until_ready();
  14404. {
  14405. Client cli(HOST, PORT);
  14406. cli.Post("/test1", "A=B",
  14407. "application/x-www-form-urlencoded\r\nevil: hello1");
  14408. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14409. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14410. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14411. }
  14412. }
  14413. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14414. auto server_thread = std::thread([] {
  14415. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14416. default_socket_options(srv);
  14417. sockaddr_in addr{};
  14418. addr.sin_family = AF_INET;
  14419. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14420. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14421. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14422. ::listen(srv, 1);
  14423. sockaddr_in cli_addr{};
  14424. socklen_t cli_len = sizeof(cli_addr);
  14425. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14426. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14427. std::string buf_all;
  14428. char buf[2048];
  14429. ssize_t n;
  14430. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14431. buf_all.append(buf, static_cast<size_t>(n));
  14432. size_t pos;
  14433. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14434. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14435. auto e = request_block.find("\r\n");
  14436. if (e != std::string::npos) {
  14437. auto request_line = request_block.substr(0, e);
  14438. std::string msg =
  14439. "CRLF injection detected in request line: '" + request_line + "'";
  14440. EXPECT_FALSE(true) << msg;
  14441. }
  14442. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14443. ::send(cli,
  14444. #ifdef _WIN32
  14445. static_cast<const char *>(resp.c_str()),
  14446. static_cast<int>(resp.size()),
  14447. #else
  14448. resp.c_str(), resp.size(),
  14449. #endif
  14450. 0);
  14451. buf_all.erase(0, pos + 4);
  14452. }
  14453. }
  14454. detail::close_socket(cli);
  14455. detail::close_socket(srv);
  14456. });
  14457. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14458. auto cli = Client("127.0.0.1", PORT + 1);
  14459. auto headers = Headers{
  14460. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14461. {"Connection", "keep-alive"}};
  14462. auto res = cli.Get("/hi", headers);
  14463. EXPECT_FALSE(res);
  14464. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14465. server_thread.join();
  14466. }
  14467. TEST(PathParamsTest, StaticMatch) {
  14468. const auto pattern = "/users/all";
  14469. detail::PathParamsMatcher matcher(pattern);
  14470. Request request;
  14471. request.path = "/users/all";
  14472. ASSERT_TRUE(matcher.match(request));
  14473. std::unordered_map<std::string, std::string> expected_params = {};
  14474. EXPECT_EQ(request.path_params, expected_params);
  14475. }
  14476. TEST(PathParamsTest, StaticMismatch) {
  14477. const auto pattern = "/users/all";
  14478. detail::PathParamsMatcher matcher(pattern);
  14479. Request request;
  14480. request.path = "/users/1";
  14481. ASSERT_FALSE(matcher.match(request));
  14482. }
  14483. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14484. const auto pattern = "/users/:id/subscriptions";
  14485. detail::PathParamsMatcher matcher(pattern);
  14486. Request request;
  14487. request.path = "/users/42/subscriptions";
  14488. ASSERT_TRUE(matcher.match(request));
  14489. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14490. EXPECT_EQ(request.path_params, expected_params);
  14491. }
  14492. TEST(PathParamsTest, SingleParamInTheEnd) {
  14493. const auto pattern = "/users/:id";
  14494. detail::PathParamsMatcher matcher(pattern);
  14495. Request request;
  14496. request.path = "/users/24";
  14497. ASSERT_TRUE(matcher.match(request));
  14498. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14499. EXPECT_EQ(request.path_params, expected_params);
  14500. }
  14501. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14502. const auto pattern = "/users/:id/";
  14503. detail::PathParamsMatcher matcher(pattern);
  14504. Request request;
  14505. request.path = "/users/42/";
  14506. ASSERT_TRUE(matcher.match(request));
  14507. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14508. EXPECT_EQ(request.path_params, expected_params);
  14509. }
  14510. TEST(PathParamsTest, EmptyParam) {
  14511. const auto pattern = "/users/:id/";
  14512. detail::PathParamsMatcher matcher(pattern);
  14513. Request request;
  14514. request.path = "/users//";
  14515. ASSERT_TRUE(matcher.match(request));
  14516. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14517. EXPECT_EQ(request.path_params, expected_params);
  14518. }
  14519. TEST(PathParamsTest, FragmentMismatch) {
  14520. const auto pattern = "/users/:id/";
  14521. detail::PathParamsMatcher matcher(pattern);
  14522. Request request;
  14523. request.path = "/admins/24/";
  14524. ASSERT_FALSE(matcher.match(request));
  14525. }
  14526. TEST(PathParamsTest, ExtraFragments) {
  14527. const auto pattern = "/users/:id";
  14528. detail::PathParamsMatcher matcher(pattern);
  14529. Request request;
  14530. request.path = "/users/42/subscriptions";
  14531. ASSERT_FALSE(matcher.match(request));
  14532. }
  14533. TEST(PathParamsTest, MissingTrailingParam) {
  14534. const auto pattern = "/users/:id";
  14535. detail::PathParamsMatcher matcher(pattern);
  14536. Request request;
  14537. request.path = "/users";
  14538. ASSERT_FALSE(matcher.match(request));
  14539. }
  14540. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14541. const auto pattern = "/users/:id/subscriptions";
  14542. detail::PathParamsMatcher matcher(pattern);
  14543. Request request;
  14544. request.path = "/users/subscriptions";
  14545. ASSERT_FALSE(matcher.match(request));
  14546. }
  14547. TEST(PathParamsTest, MultipleParams) {
  14548. const auto pattern = "/users/:userid/subscriptions/:subid";
  14549. detail::PathParamsMatcher matcher(pattern);
  14550. Request request;
  14551. request.path = "/users/42/subscriptions/2";
  14552. ASSERT_TRUE(matcher.match(request));
  14553. std::unordered_map<std::string, std::string> expected_params = {
  14554. {"userid", "42"}, {"subid", "2"}};
  14555. EXPECT_EQ(request.path_params, expected_params);
  14556. }
  14557. TEST(PathParamsTest, SequenceOfParams) {
  14558. const auto pattern = "/values/:x/:y/:z";
  14559. detail::PathParamsMatcher matcher(pattern);
  14560. Request request;
  14561. request.path = "/values/1/2/3";
  14562. ASSERT_TRUE(matcher.match(request));
  14563. std::unordered_map<std::string, std::string> expected_params = {
  14564. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14565. EXPECT_EQ(request.path_params, expected_params);
  14566. }
  14567. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14568. const auto pattern = "/prefix:suffix";
  14569. detail::PathParamsMatcher matcher(pattern);
  14570. Request request;
  14571. request.path = "/prefix:suffix";
  14572. ASSERT_TRUE(matcher.match(request));
  14573. const std::unordered_map<std::string, std::string> expected_params = {};
  14574. EXPECT_EQ(request.path_params, expected_params);
  14575. }
  14576. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14577. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14578. // calling thread's stack on a long enough path for a quantified pattern;
  14579. // RegexMatcher must refuse to run regex matching on paths beyond
  14580. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14581. detail::RegexMatcher matcher("/files/(.*)");
  14582. Request within_limit;
  14583. within_limit.path = "/files/" + std::string(10, 'A');
  14584. EXPECT_TRUE(matcher.match(within_limit));
  14585. Request over_limit;
  14586. over_limit.path =
  14587. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14588. EXPECT_FALSE(matcher.match(over_limit));
  14589. }
  14590. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14591. Server svr;
  14592. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14593. res.set_content("ok", "text/plain");
  14594. });
  14595. auto port = svr.bind_to_any_port(HOST);
  14596. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14597. auto se = detail::scope_exit([&] {
  14598. svr.stop();
  14599. thread.join();
  14600. ASSERT_FALSE(svr.is_running());
  14601. });
  14602. svr.wait_until_ready();
  14603. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14604. // request URI limit; this used to be able to crash the process.
  14605. std::string path =
  14606. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14607. std::string req = "GET " + path +
  14608. " HTTP/1.1\r\n"
  14609. "Host: " +
  14610. std::string(HOST) + ":" + std::to_string(port) +
  14611. "\r\n"
  14612. "Connection: close\r\n"
  14613. "\r\n";
  14614. std::string response;
  14615. ASSERT_TRUE(send_request(5, req, &response, port));
  14616. EXPECT_NE(std::string::npos, response.find("404"));
  14617. }
  14618. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14619. Server svr;
  14620. auto handler = [](const Request & /*req*/, Response &res) {
  14621. res.set_content("hit", "text/plain");
  14622. };
  14623. // No regex metacharacter, so this one is compared literally
  14624. svr.Get("/literal/route", handler);
  14625. // '.' is a regex metacharacter, so this one must keep regex semantics
  14626. svr.Get("/a.c", handler);
  14627. auto port = svr.bind_to_any_port(HOST);
  14628. std::thread t([&]() { svr.listen_after_bind(); });
  14629. auto se = detail::scope_exit([&] {
  14630. svr.stop();
  14631. t.join();
  14632. ASSERT_FALSE(svr.is_running());
  14633. });
  14634. svr.wait_until_ready();
  14635. Client cli(HOST, port);
  14636. struct {
  14637. const char *path;
  14638. int status;
  14639. } cases[] = {
  14640. {"/literal/route", StatusCode::OK_200},
  14641. {"/literal/routes", StatusCode::NotFound_404},
  14642. {"/literal/rout", StatusCode::NotFound_404},
  14643. {"/abc", StatusCode::OK_200},
  14644. {"/a.c", StatusCode::OK_200},
  14645. };
  14646. for (const auto &x : cases) {
  14647. auto res = cli.Get(x.path);
  14648. ASSERT_TRUE(res) << x.path;
  14649. EXPECT_EQ(x.status, res->status) << x.path;
  14650. }
  14651. }
  14652. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14653. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14654. // from exhausting the stack, so it must only constrain routes that actually
  14655. // run a regular expression. A literal route is matched by comparison and
  14656. // stays usable at any length.
  14657. Server svr;
  14658. const std::string pattern =
  14659. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14660. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14661. res.set_content("hit", "text/plain");
  14662. });
  14663. auto port = svr.bind_to_any_port(HOST);
  14664. std::thread t([&]() { svr.listen_after_bind(); });
  14665. auto se = detail::scope_exit([&] {
  14666. svr.stop();
  14667. t.join();
  14668. ASSERT_FALSE(svr.is_running());
  14669. });
  14670. svr.wait_until_ready();
  14671. Client cli(HOST, port);
  14672. auto res = cli.Get(pattern);
  14673. ASSERT_TRUE(res);
  14674. EXPECT_EQ(StatusCode::OK_200, res->status);
  14675. }
  14676. TEST(ParseUrlTest, VariousPatterns) {
  14677. {
  14678. detail::UrlComponents uc;
  14679. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14680. EXPECT_EQ("http", uc.scheme);
  14681. EXPECT_EQ("example.com", uc.host);
  14682. EXPECT_EQ("8080", uc.port);
  14683. EXPECT_EQ("/path", uc.path);
  14684. EXPECT_EQ("?q=1", uc.query);
  14685. }
  14686. {
  14687. detail::UrlComponents uc;
  14688. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14689. EXPECT_EQ("https", uc.scheme);
  14690. EXPECT_EQ("example.com", uc.host);
  14691. EXPECT_TRUE(uc.port.empty());
  14692. EXPECT_EQ("/path", uc.path);
  14693. }
  14694. {
  14695. detail::UrlComponents uc;
  14696. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14697. EXPECT_EQ("::1", uc.host);
  14698. EXPECT_EQ("8080", uc.port);
  14699. EXPECT_EQ("/path", uc.path);
  14700. }
  14701. {
  14702. detail::UrlComponents uc;
  14703. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14704. }
  14705. {
  14706. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14707. // the path while the connection still targets the bracketed host.
  14708. detail::UrlComponents uc;
  14709. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14710. }
  14711. {
  14712. detail::UrlComponents uc;
  14713. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14714. }
  14715. {
  14716. detail::UrlComponents uc;
  14717. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14718. EXPECT_EQ("::1", uc.host);
  14719. EXPECT_TRUE(uc.port.empty());
  14720. EXPECT_EQ("/path", uc.path);
  14721. }
  14722. {
  14723. detail::UrlComponents uc;
  14724. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14725. EXPECT_TRUE(uc.scheme.empty());
  14726. EXPECT_EQ("example.com", uc.host);
  14727. EXPECT_EQ("/path", uc.path);
  14728. EXPECT_EQ("?q=1", uc.query);
  14729. }
  14730. {
  14731. detail::UrlComponents uc;
  14732. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14733. EXPECT_TRUE(uc.host.empty());
  14734. EXPECT_EQ("/path", uc.path);
  14735. EXPECT_EQ("?q=1", uc.query);
  14736. }
  14737. {
  14738. detail::UrlComponents uc;
  14739. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  14740. EXPECT_EQ("example.com", uc.host);
  14741. EXPECT_EQ("8080", uc.port);
  14742. }
  14743. {
  14744. // Unix socket path — must not be parsed as host
  14745. detail::UrlComponents uc;
  14746. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14747. EXPECT_TRUE(uc.host.empty());
  14748. }
  14749. {
  14750. detail::UrlComponents uc;
  14751. ASSERT_TRUE(detail::parse_url("", uc));
  14752. EXPECT_TRUE(uc.host.empty());
  14753. EXPECT_TRUE(uc.path.empty());
  14754. }
  14755. {
  14756. detail::UrlComponents uc;
  14757. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14758. }
  14759. {
  14760. detail::UrlComponents uc;
  14761. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14762. }
  14763. {
  14764. // Accepted by parse_url; callers restrict to http/https
  14765. detail::UrlComponents uc;
  14766. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14767. EXPECT_EQ("ftp", uc.scheme);
  14768. }
  14769. {
  14770. detail::UrlComponents uc;
  14771. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14772. }
  14773. {
  14774. detail::UrlComponents uc;
  14775. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14776. }
  14777. }
  14778. TEST(ParseUrlTest, FragmentHandling) {
  14779. {
  14780. detail::UrlComponents uc;
  14781. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14782. EXPECT_EQ("/path", uc.path);
  14783. EXPECT_TRUE(uc.query.empty());
  14784. }
  14785. {
  14786. detail::UrlComponents uc;
  14787. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14788. EXPECT_TRUE(uc.path.empty());
  14789. EXPECT_TRUE(uc.query.empty());
  14790. }
  14791. }
  14792. TEST(ParseUrlTest, UserinfoHandling) {
  14793. // Userinfo with @ but no colon — host includes @
  14794. detail::UrlComponents uc;
  14795. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14796. EXPECT_EQ("user@host.com", uc.host);
  14797. EXPECT_EQ("/path", uc.path);
  14798. }
  14799. TEST(ParseUrlTest, IPv6EdgeCases) {
  14800. {
  14801. detail::UrlComponents uc;
  14802. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14803. EXPECT_TRUE(uc.scheme.empty());
  14804. EXPECT_EQ("::1", uc.host);
  14805. EXPECT_EQ("8080", uc.port);
  14806. }
  14807. {
  14808. // Zone ID '%25' is not in [a-fA-F0-9:]
  14809. detail::UrlComponents uc;
  14810. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14811. }
  14812. }
  14813. TEST(ParseUrlTest, SchemeEdgeCases) {
  14814. {
  14815. detail::UrlComponents uc;
  14816. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14817. }
  14818. {
  14819. detail::UrlComponents uc;
  14820. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14821. }
  14822. {
  14823. detail::UrlComponents uc;
  14824. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14825. }
  14826. }
  14827. TEST(ParseUrlTest, PortEdgeCases) {
  14828. {
  14829. detail::UrlComponents uc;
  14830. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14831. EXPECT_TRUE(uc.port.empty());
  14832. EXPECT_EQ("/path", uc.path);
  14833. }
  14834. {
  14835. // parse_url accepts any port string; validation is done by parse_port
  14836. detail::UrlComponents uc;
  14837. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14838. EXPECT_EQ("abc", uc.port);
  14839. }
  14840. }
  14841. TEST(ParseUrlTest, WebSocketPatterns) {
  14842. {
  14843. detail::UrlComponents uc;
  14844. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14845. EXPECT_EQ("ws", uc.scheme);
  14846. EXPECT_EQ("echo.example.com", uc.host);
  14847. EXPECT_EQ("8080", uc.port);
  14848. EXPECT_EQ("/ws", uc.path);
  14849. }
  14850. {
  14851. detail::UrlComponents uc;
  14852. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14853. EXPECT_EQ("wss", uc.scheme);
  14854. EXPECT_EQ("echo.example.com", uc.host);
  14855. EXPECT_TRUE(uc.port.empty());
  14856. EXPECT_EQ("/ws", uc.path);
  14857. }
  14858. }
  14859. TEST(ParseUrlTest, QueryOnly) {
  14860. detail::UrlComponents uc;
  14861. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14862. EXPECT_TRUE(uc.host.empty());
  14863. EXPECT_TRUE(uc.path.empty());
  14864. EXPECT_EQ("?q=1&r=2", uc.query);
  14865. }
  14866. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14867. detail::UrlComponents uc;
  14868. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14869. EXPECT_TRUE(uc.scheme.empty());
  14870. EXPECT_EQ("example.com", uc.host);
  14871. EXPECT_EQ("443", uc.port);
  14872. EXPECT_EQ("/path", uc.path);
  14873. }
  14874. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14875. // If ipv6 regex working, regex match codepath is taken.
  14876. // else port will default to 80 in Client impl
  14877. int clientImplMagicPort = 80;
  14878. int port = 4321;
  14879. // above ports must be different to avoid false negative
  14880. EXPECT_NE(clientImplMagicPort, port);
  14881. std::string ipV6TestURL = "http://[ff06::c3]";
  14882. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14883. CLIENT_PRIVATE_KEY_FILE);
  14884. EXPECT_EQ(cli.port(), port);
  14885. }
  14886. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14887. auto file_path = "./www/dir/index.html";
  14888. auto dir_path = "./www/dir";
  14889. detail::FileStat stat_file(file_path);
  14890. EXPECT_TRUE(stat_file.is_file());
  14891. EXPECT_FALSE(stat_file.is_dir());
  14892. detail::FileStat stat_dir(dir_path);
  14893. EXPECT_FALSE(stat_dir.is_file());
  14894. EXPECT_TRUE(stat_dir.is_dir());
  14895. }
  14896. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14897. // IPv4 with default HTTP port (80)
  14898. EXPECT_EQ("example.com",
  14899. detail::make_host_and_port_string("example.com", 80, false));
  14900. // IPv4 with default HTTPS port (443)
  14901. EXPECT_EQ("example.com",
  14902. detail::make_host_and_port_string("example.com", 443, true));
  14903. // IPv4 with non-default HTTP port
  14904. EXPECT_EQ("example.com:8080",
  14905. detail::make_host_and_port_string("example.com", 8080, false));
  14906. // IPv4 with non-default HTTPS port
  14907. EXPECT_EQ("example.com:8443",
  14908. detail::make_host_and_port_string("example.com", 8443, true));
  14909. // IPv6 with default HTTP port (80)
  14910. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14911. // IPv6 with default HTTPS port (443)
  14912. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14913. // IPv6 with non-default HTTP port
  14914. EXPECT_EQ("[::1]:8080",
  14915. detail::make_host_and_port_string("::1", 8080, false));
  14916. // IPv6 with non-default HTTPS port
  14917. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14918. // IPv6 full address with default port
  14919. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14920. detail::make_host_and_port_string(
  14921. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14922. // IPv6 full address with non-default port
  14923. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14924. detail::make_host_and_port_string(
  14925. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14926. // IPv6 localhost with non-default port
  14927. EXPECT_EQ("[::1]:3000",
  14928. detail::make_host_and_port_string("::1", 3000, false));
  14929. // IPv6 with zone ID (link-local address) with default port
  14930. EXPECT_EQ("[fe80::1%eth0]",
  14931. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14932. // IPv6 with zone ID (link-local address) with non-default port
  14933. EXPECT_EQ("[fe80::1%eth0]:8080",
  14934. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14935. // Edge case: Port 443 with is_ssl=false (should add port)
  14936. EXPECT_EQ("example.com:443",
  14937. detail::make_host_and_port_string("example.com", 443, false));
  14938. // Edge case: Port 80 with is_ssl=true (should add port)
  14939. EXPECT_EQ("example.com:80",
  14940. detail::make_host_and_port_string("example.com", 80, true));
  14941. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14942. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14943. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14944. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14945. // Security fix: Already bracketed IPv6 should not get double brackets
  14946. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14947. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14948. EXPECT_EQ("[::1]:8080",
  14949. detail::make_host_and_port_string("[::1]", 8080, false));
  14950. EXPECT_EQ("[2001:db8::1]:8080",
  14951. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14952. EXPECT_EQ("[fe80::1%eth0]",
  14953. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14954. EXPECT_EQ("[fe80::1%eth0]:8080",
  14955. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14956. // Edge case: Empty host (should return as-is)
  14957. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14958. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14959. // This is a known limitation but shouldn't crash
  14960. EXPECT_EQ("[host:name]",
  14961. detail::make_host_and_port_string("host:name", 80, false));
  14962. // Port number edge cases (no validation, but should not crash)
  14963. EXPECT_EQ("example.com:0",
  14964. detail::make_host_and_port_string("example.com", 0, false));
  14965. EXPECT_EQ("example.com:-1",
  14966. detail::make_host_and_port_string("example.com", -1, false));
  14967. EXPECT_EQ("example.com:65535",
  14968. detail::make_host_and_port_string("example.com", 65535, false));
  14969. EXPECT_EQ("example.com:65536",
  14970. detail::make_host_and_port_string("example.com", 65536, false));
  14971. }
  14972. #ifdef CPPHTTPLIB_SSL_ENABLED
  14973. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14974. httplib::SSLClient cli("roblox.com", 443);
  14975. cli.set_follow_location(true);
  14976. auto res = cli.Get("/");
  14977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14978. EXPECT_EQ(StatusCode::OK_200, res->status);
  14979. }
  14980. #endif
  14981. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14982. Server svr;
  14983. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14984. EXPECT_EQ(res.status, 400);
  14985. });
  14986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14987. auto se = detail::scope_exit([&] {
  14988. svr.stop();
  14989. thread.join();
  14990. ASSERT_FALSE(svr.is_running());
  14991. });
  14992. svr.wait_until_ready();
  14993. Client cli(HOST, PORT);
  14994. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14995. }
  14996. TEST(InvalidHeaderCharsTest, is_field_name) {
  14997. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14998. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14999. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15000. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15001. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15002. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15003. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15004. EXPECT_FALSE(detail::fields::is_field_name(""));
  15005. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15006. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15007. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15008. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15009. }
  15010. TEST(InvalidHeaderCharsTest, is_field_value) {
  15011. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15012. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15013. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15014. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15015. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15016. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15017. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15018. EXPECT_TRUE(detail::fields::is_field_value(""));
  15019. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15020. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15021. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15022. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15023. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15024. }
  15025. TEST(InvalidHeaderCharsTest, OnServer) {
  15026. Server svr;
  15027. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15028. std::string header = "Not Set";
  15029. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15030. res.set_header(header, "value");
  15031. res.set_content("Page Content Page Content", "text/plain");
  15032. });
  15033. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15034. std::string header = "Not Set";
  15035. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15036. res.set_header("X-Test", header);
  15037. res.set_content("Page Content Page Content", "text/plain");
  15038. });
  15039. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15040. auto se = detail::scope_exit([&] {
  15041. svr.stop();
  15042. thread.join();
  15043. ASSERT_FALSE(svr.is_running());
  15044. });
  15045. svr.wait_until_ready();
  15046. Client cli(HOST, PORT);
  15047. {
  15048. auto res = cli.Get(
  15049. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15051. EXPECT_EQ("Page Content Page Content", res->body);
  15052. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15053. }
  15054. {
  15055. auto res = cli.Get(
  15056. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15058. EXPECT_EQ("Page Content Page Content", res->body);
  15059. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15060. }
  15061. }
  15062. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15063. auto handled = false;
  15064. Server svr;
  15065. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15066. thread t = thread([&] { svr.listen(HOST, PORT); });
  15067. auto se = detail::scope_exit([&] {
  15068. svr.stop();
  15069. t.join();
  15070. ASSERT_FALSE(svr.is_running());
  15071. ASSERT_FALSE(handled);
  15072. });
  15073. svr.wait_until_ready();
  15074. auto req = "POST /test HTTP/1.1\r\n"
  15075. "Content-Length: x\r\n"
  15076. "\r\n";
  15077. std::string response;
  15078. ASSERT_TRUE(send_request(1, req, &response));
  15079. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15080. response.substr(0, response.find("\r\n")));
  15081. }
  15082. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15083. // case-insensitive, and a server that receives a 100-continue expectation in
  15084. // an HTTP/1.0 request MUST ignore it.
  15085. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15086. std::string response;
  15087. ASSERT_TRUE(send_request(1, req, &response, port));
  15088. *got_100 = response.find("100 Continue") != std::string::npos;
  15089. }
  15090. class ExpectTokenTest : public ::testing::Test {
  15091. protected:
  15092. void SetUp() override {
  15093. svr_.Post("/p", [](const Request &, Response &res) {
  15094. res.set_content("ok", "text/plain");
  15095. });
  15096. port_ = svr_.bind_to_any_port(HOST);
  15097. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15098. svr_.wait_until_ready();
  15099. }
  15100. void TearDown() override {
  15101. svr_.stop();
  15102. if (thread_.joinable()) { thread_.join(); }
  15103. }
  15104. std::string request(const char *version, const char *expect_value) const {
  15105. return std::string("POST /p ") + version +
  15106. "\r\n"
  15107. "Host: localhost\r\n"
  15108. "Content-Length: 2\r\n"
  15109. "Connection: close\r\n"
  15110. "Expect: " +
  15111. expect_value +
  15112. "\r\n"
  15113. "\r\n"
  15114. "hi";
  15115. }
  15116. Server svr_;
  15117. int port_ = 0;
  15118. thread thread_;
  15119. };
  15120. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15121. bool got_100 = false;
  15122. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15123. EXPECT_TRUE(got_100);
  15124. }
  15125. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15126. bool got_100 = true;
  15127. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15128. EXPECT_FALSE(got_100);
  15129. }
  15130. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15131. bool got_100 = false;
  15132. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15133. EXPECT_TRUE(got_100);
  15134. }
  15135. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15136. bool got_100 = false;
  15137. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15138. EXPECT_TRUE(got_100);
  15139. }
  15140. // `100 Continue` is sent only when the server starts reading the body, so a
  15141. // request rejected before that never invites the client to send it. The
  15142. // requests below carry the expectation but withhold the body, as a client
  15143. // waiting for `100 Continue` would.
  15144. // A POST that expects `100 Continue` and withholds its two-byte body.
  15145. static std::string expect_headers_only(const std::string &path) {
  15146. return "POST " + path +
  15147. " HTTP/1.1\r\n"
  15148. "Host: localhost\r\n"
  15149. "Content-Length: 2\r\n"
  15150. "Expect: 100-continue\r\n"
  15151. "\r\n";
  15152. }
  15153. class ExpectLazyContinueTest : public ::testing::Test {
  15154. protected:
  15155. void SetUp() override {
  15156. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15157. if (req.path == "/pre-routing") {
  15158. res.status = StatusCode::Unauthorized_401;
  15159. return Server::HandlerResponse::Handled;
  15160. }
  15161. return Server::HandlerResponse::Unhandled;
  15162. });
  15163. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15164. if (req.matched_route == "/pre-request") {
  15165. res.status = StatusCode::Forbidden_403;
  15166. return Server::HandlerResponse::Handled;
  15167. }
  15168. return Server::HandlerResponse::Unhandled;
  15169. });
  15170. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15171. res.set_content("ok", "text/plain");
  15172. });
  15173. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15174. res.set_content("ok", "text/plain");
  15175. });
  15176. svr_.Post("/reader-used", [](const Request &, Response &res,
  15177. const ContentReader &content_reader) {
  15178. std::string body;
  15179. content_reader([&](const char *data, size_t len) {
  15180. body.append(data, len);
  15181. return true;
  15182. });
  15183. res.set_content(body, "text/plain");
  15184. });
  15185. svr_.Post("/reader-unused",
  15186. [](const Request &, Response &res, const ContentReader &) {
  15187. res.set_content("ignored", "text/plain");
  15188. });
  15189. port_ = svr_.bind_to_any_port(HOST);
  15190. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15191. svr_.wait_until_ready();
  15192. }
  15193. void TearDown() override {
  15194. svr_.stop();
  15195. if (thread_.joinable()) { thread_.join(); }
  15196. }
  15197. // Sends `req` and reads until the server closes the connection. Returns
  15198. // false if the read had to wait for the client-side timeout instead.
  15199. bool send_until_closed(const std::string &req, std::string *resp) const {
  15200. auto start = std::chrono::steady_clock::now();
  15201. if (!send_request(3, req, resp, port_)) { return false; }
  15202. auto elapsed = std::chrono::steady_clock::now() - start;
  15203. return elapsed < std::chrono::seconds(2);
  15204. }
  15205. // The final response comes without `100 Continue`, and the server closes
  15206. // the connection since the body may or may not follow.
  15207. void expect_final_without_interim(const std::string &path,
  15208. const char *status_line) const {
  15209. std::string resp;
  15210. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15211. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15212. EXPECT_EQ(0u, resp.find(status_line));
  15213. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15214. }
  15215. Server svr_;
  15216. int port_ = 0;
  15217. thread thread_;
  15218. };
  15219. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15220. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15221. }
  15222. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15223. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15224. }
  15225. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15226. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15227. }
  15228. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15229. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15230. }
  15231. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15232. // The body follows once `100 Continue` has had time to arrive.
  15233. auto req = expect_headers_only("/reader-used");
  15234. req.insert(req.size() - 2, "Connection: close\r\n");
  15235. std::string resp;
  15236. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15237. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15238. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15239. EXPECT_NE(std::string::npos, resp.find("hi"));
  15240. }
  15241. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15242. // Large enough for the client to add `Expect: 100-continue` itself.
  15243. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15244. std::atomic<bool> body_sent{false};
  15245. Client cli(HOST, port_);
  15246. auto res = cli.Post(
  15247. "/pre-request", length,
  15248. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15249. body_sent = true;
  15250. std::string chunk(len, 'x');
  15251. sink.write(chunk.data(), chunk.size());
  15252. return true;
  15253. },
  15254. "application/octet-stream");
  15255. ASSERT_TRUE(res);
  15256. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15257. EXPECT_FALSE(body_sent);
  15258. }
  15259. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15260. Server svr;
  15261. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15262. return StatusCode::ExpectationFailed_417;
  15263. });
  15264. svr.Post("/p", [](const Request &, Response &res) {
  15265. res.set_content("ok", "text/plain");
  15266. });
  15267. auto port = svr.bind_to_any_port(HOST);
  15268. thread t = thread([&] { svr.listen_after_bind(); });
  15269. auto se = detail::scope_exit([&] {
  15270. svr.stop();
  15271. t.join();
  15272. });
  15273. svr.wait_until_ready();
  15274. std::string resp;
  15275. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15276. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15277. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15278. // Exactly one response: the route handler must not run after the 417.
  15279. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15280. }
  15281. #ifndef _WIN32
  15282. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15283. static constexpr char reject[] = "Unauthorized";
  15284. static constexpr char accept[] = "Upload accepted";
  15285. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15286. Server svr;
  15287. svr.set_expect_100_continue_handler(
  15288. [](const Request & /*req*/, Response &res) {
  15289. res.status = StatusCode::Unauthorized_401;
  15290. res.set_content(reject, "text/plain");
  15291. return res.status;
  15292. });
  15293. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15294. res.set_content(accept, "text/plain");
  15295. });
  15296. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15297. auto se = detail::scope_exit([&] {
  15298. svr.stop();
  15299. thread.join();
  15300. ASSERT_FALSE(svr.is_running());
  15301. });
  15302. svr.wait_until_ready();
  15303. {
  15304. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15305. curl_easy_init(), &curl_easy_cleanup};
  15306. ASSERT_NE(curl, nullptr);
  15307. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15308. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15309. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15310. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15311. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15312. &curl_slist_free_all};
  15313. ASSERT_NE(list, nullptr);
  15314. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15315. struct read_data {
  15316. size_t read_size;
  15317. size_t total_size;
  15318. } data = {0, total_size};
  15319. using read_callback_t =
  15320. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15321. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15322. void *userdata) -> size_t {
  15323. read_data *d = (read_data *)userdata;
  15324. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15325. std::fill_n(ptr, size * nmemb, 'A');
  15326. d->read_size += size * nmemb;
  15327. return size * nmemb;
  15328. };
  15329. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15330. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15331. std::vector<char> buffer;
  15332. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15333. using write_callback_t =
  15334. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15335. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15336. void *userdata) -> size_t {
  15337. std::vector<char> *buf = (std::vector<char> *)userdata;
  15338. buf->reserve(buf->size() + size * nmemb + 1);
  15339. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15340. return size * nmemb;
  15341. };
  15342. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15343. {
  15344. const auto res = curl_easy_perform(curl.get());
  15345. ASSERT_EQ(res, CURLE_OK);
  15346. }
  15347. {
  15348. auto response_code = long{};
  15349. const auto res =
  15350. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15351. ASSERT_EQ(res, CURLE_OK);
  15352. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15353. }
  15354. {
  15355. auto dl = curl_off_t{};
  15356. const auto res =
  15357. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15358. ASSERT_EQ(res, CURLE_OK);
  15359. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15360. }
  15361. {
  15362. buffer.push_back('\0');
  15363. ASSERT_STRCASEEQ(buffer.data(), reject);
  15364. }
  15365. }
  15366. }
  15367. #endif
  15368. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15369. // Regression test for #2458.
  15370. //
  15371. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15372. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15373. // ticket can make the client socket spuriously readable during the
  15374. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15375. // the client withholds the body and then blocks reading a response that never
  15376. // comes, failing with `Failed to read connection`.
  15377. //
  15378. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15379. // within the timeout. This raw OpenSSL server deliberately never sends
  15380. // `100 Continue`; the client must still deliver the body and receive 200.
  15381. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15382. signal(SIGPIPE, SIG_IGN);
  15383. const auto port = PORT + 4;
  15384. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15385. ASSERT_NE(srv, INVALID_SOCKET);
  15386. int opt = 1;
  15387. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15388. sockaddr_in addr{};
  15389. addr.sin_family = AF_INET;
  15390. addr.sin_port = htons(static_cast<uint16_t>(port));
  15391. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15392. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15393. ASSERT_EQ(0, ::listen(srv, 1));
  15394. std::atomic<size_t> server_body_bytes{0};
  15395. auto server_thread = std::thread([&] {
  15396. sockaddr_in cli_addr{};
  15397. socklen_t cli_len = sizeof(cli_addr);
  15398. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15399. if (cli == INVALID_SOCKET) { return; }
  15400. // Bound the lifetime of the server side so a buggy client (which never
  15401. // sends the body) cannot make this thread block forever on join.
  15402. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15403. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15404. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15405. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15406. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15407. SSL *ssl = SSL_new(ctx);
  15408. SSL_set_fd(ssl, static_cast<int>(cli));
  15409. if (SSL_accept(ssl) > 0) {
  15410. // Read the request headers. Reading here also flushes the TLS 1.3
  15411. // session tickets to the client. Deliberately do NOT send
  15412. // `100 Continue`.
  15413. std::string buf;
  15414. char tmp[1024];
  15415. while (buf.find("\r\n\r\n") == std::string::npos) {
  15416. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15417. if (n <= 0) { break; }
  15418. buf.append(tmp, static_cast<size_t>(n));
  15419. }
  15420. // A correct client sends the body now; count what arrives.
  15421. auto pos = buf.find("\r\n\r\n");
  15422. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15423. while (body < 4096) {
  15424. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15425. if (n <= 0) { break; }
  15426. body += static_cast<size_t>(n);
  15427. }
  15428. server_body_bytes = body;
  15429. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15430. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15431. SSL_shutdown(ssl);
  15432. }
  15433. SSL_free(ssl);
  15434. detail::close_socket(cli);
  15435. SSL_CTX_free(ctx);
  15436. });
  15437. auto se = detail::scope_exit([&] {
  15438. server_thread.join();
  15439. detail::close_socket(srv);
  15440. });
  15441. SSLClient cli("127.0.0.1", port);
  15442. cli.enable_server_certificate_verification(false);
  15443. cli.set_connection_timeout(5, 0);
  15444. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15445. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15446. std::string body(4096, 'A');
  15447. auto res = cli.Put("/api/test", body, "application/json");
  15448. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15449. EXPECT_EQ(StatusCode::OK_200, res->status);
  15450. EXPECT_EQ(body.size(), server_body_bytes.load());
  15451. }
  15452. #endif
  15453. template <typename S, typename C>
  15454. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15455. svr.Get("/stream", [&](const Request &, Response &res) {
  15456. auto data = new std::string("01234567890123456789");
  15457. res.set_content_provider(
  15458. data->size(), "text/plain",
  15459. [&, data](size_t offset, size_t length, DataSink &sink) {
  15460. const size_t DATA_CHUNK_SIZE = 4;
  15461. const auto &d = *data;
  15462. std::this_thread::sleep_for(std::chrono::seconds(1));
  15463. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15464. return true;
  15465. },
  15466. [data](bool success) {
  15467. EXPECT_FALSE(success);
  15468. delete data;
  15469. });
  15470. });
  15471. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15472. auto i = new size_t(0);
  15473. res.set_content_provider(
  15474. "text/plain",
  15475. [i](size_t, DataSink &sink) {
  15476. if (*i < 5) {
  15477. std::this_thread::sleep_for(std::chrono::seconds(1));
  15478. sink.write("abcd", 4);
  15479. (*i)++;
  15480. } else {
  15481. sink.done();
  15482. }
  15483. return true;
  15484. },
  15485. [i](bool success) {
  15486. EXPECT_FALSE(success);
  15487. delete i;
  15488. });
  15489. });
  15490. svr.Get("/chunked", [&](const Request &, Response &res) {
  15491. auto i = new size_t(0);
  15492. res.set_chunked_content_provider(
  15493. "text/plain",
  15494. [i](size_t, DataSink &sink) {
  15495. if (*i < 5) {
  15496. std::this_thread::sleep_for(std::chrono::seconds(1));
  15497. sink.os << "abcd";
  15498. (*i)++;
  15499. } else {
  15500. sink.done();
  15501. }
  15502. return true;
  15503. },
  15504. [i](bool success) {
  15505. EXPECT_FALSE(success);
  15506. delete i;
  15507. });
  15508. });
  15509. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15510. auto se = detail::scope_exit([&] {
  15511. svr.stop();
  15512. listen_thread.join();
  15513. ASSERT_FALSE(svr.is_running());
  15514. });
  15515. svr.wait_until_ready();
  15516. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15517. {
  15518. auto start = std::chrono::steady_clock::now();
  15519. auto res = cli.Get("/stream");
  15520. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15521. std::chrono::steady_clock::now() - start)
  15522. .count();
  15523. ASSERT_FALSE(res);
  15524. EXPECT_EQ(Error::Read, res.error());
  15525. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15526. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15527. }
  15528. {
  15529. auto start = std::chrono::steady_clock::now();
  15530. auto res = cli.Get("/stream_without_length");
  15531. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15532. std::chrono::steady_clock::now() - start)
  15533. .count();
  15534. ASSERT_FALSE(res);
  15535. EXPECT_EQ(Error::Read, res.error());
  15536. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15537. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15538. }
  15539. {
  15540. auto start = std::chrono::steady_clock::now();
  15541. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15542. EXPECT_EQ("abcd", string(data, data_length));
  15543. return true;
  15544. });
  15545. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15546. std::chrono::steady_clock::now() - start)
  15547. .count();
  15548. ASSERT_FALSE(res);
  15549. EXPECT_EQ(Error::Read, res.error());
  15550. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15551. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15552. }
  15553. }
  15554. TEST(MaxTimeoutTest, ContentStream) {
  15555. time_t timeout = 2000;
  15556. time_t threshold = 200;
  15557. Server svr;
  15558. Client cli("localhost", PORT);
  15559. max_timeout_test(svr, cli, timeout, threshold);
  15560. }
  15561. #ifdef CPPHTTPLIB_SSL_ENABLED
  15562. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15563. time_t timeout = 2000;
  15564. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15566. SSLClient cli("localhost", PORT);
  15567. cli.enable_server_certificate_verification(false);
  15568. max_timeout_test(svr, cli, timeout, threshold);
  15569. }
  15570. #endif
  15571. class EventDispatcher {
  15572. public:
  15573. EventDispatcher() {}
  15574. bool wait_event(DataSink *sink) {
  15575. unique_lock<mutex> lk(m_);
  15576. int id = id_;
  15577. // Wait with timeout to prevent hanging if client disconnects
  15578. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15579. [&] { return cid_ == id; })) {
  15580. return false; // Timeout occurred
  15581. }
  15582. sink->write(message_.data(), message_.size());
  15583. return true;
  15584. }
  15585. void send_event(const string &message) {
  15586. lock_guard<mutex> lk(m_);
  15587. cid_ = id_++;
  15588. message_ = message;
  15589. cv_.notify_all();
  15590. }
  15591. private:
  15592. mutex m_;
  15593. condition_variable cv_;
  15594. atomic_int id_{0};
  15595. atomic_int cid_{-1};
  15596. string message_;
  15597. };
  15598. TEST(ClientInThreadTest, Issue2068) {
  15599. EventDispatcher ed;
  15600. Server svr;
  15601. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15602. res.set_chunked_content_provider("text/event-stream",
  15603. [&](size_t /*offset*/, DataSink &sink) {
  15604. return ed.wait_event(&sink);
  15605. });
  15606. });
  15607. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15608. svr.wait_until_ready();
  15609. thread event_thread([&] {
  15610. int id = 0;
  15611. while (svr.is_running()) {
  15612. this_thread::sleep_for(chrono::milliseconds(500));
  15613. std::stringstream ss;
  15614. ss << "data: " << id << "\n\n";
  15615. ed.send_event(ss.str());
  15616. id++;
  15617. }
  15618. });
  15619. auto se = detail::scope_exit([&] {
  15620. svr.stop();
  15621. listen_thread.join();
  15622. event_thread.join();
  15623. ASSERT_FALSE(svr.is_running());
  15624. });
  15625. {
  15626. auto client = detail::make_unique<Client>(HOST, PORT);
  15627. client->set_read_timeout(std::chrono::minutes(10));
  15628. std::atomic<bool> stop{false};
  15629. std::thread t([&] {
  15630. client->Get("/event1",
  15631. [&](const char *, size_t) -> bool { return !stop; });
  15632. });
  15633. std::this_thread::sleep_for(std::chrono::seconds(2));
  15634. stop = true;
  15635. client->stop();
  15636. t.join();
  15637. // Reset client after thread has finished
  15638. client.reset();
  15639. }
  15640. }
  15641. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15642. auto handled = false;
  15643. Server svr;
  15644. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15645. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15646. auto se = detail::scope_exit([&] {
  15647. svr.stop();
  15648. t.join();
  15649. ASSERT_FALSE(svr.is_running());
  15650. ASSERT_FALSE(handled);
  15651. });
  15652. svr.wait_until_ready();
  15653. // Two Content-Length headers with different values — must be rejected
  15654. auto req = "POST /test HTTP/1.1\r\n"
  15655. "Content-Length: 5\r\n"
  15656. "Content-Length: 10\r\n"
  15657. "\r\n"
  15658. "hello";
  15659. std::string response;
  15660. ASSERT_TRUE(send_request(1, req, &response));
  15661. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15662. response.substr(0, response.find("\r\n")));
  15663. }
  15664. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15665. auto handled = false;
  15666. Server svr;
  15667. svr.Post("/test", [&](const Request &, Response &res) {
  15668. handled = true;
  15669. res.set_content("ok", "text/plain");
  15670. });
  15671. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15672. auto se = detail::scope_exit([&] {
  15673. svr.stop();
  15674. t.join();
  15675. ASSERT_FALSE(svr.is_running());
  15676. ASSERT_TRUE(handled);
  15677. });
  15678. svr.wait_until_ready();
  15679. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15680. auto req = "POST /test HTTP/1.1\r\n"
  15681. "Content-Length: 5\r\n"
  15682. "Content-Length: 5\r\n"
  15683. "\r\n"
  15684. "hello";
  15685. std::string response;
  15686. ASSERT_TRUE(send_request(1, req, &response));
  15687. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15688. }
  15689. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15690. Server svr;
  15691. svr.Get("/", [](const Request &req, Response &res) {
  15692. EXPECT_EQ(2U, req.trailers.size());
  15693. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15694. // Denied
  15695. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15696. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15697. // Accepted
  15698. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15699. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15700. EXPECT_TRUE(req.has_trailer("X-World"));
  15701. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15702. res.set_content("ok", "text/plain");
  15703. });
  15704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15705. auto se = detail::scope_exit([&] {
  15706. svr.stop();
  15707. t.join();
  15708. ASSERT_FALSE(svr.is_running());
  15709. });
  15710. svr.wait_until_ready();
  15711. const std::string req = "GET / HTTP/1.1\r\n"
  15712. "Transfer-Encoding: chunked\r\n"
  15713. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15714. "\r\n"
  15715. "0\r\n"
  15716. "Content-Length: 10\r\n"
  15717. "Host: internal.local\r\n"
  15718. "Content-Type: malicious/content\r\n"
  15719. "Cookie: any\r\n"
  15720. "Set-Cookie: any\r\n"
  15721. "X-Forwarded-For: attacker.com\r\n"
  15722. "X-Real-Ip: 1.1.1.1\r\n"
  15723. "X-Hello: hello\r\n"
  15724. "X-World: world\r\n"
  15725. "\r\n";
  15726. std::string res;
  15727. ASSERT_TRUE(send_request(1, req, &res));
  15728. }
  15729. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15730. // several field lines, and the combined value is what has to be parsed. A
  15731. // Trailer field split across lines therefore declares every name it lists;
  15732. // reading only the first line silently drops the trailers the later lines
  15733. // declare. The prohibited-trailer filter still applies to every line.
  15734. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  15735. Server svr;
  15736. size_t observed_trailer_count = 0;
  15737. std::string observed_hello;
  15738. std::string observed_world;
  15739. bool observed_content_length = true;
  15740. svr.Get("/", [&](const Request &req, Response &res) {
  15741. observed_trailer_count = req.trailers.size();
  15742. observed_hello = req.get_trailer_value("X-Hello");
  15743. observed_world = req.get_trailer_value("X-World");
  15744. observed_content_length = req.has_trailer("Content-Length");
  15745. res.set_content("ok", "text/plain");
  15746. });
  15747. auto port = svr.bind_to_any_port(HOST);
  15748. thread t = thread([&]() { svr.listen_after_bind(); });
  15749. auto se = detail::scope_exit([&] {
  15750. svr.stop();
  15751. t.join();
  15752. ASSERT_FALSE(svr.is_running());
  15753. });
  15754. svr.wait_until_ready();
  15755. const std::string req = "GET / HTTP/1.1\r\n"
  15756. "Transfer-Encoding: chunked\r\n"
  15757. "Trailer: X-Hello\r\n"
  15758. "Trailer: X-World, Content-Length\r\n"
  15759. "\r\n"
  15760. "0\r\n"
  15761. "X-Hello: hello\r\n"
  15762. "X-World: world\r\n"
  15763. "Content-Length: 10\r\n"
  15764. "\r\n";
  15765. std::string res;
  15766. ASSERT_TRUE(send_request(1, req, &res, port));
  15767. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  15768. // Accepted: both field lines contribute to the declared set
  15769. EXPECT_EQ(2U, observed_trailer_count);
  15770. EXPECT_EQ(observed_hello, "hello");
  15771. EXPECT_EQ(observed_world, "world");
  15772. // Denied: a prohibited name stays prohibited on a later field line
  15773. EXPECT_FALSE(observed_content_length);
  15774. }
  15775. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  15776. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  15777. // unbounded run of fields that are never declared, because the counter would
  15778. // only advance for declared fields.
  15779. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  15780. Server svr;
  15781. bool handler_called = false;
  15782. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  15783. handler_called = true;
  15784. res.set_content("ok", "text/plain");
  15785. });
  15786. auto port = svr.bind_to_any_port(HOST);
  15787. thread t = thread([&]() { svr.listen_after_bind(); });
  15788. auto se = detail::scope_exit([&] {
  15789. svr.stop();
  15790. t.join();
  15791. ASSERT_FALSE(svr.is_running());
  15792. });
  15793. svr.wait_until_ready();
  15794. // Declare nothing, then send far more undeclared trailer fields than the
  15795. // header-count limit. Parsing must stop and reject the request rather than
  15796. // read every line.
  15797. std::string req = "GET / HTTP/1.1\r\n"
  15798. "Transfer-Encoding: chunked\r\n"
  15799. "\r\n"
  15800. "0\r\n";
  15801. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  15802. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  15803. }
  15804. req += "\r\n";
  15805. std::string res;
  15806. ASSERT_TRUE(send_request(1, req, &res, port));
  15807. // The request is rejected before the handler runs.
  15808. EXPECT_FALSE(handler_called);
  15809. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  15810. }
  15811. // The set of declared trailer names is capped so a peer cannot grow it without
  15812. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  15813. // declared past the cap is not honored, even if the field is actually sent.
  15814. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  15815. Server svr;
  15816. // One name inside the cap and one past it, so the test tracks the cap rather
  15817. // than a fixed count.
  15818. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  15819. const std::string within_cap_name = "X-T-0";
  15820. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  15821. bool observed_within_cap = false;
  15822. bool observed_past_cap = false;
  15823. svr.Get("/", [&](const Request &req, Response &res) {
  15824. observed_within_cap = req.has_trailer(within_cap_name);
  15825. observed_past_cap = req.has_trailer(past_cap_name);
  15826. res.set_content("ok", "text/plain");
  15827. });
  15828. auto port = svr.bind_to_any_port(HOST);
  15829. thread t = thread([&]() { svr.listen_after_bind(); });
  15830. auto se = detail::scope_exit([&] {
  15831. svr.stop();
  15832. t.join();
  15833. ASSERT_FALSE(svr.is_running());
  15834. });
  15835. svr.wait_until_ready();
  15836. // Declare more trailer names than the cap in a single Trailer field, then
  15837. // actually send the first (within the cap) and the last (past it).
  15838. std::string trailer_decl = "Trailer: ";
  15839. for (int i = 0; i < declared_count; i++) {
  15840. if (i != 0) { trailer_decl += ", "; }
  15841. trailer_decl += "X-T-" + std::to_string(i);
  15842. }
  15843. trailer_decl += "\r\n";
  15844. const std::string req = "GET / HTTP/1.1\r\n"
  15845. "Transfer-Encoding: chunked\r\n" +
  15846. trailer_decl +
  15847. "\r\n"
  15848. "0\r\n" +
  15849. within_cap_name + ": a\r\n" + past_cap_name +
  15850. ": b\r\n"
  15851. "\r\n";
  15852. std::string res;
  15853. ASSERT_TRUE(send_request(1, req, &res, port));
  15854. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  15855. // A name within the cap is honored; one declared past the cap is dropped.
  15856. EXPECT_TRUE(observed_within_cap);
  15857. EXPECT_FALSE(observed_past_cap);
  15858. }
  15859. // A direct client that is not listed in trusted_proxies must not be able to
  15860. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  15861. // the peer address on the actual TCP connection determines whether the
  15862. // header is honored.
  15863. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  15864. Server svr;
  15865. // Deliberately does NOT include the loopback address the test client
  15866. // actually connects from, so the direct connection is not a trusted proxy.
  15867. svr.set_trusted_proxies({"203.0.113.66"});
  15868. std::string observed_remote_addr;
  15869. svr.Get("/ip", [&](const Request &req, Response &res) {
  15870. observed_remote_addr = req.remote_addr;
  15871. res.set_content("ok", "text/plain");
  15872. });
  15873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15874. auto se = detail::scope_exit([&] {
  15875. svr.stop();
  15876. t.join();
  15877. ASSERT_FALSE(svr.is_running());
  15878. });
  15879. svr.wait_until_ready();
  15880. Client cli(HOST, PORT);
  15881. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  15882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15883. EXPECT_EQ(StatusCode::OK_200, res->status);
  15884. // The connecting peer is not a trusted proxy, so the spoofed header must be
  15885. // ignored entirely and the real connection-level address retained.
  15886. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15887. observed_remote_addr == "127.0.0.1");
  15888. }
  15889. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  15890. Server svr;
  15891. std::string observed_remote_addr;
  15892. std::string observed_xff;
  15893. svr.Get("/ip", [&](const Request &req, Response &res) {
  15894. observed_remote_addr = req.remote_addr;
  15895. observed_xff = req.get_header_value("X-Forwarded-For");
  15896. res.set_content("ok", "text/plain");
  15897. });
  15898. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15899. auto se = detail::scope_exit([&] {
  15900. svr.stop();
  15901. t.join();
  15902. ASSERT_FALSE(svr.is_running());
  15903. });
  15904. svr.wait_until_ready();
  15905. Client cli(HOST, PORT);
  15906. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15908. EXPECT_EQ(StatusCode::OK_200, res->status);
  15909. EXPECT_EQ(observed_xff, "203.0.113.66");
  15910. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15911. observed_remote_addr == "127.0.0.1");
  15912. }
  15913. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15914. Server svr;
  15915. svr.set_trusted_proxies({"203.0.113.66"});
  15916. std::string observed_remote_addr;
  15917. std::string observed_xff;
  15918. svr.Get("/ip", [&](const Request &req, Response &res) {
  15919. observed_remote_addr = req.remote_addr;
  15920. observed_xff = req.get_header_value("X-Forwarded-For");
  15921. res.set_content("ok", "text/plain");
  15922. });
  15923. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15924. auto se = detail::scope_exit([&] {
  15925. svr.stop();
  15926. t.join();
  15927. ASSERT_FALSE(svr.is_running());
  15928. });
  15929. svr.wait_until_ready();
  15930. Client cli(HOST, PORT);
  15931. auto res = cli.Get("/ip");
  15932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15933. EXPECT_EQ(StatusCode::OK_200, res->status);
  15934. EXPECT_EQ(observed_xff, "");
  15935. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15936. observed_remote_addr == "127.0.0.1");
  15937. }
  15938. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15939. Server svr;
  15940. // Include the loopback address the test client actually connects from, so
  15941. // the direct connection itself is recognized as the trusted proxy hop.
  15942. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15943. std::string observed_remote_addr;
  15944. std::string observed_xff;
  15945. svr.Get("/ip", [&](const Request &req, Response &res) {
  15946. observed_remote_addr = req.remote_addr;
  15947. observed_xff = req.get_header_value("X-Forwarded-For");
  15948. res.set_content("ok", "text/plain");
  15949. });
  15950. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15951. auto se = detail::scope_exit([&] {
  15952. svr.stop();
  15953. t.join();
  15954. ASSERT_FALSE(svr.is_running());
  15955. });
  15956. svr.wait_until_ready();
  15957. Client cli(HOST, PORT);
  15958. auto res = cli.Get(
  15959. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15961. EXPECT_EQ(StatusCode::OK_200, res->status);
  15962. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15963. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15964. }
  15965. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  15966. Server svr;
  15967. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  15968. std::string observed_remote_addr;
  15969. std::string observed_xff;
  15970. svr.Get("/ip", [&](const Request &req, Response &res) {
  15971. observed_remote_addr = req.remote_addr;
  15972. observed_xff = req.get_header_value("X-Forwarded-For");
  15973. res.set_content("ok", "text/plain");
  15974. });
  15975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15976. auto se = detail::scope_exit([&] {
  15977. svr.stop();
  15978. t.join();
  15979. ASSERT_FALSE(svr.is_running());
  15980. });
  15981. svr.wait_until_ready();
  15982. Client cli(HOST, PORT);
  15983. auto res = cli.Get(
  15984. "/ip",
  15985. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15987. EXPECT_EQ(StatusCode::OK_200, res->status);
  15988. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15989. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15990. }
  15991. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  15992. Server svr;
  15993. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15994. std::string observed_remote_addr;
  15995. std::string observed_xff;
  15996. svr.Get("/ip", [&](const Request &req, Response &res) {
  15997. observed_remote_addr = req.remote_addr;
  15998. observed_xff = req.get_header_value("X-Forwarded-For");
  15999. res.set_content("ok", "text/plain");
  16000. });
  16001. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16002. auto se = detail::scope_exit([&] {
  16003. svr.stop();
  16004. t.join();
  16005. ASSERT_FALSE(svr.is_running());
  16006. });
  16007. svr.wait_until_ready();
  16008. Client cli(HOST, PORT);
  16009. auto res = cli.Get(
  16010. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16012. EXPECT_EQ(StatusCode::OK_200, res->status);
  16013. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16014. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16015. // and must not be selected.
  16016. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16017. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16018. }
  16019. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16020. Server svr;
  16021. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16022. std::string observed_remote_addr;
  16023. svr.Get("/ip", [&](const Request &req, Response &res) {
  16024. observed_remote_addr = req.remote_addr;
  16025. res.set_content("ok", "text/plain");
  16026. });
  16027. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16028. auto se = detail::scope_exit([&] {
  16029. svr.stop();
  16030. t.join();
  16031. ASSERT_FALSE(svr.is_running());
  16032. });
  16033. svr.wait_until_ready();
  16034. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16035. // a forged address and the trusted proxy's own address; the forged value must
  16036. // not win over the address the trusted proxy actually recorded.
  16037. Client cli(HOST, PORT);
  16038. auto res = cli.Get(
  16039. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16041. EXPECT_EQ(StatusCode::OK_200, res->status);
  16042. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16043. }
  16044. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16045. Server svr;
  16046. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16047. std::string observed_remote_addr;
  16048. std::string observed_xff;
  16049. svr.Get("/ip", [&](const Request &req, Response &res) {
  16050. observed_remote_addr = req.remote_addr;
  16051. observed_xff = req.get_header_value("X-Forwarded-For");
  16052. res.set_content("ok", "text/plain");
  16053. });
  16054. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16055. auto se = detail::scope_exit([&] {
  16056. svr.stop();
  16057. t.join();
  16058. ASSERT_FALSE(svr.is_running());
  16059. });
  16060. svr.wait_until_ready();
  16061. Client cli(HOST, PORT);
  16062. auto res = cli.Get(
  16063. "/ip",
  16064. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16066. EXPECT_EQ(StatusCode::OK_200, res->status);
  16067. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16068. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16069. }
  16070. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16071. Server svr;
  16072. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16073. std::string observed_remote_addr;
  16074. std::string observed_xff;
  16075. svr.Get("/ip", [&](const Request &req, Response &res) {
  16076. observed_remote_addr = req.remote_addr;
  16077. observed_xff = req.get_header_value("X-Forwarded-For");
  16078. res.set_content("ok", "text/plain");
  16079. });
  16080. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16081. auto se = detail::scope_exit([&] {
  16082. svr.stop();
  16083. t.join();
  16084. ASSERT_FALSE(svr.is_running());
  16085. });
  16086. svr.wait_until_ready();
  16087. std::string raw_req =
  16088. "GET /ip HTTP/1.1\r\n"
  16089. "Host: localhost\r\n"
  16090. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16091. "Connection: close\r\n"
  16092. "\r\n";
  16093. std::string out;
  16094. ASSERT_TRUE(send_request(5, raw_req, &out));
  16095. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16096. // Header parser trims surrounding whitespace of the header value
  16097. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16098. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16099. }
  16100. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16101. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16102. // their own X-Forwarded-For as a separate field line rather than extending the
  16103. // one the client sent, so every occurrence has to be taken into account.
  16104. // Reading only the first one hands back the address the client chose.
  16105. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16106. Server svr;
  16107. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16108. std::string observed_remote_addr;
  16109. size_t observed_xff_count = 0;
  16110. svr.Get("/ip", [&](const Request &req, Response &res) {
  16111. observed_remote_addr = req.remote_addr;
  16112. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16113. res.set_content("ok", "text/plain");
  16114. });
  16115. auto port = svr.bind_to_any_port(HOST);
  16116. thread t = thread([&]() { svr.listen_after_bind(); });
  16117. auto se = detail::scope_exit([&] {
  16118. svr.stop();
  16119. t.join();
  16120. ASSERT_FALSE(svr.is_running());
  16121. });
  16122. svr.wait_until_ready();
  16123. // The client supplies the first field line; the trusted proxy appends the
  16124. // address it observed as a second one.
  16125. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16126. "Host: localhost\r\n"
  16127. "X-Forwarded-For: 1.2.3.4\r\n"
  16128. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16129. "Connection: close\r\n"
  16130. "\r\n";
  16131. std::string out;
  16132. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16133. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16134. EXPECT_EQ(observed_xff_count, 2U);
  16135. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16136. // The same chain spread over one field line per hop derives the same client
  16137. // address, i.e. the split and the comma-joined representations agree.
  16138. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16139. "Host: localhost\r\n"
  16140. "X-Forwarded-For: 1.2.3.4\r\n"
  16141. "X-Forwarded-For: 198.51.100.23\r\n"
  16142. "X-Forwarded-For: 192.0.2.45\r\n"
  16143. "Connection: close\r\n"
  16144. "\r\n";
  16145. out.clear();
  16146. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16147. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16148. EXPECT_EQ(observed_xff_count, 3U);
  16149. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16150. }
  16151. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16152. // crash the server (it used to call front() on an empty vector inside
  16153. // get_client_ip). The connection-level remote address must be retained instead.
  16154. static void run_malformed_xff_test(const std::string &xff_value) {
  16155. Server svr;
  16156. svr.set_trusted_proxies({"192.0.2.45"});
  16157. std::string observed_remote_addr;
  16158. svr.Get("/ip", [&](const Request &req, Response &res) {
  16159. observed_remote_addr = req.remote_addr;
  16160. res.set_content("ok", "text/plain");
  16161. });
  16162. int port = 0;
  16163. thread t = thread([&]() {
  16164. port = svr.bind_to_any_port(HOST);
  16165. svr.listen_after_bind();
  16166. });
  16167. auto se = detail::scope_exit([&] {
  16168. svr.stop();
  16169. t.join();
  16170. ASSERT_FALSE(svr.is_running());
  16171. });
  16172. svr.wait_until_ready();
  16173. Client cli(HOST, port);
  16174. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16176. EXPECT_EQ(StatusCode::OK_200, res->status);
  16177. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16178. observed_remote_addr == "127.0.0.1");
  16179. }
  16180. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16181. run_malformed_xff_test("");
  16182. }
  16183. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16184. run_malformed_xff_test(",");
  16185. }
  16186. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16187. run_malformed_xff_test(", , ,");
  16188. }
  16189. // The same rule applies to Accept: a request whose acceptable types are spread
  16190. // over several field lines must be negotiated against all of them.
  16191. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16192. // case-insensitive connection options. Comparing the whole field value against
  16193. // one option misses a client that sends several of them, and misses every
  16194. // casing but the one written in the comparison.
  16195. //
  16196. // Sends req, reads the response, then reuses the same socket for a second
  16197. // request to find out whether the server kept the connection.
  16198. static void probe_connection_reuse(int port, const std::string &req,
  16199. bool *announced_close, bool *reusable) {
  16200. auto error = Error::Success;
  16201. auto sock = detail::create_client_socket(
  16202. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16203. /*connection_timeout_sec=*/5, 0,
  16204. /*read_timeout_sec=*/1, 0,
  16205. /*write_timeout_sec=*/5, 0, std::string(), error);
  16206. ASSERT_NE(sock, INVALID_SOCKET);
  16207. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16208. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16209. "Host: localhost\r\n"
  16210. "Connection: close\r\n"
  16211. "\r\n";
  16212. std::string first_response;
  16213. std::string second_response;
  16214. detail::process_client_socket(
  16215. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16216. [&](Stream &strm) {
  16217. if (strm.write(req.data(), req.size()) !=
  16218. static_cast<ssize_t>(req.size())) {
  16219. return false;
  16220. }
  16221. char buf[512];
  16222. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16223. // Headers plus the two-byte body of the handler below
  16224. while (reader.getline()) {
  16225. first_response += reader.ptr();
  16226. if (first_response.find("ok") != std::string::npos) { break; }
  16227. }
  16228. if (strm.write(second.data(), second.size()) !=
  16229. static_cast<ssize_t>(second.size())) {
  16230. return true;
  16231. }
  16232. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16233. while (reader2.getline()) {
  16234. second_response += reader2.ptr();
  16235. if (second_response.find("ok") != std::string::npos) { break; }
  16236. }
  16237. return true;
  16238. });
  16239. *announced_close =
  16240. first_response.find("Connection: close") != std::string::npos;
  16241. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16242. }
  16243. class ConnectionTokenTest : public ::testing::Test {
  16244. protected:
  16245. void SetUp() override {
  16246. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16247. res.set_content("ok", "text/plain");
  16248. });
  16249. port_ = svr_.bind_to_any_port(HOST);
  16250. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16251. svr_.wait_until_ready();
  16252. }
  16253. void TearDown() override {
  16254. svr_.stop();
  16255. if (thread_.joinable()) { thread_.join(); }
  16256. }
  16257. Server svr_;
  16258. int port_ = 0;
  16259. thread thread_;
  16260. };
  16261. // "close" alongside another option still closes the connection, and the
  16262. // response says so rather than leaving the peer to discover it.
  16263. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16264. bool announced_close = false;
  16265. bool reusable = true;
  16266. probe_connection_reuse(port_,
  16267. "GET /keepalive HTTP/1.1\r\n"
  16268. "Host: localhost\r\n"
  16269. "Connection: keep-alive, close\r\n"
  16270. "\r\n",
  16271. &announced_close, &reusable);
  16272. EXPECT_TRUE(announced_close);
  16273. EXPECT_FALSE(reusable);
  16274. }
  16275. // "close" split over two field lines is the same list, so it is honored too.
  16276. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16277. bool announced_close = false;
  16278. bool reusable = true;
  16279. probe_connection_reuse(port_,
  16280. "GET /keepalive HTTP/1.1\r\n"
  16281. "Host: localhost\r\n"
  16282. "Connection: keep-alive\r\n"
  16283. "Connection: close\r\n"
  16284. "\r\n",
  16285. &announced_close, &reusable);
  16286. EXPECT_TRUE(announced_close);
  16287. EXPECT_FALSE(reusable);
  16288. }
  16289. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16290. // keep-alive in the spelling everyone actually sends keeps its connection.
  16291. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16292. bool announced_close = false;
  16293. bool reusable = false;
  16294. probe_connection_reuse(port_,
  16295. "GET /keepalive HTTP/1.0\r\n"
  16296. "Host: localhost\r\n"
  16297. "Connection: keep-alive\r\n"
  16298. "\r\n",
  16299. &announced_close, &reusable);
  16300. EXPECT_FALSE(announced_close);
  16301. EXPECT_TRUE(reusable);
  16302. }
  16303. // A token the value merely contains is not the token itself.
  16304. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16305. bool announced_close = false;
  16306. bool reusable = false;
  16307. probe_connection_reuse(port_,
  16308. "GET /keepalive HTTP/1.1\r\n"
  16309. "Host: localhost\r\n"
  16310. "Connection: notclose\r\n"
  16311. "\r\n",
  16312. &announced_close, &reusable);
  16313. EXPECT_FALSE(announced_close);
  16314. EXPECT_TRUE(reusable);
  16315. }
  16316. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16317. Server svr;
  16318. std::vector<std::string> observed_types;
  16319. svr.Get("/", [&](const Request &req, Response &res) {
  16320. observed_types = req.accept_content_types;
  16321. res.set_content("ok", "text/plain");
  16322. });
  16323. auto port = svr.bind_to_any_port(HOST);
  16324. thread t = thread([&]() { svr.listen_after_bind(); });
  16325. auto se = detail::scope_exit([&] {
  16326. svr.stop();
  16327. t.join();
  16328. ASSERT_FALSE(svr.is_running());
  16329. });
  16330. svr.wait_until_ready();
  16331. Client cli(HOST, port);
  16332. Headers headers;
  16333. headers.emplace("Accept", "text/plain;q=0.5");
  16334. headers.emplace("Accept", "application/json");
  16335. auto res = cli.Get("/", headers);
  16336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16337. EXPECT_EQ(StatusCode::OK_200, res->status);
  16338. // Sorted by q-value, so the second field line's type comes first
  16339. ASSERT_EQ(2U, observed_types.size());
  16340. EXPECT_EQ("application/json", observed_types[0]);
  16341. EXPECT_EQ("text/plain", observed_types[1]);
  16342. }
  16343. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16344. // empty field line must not contribute a bare comma to the combined value.
  16345. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16346. Server svr;
  16347. std::vector<std::string> observed_types;
  16348. svr.Get("/", [&](const Request &req, Response &res) {
  16349. observed_types = req.accept_content_types;
  16350. res.set_content("ok", "text/plain");
  16351. });
  16352. auto port = svr.bind_to_any_port(HOST);
  16353. thread t = thread([&]() { svr.listen_after_bind(); });
  16354. auto se = detail::scope_exit([&] {
  16355. svr.stop();
  16356. t.join();
  16357. ASSERT_FALSE(svr.is_running());
  16358. });
  16359. svr.wait_until_ready();
  16360. // Empty first field line, then a real one
  16361. std::string raw_req = "GET / HTTP/1.1\r\n"
  16362. "Host: localhost\r\n"
  16363. "Accept:\r\n"
  16364. "Accept: application/json\r\n"
  16365. "Connection: close\r\n"
  16366. "\r\n";
  16367. std::string out;
  16368. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16369. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16370. ASSERT_EQ(1U, observed_types.size());
  16371. EXPECT_EQ("application/json", observed_types[0]);
  16372. }
  16373. // The skip in get_combined_header_value() is what keeps an empty field line
  16374. // from contributing a bare comma. Only a trailing empty field line exercises
  16375. // it: a leading one is already covered by the "combined is still empty" check,
  16376. // and parse_accept_header() now ignores the empty element either way, so the
  16377. // request-level test above can no longer tell the two apart.
  16378. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16379. Headers headers;
  16380. headers.emplace("Accept", "text/html");
  16381. headers.emplace("Accept", "");
  16382. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16383. headers.clear();
  16384. headers.emplace("Accept", "");
  16385. headers.emplace("Accept", "application/json");
  16386. EXPECT_EQ("application/json",
  16387. detail::get_combined_header_value(headers, "Accept"));
  16388. }
  16389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16390. // An encoding offered on a later Accept-Encoding field line is still offered.
  16391. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16392. Server svr;
  16393. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16394. res.set_content(std::string(1024, 'x'), "text/plain");
  16395. });
  16396. auto port = svr.bind_to_any_port(HOST);
  16397. thread t = thread([&]() { svr.listen_after_bind(); });
  16398. auto se = detail::scope_exit([&] {
  16399. svr.stop();
  16400. t.join();
  16401. ASSERT_FALSE(svr.is_running());
  16402. });
  16403. svr.wait_until_ready();
  16404. Client cli(HOST, port);
  16405. cli.set_decompress(false);
  16406. Headers headers;
  16407. headers.emplace("Accept-Encoding", "identity");
  16408. headers.emplace("Accept-Encoding", "gzip");
  16409. auto res = cli.Get("/", headers);
  16410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16411. EXPECT_EQ(StatusCode::OK_200, res->status);
  16412. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16413. }
  16414. #endif
  16415. #ifndef _WIN32
  16416. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16417. Server svr;
  16418. svr.Post("/post", [&](const Request &req, Response &res) {
  16419. res.set_content(req.body, "text/plain");
  16420. });
  16421. svr.Put("/put", [&](const Request &req, Response &res) {
  16422. res.set_content(req.body, "text/plain");
  16423. });
  16424. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16425. res.set_content(req.body, "text/plain");
  16426. });
  16427. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16428. res.set_content(req.body, "text/plain");
  16429. });
  16430. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16431. auto se = detail::scope_exit([&] {
  16432. svr.stop();
  16433. t.join();
  16434. ASSERT_FALSE(svr.is_running());
  16435. });
  16436. svr.wait_until_ready();
  16437. std::string resp;
  16438. // POST without Content-Length
  16439. ASSERT_TRUE(send_request(5,
  16440. "POST /post HTTP/1.1\r\n"
  16441. "Host: localhost\r\n"
  16442. "Connection: close\r\n"
  16443. "\r\n",
  16444. &resp));
  16445. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16446. // PUT without Content-Length
  16447. resp.clear();
  16448. ASSERT_TRUE(send_request(5,
  16449. "PUT /put HTTP/1.1\r\n"
  16450. "Host: localhost\r\n"
  16451. "Connection: close\r\n"
  16452. "\r\n",
  16453. &resp));
  16454. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16455. // PATCH without Content-Length
  16456. resp.clear();
  16457. ASSERT_TRUE(send_request(5,
  16458. "PATCH /patch HTTP/1.1\r\n"
  16459. "Host: localhost\r\n"
  16460. "Connection: close\r\n"
  16461. "\r\n",
  16462. &resp));
  16463. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16464. // DELETE without Content-Length
  16465. resp.clear();
  16466. ASSERT_TRUE(send_request(5,
  16467. "DELETE /delete HTTP/1.1\r\n"
  16468. "Host: localhost\r\n"
  16469. "Connection: close\r\n"
  16470. "\r\n",
  16471. &resp));
  16472. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16473. }
  16474. #endif
  16475. //==============================================================================
  16476. // open_stream() Tests
  16477. //==============================================================================
  16478. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16479. std::string result;
  16480. char buf[8192];
  16481. ssize_t n;
  16482. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16483. result.append(buf, static_cast<size_t>(n));
  16484. }
  16485. return result;
  16486. }
  16487. // Mock stream for unit tests
  16488. class MockStream : public Stream {
  16489. public:
  16490. std::string data;
  16491. size_t pos = 0;
  16492. ssize_t error_after = -1; // -1 = no error
  16493. explicit MockStream(const std::string &d, ssize_t err = -1)
  16494. : data(d), error_after(err) {}
  16495. bool is_readable() const override { return true; }
  16496. bool wait_readable() const override { return true; }
  16497. bool wait_writable() const override { return true; }
  16498. ssize_t read(char *ptr, size_t size) override {
  16499. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16500. if (pos >= data.size()) return 0;
  16501. size_t limit =
  16502. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16503. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16504. std::memcpy(ptr, data.data() + pos, to_read);
  16505. pos += to_read;
  16506. return static_cast<ssize_t>(to_read);
  16507. }
  16508. ssize_t write(const char *, size_t) override { return -1; }
  16509. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16510. ip = "127.0.0.1";
  16511. port = 0;
  16512. }
  16513. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16514. ip = "127.0.0.1";
  16515. port = 0;
  16516. }
  16517. socket_t socket() const override { return INVALID_SOCKET; }
  16518. time_t duration() const override { return 0; }
  16519. };
  16520. TEST(StreamHandleTest, Basic) {
  16521. ClientImpl::StreamHandle handle;
  16522. EXPECT_FALSE(handle.is_valid());
  16523. handle.response = detail::make_unique<Response>();
  16524. handle.error = Error::Connection;
  16525. EXPECT_FALSE(handle.is_valid());
  16526. handle.error = Error::Success;
  16527. EXPECT_TRUE(handle.is_valid());
  16528. }
  16529. TEST(BodyReaderTest, Basic) {
  16530. MockStream stream("Hello, World!");
  16531. detail::BodyReader reader;
  16532. reader.stream = &stream;
  16533. reader.content_length = 13;
  16534. char buf[32];
  16535. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16536. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16537. EXPECT_TRUE(reader.eof);
  16538. }
  16539. TEST(BodyReaderTest, NoStream) {
  16540. detail::BodyReader reader;
  16541. char buf[32];
  16542. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16543. EXPECT_EQ(Error::Connection, reader.last_error);
  16544. }
  16545. TEST(BodyReaderTest, Error) {
  16546. MockStream stream("Hello, World!", 5);
  16547. detail::BodyReader reader;
  16548. reader.stream = &stream;
  16549. reader.content_length = 13;
  16550. char buf[32];
  16551. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16552. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16553. EXPECT_EQ(Error::Read, reader.last_error);
  16554. }
  16555. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16556. // Mock-based StreamHandle tests relying on private internals are removed.
  16557. class OpenStreamTest : public ::testing::Test {
  16558. protected:
  16559. void SetUp() override {
  16560. svr_.Get("/hello", [](const Request &, Response &res) {
  16561. res.set_content("Hello World!", "text/plain");
  16562. });
  16563. svr_.Get("/large", [](const Request &, Response &res) {
  16564. res.set_content(std::string(10000, 'X'), "text/plain");
  16565. });
  16566. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16567. res.set_content("Hello World!", "image/jpeg");
  16568. res.set_header("Content-Encoding", "UTF-8");
  16569. });
  16570. svr_.Get("/chunked", [](const Request &, Response &res) {
  16571. res.set_chunked_content_provider("text/plain",
  16572. [](size_t offset, DataSink &sink) {
  16573. if (offset < 15) {
  16574. sink.write("chunk", 5);
  16575. return true;
  16576. }
  16577. sink.done();
  16578. return true;
  16579. });
  16580. });
  16581. svr_.Get("/compressible", [](const Request &, Response &res) {
  16582. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16583. DataSink &sink) {
  16584. if (offset < 100 * 1024) {
  16585. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16586. sink.write(chunk.data(), chunk.size());
  16587. return true;
  16588. }
  16589. sink.done();
  16590. return true;
  16591. });
  16592. });
  16593. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16594. [](const Request & /*req*/, Response &res) {
  16595. auto i = new int(0);
  16596. res.set_header("Trailer", "Content-Length, X-Allowed");
  16597. res.set_chunked_content_provider(
  16598. "text/plain",
  16599. [i](size_t /*offset*/, DataSink &sink) {
  16600. switch (*i) {
  16601. case 0: sink.os << "123"; break;
  16602. case 1: sink.os << "456"; break;
  16603. case 2: sink.os << "789"; break;
  16604. case 3: {
  16605. sink.done_with_trailer(
  16606. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16607. } break;
  16608. }
  16609. (*i)++;
  16610. return true;
  16611. },
  16612. [i](bool success) {
  16613. EXPECT_TRUE(success);
  16614. delete i;
  16615. });
  16616. });
  16617. // Echo headers endpoint for header-related tests
  16618. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16619. std::string body;
  16620. for (const auto &h : req.headers) {
  16621. body.append(h.first);
  16622. body.push_back(':');
  16623. body.append(h.second);
  16624. body.push_back('\n');
  16625. }
  16626. res.set_content(body, "text/plain");
  16627. });
  16628. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16629. std::string body;
  16630. for (const auto &h : req.headers) {
  16631. body.append(h.first);
  16632. body.push_back(':');
  16633. body.append(h.second);
  16634. body.push_back('\n');
  16635. }
  16636. res.set_content(body, "text/plain");
  16637. });
  16638. port_ = svr_.bind_to_any_port("127.0.0.1");
  16639. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16640. svr_.wait_until_ready();
  16641. }
  16642. void TearDown() override {
  16643. svr_.stop();
  16644. if (thread_.joinable()) thread_.join();
  16645. }
  16646. Server svr_;
  16647. std::thread thread_;
  16648. int port_ = 0;
  16649. };
  16650. TEST_F(OpenStreamTest, Basic) {
  16651. Client cli("127.0.0.1", port_);
  16652. auto handle = cli.open_stream("GET", "/hello");
  16653. EXPECT_TRUE(handle.is_valid());
  16654. EXPECT_EQ("Hello World!", read_all(handle));
  16655. }
  16656. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16657. Client cli("127.0.0.1", port_);
  16658. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16659. ASSERT_TRUE(handle.is_valid());
  16660. EXPECT_EQ("Hello World!", read_all(handle));
  16661. }
  16662. TEST_F(OpenStreamTest, SmallBuffer) {
  16663. Client cli("127.0.0.1", port_);
  16664. auto handle = cli.open_stream("GET", "/hello");
  16665. std::string result;
  16666. char buf[4];
  16667. ssize_t n;
  16668. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16669. result.append(buf, static_cast<size_t>(n));
  16670. EXPECT_EQ("Hello World!", result);
  16671. }
  16672. TEST_F(OpenStreamTest, DefaultHeaders) {
  16673. Client cli("127.0.0.1", port_);
  16674. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16675. {
  16676. auto handle = cli.open_stream("GET", "/echo-headers");
  16677. ASSERT_TRUE(handle.is_valid());
  16678. auto body = read_all(handle);
  16679. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16680. std::string::npos);
  16681. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16682. std::string::npos);
  16683. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16684. }
  16685. // open_stream POST with body and no explicit content_type should NOT add
  16686. // text/plain Content-Type (behavior differs from non-streaming path), but
  16687. // should include Content-Length
  16688. {
  16689. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16690. ASSERT_TRUE(handle.is_valid());
  16691. auto body = read_all(handle);
  16692. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16693. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16694. }
  16695. // open_stream POST with explicit Content-Type should preserve it
  16696. {
  16697. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16698. {{"Content-Type", "application/custom"}},
  16699. "{}", "application/custom");
  16700. ASSERT_TRUE(handle.is_valid());
  16701. auto body = read_all(handle);
  16702. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16703. }
  16704. // User-specified User-Agent must not be overwritten for stream API
  16705. {
  16706. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16707. {{"User-Agent", "MyAgent/1.2"}});
  16708. ASSERT_TRUE(handle.is_valid());
  16709. auto body = read_all(handle);
  16710. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16711. }
  16712. }
  16713. TEST_F(OpenStreamTest, Large) {
  16714. Client cli("127.0.0.1", port_);
  16715. auto handle = cli.open_stream("GET", "/large");
  16716. EXPECT_EQ(10000u, read_all(handle).size());
  16717. }
  16718. TEST_F(OpenStreamTest, ConnectionError) {
  16719. Client cli("127.0.0.1", 9999);
  16720. auto handle = cli.open_stream("GET", "/hello");
  16721. EXPECT_FALSE(handle.is_valid());
  16722. }
  16723. TEST_F(OpenStreamTest, Chunked) {
  16724. Client cli("127.0.0.1", port_);
  16725. auto handle = cli.open_stream("GET", "/chunked");
  16726. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16727. "Transfer-Encoding") == "chunked");
  16728. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  16729. }
  16730. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  16731. Client cli("127.0.0.1", port_);
  16732. auto handle =
  16733. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  16734. ASSERT_TRUE(handle.is_valid());
  16735. // Consume body to allow trailers to be received/parsed
  16736. auto body = read_all(handle);
  16737. // Explicitly parse trailers (ensure trailers are available for assertion)
  16738. handle.parse_trailers_if_needed();
  16739. EXPECT_EQ(std::string("123456789"), body);
  16740. // The response should include a Trailer header declaring both names
  16741. ASSERT_TRUE(handle.response);
  16742. EXPECT_TRUE(handle.response->has_header("Trailer"));
  16743. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  16744. handle.response->get_header_value("Trailer"));
  16745. // Prohibited trailer must not be present
  16746. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  16747. // Allowed trailer should be present
  16748. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  16749. EXPECT_EQ(std::string("yes"),
  16750. handle.response->get_trailer_value("X-Allowed"));
  16751. // Verify trailers are NOT present as regular headers
  16752. EXPECT_EQ(std::string(""),
  16753. handle.response->get_header_value("Content-Length"));
  16754. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  16755. }
  16756. static std::thread serve_single_response(std::promise<int> &port_promise,
  16757. const std::string &response) {
  16758. return std::thread([&port_promise, response] {
  16759. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16760. default_socket_options(srv);
  16761. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  16763. sockaddr_in addr{};
  16764. addr.sin_family = AF_INET;
  16765. addr.sin_port = htons(0); // Let OS assign a free port
  16766. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16767. int opt = 1;
  16768. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  16769. #ifdef _WIN32
  16770. reinterpret_cast<const char *>(&opt),
  16771. #else
  16772. &opt,
  16773. #endif
  16774. sizeof(opt));
  16775. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  16776. ::listen(srv, 1) != 0) {
  16777. port_promise.set_value(-1);
  16778. detail::close_socket(srv);
  16779. return;
  16780. }
  16781. socklen_t addr_len = sizeof(addr);
  16782. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  16783. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  16784. sockaddr_in cli_addr{};
  16785. socklen_t cli_len = sizeof(cli_addr);
  16786. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16787. if (cli != INVALID_SOCKET) {
  16788. // Read the complete HTTP request (until the blank line that terminates
  16789. // headers) before sending the response. If the server closes the socket
  16790. // while the client's request data is still unread in the kernel receive
  16791. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  16792. // connection on both sides: it discards the client's receive buffer
  16793. // (which already holds our response) and causes any in-progress write on
  16794. // the client to fail with ECONNRESET. Reading all request data first
  16795. // ensures close() emits a graceful FIN.
  16796. {
  16797. char rbuf[256];
  16798. std::string req;
  16799. while (req.find("\r\n\r\n") == std::string::npos) {
  16800. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  16801. if (n <= 0) { break; }
  16802. req.append(rbuf, static_cast<size_t>(n));
  16803. }
  16804. }
  16805. ::send(cli,
  16806. #ifdef _WIN32
  16807. static_cast<const char *>(response.c_str()),
  16808. static_cast<int>(response.size()),
  16809. #else
  16810. response.c_str(), response.size(),
  16811. #endif
  16812. 0);
  16813. detail::close_socket(cli);
  16814. }
  16815. detail::close_socket(srv);
  16816. });
  16817. }
  16818. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  16819. #ifndef _WIN32
  16820. signal(SIGPIPE, SIG_IGN);
  16821. #endif
  16822. std::promise<int> port_promise;
  16823. auto port_future = port_promise.get_future();
  16824. auto server_thread =
  16825. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  16826. "Content-Type: text/plain\r\n"
  16827. "Content-Length: not-a-number\r\n"
  16828. "Connection: close\r\n"
  16829. "\r\n"
  16830. "hello");
  16831. auto port = port_future.get();
  16832. ASSERT_GT(port, 0);
  16833. Client cli("127.0.0.1", port);
  16834. auto handle = cli.open_stream("GET", "/");
  16835. EXPECT_FALSE(handle.is_valid());
  16836. server_thread.join();
  16837. }
  16838. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  16839. #ifndef _WIN32
  16840. signal(SIGPIPE, SIG_IGN);
  16841. #endif
  16842. std::promise<int> port_promise;
  16843. auto port_future = port_promise.get_future();
  16844. auto server_thread = serve_single_response(
  16845. port_promise, "HTTP/1.1 200 OK\r\n"
  16846. "Content-Type: text/plain\r\n"
  16847. "Content-Length: 99999999999999999999999999\r\n"
  16848. "Connection: close\r\n"
  16849. "\r\n"
  16850. "hello");
  16851. auto port = port_future.get();
  16852. ASSERT_GT(port, 0);
  16853. // Historically std::stoull would throw std::out_of_range here and crash
  16854. // the process, then parsing silently clamped to a bogus framing length and
  16855. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  16856. // so the stream fails to open, matching the not-a-number case above. The
  16857. // process still must NOT terminate.
  16858. Client cli("127.0.0.1", port);
  16859. auto handle = cli.open_stream("GET", "/");
  16860. EXPECT_FALSE(handle.is_valid());
  16861. server_thread.join();
  16862. }
  16863. // Serves `response` to the single request `fn` makes with a fresh client.
  16864. template <typename Fn>
  16865. static void with_single_response(const std::string &response, Fn fn) {
  16866. #ifndef _WIN32
  16867. signal(SIGPIPE, SIG_IGN);
  16868. #endif
  16869. std::promise<int> port_promise;
  16870. auto port_future = port_promise.get_future();
  16871. auto server_thread = serve_single_response(port_promise, response);
  16872. auto se = detail::scope_exit([&] { server_thread.join(); });
  16873. auto port = port_future.get();
  16874. ASSERT_GT(port, 0);
  16875. Client cli("127.0.0.1", port);
  16876. fn(cli);
  16877. }
  16878. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  16879. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  16880. // the chunked coding and drop Content-Length, so a front-end that trusts
  16881. // Content-Length would disagree about where the body ends (response
  16882. // smuggling). The client must reject such a response.
  16883. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16884. for (const char *te : {"chunked", "gzip, chunked"}) {
  16885. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  16886. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  16887. "\r\n" + "Connection: close\r\n" + "\r\n" +
  16888. "5\r\nhello\r\n0\r\n\r\n";
  16889. with_single_response(response, [&](Client &cli) {
  16890. auto res = cli.Get("/");
  16891. EXPECT_FALSE(static_cast<bool>(res)) << te;
  16892. EXPECT_EQ(Error::Read, res.error()) << te;
  16893. });
  16894. with_single_response(response, [&](Client &cli) {
  16895. auto handle = cli.open_stream("GET", "/");
  16896. EXPECT_FALSE(handle.is_valid()) << te;
  16897. EXPECT_EQ(Error::Read, handle.error) << te;
  16898. });
  16899. }
  16900. }
  16901. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  16902. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  16903. // closing the connection (unlike a request, which must be rejected).
  16904. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  16905. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  16906. "Transfer-Encoding: chunked\r\n"
  16907. "Connection: close\r\n"
  16908. "\r\n"
  16909. "5\r\nhello\r\n0\r\n\r\n",
  16910. "HTTP/1.1 200 OK\r\n"
  16911. "Transfer-Encoding: gzip\r\n"
  16912. "Connection: close\r\n"
  16913. "\r\n"
  16914. "hello"}) {
  16915. with_single_response(response, [&](Client &cli) {
  16916. auto res = cli.Get("/");
  16917. ASSERT_TRUE(static_cast<bool>(res)) << response;
  16918. EXPECT_EQ("hello", res->body);
  16919. });
  16920. with_single_response(response, [&](Client &cli) {
  16921. auto handle = cli.open_stream("GET", "/");
  16922. ASSERT_TRUE(handle.is_valid()) << response;
  16923. EXPECT_EQ("hello", read_all(handle));
  16924. });
  16925. }
  16926. }
  16927. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  16928. // framing headers describe nothing to read and must not be rejected.
  16929. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  16930. const std::string framing = "Content-Length: 5\r\n"
  16931. "Transfer-Encoding: chunked\r\n"
  16932. "Connection: close\r\n"
  16933. "\r\n";
  16934. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  16935. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  16936. });
  16937. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  16938. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  16939. });
  16940. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  16941. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  16942. with_single_response(response, [&](Client &cli) {
  16943. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  16944. });
  16945. with_single_response(response, [&](Client &cli) {
  16946. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  16947. });
  16948. }
  16949. }
  16950. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16951. TEST_F(OpenStreamTest, Gzip) {
  16952. Client cli("127.0.0.1", port_);
  16953. auto handle = cli.open_stream("GET", "/compressible", {},
  16954. {{"Accept-Encoding", "gzip"}});
  16955. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  16956. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16957. }
  16958. #endif
  16959. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16960. TEST_F(OpenStreamTest, Brotli) {
  16961. Client cli("127.0.0.1", port_);
  16962. auto handle =
  16963. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  16964. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  16965. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16966. }
  16967. #endif
  16968. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16969. TEST_F(OpenStreamTest, Zstd) {
  16970. Client cli("127.0.0.1", port_);
  16971. auto handle = cli.open_stream("GET", "/compressible", {},
  16972. {{"Accept-Encoding", "zstd"}});
  16973. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  16974. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16975. }
  16976. #endif
  16977. #ifdef CPPHTTPLIB_SSL_ENABLED
  16978. class SSLOpenStreamTest : public ::testing::Test {
  16979. protected:
  16980. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  16981. void SetUp() override {
  16982. svr_.Get("/hello", [](const Request &, Response &res) {
  16983. res.set_content("Hello SSL World!", "text/plain");
  16984. });
  16985. svr_.Get("/chunked", [](const Request &, Response &res) {
  16986. res.set_chunked_content_provider("text/plain",
  16987. [](size_t offset, DataSink &sink) {
  16988. if (offset < 15) {
  16989. sink.write("chunk", 5);
  16990. return true;
  16991. }
  16992. sink.done();
  16993. return true;
  16994. });
  16995. });
  16996. svr_.Post("/echo", [](const Request &req, Response &res) {
  16997. res.set_content(req.body, req.get_header_value("Content-Type"));
  16998. });
  16999. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17000. std::string body = req.body;
  17001. res.set_chunked_content_provider(
  17002. "text/plain", [body](size_t offset, DataSink &sink) {
  17003. if (offset < body.size()) {
  17004. sink.write(body.data() + offset, body.size() - offset);
  17005. }
  17006. sink.done();
  17007. return true;
  17008. });
  17009. });
  17010. port_ = svr_.bind_to_any_port("127.0.0.1");
  17011. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17012. svr_.wait_until_ready();
  17013. }
  17014. void TearDown() override {
  17015. svr_.stop();
  17016. if (thread_.joinable()) thread_.join();
  17017. }
  17018. SSLServer svr_;
  17019. std::thread thread_;
  17020. int port_ = 0;
  17021. };
  17022. TEST_F(SSLOpenStreamTest, Basic) {
  17023. SSLClient cli("127.0.0.1", port_);
  17024. cli.enable_server_certificate_verification(false);
  17025. auto handle = cli.open_stream("GET", "/hello");
  17026. ASSERT_TRUE(handle.is_valid());
  17027. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17028. }
  17029. TEST_F(SSLOpenStreamTest, Chunked) {
  17030. SSLClient cli("127.0.0.1", port_);
  17031. cli.enable_server_certificate_verification(false);
  17032. auto handle = cli.open_stream("GET", "/chunked");
  17033. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17034. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17035. "Transfer-Encoding") == "chunked");
  17036. auto body = read_all(handle);
  17037. EXPECT_EQ("chunkchunkchunk", body);
  17038. }
  17039. TEST_F(SSLOpenStreamTest, Post) {
  17040. SSLClient cli("127.0.0.1", port_);
  17041. cli.enable_server_certificate_verification(false);
  17042. auto handle =
  17043. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17044. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17045. EXPECT_EQ(200, handle.response->status);
  17046. auto body = read_all(handle);
  17047. EXPECT_EQ("Hello SSL POST", body);
  17048. }
  17049. TEST_F(SSLOpenStreamTest, PostChunked) {
  17050. SSLClient cli("127.0.0.1", port_);
  17051. cli.enable_server_certificate_verification(false);
  17052. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17053. "Chunked SSL Data", "text/plain");
  17054. ASSERT_TRUE(handle.is_valid());
  17055. EXPECT_EQ(200, handle.response->status);
  17056. auto body = read_all(handle);
  17057. EXPECT_EQ("Chunked SSL Data", body);
  17058. }
  17059. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17060. // Content-Length is terminated by the server closing the connection. When the
  17061. // SSL peer sends a close_notify after the body, the client must treat it as a
  17062. // clean EOF and return a successful response rather than an error.
  17063. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17065. ASSERT_TRUE(svr.is_valid());
  17066. svr.set_keep_alive_max_count(1);
  17067. const std::string expected_body = "Hello from connection-close response!";
  17068. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17069. res.set_content_provider("text/plain",
  17070. [&](size_t offset, DataSink &sink) -> bool {
  17071. if (offset < expected_body.size()) {
  17072. sink.write(expected_body.data() + offset,
  17073. expected_body.size() - offset);
  17074. }
  17075. sink.done();
  17076. return true;
  17077. });
  17078. });
  17079. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17080. auto se = detail::scope_exit([&] {
  17081. svr.stop();
  17082. listen_thread.join();
  17083. ASSERT_FALSE(svr.is_running());
  17084. });
  17085. svr.wait_until_ready();
  17086. SSLClient cli(HOST, PORT);
  17087. cli.enable_server_certificate_verification(false);
  17088. auto res = cli.Get("/no-content-length");
  17089. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17090. EXPECT_EQ(StatusCode::OK_200, res->status);
  17091. EXPECT_EQ(expected_body, res->body);
  17092. }
  17093. #endif // CPPHTTPLIB_SSL_ENABLED
  17094. //==============================================================================
  17095. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17096. // results for various scenarios.
  17097. //==============================================================================
  17098. TEST(ParityTest, GetVsOpenStream) {
  17099. Server svr;
  17100. const std::string path = "/parity";
  17101. const std::string content = "Parity test content: hello world";
  17102. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17103. res.set_content(content, "text/plain");
  17104. });
  17105. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17106. auto se = detail::scope_exit([&] {
  17107. svr.stop();
  17108. t.join();
  17109. ASSERT_FALSE(svr.is_running());
  17110. });
  17111. svr.wait_until_ready();
  17112. Client cli(HOST, PORT);
  17113. // Non-stream path
  17114. auto r1 = cli.Get(path);
  17115. ASSERT_TRUE(r1);
  17116. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17117. // Stream path
  17118. auto h = cli.open_stream("GET", path);
  17119. ASSERT_TRUE(h.is_valid());
  17120. EXPECT_EQ(r1->body, read_all(h));
  17121. }
  17122. // Helper to compress data with provided compressor type T
  17123. template <typename Compressor>
  17124. static std::string compress_payload_for_parity(const std::string &in) {
  17125. std::string out;
  17126. Compressor compressor;
  17127. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17128. [&](const char *data, size_t n) {
  17129. out.append(data, n);
  17130. return true;
  17131. });
  17132. EXPECT_TRUE(ok);
  17133. return out;
  17134. }
  17135. // Helper function for compression parity tests
  17136. template <typename Compressor>
  17137. static void test_compression_parity(const std::string &original,
  17138. const std::string &path,
  17139. const std::string &encoding) {
  17140. const std::string compressed =
  17141. compress_payload_for_parity<Compressor>(original);
  17142. Server svr;
  17143. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17144. res.set_content(compressed, "application/octet-stream");
  17145. res.set_header("Content-Encoding", encoding);
  17146. });
  17147. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17148. auto se = detail::scope_exit([&] {
  17149. svr.stop();
  17150. t.join();
  17151. ASSERT_FALSE(svr.is_running());
  17152. });
  17153. svr.wait_until_ready();
  17154. Client cli(HOST, PORT);
  17155. // Non-streaming
  17156. {
  17157. auto res = cli.Get(path);
  17158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17159. EXPECT_EQ(StatusCode::OK_200, res->status);
  17160. EXPECT_EQ(original, res->body);
  17161. }
  17162. // Streaming
  17163. {
  17164. auto h = cli.open_stream("GET", path);
  17165. ASSERT_TRUE(h.is_valid());
  17166. EXPECT_EQ(original, read_all(h));
  17167. }
  17168. }
  17169. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17170. TEST(ParityTest, Gzip) {
  17171. test_compression_parity<detail::gzip_compressor>(
  17172. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17173. }
  17174. #endif
  17175. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17176. TEST(ParityTest, Brotli) {
  17177. test_compression_parity<detail::brotli_compressor>(
  17178. "Hello, brotli parity test payload", "/parity-br", "br");
  17179. }
  17180. #endif
  17181. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17182. TEST(ParityTest, Zstd) {
  17183. test_compression_parity<detail::zstd_compressor>(
  17184. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17185. }
  17186. #endif
  17187. //==============================================================================
  17188. // New Stream API Tests
  17189. //==============================================================================
  17190. inline std::string read_body(httplib::stream::Result &result) {
  17191. std::string body;
  17192. while (result.next()) {
  17193. body.append(result.data(), result.size());
  17194. }
  17195. return body;
  17196. }
  17197. TEST(ClientConnectionTest, Basic) {
  17198. httplib::ClientConnection conn;
  17199. EXPECT_FALSE(conn.is_open());
  17200. conn.sock = 1;
  17201. EXPECT_TRUE(conn.is_open());
  17202. httplib::ClientConnection conn2(std::move(conn));
  17203. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17204. conn2.sock = INVALID_SOCKET;
  17205. }
  17206. // Unified test server for all stream::* tests
  17207. class StreamApiTest : public ::testing::Test {
  17208. protected:
  17209. void SetUp() override {
  17210. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17211. res.set_content("Hello World!", "text/plain");
  17212. });
  17213. svr_.Get("/echo-params",
  17214. [](const httplib::Request &req, httplib::Response &res) {
  17215. std::string r;
  17216. for (const auto &p : req.params) {
  17217. if (!r.empty()) r += "&";
  17218. r += p.first + "=" + p.second;
  17219. }
  17220. res.set_content(r, "text/plain");
  17221. });
  17222. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17223. res.set_content(req.body, req.get_header_value("Content-Type"));
  17224. });
  17225. svr_.Post("/echo-headers",
  17226. [](const httplib::Request &req, httplib::Response &res) {
  17227. std::string r;
  17228. for (const auto &h : req.headers)
  17229. r += h.first + ": " + h.second + "\n";
  17230. res.set_content(r, "text/plain");
  17231. });
  17232. svr_.Post("/echo-params",
  17233. [](const httplib::Request &req, httplib::Response &res) {
  17234. std::string r = "params:";
  17235. for (const auto &p : req.params)
  17236. r += p.first + "=" + p.second + ";";
  17237. res.set_content(r + " body:" + req.body, "text/plain");
  17238. });
  17239. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17240. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17241. });
  17242. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17243. res.set_content("PUT:" + req.body, "text/plain");
  17244. });
  17245. svr_.Patch("/echo",
  17246. [](const httplib::Request &req, httplib::Response &res) {
  17247. res.set_content("PATCH:" + req.body, "text/plain");
  17248. });
  17249. svr_.Delete(
  17250. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17251. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17252. "text/plain");
  17253. });
  17254. svr_.Get("/head-test",
  17255. [](const httplib::Request &, httplib::Response &res) {
  17256. res.set_content("body for HEAD", "text/plain");
  17257. });
  17258. svr_.Options("/options",
  17259. [](const httplib::Request &, httplib::Response &res) {
  17260. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17261. });
  17262. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17263. svr_.wait_until_ready();
  17264. }
  17265. void TearDown() override {
  17266. svr_.stop();
  17267. if (thread_.joinable()) thread_.join();
  17268. }
  17269. httplib::Server svr_;
  17270. std::thread thread_;
  17271. };
  17272. // stream::Get tests
  17273. TEST_F(StreamApiTest, GetBasic) {
  17274. httplib::Client cli(HOST, PORT);
  17275. auto result = httplib::stream::Get(cli, "/hello");
  17276. ASSERT_TRUE(result.is_valid());
  17277. EXPECT_EQ(200, result.status());
  17278. EXPECT_EQ("Hello World!", read_body(result));
  17279. }
  17280. TEST_F(StreamApiTest, GetWithParams) {
  17281. httplib::Client cli(HOST, PORT);
  17282. httplib::Params params{{"foo", "bar"}};
  17283. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17284. ASSERT_TRUE(result.is_valid());
  17285. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17286. }
  17287. TEST_F(StreamApiTest, GetConnectionError) {
  17288. httplib::Client cli(HOST, 9999);
  17289. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17290. }
  17291. TEST_F(StreamApiTest, Get404) {
  17292. httplib::Client cli(HOST, PORT);
  17293. auto result = httplib::stream::Get(cli, "/nonexistent");
  17294. EXPECT_TRUE(result.is_valid());
  17295. EXPECT_EQ(404, result.status());
  17296. }
  17297. // stream::Post tests
  17298. TEST_F(StreamApiTest, PostBasic) {
  17299. httplib::Client cli(HOST, PORT);
  17300. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17301. "application/json");
  17302. ASSERT_TRUE(result.is_valid());
  17303. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17304. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17305. }
  17306. TEST_F(StreamApiTest, PostWithHeaders) {
  17307. httplib::Client cli(HOST, PORT);
  17308. httplib::Headers headers{{"X-Custom", "value"}};
  17309. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17310. "text/plain");
  17311. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17312. }
  17313. TEST_F(StreamApiTest, PostWithParams) {
  17314. httplib::Client cli(HOST, PORT);
  17315. httplib::Params params{{"k", "v"}};
  17316. auto result =
  17317. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17318. auto body = read_body(result);
  17319. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17320. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17321. }
  17322. TEST_F(StreamApiTest, PostLarge) {
  17323. httplib::Client cli(HOST, PORT);
  17324. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17325. size_t total = 0;
  17326. while (result.next()) {
  17327. total += result.size();
  17328. }
  17329. EXPECT_EQ(100u * 1024u, total);
  17330. }
  17331. // stream::Put/Patch tests
  17332. TEST_F(StreamApiTest, PutAndPatch) {
  17333. httplib::Client cli(HOST, PORT);
  17334. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17335. EXPECT_EQ("PUT:test", read_body(put));
  17336. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17337. EXPECT_EQ("PATCH:test", read_body(patch));
  17338. }
  17339. // stream::Delete tests
  17340. TEST_F(StreamApiTest, Delete) {
  17341. httplib::Client cli(HOST, PORT);
  17342. auto del1 = httplib::stream::Delete(cli, "/resource");
  17343. EXPECT_EQ("Deleted", read_body(del1));
  17344. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17345. EXPECT_EQ("Deleted:data", read_body(del2));
  17346. }
  17347. // stream::Head/Options tests
  17348. TEST_F(StreamApiTest, HeadAndOptions) {
  17349. httplib::Client cli(HOST, PORT);
  17350. auto head = httplib::stream::Head(cli, "/head-test");
  17351. EXPECT_TRUE(head.is_valid());
  17352. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17353. auto opts = httplib::stream::Options(cli, "/options");
  17354. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17355. }
  17356. // SSL stream::* tests
  17357. #ifdef CPPHTTPLIB_SSL_ENABLED
  17358. class SSLStreamApiTest : public ::testing::Test {
  17359. protected:
  17360. void SetUp() override {
  17361. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17362. res.set_content("Hello SSL!", "text/plain");
  17363. });
  17364. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17365. res.set_content(req.body, "text/plain");
  17366. });
  17367. port_ = svr_.bind_to_any_port("127.0.0.1");
  17368. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17369. svr_.wait_until_ready();
  17370. }
  17371. void TearDown() override {
  17372. svr_.stop();
  17373. if (thread_.joinable()) thread_.join();
  17374. }
  17375. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17376. std::thread thread_;
  17377. int port_ = 0;
  17378. };
  17379. TEST_F(SSLStreamApiTest, GetAndPost) {
  17380. httplib::SSLClient cli("127.0.0.1", port_);
  17381. cli.enable_server_certificate_verification(false);
  17382. auto get = httplib::stream::Get(cli, "/hello");
  17383. EXPECT_EQ("Hello SSL!", read_body(get));
  17384. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17385. EXPECT_EQ("test", read_body(post));
  17386. }
  17387. #endif
  17388. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17389. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17390. // BodyReader
  17391. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17392. // Test that read timeout during streaming is detected
  17393. // Use a large content-length response where server delays mid-stream
  17394. Server svr;
  17395. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17396. // Send a large response with delay in the middle
  17397. res.set_content_provider(
  17398. 1000, // content_length
  17399. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17400. if (offset < 100) {
  17401. // Send first 100 bytes immediately
  17402. std::string data(100, 'A');
  17403. sink.write(data.c_str(), data.size());
  17404. return true;
  17405. }
  17406. // Then delay longer than client timeout
  17407. std::this_thread::sleep_for(std::chrono::seconds(3));
  17408. std::string data(900, 'B');
  17409. sink.write(data.c_str(), data.size());
  17410. return true;
  17411. });
  17412. });
  17413. auto port = 8091;
  17414. std::thread t([&]() { svr.listen("localhost", port); });
  17415. svr.wait_until_ready();
  17416. Client cli("localhost", port);
  17417. cli.set_read_timeout(1, 0); // 1 second timeout
  17418. auto handle = cli.open_stream("GET", "/slow-stream");
  17419. ASSERT_TRUE(handle.is_valid());
  17420. char buf[256];
  17421. ssize_t total = 0;
  17422. ssize_t n;
  17423. bool got_error = false;
  17424. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17425. total += n;
  17426. }
  17427. if (n < 0) {
  17428. got_error = true;
  17429. // Should be timeout or read error
  17430. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17431. handle.get_read_error() == Error::Read)
  17432. << "Actual error: " << to_string(handle.get_read_error());
  17433. }
  17434. // Either we got an error, or we got less data than expected
  17435. EXPECT_TRUE(got_error || total < 1000)
  17436. << "Expected timeout but got all " << total << " bytes";
  17437. svr.stop();
  17438. t.join();
  17439. }
  17440. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17441. // Test connection closed detection via BodyReader
  17442. Server svr;
  17443. std::atomic<bool> close_now{false};
  17444. svr.Get("/will-close", [&](const Request &, Response &res) {
  17445. res.set_content_provider(
  17446. 10000, // Large content_length that we won't fully send
  17447. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17448. if (offset < 100) {
  17449. std::string data(100, 'X');
  17450. sink.write(data.c_str(), data.size());
  17451. return true;
  17452. }
  17453. // Wait for signal then abort
  17454. while (!close_now) {
  17455. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17456. }
  17457. return false; // Abort - server will close connection
  17458. });
  17459. });
  17460. auto port = 8092;
  17461. std::thread t([&]() { svr.listen("localhost", port); });
  17462. svr.wait_until_ready();
  17463. Client cli("localhost", port);
  17464. auto handle = cli.open_stream("GET", "/will-close");
  17465. ASSERT_TRUE(handle.is_valid());
  17466. char buf[256];
  17467. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17468. EXPECT_GT(n, 0) << "First read should succeed";
  17469. // Signal server to close
  17470. close_now = true;
  17471. // Keep reading until error or EOF
  17472. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17473. // Keep reading
  17474. }
  17475. // Should get an error since content_length wasn't satisfied
  17476. if (n < 0) {
  17477. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17478. handle.get_read_error() == Error::Read)
  17479. << "Actual error: " << to_string(handle.get_read_error());
  17480. }
  17481. svr.stop();
  17482. t.join();
  17483. }
  17484. #ifdef CPPHTTPLIB_SSL_ENABLED
  17485. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17486. // Test that read timeout during SSL streaming is detected
  17487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17488. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17489. res.set_content_provider(
  17490. 1000, "text/plain",
  17491. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17492. if (offset < 100) {
  17493. std::string data(100, 'A');
  17494. sink.write(data.c_str(), data.size());
  17495. return true;
  17496. }
  17497. std::this_thread::sleep_for(std::chrono::seconds(3));
  17498. std::string data(900, 'B');
  17499. sink.write(data.c_str(), data.size());
  17500. return true;
  17501. });
  17502. });
  17503. auto port = 8093;
  17504. std::thread t([&]() { svr.listen("localhost", port); });
  17505. svr.wait_until_ready();
  17506. SSLClient cli("localhost", port);
  17507. cli.enable_server_certificate_verification(false);
  17508. cli.set_read_timeout(1, 0); // 1 second timeout
  17509. auto handle = cli.open_stream("GET", "/slow-stream");
  17510. ASSERT_TRUE(handle.is_valid());
  17511. char buf[256];
  17512. ssize_t total = 0;
  17513. ssize_t n;
  17514. bool got_error = false;
  17515. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17516. total += n;
  17517. }
  17518. if (n < 0) {
  17519. got_error = true;
  17520. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17521. handle.get_read_error() == Error::Read)
  17522. << "Actual error: " << to_string(handle.get_read_error());
  17523. }
  17524. EXPECT_TRUE(got_error || total < 1000)
  17525. << "Expected timeout but got all " << total << " bytes";
  17526. svr.stop();
  17527. t.join();
  17528. }
  17529. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17530. // Test SSL connection closed detection
  17531. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17532. std::atomic<bool> close_now{false};
  17533. svr.Get("/will-close", [&](const Request &, Response &res) {
  17534. res.set_content_provider(
  17535. 10000, "text/plain",
  17536. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17537. if (offset < 100) {
  17538. std::string data(100, 'X');
  17539. sink.write(data.c_str(), data.size());
  17540. return true;
  17541. }
  17542. while (!close_now) {
  17543. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17544. }
  17545. return false;
  17546. });
  17547. });
  17548. auto port = 8094;
  17549. std::thread t([&]() { svr.listen("localhost", port); });
  17550. svr.wait_until_ready();
  17551. SSLClient cli("localhost", port);
  17552. cli.enable_server_certificate_verification(false);
  17553. auto handle = cli.open_stream("GET", "/will-close");
  17554. ASSERT_TRUE(handle.is_valid());
  17555. char buf[256];
  17556. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17557. EXPECT_GT(n, 0);
  17558. // Signal server to close
  17559. close_now = true;
  17560. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17561. // Keep reading
  17562. }
  17563. if (n < 0) {
  17564. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17565. handle.get_read_error() == Error::Read)
  17566. << "Actual error: " << to_string(handle.get_read_error());
  17567. }
  17568. svr.stop();
  17569. t.join();
  17570. }
  17571. #endif
  17572. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17573. using namespace httplib;
  17574. // Create a test file
  17575. const char *fname = "etag_testfile.txt";
  17576. const char *content = "etag-content";
  17577. {
  17578. std::ofstream ofs(fname);
  17579. ofs << content;
  17580. ASSERT_TRUE(ofs.good());
  17581. }
  17582. Server svr;
  17583. svr.set_mount_point("/static", ".");
  17584. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17585. svr.wait_until_ready();
  17586. Client cli(HOST, PORT);
  17587. // First request: should get 200 with ETag header
  17588. auto res1 = cli.Get("/static/etag_testfile.txt");
  17589. ASSERT_TRUE(res1);
  17590. ASSERT_EQ(200, res1->status);
  17591. ASSERT_TRUE(res1->has_header("ETag"));
  17592. std::string etag = res1->get_header_value("ETag");
  17593. EXPECT_FALSE(etag.empty());
  17594. // Verify ETag format: W/"hex-hex"
  17595. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17596. EXPECT_EQ('W', etag[0]);
  17597. EXPECT_EQ('/', etag[1]);
  17598. EXPECT_EQ('"', etag[2]);
  17599. EXPECT_EQ('"', etag.back());
  17600. // Exact match: expect 304 Not Modified
  17601. Headers h2 = {{"If-None-Match", etag}};
  17602. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17603. ASSERT_TRUE(res2);
  17604. EXPECT_EQ(304, res2->status);
  17605. // Wildcard match: expect 304 Not Modified
  17606. Headers h3 = {{"If-None-Match", "*"}};
  17607. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17608. ASSERT_TRUE(res3);
  17609. EXPECT_EQ(304, res3->status);
  17610. // Non-matching ETag: expect 200
  17611. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17612. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17613. ASSERT_TRUE(res4);
  17614. EXPECT_EQ(200, res4->status);
  17615. // Multiple ETags with one matching: expect 304
  17616. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17617. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17618. ASSERT_TRUE(res5);
  17619. EXPECT_EQ(304, res5->status);
  17620. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17621. // that equivalent to the single comma-separated list above, so the match on
  17622. // the second line must still be found.
  17623. Headers h6;
  17624. h6.emplace("If-None-Match", "W/\"other\"");
  17625. h6.emplace("If-None-Match", etag);
  17626. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17627. ASSERT_TRUE(res6);
  17628. EXPECT_EQ(304, res6->status);
  17629. svr.stop();
  17630. t.join();
  17631. std::remove(fname);
  17632. }
  17633. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17634. using namespace httplib;
  17635. Server svr;
  17636. svr.set_mount_point("/static", ".");
  17637. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17638. svr.wait_until_ready();
  17639. Client cli(HOST, PORT);
  17640. // Send If-None-Match: * to a non-existent file
  17641. Headers h = {{"If-None-Match", "*"}};
  17642. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17644. EXPECT_EQ(404, res->status);
  17645. svr.stop();
  17646. t.join();
  17647. }
  17648. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17649. using namespace httplib;
  17650. // Create a test file
  17651. const char *fname = "etag_boundary_testfile.txt";
  17652. const char *content = "boundary-test";
  17653. {
  17654. std::ofstream ofs(fname);
  17655. ofs << content;
  17656. ASSERT_TRUE(ofs.good());
  17657. }
  17658. Server svr;
  17659. svr.set_mount_point("/static", ".");
  17660. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17661. svr.wait_until_ready();
  17662. Client cli(HOST, PORT);
  17663. // Get the actual ETag
  17664. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17665. ASSERT_TRUE(res1);
  17666. ASSERT_EQ(200, res1->status);
  17667. ASSERT_TRUE(res1->has_header("ETag"));
  17668. std::string etag = res1->get_header_value("ETag");
  17669. // Test 1: Very long ETag value (longer than actual ETag)
  17670. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17671. Headers h1 = {{"If-None-Match", "W/"
  17672. "\"very-long-etag-value-that-is-much-longer-"
  17673. "than-the-actual-etag-value\""}};
  17674. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17675. ASSERT_TRUE(res2);
  17676. EXPECT_EQ(200, res2->status); // Should not match
  17677. // Test 2: Long string followed by wildcard
  17678. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17679. // string)
  17680. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17681. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17682. ASSERT_TRUE(res3);
  17683. EXPECT_EQ(304, res3->status); // Should match on "*"
  17684. // Test 3: Wildcard followed by long string
  17685. // Should match on "*" immediately and return 304
  17686. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17687. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17688. ASSERT_TRUE(res4);
  17689. EXPECT_EQ(304, res4->status); // Should match on "*"
  17690. // Test 4: Multiple long non-matching values
  17691. // Should NOT match and return 200 (test that all comparisons are safe)
  17692. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17693. "W/\"second-long-non-matching-value\", "
  17694. "W/\"third-long-non-matching-value\""}};
  17695. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17696. ASSERT_TRUE(res5);
  17697. EXPECT_EQ(200, res5->status); // Should not match
  17698. // Test 5: Single character that is not "*" (edge case)
  17699. Headers h5 = {{"If-None-Match", "X"}};
  17700. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17701. ASSERT_TRUE(res6);
  17702. EXPECT_EQ(200, res6->status); // Should not match
  17703. svr.stop();
  17704. t.join();
  17705. std::remove(fname);
  17706. }
  17707. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17708. using namespace httplib;
  17709. // Create a test file
  17710. const char *fname = "ims_testfile.txt";
  17711. const char *content = "if-modified-since-test";
  17712. {
  17713. std::ofstream ofs(fname);
  17714. ofs << content;
  17715. ASSERT_TRUE(ofs.good());
  17716. }
  17717. Server svr;
  17718. svr.set_mount_point("/static", ".");
  17719. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17720. svr.wait_until_ready();
  17721. Client cli(HOST, PORT);
  17722. // First request: should get 200 with Last-Modified header
  17723. auto res1 = cli.Get("/static/ims_testfile.txt");
  17724. ASSERT_TRUE(res1);
  17725. ASSERT_EQ(200, res1->status);
  17726. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17727. std::string last_modified = res1->get_header_value("Last-Modified");
  17728. EXPECT_FALSE(last_modified.empty());
  17729. // If-Modified-Since with same time: expect 304
  17730. Headers h2 = {{"If-Modified-Since", last_modified}};
  17731. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  17732. ASSERT_TRUE(res2);
  17733. EXPECT_EQ(304, res2->status);
  17734. // If-Modified-Since with future time: expect 304
  17735. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17736. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  17737. ASSERT_TRUE(res3);
  17738. EXPECT_EQ(304, res3->status);
  17739. // If-Modified-Since with past time: expect 200
  17740. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17741. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  17742. ASSERT_TRUE(res4);
  17743. EXPECT_EQ(200, res4->status);
  17744. // If-None-Match takes precedence over If-Modified-Since
  17745. // (send matching ETag with old If-Modified-Since -> should still be 304)
  17746. ASSERT_TRUE(res1->has_header("ETag"));
  17747. std::string etag = res1->get_header_value("ETag");
  17748. Headers h5 = {{"If-None-Match", etag},
  17749. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17750. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  17751. ASSERT_TRUE(res5);
  17752. EXPECT_EQ(304, res5->status);
  17753. svr.stop();
  17754. t.join();
  17755. std::remove(fname);
  17756. }
  17757. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  17758. using namespace httplib;
  17759. Server svr;
  17760. // Endpoint that returns compressible content
  17761. svr.Get("/compressible", [](const Request &, Response &res) {
  17762. // Return a large enough body to trigger compression
  17763. std::string body(1000, 'a');
  17764. res.set_content(body, "text/plain");
  17765. });
  17766. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17767. svr.wait_until_ready();
  17768. Client cli(HOST, PORT);
  17769. // Request with gzip support: should get Vary header when compressed
  17770. cli.set_compress(true);
  17771. auto res1 = cli.Get("/compressible");
  17772. ASSERT_TRUE(res1);
  17773. EXPECT_EQ(200, res1->status);
  17774. // If Content-Encoding is set, Vary should also be set
  17775. if (res1->has_header("Content-Encoding")) {
  17776. EXPECT_TRUE(res1->has_header("Vary"));
  17777. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  17778. }
  17779. // Request without Accept-Encoding header: should not have compression
  17780. Headers h_no_compress;
  17781. auto res2 = cli.Get("/compressible", h_no_compress);
  17782. ASSERT_TRUE(res2);
  17783. EXPECT_EQ(200, res2->status);
  17784. // Verify Vary header is present when compression is applied
  17785. // (the exact behavior depends on server configuration)
  17786. svr.stop();
  17787. t.join();
  17788. }
  17789. TEST(ETagTest, IfRangeWithETag) {
  17790. using namespace httplib;
  17791. // Create a test file with known content
  17792. const char *fname = "if_range_testfile.txt";
  17793. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  17794. {
  17795. std::ofstream ofs(fname);
  17796. ofs << content;
  17797. ASSERT_TRUE(ofs.good());
  17798. }
  17799. Server svr;
  17800. svr.set_mount_point("/static", ".");
  17801. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17802. svr.wait_until_ready();
  17803. Client cli(HOST, PORT);
  17804. // First request: get ETag
  17805. auto res1 = cli.Get("/static/if_range_testfile.txt");
  17806. ASSERT_TRUE(res1);
  17807. ASSERT_EQ(200, res1->status);
  17808. ASSERT_TRUE(res1->has_header("ETag"));
  17809. std::string etag = res1->get_header_value("ETag");
  17810. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  17811. // Since our server generates weak ETags (W/"..."), If-Range with our
  17812. // ETag should NOT result in partial content - it should return full content.
  17813. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  17814. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  17815. ASSERT_TRUE(res2);
  17816. // Weak ETag in If-Range -> full content (200), not partial (206)
  17817. EXPECT_EQ(200, res2->status);
  17818. EXPECT_EQ(content, res2->body);
  17819. EXPECT_FALSE(res2->has_header("Content-Range"));
  17820. // Range request with non-matching If-Range (ETag): should get 200 (full
  17821. // content)
  17822. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  17823. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  17824. ASSERT_TRUE(res3);
  17825. EXPECT_EQ(200, res3->status);
  17826. EXPECT_EQ(content, res3->body);
  17827. EXPECT_FALSE(res3->has_header("Content-Range"));
  17828. // Range request with strong ETag (hypothetical - our server doesn't generate
  17829. // strong ETags, but if client sends a strong ETag that doesn't match, it
  17830. // should return full content)
  17831. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  17832. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  17833. ASSERT_TRUE(res4);
  17834. EXPECT_EQ(200, res4->status);
  17835. EXPECT_EQ(content, res4->body);
  17836. EXPECT_FALSE(res4->has_header("Content-Range"));
  17837. svr.stop();
  17838. t.join();
  17839. std::remove(fname);
  17840. }
  17841. TEST(ETagTest, IfRangeWithDate) {
  17842. using namespace httplib;
  17843. // Create a test file
  17844. const char *fname = "if_range_date_testfile.txt";
  17845. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  17846. {
  17847. std::ofstream ofs(fname);
  17848. ofs << content;
  17849. ASSERT_TRUE(ofs.good());
  17850. }
  17851. Server svr;
  17852. svr.set_mount_point("/static", ".");
  17853. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17854. svr.wait_until_ready();
  17855. Client cli(HOST, PORT);
  17856. // First request: get Last-Modified
  17857. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  17858. ASSERT_TRUE(res1);
  17859. ASSERT_EQ(200, res1->status);
  17860. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17861. std::string last_modified = res1->get_header_value("Last-Modified");
  17862. // Range request with matching If-Range (date): should get 206
  17863. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  17864. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  17865. ASSERT_TRUE(res2);
  17866. EXPECT_EQ(206, res2->status);
  17867. EXPECT_EQ("FGHIJ", res2->body);
  17868. // Range request with old If-Range date: should get 200 (full content)
  17869. Headers h3 = {{"Range", "bytes=5-9"},
  17870. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17871. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  17872. ASSERT_TRUE(res3);
  17873. EXPECT_EQ(200, res3->status);
  17874. EXPECT_EQ(content, res3->body);
  17875. // Range request with future If-Range date: should get 206
  17876. Headers h4 = {{"Range", "bytes=0-4"},
  17877. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17878. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  17879. ASSERT_TRUE(res4);
  17880. EXPECT_EQ(206, res4->status);
  17881. EXPECT_EQ("ABCDE", res4->body);
  17882. svr.stop();
  17883. t.join();
  17884. std::remove(fname);
  17885. }
  17886. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  17887. using namespace httplib;
  17888. const char *fname = "etag_malformed.txt";
  17889. const char *content = "malformed-etag";
  17890. {
  17891. std::ofstream ofs(fname);
  17892. ofs << content;
  17893. ASSERT_TRUE(ofs.good());
  17894. }
  17895. Server svr;
  17896. svr.set_mount_point("/static", ".");
  17897. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17898. svr.wait_until_ready();
  17899. Client cli(HOST, PORT);
  17900. // baseline: should get 200 and an ETag
  17901. auto res1 = cli.Get("/static/etag_malformed.txt");
  17902. ASSERT_TRUE(res1);
  17903. ASSERT_EQ(200, res1->status);
  17904. ASSERT_TRUE(res1->has_header("ETag"));
  17905. // Malformed ETag value (missing quotes) should be treated as non-matching
  17906. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  17907. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  17908. ASSERT_TRUE(res_bad);
  17909. EXPECT_EQ(200, res_bad->status);
  17910. // Whitespace-only header value should be considered invalid / non-matching
  17911. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  17912. "Host: localhost\r\n"
  17913. "If-None-Match: \r\n"
  17914. "Connection: close\r\n"
  17915. "\r\n";
  17916. std::string out;
  17917. ASSERT_TRUE(send_request(5, raw_req, &out));
  17918. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17919. svr.stop();
  17920. t.join();
  17921. std::remove(fname);
  17922. }
  17923. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  17924. using namespace httplib;
  17925. const char *fname = "ims_invalid_format.txt";
  17926. const char *content = "ims-bad-format";
  17927. {
  17928. std::ofstream ofs(fname);
  17929. ofs << content;
  17930. ASSERT_TRUE(ofs.good());
  17931. }
  17932. Server svr;
  17933. svr.set_mount_point("/static", ".");
  17934. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17935. svr.wait_until_ready();
  17936. Client cli(HOST, PORT);
  17937. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  17938. ASSERT_TRUE(res1);
  17939. ASSERT_EQ(200, res1->status);
  17940. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17941. // If-Modified-Since with invalid format should not result in 304
  17942. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  17943. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  17944. ASSERT_TRUE(res_bad);
  17945. EXPECT_EQ(200, res_bad->status);
  17946. // If-Range with invalid date format should be treated as mismatch -> full
  17947. // content (200)
  17948. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  17949. {"If-Range", "invalid-date"}};
  17950. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  17951. ASSERT_TRUE(res_ifrange);
  17952. EXPECT_EQ(200, res_ifrange->status);
  17953. svr.stop();
  17954. t.join();
  17955. std::remove(fname);
  17956. }
  17957. TEST(ETagTest, IfRangeWithMalformedETag) {
  17958. using namespace httplib;
  17959. const char *fname = "ifrange_malformed.txt";
  17960. const std::string content = "0123456789";
  17961. {
  17962. std::ofstream ofs(fname);
  17963. ofs << content;
  17964. ASSERT_TRUE(ofs.good());
  17965. }
  17966. Server svr;
  17967. svr.set_mount_point("/static", ".");
  17968. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17969. svr.wait_until_ready();
  17970. Client cli(HOST, PORT);
  17971. // First request: get ETag
  17972. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  17973. ASSERT_TRUE(res1);
  17974. ASSERT_EQ(200, res1->status);
  17975. ASSERT_TRUE(res1->has_header("ETag"));
  17976. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  17977. // full content (200)
  17978. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  17979. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  17980. ASSERT_TRUE(res2);
  17981. EXPECT_EQ(200, res2->status);
  17982. EXPECT_EQ(content, res2->body);
  17983. svr.stop();
  17984. t.join();
  17985. std::remove(fname);
  17986. }
  17987. TEST(ETagTest, ExtremeLargeDateValues) {
  17988. using namespace httplib;
  17989. const char *fname = "ims_extreme_date.txt";
  17990. const char *content = "ims-extreme-date";
  17991. {
  17992. std::ofstream ofs(fname);
  17993. ofs << content;
  17994. ASSERT_TRUE(ofs.good());
  17995. }
  17996. Server svr;
  17997. svr.set_mount_point("/static", ".");
  17998. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17999. svr.wait_until_ready();
  18000. Client cli(HOST, PORT);
  18001. auto res1 = cli.Get(std::string("/static/") + fname);
  18002. ASSERT_TRUE(res1);
  18003. ASSERT_EQ(200, res1->status);
  18004. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18005. // Extremely large year that may overflow date parsing routines.
  18006. Headers h_large_date = {
  18007. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18008. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18009. ASSERT_TRUE(res_bad);
  18010. // Expect server to treat this as invalid/mismatch and return full content
  18011. EXPECT_EQ(200, res_bad->status);
  18012. // If-Range with extremely large date should be treated as mismatch -> full
  18013. // content (200)
  18014. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18015. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18016. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18017. ASSERT_TRUE(res_ifrange);
  18018. EXPECT_EQ(200, res_ifrange->status);
  18019. svr.stop();
  18020. t.join();
  18021. std::remove(fname);
  18022. }
  18023. TEST(ETagTest, NegativeFileModificationTime) {
  18024. using namespace httplib;
  18025. const char *fname = "ims_negative_mtime.txt";
  18026. const std::string content = "negative-mtime";
  18027. {
  18028. std::ofstream ofs(fname);
  18029. ofs << content;
  18030. ASSERT_TRUE(ofs.good());
  18031. }
  18032. // Try to set file mtime to a negative value. This may fail on some
  18033. // platforms/filesystems; if it fails, the test will still verify server
  18034. // behaves safely by performing a regular conditional request.
  18035. #if defined(__APPLE__) || defined(__linux__)
  18036. bool set_negative = false;
  18037. do {
  18038. struct timeval times[2];
  18039. // access time: now
  18040. times[0].tv_sec = time(nullptr);
  18041. times[0].tv_usec = 0;
  18042. // modification time: negative (e.g., -1)
  18043. times[1].tv_sec = -1;
  18044. times[1].tv_usec = 0;
  18045. if (utimes(fname, times) == 0) { set_negative = true; }
  18046. } while (0);
  18047. #else
  18048. bool set_negative = false;
  18049. #endif
  18050. Server svr;
  18051. svr.set_mount_point("/static", ".");
  18052. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18053. svr.wait_until_ready();
  18054. Client cli(HOST, PORT);
  18055. auto res1 = cli.Get(std::string("/static/") + fname);
  18056. ASSERT_TRUE(res1);
  18057. ASSERT_EQ(200, res1->status);
  18058. bool has_last_modified = res1->has_header("Last-Modified");
  18059. std::string last_modified;
  18060. if (has_last_modified) {
  18061. last_modified = res1->get_header_value("Last-Modified");
  18062. }
  18063. if (set_negative) {
  18064. // If we successfully set a negative mtime, ensure server returns a
  18065. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18066. // with an old date and ensure server handles it without crash.
  18067. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18068. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18069. ASSERT_TRUE(res2);
  18070. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18071. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18072. } else {
  18073. // Could not set negative mtime on this platform; fall back to verifying
  18074. // that normal invalid/malformed dates are treated safely (non-304).
  18075. Headers h_bad_date = {
  18076. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18077. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18078. ASSERT_TRUE(res_bad);
  18079. EXPECT_EQ(200, res_bad->status);
  18080. }
  18081. svr.stop();
  18082. t.join();
  18083. std::remove(fname);
  18084. }
  18085. //==============================================================================
  18086. // SSE Parsing Tests
  18087. //==============================================================================
  18088. class SSEParsingTest : public ::testing::Test {
  18089. protected:
  18090. // Test helper that mimics SSE parsing behavior
  18091. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18092. int &retry_ms) {
  18093. // Blank line signals end of event
  18094. if (line.empty() || line == "\r") { return true; }
  18095. // Lines starting with ':' are comments (ignored)
  18096. if (!line.empty() && line[0] == ':') { return false; }
  18097. // Find the colon separator
  18098. auto colon_pos = line.find(':');
  18099. if (colon_pos == std::string::npos) {
  18100. // Line with no colon is treated as field name with empty value
  18101. return false;
  18102. }
  18103. std::string field = line.substr(0, colon_pos);
  18104. std::string value;
  18105. // Value starts after colon, skip optional single space
  18106. if (colon_pos + 1 < line.size()) {
  18107. size_t value_start = colon_pos + 1;
  18108. if (line[value_start] == ' ') { value_start++; }
  18109. value = line.substr(value_start);
  18110. // Remove trailing \r if present
  18111. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18112. }
  18113. // Handle known fields
  18114. if (field == "event") {
  18115. msg.event = value;
  18116. } else if (field == "data") {
  18117. // Multiple data lines are concatenated with newlines
  18118. if (!msg.data.empty()) { msg.data += "\n"; }
  18119. msg.data += value;
  18120. } else if (field == "id") {
  18121. // Empty id is valid (clears the last event ID)
  18122. msg.id = value;
  18123. } else if (field == "retry") {
  18124. // Parse retry interval in milliseconds
  18125. {
  18126. int v = 0;
  18127. auto res =
  18128. detail::from_chars(value.data(), value.data() + value.size(), v);
  18129. if (res.ec == std::errc{}) { retry_ms = v; }
  18130. }
  18131. }
  18132. // Unknown fields are ignored per SSE spec
  18133. return false;
  18134. }
  18135. };
  18136. // Test: Single-line data
  18137. TEST_F(SSEParsingTest, SingleLineData) {
  18138. sse::SSEMessage msg;
  18139. int retry_ms = 3000;
  18140. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18141. EXPECT_EQ(msg.data, "hello");
  18142. EXPECT_EQ(msg.event, "message");
  18143. // Blank line ends event
  18144. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18145. }
  18146. // Test: Multi-line data
  18147. TEST_F(SSEParsingTest, MultiLineData) {
  18148. sse::SSEMessage msg;
  18149. int retry_ms = 3000;
  18150. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18151. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18152. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18153. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18154. }
  18155. // Test: Custom event types
  18156. TEST_F(SSEParsingTest, CustomEventType) {
  18157. sse::SSEMessage msg;
  18158. int retry_ms = 3000;
  18159. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18160. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18161. EXPECT_EQ(msg.event, "update");
  18162. EXPECT_EQ(msg.data, "payload");
  18163. }
  18164. // Test: Event ID handling
  18165. TEST_F(SSEParsingTest, EventIdHandling) {
  18166. sse::SSEMessage msg;
  18167. int retry_ms = 3000;
  18168. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18169. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18170. EXPECT_EQ(msg.id, "12345");
  18171. }
  18172. // Test: Empty event ID (clears last event ID)
  18173. TEST_F(SSEParsingTest, EmptyEventId) {
  18174. sse::SSEMessage msg;
  18175. msg.id = "previous";
  18176. int retry_ms = 3000;
  18177. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18178. EXPECT_EQ(msg.id, "");
  18179. }
  18180. // Test: Retry field parsing
  18181. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18182. sse::SSEMessage msg;
  18183. int retry_ms = 3000;
  18184. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18185. EXPECT_EQ(retry_ms, 5000);
  18186. }
  18187. // Test: Invalid retry value
  18188. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18189. sse::SSEMessage msg;
  18190. int retry_ms = 3000;
  18191. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18192. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18193. }
  18194. // Test: Comments (lines starting with :)
  18195. TEST_F(SSEParsingTest, CommentsIgnored) {
  18196. sse::SSEMessage msg;
  18197. int retry_ms = 3000;
  18198. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18199. EXPECT_EQ(msg.data, "");
  18200. EXPECT_EQ(msg.event, "message");
  18201. }
  18202. // Test: Colon in value
  18203. TEST_F(SSEParsingTest, ColonInValue) {
  18204. sse::SSEMessage msg;
  18205. int retry_ms = 3000;
  18206. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18207. EXPECT_EQ(msg.data, "hello:world:test");
  18208. }
  18209. // Test: Line with no colon (field name only)
  18210. TEST_F(SSEParsingTest, FieldNameOnly) {
  18211. sse::SSEMessage msg;
  18212. int retry_ms = 3000;
  18213. // According to SSE spec, this is treated as field name with empty value
  18214. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18215. // Since we don't recognize "data" without colon, data should be empty
  18216. EXPECT_EQ(msg.data, "");
  18217. }
  18218. // Test: Trailing \r handling
  18219. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18220. sse::SSEMessage msg;
  18221. int retry_ms = 3000;
  18222. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18223. EXPECT_EQ(msg.data, "hello");
  18224. }
  18225. // Test: Unknown fields ignored
  18226. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18227. sse::SSEMessage msg;
  18228. int retry_ms = 3000;
  18229. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18230. EXPECT_EQ(msg.data, "");
  18231. EXPECT_EQ(msg.event, "message");
  18232. }
  18233. // Test: Space after colon is optional
  18234. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18235. sse::SSEMessage msg1, msg2;
  18236. int retry_ms = 3000;
  18237. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18238. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18239. EXPECT_EQ(msg1.data, "hello");
  18240. EXPECT_EQ(msg2.data, "hello");
  18241. }
  18242. // Test: SSEMessage clear
  18243. TEST_F(SSEParsingTest, MessageClear) {
  18244. sse::SSEMessage msg;
  18245. msg.event = "custom";
  18246. msg.data = "some data";
  18247. msg.id = "123";
  18248. msg.clear();
  18249. EXPECT_EQ(msg.event, "message");
  18250. EXPECT_EQ(msg.data, "");
  18251. EXPECT_EQ(msg.id, "");
  18252. }
  18253. // Test: Complete event parsing
  18254. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18255. sse::SSEMessage msg;
  18256. int retry_ms = 3000;
  18257. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18258. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18259. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18260. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18261. // Blank line ends event
  18262. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18263. EXPECT_EQ(msg.event, "notification");
  18264. EXPECT_EQ(msg.id, "evt-42");
  18265. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18266. EXPECT_EQ(retry_ms, 1000);
  18267. }
  18268. //==============================================================================
  18269. // Integration Tests with Server
  18270. //==============================================================================
  18271. class SSEIntegrationTest : public ::testing::Test {
  18272. protected:
  18273. void SetUp() override {
  18274. stop_server_.store(false);
  18275. events_.clear();
  18276. server_ = httplib::detail::make_unique<Server>();
  18277. setup_server();
  18278. start_server();
  18279. }
  18280. void TearDown() override {
  18281. stop_server_.store(true);
  18282. event_cv_.notify_all();
  18283. server_->stop();
  18284. if (server_thread_.joinable()) { server_thread_.join(); }
  18285. }
  18286. void setup_server() {
  18287. // Simple SSE endpoint
  18288. server_->Get("/events", [this](const Request &req, Response &res) {
  18289. auto last_id = req.get_header_value("Last-Event-ID");
  18290. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18291. res.set_chunked_content_provider(
  18292. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18293. std::unique_lock<std::mutex> lock(event_mutex_);
  18294. if (event_cv_.wait_for(
  18295. lock, std::chrono::milliseconds(200), [this] {
  18296. return !events_.empty() || stop_server_.load();
  18297. })) {
  18298. if (stop_server_.load()) { return false; }
  18299. if (!events_.empty()) {
  18300. std::string event = events_.front();
  18301. events_.erase(events_.begin());
  18302. sink.write(event.data(), event.size());
  18303. return true;
  18304. }
  18305. }
  18306. return !stop_server_.load();
  18307. });
  18308. });
  18309. // Endpoint that returns error
  18310. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18311. res.status = 500;
  18312. res.set_content("Internal Server Error", "text/plain");
  18313. });
  18314. // Endpoint for custom event types
  18315. server_->Get("/custom-events", [](const Request &, Response &res) {
  18316. res.set_chunked_content_provider(
  18317. "text/event-stream", [](size_t offset, DataSink &sink) {
  18318. if (offset == 0) {
  18319. std::string event = "event: update\ndata: updated\n\n"
  18320. "event: delete\ndata: deleted\n\n";
  18321. sink.write(event.data(), event.size());
  18322. }
  18323. return false; // End stream after sending
  18324. });
  18325. });
  18326. }
  18327. void start_server() {
  18328. port_ = server_->bind_to_any_port(HOST);
  18329. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18330. // Wait for server to start
  18331. while (!server_->is_running()) {
  18332. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18333. }
  18334. }
  18335. int get_port() const { return port_; }
  18336. void send_event(const std::string &event) {
  18337. std::lock_guard<std::mutex> lock(event_mutex_);
  18338. events_.push_back(event);
  18339. event_cv_.notify_all();
  18340. }
  18341. std::unique_ptr<Server> server_;
  18342. std::thread server_thread_;
  18343. std::mutex event_mutex_;
  18344. std::condition_variable event_cv_;
  18345. std::vector<std::string> events_;
  18346. std::atomic<bool> stop_server_{false};
  18347. std::string last_received_event_id_;
  18348. int port_ = 0;
  18349. };
  18350. // Test: Successful connection and on_open callback
  18351. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18352. // Add a simple endpoint that sends one event and closes
  18353. server_->Get("/simple-event", [](const Request &, Response &res) {
  18354. res.set_chunked_content_provider(
  18355. "text/event-stream", [](size_t offset, DataSink &sink) {
  18356. if (offset == 0) {
  18357. std::string event = "data: hello\n\n";
  18358. sink.write(event.data(), event.size());
  18359. }
  18360. return false; // Close stream after sending
  18361. });
  18362. });
  18363. Client client("localhost", get_port());
  18364. sse::SSEClient sse(client, "/simple-event");
  18365. std::atomic<bool> open_called{false};
  18366. std::atomic<bool> message_received{false};
  18367. sse.on_open([&open_called]() { open_called.store(true); });
  18368. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18369. if (msg.data == "hello") { message_received.store(true); }
  18370. });
  18371. sse.set_reconnect_interval(100);
  18372. sse.set_max_reconnect_attempts(1);
  18373. // Start async
  18374. sse.start_async();
  18375. // Wait for message to be processed
  18376. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18377. sse.stop();
  18378. EXPECT_TRUE(open_called.load());
  18379. EXPECT_TRUE(message_received.load());
  18380. }
  18381. // Test: on_message callback
  18382. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18383. // Endpoint that sends multiple events then closes
  18384. server_->Get("/multi-event", [](const Request &, Response &res) {
  18385. res.set_chunked_content_provider(
  18386. "text/event-stream", [](size_t offset, DataSink &sink) {
  18387. if (offset == 0) {
  18388. std::string events = "data: message1\n\ndata: message2\n\n";
  18389. sink.write(events.data(), events.size());
  18390. }
  18391. return false;
  18392. });
  18393. });
  18394. Client client("localhost", get_port());
  18395. sse::SSEClient sse(client, "/multi-event");
  18396. std::vector<std::string> received_messages;
  18397. std::mutex messages_mutex;
  18398. sse.on_message([&](const sse::SSEMessage &msg) {
  18399. std::lock_guard<std::mutex> lock(messages_mutex);
  18400. received_messages.push_back(msg.data);
  18401. });
  18402. sse.set_reconnect_interval(100);
  18403. sse.set_max_reconnect_attempts(1);
  18404. sse.start_async();
  18405. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18406. sse.stop();
  18407. std::lock_guard<std::mutex> lock(messages_mutex);
  18408. EXPECT_GE(received_messages.size(), 2u);
  18409. if (received_messages.size() >= 2) {
  18410. EXPECT_EQ(received_messages[0], "message1");
  18411. EXPECT_EQ(received_messages[1], "message2");
  18412. }
  18413. }
  18414. // Test: on_event for specific types
  18415. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18416. Client client("localhost", get_port());
  18417. sse::SSEClient sse(client, "/custom-events");
  18418. std::atomic<bool> update_received{false};
  18419. std::atomic<bool> delete_received{false};
  18420. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18421. if (msg.data == "updated") { update_received.store(true); }
  18422. });
  18423. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18424. if (msg.data == "deleted") { delete_received.store(true); }
  18425. });
  18426. sse.set_max_reconnect_attempts(1);
  18427. sse.start_async();
  18428. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18429. sse.stop();
  18430. EXPECT_TRUE(update_received.load());
  18431. EXPECT_TRUE(delete_received.load());
  18432. }
  18433. // Test: on_error callback on connection failure
  18434. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18435. // Connect to a non-existent port
  18436. Client client("localhost", 59999);
  18437. sse::SSEClient sse(client, "/events");
  18438. std::atomic<bool> error_called{false};
  18439. Error received_error = Error::Success;
  18440. sse.on_error([&](Error err) {
  18441. error_called.store(true);
  18442. received_error = err;
  18443. });
  18444. sse.set_reconnect_interval(50);
  18445. sse.set_max_reconnect_attempts(1);
  18446. sse.start_async();
  18447. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18448. sse.stop();
  18449. EXPECT_TRUE(error_called.load());
  18450. EXPECT_NE(received_error, Error::Success);
  18451. }
  18452. // Test: Last-Event-ID header sent on reconnect
  18453. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18454. // Endpoint that sends event with ID
  18455. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18456. res.set_chunked_content_provider(
  18457. "text/event-stream", [](size_t offset, DataSink &sink) {
  18458. if (offset == 0) {
  18459. std::string event = "id: evt-123\ndata: test\n\n";
  18460. sink.write(event.data(), event.size());
  18461. }
  18462. return false;
  18463. });
  18464. });
  18465. Client client("localhost", get_port());
  18466. sse::SSEClient sse(client, "/event-with-id");
  18467. std::atomic<bool> id_received{false};
  18468. sse.on_message([&](const sse::SSEMessage &msg) {
  18469. if (!msg.id.empty()) { id_received.store(true); }
  18470. });
  18471. sse.set_reconnect_interval(100);
  18472. sse.set_max_reconnect_attempts(1);
  18473. sse.start_async();
  18474. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18475. sse.stop();
  18476. EXPECT_TRUE(id_received.load());
  18477. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18478. }
  18479. // Test: Manual stop
  18480. TEST_F(SSEIntegrationTest, ManualStop) {
  18481. // Endpoint that sends one event and stays open briefly
  18482. std::atomic<bool> handler_running{true};
  18483. server_->Get("/stay-open", [&handler_running](const Request &,
  18484. Response &res) {
  18485. res.set_chunked_content_provider(
  18486. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18487. if (offset == 0) {
  18488. std::string event = "data: connected\n\n";
  18489. sink.write(event.data(), event.size());
  18490. }
  18491. // Keep connection open while handler_running is true
  18492. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18493. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18494. }
  18495. return false;
  18496. });
  18497. });
  18498. Client client("localhost", get_port());
  18499. sse::SSEClient sse(client, "/stay-open");
  18500. std::atomic<bool> connected{false};
  18501. sse.on_open([&connected]() { connected.store(true); });
  18502. sse.set_reconnect_interval(100);
  18503. sse.set_max_reconnect_attempts(1);
  18504. sse.start_async();
  18505. // Wait for connection to establish
  18506. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18507. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18508. }
  18509. EXPECT_TRUE(connected.load());
  18510. EXPECT_TRUE(sse.is_connected());
  18511. // Signal handler to stop
  18512. handler_running.store(false);
  18513. // Stop SSE client
  18514. sse.stop();
  18515. EXPECT_FALSE(sse.is_connected());
  18516. }
  18517. // Test: SSEClient with custom headers
  18518. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18519. // Setup a server endpoint that checks for custom header
  18520. std::atomic<bool> header_received{false};
  18521. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18522. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18523. header_received.store(true);
  18524. }
  18525. res.set_chunked_content_provider("text/event-stream",
  18526. [](size_t, DataSink &) { return false; });
  18527. });
  18528. Client client("localhost", get_port());
  18529. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18530. sse::SSEClient sse(client, "/header-check", headers);
  18531. sse.set_max_reconnect_attempts(1);
  18532. sse.start_async();
  18533. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18534. sse.stop();
  18535. EXPECT_TRUE(header_received.load());
  18536. }
  18537. // Test: Reconnect interval configuration
  18538. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18539. Client client("localhost", get_port());
  18540. sse::SSEClient sse(client, "/events");
  18541. auto &result = sse.set_reconnect_interval(500);
  18542. // Builder pattern should return reference to self
  18543. EXPECT_EQ(&result, &sse);
  18544. }
  18545. // Test: Max reconnect attempts
  18546. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18547. // Connect to non-existent port to force reconnects
  18548. Client client("localhost", 59998);
  18549. sse::SSEClient sse(client, "/events");
  18550. std::atomic<int> error_count{0};
  18551. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18552. sse.set_reconnect_interval(50);
  18553. sse.set_max_reconnect_attempts(2);
  18554. auto start = std::chrono::steady_clock::now();
  18555. sse.start(); // Blocking call
  18556. auto end = std::chrono::steady_clock::now();
  18557. // Should have stopped after 2 failed attempts
  18558. EXPECT_GE(error_count.load(), 2);
  18559. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18560. auto duration =
  18561. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18562. #ifdef _WIN32
  18563. // Windows is much slower for socket connection failures
  18564. EXPECT_LT(duration.count(), 7000);
  18565. #else
  18566. EXPECT_LT(duration.count(), 1000);
  18567. #endif
  18568. }
  18569. // Test: Multi-line data in integration
  18570. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18571. // Endpoint with multi-line data
  18572. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18573. res.set_chunked_content_provider(
  18574. "text/event-stream", [](size_t offset, DataSink &sink) {
  18575. if (offset == 0) {
  18576. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18577. sink.write(event.data(), event.size());
  18578. }
  18579. return false;
  18580. });
  18581. });
  18582. Client client("localhost", get_port());
  18583. sse::SSEClient sse(client, "/multiline-data");
  18584. std::string received_data;
  18585. std::mutex data_mutex;
  18586. sse.on_message([&](const sse::SSEMessage &msg) {
  18587. std::lock_guard<std::mutex> lock(data_mutex);
  18588. received_data = msg.data;
  18589. });
  18590. sse.set_reconnect_interval(100);
  18591. sse.set_max_reconnect_attempts(1);
  18592. sse.start_async();
  18593. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18594. sse.stop();
  18595. std::lock_guard<std::mutex> lock(data_mutex);
  18596. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18597. }
  18598. // Test: Auto-reconnect after server disconnection
  18599. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18600. std::atomic<int> connection_count{0};
  18601. std::atomic<int> message_count{0};
  18602. // Endpoint that sends one event and closes, forcing reconnect
  18603. server_->Get("/reconnect-test",
  18604. [&connection_count](const Request &, Response &res) {
  18605. connection_count.fetch_add(1);
  18606. res.set_chunked_content_provider(
  18607. "text/event-stream", [](size_t offset, DataSink &sink) {
  18608. if (offset == 0) {
  18609. std::string event = "data: hello\n\n";
  18610. sink.write(event.data(), event.size());
  18611. }
  18612. return false; // Close connection after sending
  18613. });
  18614. });
  18615. Client client("localhost", get_port());
  18616. sse::SSEClient sse(client, "/reconnect-test");
  18617. sse.on_message([&message_count](const sse::SSEMessage &) {
  18618. message_count.fetch_add(1);
  18619. });
  18620. sse.set_reconnect_interval(100);
  18621. sse.set_max_reconnect_attempts(3);
  18622. sse.start_async();
  18623. // Wait long enough for multiple reconnects
  18624. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18625. sse.stop();
  18626. // Should have connected multiple times (initial + reconnects)
  18627. EXPECT_GE(connection_count.load(), 2);
  18628. // Should have received messages from multiple connections
  18629. EXPECT_GE(message_count.load(), 2);
  18630. }
  18631. // Test: Last-Event-ID sent on reconnect
  18632. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18633. std::atomic<int> connection_count{0};
  18634. std::vector<std::string> received_last_event_ids;
  18635. std::mutex id_mutex;
  18636. // Endpoint that checks Last-Event-ID header and sends event with ID
  18637. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18638. int conn = connection_count.fetch_add(1);
  18639. // Capture the Last-Event-ID header from each connection
  18640. {
  18641. std::lock_guard<std::mutex> lock(id_mutex);
  18642. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18643. }
  18644. res.set_chunked_content_provider(
  18645. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18646. if (offset == 0) {
  18647. std::string event =
  18648. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18649. sink.write(event.data(), event.size());
  18650. }
  18651. return false;
  18652. });
  18653. });
  18654. Client client("localhost", get_port());
  18655. sse::SSEClient sse(client, "/reconnect-with-id");
  18656. sse.set_reconnect_interval(100);
  18657. sse.set_max_reconnect_attempts(3);
  18658. sse.start_async();
  18659. // Wait for at least 2 connections
  18660. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18661. sse.stop();
  18662. // Verify behavior
  18663. std::lock_guard<std::mutex> lock(id_mutex);
  18664. EXPECT_GE(received_last_event_ids.size(), 2u);
  18665. // First connection should have no Last-Event-ID
  18666. if (!received_last_event_ids.empty()) {
  18667. EXPECT_EQ(received_last_event_ids[0], "");
  18668. }
  18669. // Second connection should have Last-Event-ID from first connection
  18670. if (received_last_event_ids.size() >= 2) {
  18671. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18672. }
  18673. }
  18674. // Test: set_headers updates headers used on reconnect
  18675. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18676. std::vector<std::string> received_tokens;
  18677. std::mutex token_mutex;
  18678. // Endpoint that captures Authorization header
  18679. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18680. {
  18681. std::lock_guard<std::mutex> lock(token_mutex);
  18682. received_tokens.push_back(req.get_header_value("Authorization"));
  18683. }
  18684. res.set_chunked_content_provider(
  18685. "text/event-stream", [](size_t offset, DataSink &sink) {
  18686. if (offset == 0) {
  18687. std::string event = "data: hello\n\n";
  18688. sink.write(event.data(), event.size());
  18689. }
  18690. return false; // Close connection to trigger reconnect
  18691. });
  18692. });
  18693. Client client("localhost", get_port());
  18694. Headers headers = {{"Authorization", "Bearer old-token"}};
  18695. sse::SSEClient sse(client, "/auth-check", headers);
  18696. // Update headers on each successful connection
  18697. sse.on_open(
  18698. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18699. sse.set_reconnect_interval(100);
  18700. sse.set_max_reconnect_attempts(3);
  18701. sse.start_async();
  18702. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18703. sse.stop();
  18704. std::lock_guard<std::mutex> lock(token_mutex);
  18705. ASSERT_GE(received_tokens.size(), 2u);
  18706. // First connection uses original header
  18707. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18708. // Second connection uses updated header from set_headers
  18709. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18710. }
  18711. // Test: 401 allows reconnection (so on_error can refresh headers)
  18712. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18713. std::atomic<int> connection_count{0};
  18714. // Endpoint: returns 401 on first attempt, 200 on second
  18715. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18716. int conn = connection_count.fetch_add(1);
  18717. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  18718. res.status = StatusCode::Unauthorized_401;
  18719. res.set_content("Unauthorized", "text/plain");
  18720. return;
  18721. }
  18722. res.set_chunked_content_provider(
  18723. "text/event-stream", [](size_t offset, DataSink &sink) {
  18724. if (offset == 0) {
  18725. std::string event = "data: authenticated\n\n";
  18726. sink.write(event.data(), event.size());
  18727. }
  18728. return false;
  18729. });
  18730. });
  18731. Client client("localhost", get_port());
  18732. Headers headers = {{"Authorization", "Bearer expired"}};
  18733. sse::SSEClient sse(client, "/auth-retry", headers);
  18734. std::atomic<bool> message_received{false};
  18735. // Refresh token on error
  18736. sse.on_error(
  18737. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  18738. sse.on_message([&](const sse::SSEMessage &msg) {
  18739. if (msg.data == "authenticated") { message_received.store(true); }
  18740. });
  18741. sse.set_reconnect_interval(100);
  18742. sse.set_max_reconnect_attempts(3);
  18743. sse.start_async();
  18744. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18745. sse.stop();
  18746. // Should have reconnected after 401 and succeeded with new token
  18747. EXPECT_GE(connection_count.load(), 2);
  18748. EXPECT_TRUE(message_received.load());
  18749. }
  18750. TEST(Issue2318Test, EmptyHostString) {
  18751. {
  18752. httplib::Client cli_empty("", PORT);
  18753. auto res = cli_empty.Get("/");
  18754. ASSERT_FALSE(res);
  18755. EXPECT_EQ(httplib::Error::Connection, res.error());
  18756. }
  18757. {
  18758. httplib::Client cli(" ", PORT);
  18759. auto res = cli.Get("/");
  18760. ASSERT_FALSE(res);
  18761. EXPECT_EQ(httplib::Error::Connection, res.error());
  18762. }
  18763. }
  18764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18765. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  18766. Server svr;
  18767. // Set a small payload limit (1KB)
  18768. svr.set_payload_max_length(1024);
  18769. svr.Post("/test", [&](const Request &req, Response &res) {
  18770. res.set_content("Body size: " + std::to_string(req.body.size()),
  18771. "text/plain");
  18772. });
  18773. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18774. auto se = detail::scope_exit([&] {
  18775. svr.stop();
  18776. listen_thread.join();
  18777. });
  18778. svr.wait_until_ready();
  18779. // Create data that compresses well but exceeds limit when decompressed
  18780. // 8KB of repeated null bytes compresses to a very small size
  18781. std::string original_data(8 * 1024, '\0');
  18782. // Compress the data using gzip
  18783. std::string compressed_data;
  18784. detail::gzip_compressor compressor;
  18785. compressor.compress(original_data.data(), original_data.size(), true,
  18786. [&](const char *data, size_t size) {
  18787. compressed_data.append(data, size);
  18788. return true;
  18789. });
  18790. // Verify compression worked (compressed should be much smaller)
  18791. ASSERT_LT(compressed_data.size(), original_data.size());
  18792. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  18793. // Send compressed data with Content-Encoding: gzip
  18794. Client cli(HOST, PORT);
  18795. Headers headers = {{"Content-Encoding", "gzip"}};
  18796. auto res =
  18797. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  18798. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  18799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18800. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  18801. }
  18802. #endif
  18803. // ============================================================================
  18804. // OpenSSL-Specific Tests
  18805. // ============================================================================
  18806. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18807. X509 *readCertificate(const std::string &strFileName) {
  18808. std::ifstream inStream(strFileName);
  18809. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  18810. std::istreambuf_iterator<char>());
  18811. if (strCertPEM.empty()) return (nullptr);
  18812. BIO *pbCert = BIO_new(BIO_s_mem());
  18813. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  18814. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  18815. BIO_free(pbCert);
  18816. return (pCert);
  18817. }
  18818. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  18819. std::ifstream inStream(strFileName);
  18820. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  18821. std::istreambuf_iterator<char>());
  18822. if (strPrivateKeyPEM.empty()) return (nullptr);
  18823. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  18824. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  18825. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  18826. BIO_free(pbPrivKey);
  18827. return (pPrivateKey);
  18828. }
  18829. TEST(BindServerTest, UpdateCerts) {
  18830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18831. int port = svr.bind_to_any_port("0.0.0.0");
  18832. ASSERT_TRUE(svr.is_valid());
  18833. ASSERT_TRUE(port > 0);
  18834. X509 *cert = readCertificate(SERVER_CERT_FILE);
  18835. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  18836. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  18837. ASSERT_TRUE(cert != nullptr);
  18838. ASSERT_TRUE(ca_cert != nullptr);
  18839. ASSERT_TRUE(key != nullptr);
  18840. X509_STORE *cert_store = X509_STORE_new();
  18841. X509_STORE_add_cert(cert_store, ca_cert);
  18842. // svr.update_certs(cert, key, cert_store); // deprecated
  18843. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  18844. CLIENT_CA_CERT_FILE);
  18845. ASSERT_TRUE(svr.is_valid());
  18846. svr.stop();
  18847. X509_STORE_free(cert_store);
  18848. X509_free(cert);
  18849. X509_free(ca_cert);
  18850. EVP_PKEY_free(key);
  18851. }
  18852. // Test that update_certs() updates client CA list correctly
  18853. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  18854. // Start with file-based constructor
  18855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18856. ASSERT_TRUE(svr.is_valid());
  18857. // Initially no client CA list should be set
  18858. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18859. ASSERT_TRUE(ssl_ctx != nullptr);
  18860. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  18861. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  18862. EXPECT_EQ(0, count_before);
  18863. // Now update with client CA (PEM string)
  18864. std::string cert_pem, key_pem, ca_pem;
  18865. read_file(SERVER_CERT_FILE, cert_pem);
  18866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  18867. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  18868. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  18869. ASSERT_TRUE(svr.is_valid());
  18870. // Now client CA list should be set
  18871. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  18872. ASSERT_TRUE(ca_list_after != nullptr);
  18873. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  18874. }
  18875. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  18876. // Test that the file-path SSLServer constructor properly sets the client CA
  18877. // list that is sent to clients during the TLS handshake (CertificateRequest)
  18878. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18879. ASSERT_TRUE(svr.is_valid());
  18880. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18881. ASSERT_TRUE(ssl_ctx != nullptr);
  18882. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  18883. ASSERT_TRUE(ca_list != nullptr);
  18884. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  18885. }
  18886. #endif
  18887. // ============================================================================
  18888. // MbedTLS-Specific Tests
  18889. // ============================================================================
  18890. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  18891. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  18892. using namespace httplib::tls;
  18893. // Track if callback was invoked
  18894. bool callback_invoked = false;
  18895. // The callback receives void* ctx which is actually MbedTlsContext*
  18896. // We can access the mbedtls_ssl_config via the context
  18897. auto setup_callback = [&callback_invoked](void *ctx) {
  18898. callback_invoked = true;
  18899. // Cast to MbedTlsContext* to access the ssl config
  18900. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  18901. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  18902. // Use static variables to hold certificate data (simplified for test)
  18903. static mbedtls_x509_crt own_cert;
  18904. static mbedtls_pk_context own_key;
  18905. static mbedtls_x509_crt ca_chain;
  18906. static bool initialized = false;
  18907. if (!initialized) {
  18908. mbedtls_x509_crt_init(&own_cert);
  18909. mbedtls_pk_init(&own_key);
  18910. mbedtls_x509_crt_init(&ca_chain);
  18911. // Load server certificate
  18912. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  18913. return false;
  18914. }
  18915. // Load server private key.
  18916. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  18917. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  18918. #if MBEDTLS_VERSION_MAJOR == 3
  18919. ,
  18920. mbedtls_ctr_drbg_random, nullptr
  18921. #endif
  18922. ) != 0) {
  18923. return false;
  18924. }
  18925. // Load CA chain for client verification
  18926. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  18927. return false;
  18928. }
  18929. initialized = true;
  18930. }
  18931. // Configure the SSL config
  18932. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  18933. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  18934. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  18935. // Set minimum TLS version using mbedTLS native API
  18936. #if MBEDTLS_VERSION_MAJOR >= 3
  18937. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  18938. #else
  18939. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  18940. MBEDTLS_SSL_MINOR_VERSION_3);
  18941. #endif
  18942. return true;
  18943. };
  18944. SSLServer svr(setup_callback);
  18945. ASSERT_TRUE(svr.is_valid());
  18946. ASSERT_TRUE(callback_invoked);
  18947. svr.Get("/test", [&](const Request &req, Response &res) {
  18948. res.set_content("test", "text/plain");
  18949. auto cert = req.peer_cert();
  18950. ASSERT_TRUE(static_cast<bool>(cert));
  18951. auto common_name = cert.subject_cn();
  18952. EXPECT_EQ("Common Name", common_name);
  18953. });
  18954. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18955. auto se = detail::scope_exit([&] {
  18956. svr.stop();
  18957. t.join();
  18958. ASSERT_FALSE(svr.is_running());
  18959. });
  18960. svr.wait_until_ready();
  18961. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  18962. cli.enable_server_certificate_verification(false);
  18963. cli.set_connection_timeout(30);
  18964. auto res = cli.Get("/test");
  18965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18966. ASSERT_EQ(StatusCode::OK_200, res->status);
  18967. }
  18968. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  18969. // context (owning mbedtls_ssl_config) before shutting down a still-open
  18970. // keep-alive SSL session, which reads through that config in
  18971. // mbedtls_ssl_close_notify.
  18972. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  18973. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18974. ASSERT_TRUE(svr.is_valid());
  18975. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18976. res.set_content("test", "text/plain");
  18977. });
  18978. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18979. auto se = detail::scope_exit([&] {
  18980. svr.stop();
  18981. t.join();
  18982. ASSERT_FALSE(svr.is_running());
  18983. });
  18984. svr.wait_until_ready();
  18985. {
  18986. SSLClient cli(HOST, PORT);
  18987. cli.enable_server_certificate_verification(false);
  18988. cli.set_keep_alive(true);
  18989. auto res = cli.Get("/test");
  18990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18991. ASSERT_EQ(StatusCode::OK_200, res->status);
  18992. // cli is destructed here with the keep-alive SSL session still open.
  18993. }
  18994. }
  18995. #endif
  18996. // WebSocket Tests
  18997. TEST(WebSocketTest, RSVBitsMustBeZero) {
  18998. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  18999. // defining the meaning of these bits has been negotiated.
  19000. auto make_frame = [](uint8_t first_byte) {
  19001. std::string frame;
  19002. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19003. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19004. frame += "Hello";
  19005. return frame;
  19006. };
  19007. // RSV1 set (0x40)
  19008. {
  19009. detail::BufferStream strm;
  19010. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19011. ws::Opcode opcode;
  19012. std::string payload;
  19013. bool fin;
  19014. EXPECT_EQ(
  19015. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19016. ws::impl::FrameRead::Fail);
  19017. }
  19018. // RSV2 set (0x20)
  19019. {
  19020. detail::BufferStream strm;
  19021. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19022. ws::Opcode opcode;
  19023. std::string payload;
  19024. bool fin;
  19025. EXPECT_EQ(
  19026. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19027. ws::impl::FrameRead::Fail);
  19028. }
  19029. // RSV3 set (0x10)
  19030. {
  19031. detail::BufferStream strm;
  19032. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19033. ws::Opcode opcode;
  19034. std::string payload;
  19035. bool fin;
  19036. EXPECT_EQ(
  19037. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19038. ws::impl::FrameRead::Fail);
  19039. }
  19040. // No RSV bits set - should succeed
  19041. {
  19042. detail::BufferStream strm;
  19043. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19044. ws::Opcode opcode;
  19045. std::string payload;
  19046. bool fin;
  19047. EXPECT_EQ(
  19048. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19049. ws::impl::FrameRead::Ok);
  19050. EXPECT_EQ(ws::Opcode::Text, opcode);
  19051. EXPECT_EQ("Hello", payload);
  19052. EXPECT_TRUE(fin);
  19053. }
  19054. }
  19055. TEST(WebSocketTest, ControlFrameValidation) {
  19056. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19057. // payload length <= 125.
  19058. // Ping with FIN=0 - must be rejected
  19059. {
  19060. detail::BufferStream strm;
  19061. std::string frame;
  19062. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19063. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19064. strm.write(frame.data(), frame.size());
  19065. ws::Opcode opcode;
  19066. std::string payload;
  19067. bool fin;
  19068. EXPECT_EQ(
  19069. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19070. ws::impl::FrameRead::Fail);
  19071. }
  19072. // Close with FIN=0 - must be rejected
  19073. {
  19074. detail::BufferStream strm;
  19075. std::string frame;
  19076. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19077. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19078. strm.write(frame.data(), frame.size());
  19079. ws::Opcode opcode;
  19080. std::string payload;
  19081. bool fin;
  19082. EXPECT_EQ(
  19083. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19084. ws::impl::FrameRead::Fail);
  19085. }
  19086. // Ping with payload_len=126 (extended length) - must be rejected
  19087. {
  19088. detail::BufferStream strm;
  19089. std::string frame;
  19090. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19091. frame += static_cast<char>(126); // payload_len=126 (>125)
  19092. frame += static_cast<char>(0x00); // extended length high byte
  19093. frame += static_cast<char>(126); // extended length low byte
  19094. frame += std::string(126, 'x');
  19095. strm.write(frame.data(), frame.size());
  19096. ws::Opcode opcode;
  19097. std::string payload;
  19098. bool fin;
  19099. EXPECT_EQ(
  19100. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19101. ws::impl::FrameRead::Fail);
  19102. }
  19103. // Ping with FIN=1 and payload_len=125 - should succeed
  19104. {
  19105. detail::BufferStream strm;
  19106. std::string frame;
  19107. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19108. frame += static_cast<char>(125); // payload_len=125
  19109. frame += std::string(125, 'x');
  19110. strm.write(frame.data(), frame.size());
  19111. ws::Opcode opcode;
  19112. std::string payload;
  19113. bool fin;
  19114. EXPECT_EQ(
  19115. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19116. ws::impl::FrameRead::Ok);
  19117. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19118. EXPECT_EQ(125u, payload.size());
  19119. EXPECT_TRUE(fin);
  19120. }
  19121. }
  19122. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19123. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19124. // length MUST be 0.
  19125. // MSB set - must be rejected
  19126. {
  19127. detail::BufferStream strm;
  19128. std::string frame;
  19129. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19130. frame += static_cast<char>(127); // 64-bit extended length
  19131. frame += static_cast<char>(0x80); // MSB set (invalid)
  19132. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19133. strm.write(frame.data(), frame.size());
  19134. ws::Opcode opcode;
  19135. std::string payload;
  19136. bool fin;
  19137. EXPECT_EQ(
  19138. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19139. ws::impl::FrameRead::Fail);
  19140. }
  19141. // MSB clear - should pass length parsing (will be rejected by max_len,
  19142. // but that's a different check; use a small length to verify)
  19143. {
  19144. detail::BufferStream strm;
  19145. std::string frame;
  19146. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19147. frame += static_cast<char>(127); // 64-bit extended length
  19148. frame += std::string(7, '\0'); // high bytes = 0
  19149. frame += static_cast<char>(0x03); // length = 3
  19150. frame += "abc";
  19151. strm.write(frame.data(), frame.size());
  19152. ws::Opcode opcode;
  19153. std::string payload;
  19154. bool fin;
  19155. EXPECT_EQ(
  19156. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19157. ws::impl::FrameRead::Ok);
  19158. EXPECT_EQ(ws::Opcode::Text, opcode);
  19159. EXPECT_EQ("abc", payload);
  19160. }
  19161. }
  19162. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19163. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19164. // Valid UTF-8
  19165. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19166. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19167. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19168. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19169. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19170. // Invalid UTF-8
  19171. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19172. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19173. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19174. EXPECT_FALSE(
  19175. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19176. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19177. }
  19178. TEST(WebSocketTest, ConnectAndDisconnect) {
  19179. Server svr;
  19180. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19181. std::string msg;
  19182. while (ws.read(msg)) {}
  19183. });
  19184. auto port = svr.bind_to_any_port(HOST);
  19185. std::thread t([&]() { svr.listen_after_bind(); });
  19186. svr.wait_until_ready();
  19187. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19188. auto res = client.connect();
  19189. ASSERT_TRUE(res);
  19190. EXPECT_EQ(Error::Success, res.error());
  19191. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19192. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19193. EXPECT_TRUE(client.is_open());
  19194. client.close();
  19195. EXPECT_FALSE(client.is_open());
  19196. svr.stop();
  19197. t.join();
  19198. }
  19199. TEST(WebSocketTest, ValidURL) {
  19200. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19201. EXPECT_TRUE(ws1.is_valid());
  19202. ws::WebSocketClient ws2("ws://example.com/path");
  19203. EXPECT_TRUE(ws2.is_valid());
  19204. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19205. EXPECT_TRUE(ws3.is_valid());
  19206. #ifdef CPPHTTPLIB_SSL_ENABLED
  19207. ws::WebSocketClient wss1("wss://example.com/path");
  19208. EXPECT_TRUE(wss1.is_valid());
  19209. ws::WebSocketClient wss2("wss://example.com:443/path");
  19210. EXPECT_TRUE(wss2.is_valid());
  19211. #endif
  19212. }
  19213. TEST(WebSocketTest, InvalidURL) {
  19214. // No scheme
  19215. ws::WebSocketClient ws1("localhost:8080/path");
  19216. EXPECT_FALSE(ws1.is_valid());
  19217. // No path
  19218. ws::WebSocketClient ws2("ws://localhost:8080");
  19219. EXPECT_FALSE(ws2.is_valid());
  19220. // Empty string
  19221. ws::WebSocketClient ws3("");
  19222. EXPECT_FALSE(ws3.is_valid());
  19223. // Missing host
  19224. ws::WebSocketClient ws4("ws://:8080/path");
  19225. EXPECT_FALSE(ws4.is_valid());
  19226. // Port number overflow — should not crash
  19227. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19228. EXPECT_FALSE(ws5.is_valid());
  19229. // Port out of range
  19230. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19231. EXPECT_FALSE(ws6.is_valid());
  19232. }
  19233. TEST(WebSocketTest, UnsupportedScheme) {
  19234. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19235. ws::WebSocketClient ws1("http://localhost:8080/path");
  19236. EXPECT_FALSE(ws1.is_valid());
  19237. ws::WebSocketClient ws2("https://localhost:8080/path");
  19238. EXPECT_FALSE(ws2.is_valid());
  19239. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19240. EXPECT_FALSE(ws3.is_valid());
  19241. #else
  19242. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19243. std::invalid_argument);
  19244. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19245. std::invalid_argument);
  19246. #endif
  19247. }
  19248. TEST(WebSocketTest, ConnectWhenInvalid) {
  19249. ws::WebSocketClient ws("not a valid url");
  19250. EXPECT_FALSE(ws.is_valid());
  19251. auto res = ws.connect();
  19252. EXPECT_FALSE(res);
  19253. EXPECT_EQ(Error::Connection, res.error());
  19254. EXPECT_EQ(-1, res.status());
  19255. }
  19256. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19257. // Grab a port that is free, then close it again so nothing listens there
  19258. Server svr;
  19259. auto port = svr.bind_to_any_port(HOST);
  19260. svr.stop();
  19261. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19262. auto res = client.connect();
  19263. ASSERT_FALSE(res);
  19264. EXPECT_EQ(Error::Connection, res.error());
  19265. EXPECT_EQ(-1, res.status());
  19266. }
  19267. TEST(WebSocketTest, DefaultPort) {
  19268. ws::WebSocketClient ws1("ws://example.com/path");
  19269. EXPECT_TRUE(ws1.is_valid());
  19270. // ws:// defaults to port 80 (verified by successful parse)
  19271. #ifdef CPPHTTPLIB_SSL_ENABLED
  19272. ws::WebSocketClient ws2("wss://example.com/path");
  19273. EXPECT_TRUE(ws2.is_valid());
  19274. // wss:// defaults to port 443 (verified by successful parse)
  19275. #endif
  19276. }
  19277. TEST(WebSocketTest, IPv6LiteralAddress) {
  19278. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19279. EXPECT_TRUE(ws1.is_valid());
  19280. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19281. EXPECT_TRUE(ws2.is_valid());
  19282. }
  19283. TEST(WebSocketTest, ComplexPath) {
  19284. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19285. EXPECT_TRUE(ws1.is_valid());
  19286. ws::WebSocketClient ws2("ws://localhost:8080/");
  19287. EXPECT_TRUE(ws2.is_valid());
  19288. }
  19289. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19290. Server svr;
  19291. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19292. std::string msg;
  19293. while (ws.read(msg)) {}
  19294. });
  19295. auto port = svr.bind_to_any_port(HOST);
  19296. std::thread t([&]() { svr.listen_after_bind(); });
  19297. svr.wait_until_ready();
  19298. auto another_host = "example.com";
  19299. auto wrong_ip = "192.0.2.1";
  19300. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19301. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19302. ASSERT_TRUE(client.connect());
  19303. EXPECT_TRUE(client.is_open());
  19304. client.close();
  19305. svr.stop();
  19306. t.join();
  19307. }
  19308. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19309. Server svr;
  19310. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19311. std::string msg;
  19312. while (ws.read(msg)) {}
  19313. });
  19314. auto port = svr.bind_to_any_port(HOST);
  19315. std::thread t([&]() { svr.listen_after_bind(); });
  19316. svr.wait_until_ready();
  19317. auto wrong_ip = "192.0.2.1";
  19318. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19319. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19320. client.set_connection_timeout(1);
  19321. client.set_read_timeout(1);
  19322. client.set_write_timeout(1);
  19323. EXPECT_FALSE(client.connect());
  19324. EXPECT_FALSE(client.is_open());
  19325. svr.stop();
  19326. t.join();
  19327. }
  19328. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19329. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19330. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19331. // (RFC 6761) is only a map key and the Host header value.
  19332. auto host = "target.invalid";
  19333. Server svr;
  19334. std::string received_host;
  19335. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19336. received_host = req.get_header_value("Host");
  19337. std::string msg;
  19338. while (ws.read(msg)) {}
  19339. });
  19340. auto port = svr.bind_to_any_port(HOST);
  19341. std::thread t([&]() { svr.listen_after_bind(); });
  19342. // ASSERT_* below returns from the test body, which would leave t joinable
  19343. // and make ~thread call std::terminate.
  19344. auto se = detail::scope_exit([&] {
  19345. svr.stop();
  19346. if (t.joinable()) { t.join(); }
  19347. });
  19348. svr.wait_until_ready();
  19349. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19350. std::to_string(port) + "/ws");
  19351. client.set_hostname_addr_map({{host, HOST}});
  19352. ASSERT_TRUE(client.connect());
  19353. EXPECT_TRUE(client.is_open());
  19354. client.close();
  19355. svr.stop();
  19356. t.join();
  19357. // The mapping only redirects the connection; the identity stays host_.
  19358. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19359. }
  19360. class WebSocketIntegrationTest : public ::testing::Test {
  19361. protected:
  19362. void SetUp() override {
  19363. server_ = httplib::detail::make_unique<Server>();
  19364. setup_server();
  19365. start_server();
  19366. }
  19367. void TearDown() override {
  19368. server_->stop();
  19369. if (server_thread_.joinable()) { server_thread_.join(); }
  19370. }
  19371. void setup_server() {
  19372. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19373. std::string msg;
  19374. ws::ReadResult ret;
  19375. while ((ret = ws.read(msg))) {
  19376. if (ret == ws::Binary) {
  19377. ws.send(msg.data(), msg.size());
  19378. } else {
  19379. ws.send(msg);
  19380. }
  19381. }
  19382. });
  19383. server_->WebSocket("/ws-echo-string",
  19384. [](const Request &, ws::WebSocket &ws) {
  19385. std::string msg;
  19386. while (ws.read(msg)) {
  19387. ws.send("echo: " + msg);
  19388. }
  19389. });
  19390. server_->WebSocket(
  19391. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19392. // Echo back request metadata
  19393. ws.send("path:" + req.path);
  19394. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19395. std::string msg;
  19396. while (ws.read(msg)) {}
  19397. });
  19398. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19399. std::string msg;
  19400. ws.read(msg); // wait for a message
  19401. ws.close();
  19402. });
  19403. server_->WebSocket("/ws-close-status",
  19404. [](const Request &, ws::WebSocket &ws) {
  19405. std::string msg;
  19406. ws.read(msg); // wait for a message
  19407. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19408. });
  19409. server_->WebSocket(
  19410. "/ws-subprotocol",
  19411. [](const Request &, ws::WebSocket &ws) {
  19412. std::string msg;
  19413. while (ws.read(msg)) {
  19414. ws.send(msg);
  19415. }
  19416. },
  19417. [](const std::vector<std::string> &protocols) -> std::string {
  19418. for (const auto &p : protocols) {
  19419. if (p == "graphql-ws") { return p; }
  19420. }
  19421. return "";
  19422. });
  19423. }
  19424. void start_server() {
  19425. port_ = server_->bind_to_any_port(HOST);
  19426. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19427. server_->wait_until_ready();
  19428. }
  19429. std::unique_ptr<Server> server_;
  19430. std::thread server_thread_;
  19431. int port_ = 0;
  19432. };
  19433. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19434. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19435. "/ws-echo");
  19436. ASSERT_TRUE(client.connect());
  19437. ASSERT_TRUE(client.is_open());
  19438. ASSERT_TRUE(client.send("Hello WebSocket"));
  19439. std::string msg;
  19440. EXPECT_EQ(ws::Text, client.read(msg));
  19441. EXPECT_EQ("Hello WebSocket", msg);
  19442. client.close();
  19443. }
  19444. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19445. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19446. "/ws-echo");
  19447. ASSERT_TRUE(client.connect());
  19448. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19449. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19450. std::string msg;
  19451. EXPECT_EQ(ws::Binary, client.read(msg));
  19452. EXPECT_EQ(binary_data, msg);
  19453. client.close();
  19454. }
  19455. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19457. "/ws-echo");
  19458. ASSERT_TRUE(client.connect());
  19459. for (int i = 0; i < 10; i++) {
  19460. auto text = "message " + std::to_string(i);
  19461. ASSERT_TRUE(client.send(text));
  19462. std::string msg;
  19463. ASSERT_TRUE(client.read(msg));
  19464. EXPECT_EQ(text, msg);
  19465. }
  19466. client.close();
  19467. }
  19468. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19469. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19470. "/ws-close");
  19471. ASSERT_TRUE(client.connect());
  19472. // Send a message to trigger the server to close
  19473. ASSERT_TRUE(client.send("trigger close"));
  19474. // The server will close, so read should return false
  19475. std::string msg;
  19476. EXPECT_FALSE(client.read(msg));
  19477. EXPECT_FALSE(client.is_open());
  19478. }
  19479. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19480. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19481. "/ws-echo");
  19482. ASSERT_TRUE(client.connect());
  19483. // 128KB message
  19484. std::string large_data(128 * 1024, 'X');
  19485. ASSERT_TRUE(client.send(large_data));
  19486. std::string msg;
  19487. ASSERT_TRUE(client.read(msg));
  19488. EXPECT_EQ(large_data, msg);
  19489. client.close();
  19490. }
  19491. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19492. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19493. "/ws-echo");
  19494. ASSERT_TRUE(client.connect());
  19495. const int num_threads = 4;
  19496. std::vector<std::thread> threads;
  19497. std::atomic<int> send_count{0};
  19498. for (int t = 0; t < num_threads; t++) {
  19499. threads.emplace_back([&client, &send_count, t]() {
  19500. for (int i = 0; i < 5; i++) {
  19501. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19502. if (client.send(text)) { send_count++; }
  19503. }
  19504. });
  19505. }
  19506. for (auto &th : threads) {
  19507. th.join();
  19508. }
  19509. int received = 0;
  19510. std::string msg;
  19511. while (received < send_count.load()) {
  19512. if (!client.read(msg)) { break; }
  19513. received++;
  19514. }
  19515. EXPECT_EQ(send_count.load(), received);
  19516. client.close();
  19517. }
  19518. TEST_F(WebSocketIntegrationTest, ReadString) {
  19519. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19520. "/ws-echo-string");
  19521. ASSERT_TRUE(client.connect());
  19522. ASSERT_TRUE(client.send("hello"));
  19523. std::string msg;
  19524. ASSERT_TRUE(client.read(msg));
  19525. EXPECT_EQ("echo: hello", msg);
  19526. ASSERT_TRUE(client.send("world"));
  19527. ASSERT_TRUE(client.read(msg));
  19528. EXPECT_EQ("echo: world", msg);
  19529. client.close();
  19530. }
  19531. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19532. Headers headers = {{"X-Test-Header", "test-value"}};
  19533. ws::WebSocketClient client(
  19534. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19535. ASSERT_TRUE(client.connect());
  19536. std::string msg;
  19537. ASSERT_TRUE(client.read(msg));
  19538. EXPECT_EQ("path:/ws-request-info", msg);
  19539. ASSERT_TRUE(client.read(msg));
  19540. EXPECT_EQ("header:test-value", msg);
  19541. client.close();
  19542. }
  19543. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19544. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19545. "/ws-echo");
  19546. client.set_read_timeout(1, 0); // 1 second
  19547. ASSERT_TRUE(client.connect());
  19548. // Don't send anything — server echo handler waits for a message, so read()
  19549. // should time out. The connection survives it: nothing was consumed.
  19550. std::string msg;
  19551. EXPECT_EQ(client.read(msg), ws::Timeout);
  19552. EXPECT_TRUE(client.is_open());
  19553. // And it is still usable afterwards.
  19554. EXPECT_TRUE(client.send("after timeout"));
  19555. EXPECT_EQ(client.read(msg), ws::Text);
  19556. EXPECT_EQ(msg, "after timeout");
  19557. }
  19558. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19559. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19560. "/ws-echo");
  19561. client.set_read_timeout(1, 0);
  19562. ASSERT_TRUE(client.connect());
  19563. ASSERT_TRUE(client.send("first"));
  19564. std::string msg;
  19565. ASSERT_EQ(client.read(msg), ws::Text);
  19566. ASSERT_EQ(msg, "first");
  19567. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19568. // not be used with a read timeout: it would reprocess the previous message.
  19569. EXPECT_EQ(client.read(msg), ws::Timeout);
  19570. EXPECT_EQ(msg, "first");
  19571. }
  19572. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19573. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19574. "/ws-echo");
  19575. ASSERT_TRUE(client.connect());
  19576. // Setting it once the connection is open reaches the live stream, not just
  19577. // the seed for the next connect().
  19578. client.set_read_timeout(1, 0);
  19579. std::string msg;
  19580. EXPECT_EQ(client.read(msg), ws::Timeout);
  19581. EXPECT_TRUE(client.is_open());
  19582. }
  19583. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19584. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19585. "/ws-echo");
  19586. client.set_read_timeout(5, 0);
  19587. ASSERT_TRUE(client.connect());
  19588. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19589. // The server should reject it and close the connection.
  19590. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19591. client.send(oversized);
  19592. // The server's read() should have failed due to payload limit,
  19593. // so our read() should return false (connection closed).
  19594. std::string msg;
  19595. EXPECT_FALSE(client.read(msg));
  19596. }
  19597. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19598. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19599. "/ws-echo");
  19600. client.set_read_timeout(10, 0);
  19601. ASSERT_TRUE(client.connect());
  19602. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19603. // This should succeed.
  19604. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19605. ASSERT_TRUE(client.send(at_limit));
  19606. std::string msg;
  19607. ASSERT_TRUE(client.read(msg));
  19608. EXPECT_EQ(at_limit.size(), msg.size());
  19609. client.close();
  19610. }
  19611. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19613. "/nonexistent");
  19614. auto res = client.connect();
  19615. EXPECT_FALSE(res);
  19616. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19617. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19618. EXPECT_FALSE(client.is_open());
  19619. }
  19620. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19621. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19622. "/ws-echo");
  19623. ASSERT_TRUE(client.connect());
  19624. ASSERT_TRUE(client.send(""));
  19625. std::string msg;
  19626. EXPECT_EQ(ws::Text, client.read(msg));
  19627. EXPECT_EQ("", msg);
  19628. client.close();
  19629. }
  19630. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19631. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19632. "/ws-echo");
  19633. // First connection
  19634. ASSERT_TRUE(client.connect());
  19635. ASSERT_TRUE(client.send("first"));
  19636. std::string msg;
  19637. ASSERT_TRUE(client.read(msg));
  19638. EXPECT_EQ("first", msg);
  19639. client.close();
  19640. EXPECT_FALSE(client.is_open());
  19641. // Reconnect using the same client object
  19642. ASSERT_TRUE(client.connect());
  19643. ASSERT_TRUE(client.is_open());
  19644. ASSERT_TRUE(client.send("second"));
  19645. ASSERT_TRUE(client.read(msg));
  19646. EXPECT_EQ("second", msg);
  19647. client.close();
  19648. }
  19649. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19650. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19651. "/ws-close-status");
  19652. ASSERT_TRUE(client.connect());
  19653. // Trigger the server to close with GoingAway status
  19654. ASSERT_TRUE(client.send("trigger"));
  19655. // read() should return false after receiving the close frame
  19656. std::string msg;
  19657. EXPECT_FALSE(client.read(msg));
  19658. EXPECT_FALSE(client.is_open());
  19659. }
  19660. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19661. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19662. "/ws-echo");
  19663. ASSERT_TRUE(client.connect());
  19664. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19665. EXPECT_FALSE(client.is_open());
  19666. }
  19667. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19668. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19669. ws::WebSocketClient client(
  19670. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19671. ASSERT_TRUE(client.connect());
  19672. // Server should have selected graphql-ws
  19673. EXPECT_EQ("graphql-ws", client.subprotocol());
  19674. client.close();
  19675. }
  19676. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19677. Headers headers;
  19678. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19679. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19680. ws::WebSocketClient client(
  19681. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19682. ASSERT_TRUE(client.connect());
  19683. // The offer on the second field line counts too, so graphql-ws is selected
  19684. EXPECT_EQ("graphql-ws", client.subprotocol());
  19685. client.close();
  19686. }
  19687. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19688. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19689. ws::WebSocketClient client(
  19690. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19691. ASSERT_TRUE(client.connect());
  19692. // Server should not have selected any subprotocol
  19693. EXPECT_TRUE(client.subprotocol().empty());
  19694. client.close();
  19695. }
  19696. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19697. // Connect without requesting any subprotocol
  19698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19699. "/ws-subprotocol");
  19700. ASSERT_TRUE(client.connect());
  19701. EXPECT_TRUE(client.subprotocol().empty());
  19702. client.close();
  19703. }
  19704. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19705. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19706. "/ws-echo");
  19707. client.set_tcp_nodelay(true);
  19708. client.set_connection_timeout(3, 0);
  19709. bool socket_options_called = false;
  19710. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19711. ASSERT_TRUE(client.connect());
  19712. ASSERT_TRUE(client.is_open());
  19713. EXPECT_TRUE(socket_options_called);
  19714. ASSERT_TRUE(client.send("hello"));
  19715. std::string msg;
  19716. auto result = client.read(msg);
  19717. EXPECT_EQ(result, ws::ReadResult::Text);
  19718. EXPECT_EQ(msg, "hello");
  19719. client.close();
  19720. }
  19721. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  19722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19723. "/ws-echo");
  19724. client.set_connection_timeout(std::chrono::seconds(3));
  19725. client.set_write_timeout(std::chrono::seconds(3));
  19726. // A sub-second remainder exercises the seconds/microseconds split.
  19727. client.set_read_timeout(std::chrono::milliseconds(1500));
  19728. ASSERT_TRUE(client.connect());
  19729. auto start = std::chrono::steady_clock::now();
  19730. std::string msg;
  19731. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  19732. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19733. std::chrono::steady_clock::now() - start)
  19734. .count();
  19735. // Above 1s so that dropping the microseconds half of the split fails here.
  19736. // Ignoring the setter altogether would not reach this line at all: a client
  19737. // waits forever by default.
  19738. EXPECT_GE(elapsed, 1400);
  19739. EXPECT_LT(elapsed, 30000);
  19740. }
  19741. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  19742. Server svr;
  19743. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  19744. if (!req.has_header("Authorization")) {
  19745. res.status = StatusCode::Unauthorized_401;
  19746. res.set_content("Unauthorized", "text/plain");
  19747. return Server::HandlerResponse::Handled;
  19748. }
  19749. return Server::HandlerResponse::Unhandled;
  19750. });
  19751. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19752. std::string msg;
  19753. while (ws.read(msg)) {
  19754. ws.send(msg);
  19755. }
  19756. });
  19757. auto port = svr.bind_to_any_port("localhost");
  19758. std::thread t([&]() { svr.listen_after_bind(); });
  19759. svr.wait_until_ready();
  19760. // Without Authorization header - should be rejected before upgrade
  19761. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  19762. EXPECT_FALSE(client1.connect());
  19763. // The rejection is framed like any other HTTP response
  19764. {
  19765. Client cli("localhost", port);
  19766. Headers headers = {{"Upgrade", "websocket"},
  19767. {"Connection", "Upgrade"},
  19768. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19769. {"Sec-WebSocket-Version", "13"}};
  19770. auto res = cli.Get("/ws", headers);
  19771. ASSERT_TRUE(res);
  19772. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19773. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  19774. EXPECT_EQ("Unauthorized", res->body);
  19775. }
  19776. // With Authorization header - should succeed
  19777. Headers headers = {{"Authorization", "Bearer token123"}};
  19778. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  19779. headers);
  19780. ASSERT_TRUE(client2.connect());
  19781. ASSERT_TRUE(client2.send("hello"));
  19782. std::string msg;
  19783. ASSERT_TRUE(client2.read(msg));
  19784. EXPECT_EQ("hello", msg);
  19785. client2.close();
  19786. svr.stop();
  19787. t.join();
  19788. }
  19789. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  19790. Server svr;
  19791. std::atomic<int> pre_request_calls{0};
  19792. std::atomic<bool> route_matched{false};
  19793. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  19794. pre_request_calls++;
  19795. if (req.matched_route == "/ws/:id") { route_matched = true; }
  19796. if (req.get_header_value("Authorization") != "Bearer token123") {
  19797. res.status = StatusCode::Unauthorized_401;
  19798. res.set_content("Unauthorized", "text/plain");
  19799. return Server::HandlerResponse::Handled;
  19800. }
  19801. return Server::HandlerResponse::Unhandled;
  19802. });
  19803. std::atomic<bool> handler_called{false};
  19804. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  19805. handler_called = true;
  19806. ws.send(req.matched_route + " " + req.path_params.at("id"));
  19807. });
  19808. auto port = svr.bind_to_any_port("localhost");
  19809. std::thread t([&]() { svr.listen_after_bind(); });
  19810. svr.wait_until_ready();
  19811. // Without Authorization header - should be rejected before upgrade
  19812. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  19813. "/ws/1");
  19814. EXPECT_FALSE(client1.connect());
  19815. EXPECT_FALSE(handler_called);
  19816. EXPECT_EQ(1, pre_request_calls);
  19817. EXPECT_TRUE(route_matched);
  19818. // The rejection is an ordinary HTTP response, not a protocol switch
  19819. {
  19820. Client cli("localhost", port);
  19821. Headers headers = {{"Upgrade", "websocket"},
  19822. {"Connection", "Upgrade"},
  19823. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19824. {"Sec-WebSocket-Version", "13"}};
  19825. auto res = cli.Get("/ws/1", headers);
  19826. ASSERT_TRUE(res);
  19827. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19828. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  19829. EXPECT_EQ("Unauthorized", res->body);
  19830. }
  19831. EXPECT_FALSE(handler_called);
  19832. // With Authorization header - should succeed
  19833. Headers headers = {{"Authorization", "Bearer token123"}};
  19834. ws::WebSocketClient client2(
  19835. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  19836. ASSERT_TRUE(client2.connect());
  19837. std::string msg;
  19838. ASSERT_TRUE(client2.read(msg));
  19839. EXPECT_EQ("/ws/:id 2", msg);
  19840. EXPECT_TRUE(handler_called);
  19841. client2.close();
  19842. svr.stop();
  19843. t.join();
  19844. }
  19845. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  19846. Server svr;
  19847. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19848. // A read timeout is how a handler gets control back. Without it, a handler
  19849. // parked in read() can never write on the connection it is reading.
  19850. ws.set_read_timeout(std::chrono::milliseconds(100));
  19851. std::string msg;
  19852. while (ws.is_open()) {
  19853. auto r = ws.read(msg);
  19854. if (r == httplib::ws::Timeout) {
  19855. ws.send("tick");
  19856. continue;
  19857. }
  19858. if (r == httplib::ws::Fail) { break; }
  19859. ws.send(msg);
  19860. }
  19861. });
  19862. auto port = svr.bind_to_any_port("localhost");
  19863. std::thread t([&]() { svr.listen_after_bind(); });
  19864. svr.wait_until_ready();
  19865. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19866. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  19867. ASSERT_TRUE(client.connect());
  19868. // The client sends nothing, so anything it receives came out of the
  19869. // handler's timeout path.
  19870. std::string msg;
  19871. ASSERT_EQ(client.read(msg), ws::Text);
  19872. EXPECT_EQ("tick", msg);
  19873. client.close();
  19874. svr.stop();
  19875. t.join();
  19876. }
  19877. // Stream::read may return fewer bytes than asked for. This is that contract at
  19878. // its worst -- one byte per call -- which is what a frame header straddling a
  19879. // read buffer's boundary looks like to the frame parser.
  19880. class WsByteAtATimeStream : public Stream {
  19881. public:
  19882. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  19883. bool is_readable() const override { return true; }
  19884. bool wait_readable() const override { return true; }
  19885. bool wait_writable() const override { return true; }
  19886. ssize_t read(char *ptr, size_t size) override {
  19887. if (size == 0 || pos_ >= data_.size()) { return 0; }
  19888. *ptr = data_[pos_++];
  19889. return 1;
  19890. }
  19891. ssize_t write(const char *, size_t size) override {
  19892. return static_cast<ssize_t>(size);
  19893. }
  19894. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19895. ip = "127.0.0.1";
  19896. port = 0;
  19897. }
  19898. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19899. ip = "127.0.0.1";
  19900. port = 0;
  19901. }
  19902. socket_t socket() const override { return INVALID_SOCKET; }
  19903. time_t duration() const override { return 0; }
  19904. private:
  19905. std::string data_;
  19906. size_t pos_ = 0;
  19907. };
  19908. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  19909. // A 200-byte payload uses the 16-bit extended length, so the header, the
  19910. // length and the mask key are all multi-byte fields here. Each used to be
  19911. // read with a single read() call, which fails as soon as one is split.
  19912. std::string body(200, 'x');
  19913. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  19914. std::string frame;
  19915. frame += static_cast<char>(0x81); // FIN + Text
  19916. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  19917. frame += static_cast<char>(body.size() >> 8);
  19918. frame += static_cast<char>(body.size() & 0xff);
  19919. for (size_t i = 0; i < 4; i++) {
  19920. frame += static_cast<char>(mask[i]);
  19921. }
  19922. for (size_t i = 0; i < body.size(); i++) {
  19923. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  19924. }
  19925. WsByteAtATimeStream strm(frame);
  19926. ws::Opcode opcode;
  19927. std::string payload;
  19928. bool fin = false;
  19929. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  19930. /*expect_masked=*/true, 1024),
  19931. ws::impl::FrameRead::Ok);
  19932. EXPECT_TRUE(fin);
  19933. EXPECT_EQ(opcode, ws::Opcode::Text);
  19934. EXPECT_EQ(payload, body);
  19935. }
  19936. TEST(WebSocketTest, QueryStringInHandshake) {
  19937. Server svr;
  19938. std::mutex mtx;
  19939. std::string received_target;
  19940. std::string received_token;
  19941. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19942. {
  19943. std::lock_guard<std::mutex> lock(mtx);
  19944. received_target = req.target;
  19945. if (req.has_param("token")) {
  19946. received_token = req.get_param_value("token");
  19947. }
  19948. }
  19949. std::string msg;
  19950. while (ws.read(msg)) {
  19951. ws.send(msg);
  19952. }
  19953. });
  19954. auto port = svr.bind_to_any_port("localhost");
  19955. std::thread t([&]() { svr.listen_after_bind(); });
  19956. svr.wait_until_ready();
  19957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  19958. "/ws?token=ABC&session=123");
  19959. ASSERT_TRUE(client.connect());
  19960. // Round-trip ensures the handler has run and captured the request.
  19961. ASSERT_TRUE(client.send("hello"));
  19962. std::string msg;
  19963. ASSERT_TRUE(client.read(msg));
  19964. EXPECT_EQ("hello", msg);
  19965. client.close();
  19966. {
  19967. std::lock_guard<std::mutex> lock(mtx);
  19968. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  19969. EXPECT_EQ("ABC", received_token);
  19970. }
  19971. svr.stop();
  19972. t.join();
  19973. }
  19974. // Run a handshake against a throwaway server and hand the request the server
  19975. // received back to the caller, so tests can assert on the headers the client
  19976. // actually put on the wire.
  19977. static void capture_websocket_handshake_request(
  19978. const Headers &client_headers,
  19979. std::function<void(const Request &, int port)> verify) {
  19980. Server svr;
  19981. std::mutex mtx;
  19982. Request received;
  19983. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19984. {
  19985. std::lock_guard<std::mutex> lock(mtx);
  19986. received = req;
  19987. }
  19988. std::string msg;
  19989. while (ws.read(msg)) {
  19990. ws.send(msg);
  19991. }
  19992. });
  19993. auto port = svr.bind_to_any_port("localhost");
  19994. std::thread t([&]() { svr.listen_after_bind(); });
  19995. auto se = detail::scope_exit([&] {
  19996. svr.stop();
  19997. t.join();
  19998. });
  19999. svr.wait_until_ready();
  20000. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20001. client_headers);
  20002. ASSERT_TRUE(client.connect());
  20003. ASSERT_TRUE(client.send("hello"));
  20004. std::string msg;
  20005. ASSERT_TRUE(client.read(msg));
  20006. client.close();
  20007. {
  20008. std::lock_guard<std::mutex> lock(mtx);
  20009. verify(received, port);
  20010. }
  20011. }
  20012. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20013. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20014. // Non-default port must be present in the Host header. Default ports
  20015. // (80/443) are omitted; that logic is covered by
  20016. // MakeHostAndPortStringTest.
  20017. EXPECT_EQ("localhost:" + std::to_string(port),
  20018. req.get_header_value("Host"));
  20019. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20020. req.get_header_value("User-Agent"));
  20021. EXPECT_FALSE(req.has_header("Accept"));
  20022. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20023. EXPECT_FALSE(req.has_header("Content-Length"));
  20024. });
  20025. }
  20026. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20027. capture_websocket_handshake_request(
  20028. {{"Host", "example.com"},
  20029. {"User-Agent", "custom-agent"},
  20030. {"X-Custom", "value"}},
  20031. [](const Request &req, int) {
  20032. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20033. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20034. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20035. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20036. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20037. });
  20038. }
  20039. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20040. capture_websocket_handshake_request(
  20041. {{"Upgrade", "bogus"},
  20042. {"Connection", "close"},
  20043. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20044. {"Sec-WebSocket-Version", "8"}},
  20045. [](const Request &req, int) {
  20046. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20047. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20048. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20049. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20050. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20051. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20052. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20053. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20054. req.get_header_value("Sec-WebSocket-Key"));
  20055. });
  20056. }
  20057. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20058. // A header the client refuses to send must abort the handshake before any
  20059. // part of it reaches the wire; a lone request line would otherwise sit in
  20060. // the peer's buffer as a truncated request.
  20061. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20062. ASSERT_NE(INVALID_SOCKET, srv);
  20063. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20064. sockaddr_in addr{};
  20065. addr.sin_family = AF_INET;
  20066. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20067. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20068. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20069. ASSERT_EQ(0, ::listen(srv, 1));
  20070. sockaddr_in bound{};
  20071. socklen_t bound_len = sizeof(bound);
  20072. ASSERT_EQ(
  20073. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20074. auto port = ntohs(bound.sin_port);
  20075. ssize_t received = -1;
  20076. std::thread t([&] {
  20077. // Bound every blocking call so a regression fails the test with a bad
  20078. // value instead of hanging the suite.
  20079. fd_set rfds;
  20080. FD_ZERO(&rfds);
  20081. FD_SET(srv, &rfds);
  20082. timeval tv{5, 0};
  20083. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20084. 0) {
  20085. return;
  20086. }
  20087. sockaddr_in cli_addr{};
  20088. socklen_t cli_len = sizeof(cli_addr);
  20089. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20090. if (cli == INVALID_SOCKET) { return; }
  20091. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20092. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20093. char buf[4096];
  20094. received = ::recv(cli, buf, sizeof(buf), 0);
  20095. });
  20096. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20097. // connect() has already shut the socket down by the time it returns false,
  20098. // so the peer sees EOF without waiting for the client to be destroyed.
  20099. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20100. {{"X-Bad", "a\r\nInjected: 1"}});
  20101. EXPECT_FALSE(client.connect());
  20102. t.join();
  20103. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20104. EXPECT_EQ(0, received);
  20105. }
  20106. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20107. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20108. // contains "upgrade" as a substring is a different token and must not
  20109. // start a WebSocket handshake.
  20110. auto make_request = [](const std::vector<std::string> &connection_values) {
  20111. Request req;
  20112. req.method = "GET";
  20113. req.headers.emplace("Upgrade", "websocket");
  20114. for (const auto &value : connection_values) {
  20115. req.headers.emplace("Connection", value);
  20116. }
  20117. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20118. req.headers.emplace("Sec-WebSocket-Version", "13");
  20119. return req;
  20120. };
  20121. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20122. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20123. EXPECT_TRUE(
  20124. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20125. EXPECT_TRUE(
  20126. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20127. EXPECT_TRUE(
  20128. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20129. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20130. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20131. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20132. EXPECT_FALSE(
  20133. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20134. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20135. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20136. }
  20137. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20138. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20139. // asks recipients to match each protocol-name case-insensitively, and RFC
  20140. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20141. // client naming websocket alongside another protocol, or on a second field
  20142. // line, is offering websocket; a value that merely contains "websocket" as a
  20143. // substring is a different protocol name and is not.
  20144. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20145. Request req;
  20146. req.method = "GET";
  20147. for (const auto &value : upgrade_values) {
  20148. req.headers.emplace("Upgrade", value);
  20149. }
  20150. req.headers.emplace("Connection", "Upgrade");
  20151. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20152. req.headers.emplace("Sec-WebSocket-Version", "13");
  20153. return req;
  20154. };
  20155. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20156. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20157. EXPECT_TRUE(
  20158. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20159. EXPECT_TRUE(
  20160. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20161. EXPECT_TRUE(
  20162. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20163. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20164. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20165. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20166. EXPECT_FALSE(
  20167. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20168. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20169. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20170. }
  20171. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20172. Server svr;
  20173. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20174. auto port = svr.bind_to_any_port("localhost");
  20175. std::thread t([&]() { svr.listen_after_bind(); });
  20176. auto se = detail::scope_exit([&] {
  20177. svr.stop();
  20178. t.join();
  20179. });
  20180. svr.wait_until_ready();
  20181. Headers headers = {{"Upgrade", "websocket"},
  20182. {"Connection", "notupgrade"},
  20183. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20184. {"Sec-WebSocket-Version", "13"}};
  20185. Client cli("localhost", port);
  20186. auto res = cli.Get("/ws", headers);
  20187. // The route exists only as a WebSocket route, so a request that fails the
  20188. // handshake check falls through to ordinary routing.
  20189. ASSERT_TRUE(res);
  20190. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20191. }
  20192. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20193. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20194. // Connection value is the only thing left for the client to reject.
  20195. Server svr;
  20196. svr.Get("/ws", [](const Request &req, Response &res) {
  20197. res.status = StatusCode::SwitchingProtocol_101;
  20198. res.set_header("Upgrade", "websocket");
  20199. res.set_header("Connection", "notupgrade");
  20200. res.set_header("Sec-WebSocket-Accept",
  20201. detail::websocket_accept_key(
  20202. req.get_header_value("Sec-WebSocket-Key")));
  20203. });
  20204. auto port = svr.bind_to_any_port("localhost");
  20205. std::thread t([&]() { svr.listen_after_bind(); });
  20206. auto se = detail::scope_exit([&] {
  20207. svr.stop();
  20208. t.join();
  20209. });
  20210. svr.wait_until_ready();
  20211. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20212. auto res = client.connect();
  20213. EXPECT_FALSE(res);
  20214. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20215. EXPECT_FALSE(client.is_open());
  20216. }
  20217. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20218. // The socket path doubles as the URL host, so it must not contain '/'.
  20219. const char *shard = getenv("GTEST_SHARD_INDEX");
  20220. const std::string sock_path =
  20221. shard ? std::string("httplib-ws-") + shard + ".sock"
  20222. : std::string("httplib-ws.sock");
  20223. std::remove(sock_path.c_str());
  20224. Server svr;
  20225. std::mutex mtx;
  20226. std::string received_host;
  20227. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20228. {
  20229. std::lock_guard<std::mutex> lock(mtx);
  20230. received_host = req.get_header_value("Host");
  20231. }
  20232. std::string msg;
  20233. while (ws.read(msg)) {
  20234. ws.send(msg);
  20235. }
  20236. });
  20237. svr.set_address_family(AF_UNIX);
  20238. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20239. auto se = detail::scope_exit([&] {
  20240. svr.stop();
  20241. t.join();
  20242. std::remove(sock_path.c_str());
  20243. });
  20244. svr.wait_until_ready();
  20245. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20246. client.set_address_family(AF_UNIX);
  20247. ASSERT_TRUE(client.connect());
  20248. ASSERT_TRUE(client.send("hello"));
  20249. std::string msg;
  20250. ASSERT_TRUE(client.read(msg));
  20251. client.close();
  20252. {
  20253. std::lock_guard<std::mutex> lock(mtx);
  20254. // There is no host:port for a Unix socket, so the same "localhost"
  20255. // placeholder the HTTP client uses is expected.
  20256. EXPECT_EQ("localhost", received_host);
  20257. }
  20258. }
  20259. // Two threads must never parse WebSocket frames from the same stream.
  20260. // close() used to read the peer's Close reply with its own frame read, so it
  20261. // raced a reader thread that was in the middle of a payload: the payload loop
  20262. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20263. // so bytes taken by close() were replaced with bytes from further along the
  20264. // stream. The message kept its length and silently changed content.
  20265. //
  20266. // The raw peer below sends a frame header plus part of the payload, waits for
  20267. // the handler to call close(), and only then sends the rest. Whichever thread
  20268. // would win the race for those bytes, the message must arrive intact, because
  20269. // close() must not touch the stream while read() owns it.
  20270. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20271. #ifndef _WIN32
  20272. signal(SIGPIPE, SIG_IGN);
  20273. #endif
  20274. const size_t payload_len = 120; // fits the 7-bit length field
  20275. const size_t prefix_len = 8;
  20276. const int attempts = 8;
  20277. std::string expected(payload_len, '\0');
  20278. for (size_t i = 0; i < payload_len; i++) {
  20279. expected[i] = static_cast<char>('a' + i % 26);
  20280. }
  20281. std::atomic<bool> peer_stalled{false};
  20282. std::atomic<bool> handler_done{false};
  20283. std::mutex received_mutex;
  20284. std::vector<std::string> received;
  20285. // Bound every wait, so a regression fails the test instead of hanging the
  20286. // suite.
  20287. auto wait_for = [](const std::atomic<bool> &flag) {
  20288. for (int i = 0; i < 500 && !flag; i++) {
  20289. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20290. }
  20291. };
  20292. Server svr;
  20293. svr.set_websocket_ping_interval(0);
  20294. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20295. std::thread reader([&]() {
  20296. std::string msg;
  20297. while (ws.read(msg)) {
  20298. std::lock_guard<std::mutex> guard(received_mutex);
  20299. received.push_back(msg);
  20300. }
  20301. });
  20302. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20303. // inside read_websocket_frame() when close() runs.
  20304. wait_for(peer_stalled);
  20305. ws.close();
  20306. reader.join();
  20307. handler_done = true;
  20308. });
  20309. auto port = svr.bind_to_any_port("127.0.0.1");
  20310. std::thread t([&]() { svr.listen_after_bind(); });
  20311. auto se = detail::scope_exit([&] {
  20312. svr.stop();
  20313. t.join();
  20314. });
  20315. svr.wait_until_ready();
  20316. auto send_bytes = [](socket_t s, const std::string &data) {
  20317. #ifdef _WIN32
  20318. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20319. #else
  20320. auto n = ::send(s, data.data(), data.size(), 0);
  20321. #endif
  20322. return n == static_cast<decltype(n)>(data.size());
  20323. };
  20324. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20325. // Every length used here fits the 7-bit length field.
  20326. auto masked_header = [](uint8_t first_byte, size_t len) {
  20327. std::string h;
  20328. h += static_cast<char>(first_byte);
  20329. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20330. h.append(4, '\0'); // mask key
  20331. return h;
  20332. };
  20333. for (int attempt = 0; attempt < attempts; attempt++) {
  20334. peer_stalled = false;
  20335. handler_done = false;
  20336. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20337. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20338. auto se_sock = detail::scope_exit([&] {
  20339. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20340. });
  20341. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20342. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20343. sockaddr_in addr{};
  20344. addr.sin_family = AF_INET;
  20345. addr.sin_port = htons(static_cast<uint16_t>(port));
  20346. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20347. ASSERT_EQ(
  20348. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20349. << "attempt " << attempt;
  20350. ASSERT_TRUE(send_bytes(sock,
  20351. "GET /ws HTTP/1.1\r\n"
  20352. "Host: 127.0.0.1\r\n"
  20353. "Upgrade: websocket\r\n"
  20354. "Connection: Upgrade\r\n"
  20355. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20356. "Sec-WebSocket-Version: 13\r\n"
  20357. "\r\n"))
  20358. << "attempt " << attempt;
  20359. std::string response;
  20360. while (response.find("\r\n\r\n") == std::string::npos) {
  20361. char buf[512];
  20362. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20363. if (n <= 0) { break; }
  20364. response.append(buf, static_cast<size_t>(n));
  20365. }
  20366. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20367. << "attempt " << attempt;
  20368. // Send the header of a Binary message but only the first prefix_len bytes
  20369. // of its payload, leaving the reader thread stalled inside the payload.
  20370. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20371. expected.substr(0, prefix_len)))
  20372. << "attempt " << attempt;
  20373. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20374. peer_stalled = true;
  20375. // Let close() send its Close frame and park in its own read before the
  20376. // rest of the payload arrives, so both threads are waiting for it.
  20377. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20378. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20379. close_frame += static_cast<char>(0x03); // status 1000
  20380. close_frame += static_cast<char>(0xE8);
  20381. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20382. << "attempt " << attempt;
  20383. // Closing the peer releases the reader thread even on the buggy path,
  20384. // where it waits for bytes another thread already consumed.
  20385. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20386. detail::close_socket(sock);
  20387. sock = INVALID_SOCKET;
  20388. wait_for(handler_done);
  20389. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20390. }
  20391. std::lock_guard<std::mutex> guard(received_mutex);
  20392. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20393. << "a message in flight when close() ran was dropped";
  20394. for (size_t i = 0; i < received.size(); i++) {
  20395. EXPECT_EQ(expected, received[i]) << "message " << i;
  20396. }
  20397. }
  20398. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20399. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20400. protected:
  20401. void SetUp() override {
  20402. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20403. SERVER_PRIVATE_KEY_FILE);
  20404. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20405. std::string msg;
  20406. ws::ReadResult ret;
  20407. while ((ret = ws.read(msg))) {
  20408. if (ret == ws::Binary) {
  20409. ws.send(msg.data(), msg.size());
  20410. } else {
  20411. ws.send(msg);
  20412. }
  20413. }
  20414. });
  20415. port_ = server_->bind_to_any_port(HOST);
  20416. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20417. server_->wait_until_ready();
  20418. }
  20419. void TearDown() override {
  20420. server_->stop();
  20421. if (server_thread_.joinable()) { server_thread_.join(); }
  20422. }
  20423. std::unique_ptr<SSLServer> server_;
  20424. std::thread server_thread_;
  20425. int port_ = 0;
  20426. };
  20427. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20428. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20429. "/ws-echo");
  20430. client.enable_server_certificate_verification(false);
  20431. ASSERT_TRUE(client.connect());
  20432. ASSERT_TRUE(client.is_open());
  20433. ASSERT_TRUE(client.send("Hello WSS"));
  20434. std::string msg;
  20435. EXPECT_EQ(ws::Text, client.read(msg));
  20436. EXPECT_EQ("Hello WSS", msg);
  20437. client.close();
  20438. }
  20439. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20440. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20441. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20442. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20443. // client (without calling close() first) is the only path that runs
  20444. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20445. // bug exactly.
  20446. //
  20447. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20448. // when linked against an instrumented libssl; run under Valgrind to catch it
  20449. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20450. // suite (the freed session otherwise stalls on the close handshake) — this test
  20451. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20452. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20453. {
  20454. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20455. "/ws-echo");
  20456. client.enable_server_certificate_verification(false);
  20457. client.set_read_timeout(2, 0);
  20458. client.set_write_timeout(2, 0);
  20459. ASSERT_TRUE(client.connect());
  20460. ASSERT_TRUE(client.is_open());
  20461. ASSERT_TRUE(client.send("still open"));
  20462. // Intentionally do NOT call client.close(): leaving scope runs
  20463. // shutdown_and_close() with the WebSocket still open, which must send the
  20464. // close frame while the TLS session is still alive.
  20465. }
  20466. }
  20467. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20468. // shutdown_and_close() at the start of connect(), reproducing the same
  20469. // use-after-free within the test body rather than at scope exit. The second
  20470. // connect must succeed and echo, proving the close handshake ran over a live
  20471. // session. See the note above about memory-tool requirements.
  20472. TEST_F(WebSocketSSLIntegrationTest,
  20473. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20474. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20475. "/ws-echo");
  20476. client.enable_server_certificate_verification(false);
  20477. client.set_read_timeout(2, 0);
  20478. client.set_write_timeout(2, 0);
  20479. ASSERT_TRUE(client.connect());
  20480. ASSERT_TRUE(client.is_open());
  20481. ASSERT_TRUE(client.send("still open"));
  20482. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20483. // the still-open connection, which must not touch a freed TLS session.
  20484. ASSERT_TRUE(client.connect());
  20485. ASSERT_TRUE(client.is_open());
  20486. ASSERT_TRUE(client.send("after reconnect"));
  20487. std::string msg;
  20488. EXPECT_EQ(ws::Text, client.read(msg));
  20489. EXPECT_EQ("after reconnect", msg);
  20490. client.close();
  20491. }
  20492. #endif
  20493. #ifdef CPPHTTPLIB_SSL_ENABLED
  20494. class WebSocketSSLCATest : public ::testing::Test {
  20495. protected:
  20496. void SetUp() override {
  20497. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20498. SERVER_PRIVATE_KEY_FILE);
  20499. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20500. std::string msg;
  20501. while (ws.read(msg)) {
  20502. ws.send(msg);
  20503. }
  20504. });
  20505. port_ = server_->bind_to_any_port("127.0.0.1");
  20506. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20507. server_->wait_until_ready();
  20508. }
  20509. void TearDown() override {
  20510. server_->stop();
  20511. if (server_thread_.joinable()) { server_thread_.join(); }
  20512. }
  20513. std::string url() const {
  20514. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20515. }
  20516. std::unique_ptr<SSLServer> server_;
  20517. std::thread server_thread_;
  20518. int port_ = 0;
  20519. };
  20520. // A custom CA loaded as PEM verifies the server with full certificate
  20521. // verification enabled
  20522. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20523. ws::WebSocketClient client(url());
  20524. std::string cert;
  20525. read_file(SERVER_CERT2_FILE, cert);
  20526. client.load_ca_cert_store(cert.c_str(), cert.size());
  20527. ASSERT_TRUE(client.connect());
  20528. ASSERT_TRUE(client.send("hello"));
  20529. std::string msg;
  20530. EXPECT_EQ(ws::Text, client.read(msg));
  20531. EXPECT_EQ("hello", msg);
  20532. client.close();
  20533. }
  20534. // A custom CA that does not cover the server must fail verification (the
  20535. // custom CA is exclusive; system certs are not loaded alongside it)
  20536. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20537. ws::WebSocketClient client(url());
  20538. std::string cert;
  20539. read_file(CLIENT_CA_CERT_FILE, cert);
  20540. client.load_ca_cert_store(cert.c_str(), cert.size());
  20541. auto res = client.connect();
  20542. ASSERT_FALSE(res);
  20543. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20544. EXPECT_EQ(-1, res.status());
  20545. EXPECT_NE(0u, res.ssl_backend_error());
  20546. }
  20547. // The same CA as a file path rather than PEM in memory
  20548. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20549. ws::WebSocketClient client(url());
  20550. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20551. ASSERT_TRUE(client.connect());
  20552. ASSERT_TRUE(client.send("hello"));
  20553. std::string msg;
  20554. EXPECT_EQ(ws::Text, client.read(msg));
  20555. EXPECT_EQ("hello", msg);
  20556. client.close();
  20557. }
  20558. // ...and a CA file that does not cover the server still fails, so it is the
  20559. // path above that decides the outcome
  20560. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20561. ws::WebSocketClient client(url());
  20562. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20563. ASSERT_FALSE(client.connect());
  20564. }
  20565. // Regression test: reconnecting with a native custom CA store used to reuse
  20566. // a store handle the previous TLS context had already freed (use-after-free
  20567. // under the OpenSSL backend). The context now lives as long as the client.
  20568. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20569. ws::WebSocketClient client(url());
  20570. std::string cert;
  20571. read_file(SERVER_CERT2_FILE, cert);
  20572. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20573. ASSERT_TRUE(client.connect());
  20574. client.close();
  20575. ASSERT_TRUE(client.connect());
  20576. ASSERT_TRUE(client.send("again"));
  20577. std::string msg;
  20578. EXPECT_EQ(ws::Text, client.read(msg));
  20579. EXPECT_EQ("again", msg);
  20580. client.close();
  20581. }
  20582. // Regression test: a certificate with a trusted chain but no identity match
  20583. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20584. // verification entirely for IP hosts, so this connection succeeded there.
  20585. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20586. // chain verification while the identity check must still fail.
  20587. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20588. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20589. ASSERT_TRUE(svr.is_valid());
  20590. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20591. std::string msg;
  20592. while (ws.read(msg)) {
  20593. ws.send(msg);
  20594. }
  20595. });
  20596. auto port = svr.bind_to_any_port("127.0.0.1");
  20597. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20598. auto se = detail::scope_exit([&] {
  20599. svr.stop();
  20600. t.join();
  20601. });
  20602. svr.wait_until_ready();
  20603. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20604. "/echo");
  20605. std::string cert;
  20606. read_file(SERVER_CERT_FILE, cert);
  20607. client.load_ca_cert_store(cert.c_str(), cert.size());
  20608. ASSERT_FALSE(client.connect());
  20609. }
  20610. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20611. // SNI, so nothing binds the host name to the TLS session. These bind the
  20612. // server to "localhost" instead, the only shape that exercises the SNI and
  20613. // hostname-verification path with certificate verification left enabled.
  20614. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20615. protected:
  20616. void Start(const char *cert_file) {
  20617. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20618. SERVER_PRIVATE_KEY_FILE);
  20619. ASSERT_TRUE(server_->is_valid());
  20620. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20621. std::string msg;
  20622. while (ws.read(msg)) {
  20623. ws.send(msg);
  20624. }
  20625. });
  20626. port_ = server_->bind_to_any_port("localhost");
  20627. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20628. server_->wait_until_ready();
  20629. }
  20630. void TearDown() override {
  20631. if (server_) { server_->stop(); }
  20632. if (server_thread_.joinable()) { server_thread_.join(); }
  20633. }
  20634. std::string url() const {
  20635. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20636. }
  20637. std::unique_ptr<SSLServer> server_;
  20638. std::thread server_thread_;
  20639. int port_ = 0;
  20640. };
  20641. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  20642. // out and the connection is usable
  20643. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  20644. Start(SERVER_CERT2_FILE);
  20645. ws::WebSocketClient client(url());
  20646. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20647. ASSERT_TRUE(client.connect());
  20648. ASSERT_TRUE(client.send("hello"));
  20649. std::string msg;
  20650. EXPECT_EQ(ws::Text, client.read(msg));
  20651. EXPECT_EQ("hello", msg);
  20652. client.close();
  20653. }
  20654. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  20655. // while the identity check must still reject "localhost"
  20656. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  20657. Start(SERVER_CERT_FILE);
  20658. ws::WebSocketClient client(url());
  20659. client.set_ca_cert_path(SERVER_CERT_FILE);
  20660. auto res = client.connect();
  20661. ASSERT_FALSE(res);
  20662. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  20663. EXPECT_EQ(-1, res.status());
  20664. }
  20665. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  20666. // disabled: the chain is still checked, only the identity check is skipped
  20667. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  20668. Start(SERVER_CERT_FILE);
  20669. ws::WebSocketClient client(url());
  20670. client.set_ca_cert_path(SERVER_CERT_FILE);
  20671. client.enable_server_hostname_verification(false);
  20672. ASSERT_TRUE(client.connect());
  20673. ASSERT_TRUE(client.send("hello"));
  20674. std::string msg;
  20675. EXPECT_EQ(ws::Text, client.read(msg));
  20676. EXPECT_EQ("hello", msg);
  20677. client.close();
  20678. }
  20679. // A CA that did not sign the server certificate fails the chain, even though
  20680. // the name would match
  20681. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  20682. Start(SERVER_CERT2_FILE);
  20683. ws::WebSocketClient client(url());
  20684. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20685. ASSERT_FALSE(client.connect());
  20686. }
  20687. // With verification disabled, neither the chain nor the name is checked
  20688. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  20689. Start(SERVER_CERT_FILE);
  20690. ws::WebSocketClient client(url());
  20691. client.enable_server_certificate_verification(false);
  20692. ASSERT_TRUE(client.connect());
  20693. ASSERT_TRUE(client.send("hello"));
  20694. std::string msg;
  20695. EXPECT_EQ(ws::Text, client.read(msg));
  20696. EXPECT_EQ("hello", msg);
  20697. client.close();
  20698. }
  20699. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  20700. protected:
  20701. void SetUp() override {
  20702. server_ = httplib::detail::make_unique<SSLServer>(
  20703. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20704. ASSERT_TRUE(server_->is_valid());
  20705. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20706. std::string msg;
  20707. while (ws.read(msg)) {
  20708. ws.send(msg);
  20709. }
  20710. });
  20711. port_ = server_->bind_to_any_port("localhost");
  20712. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20713. server_->wait_until_ready();
  20714. }
  20715. void TearDown() override {
  20716. server_->stop();
  20717. if (server_thread_.joinable()) { server_thread_.join(); }
  20718. }
  20719. std::string url() const {
  20720. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  20721. }
  20722. void ConnectWithClientCert(const std::string &client_cert_file,
  20723. const std::string &client_private_key_file,
  20724. const char *private_key_password) {
  20725. std::string cert_pem, key_pem;
  20726. read_file(client_cert_file, cert_pem);
  20727. read_file(client_private_key_file, key_pem);
  20728. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  20729. key_pem.c_str(), key_pem.size(),
  20730. private_key_password};
  20731. ws::WebSocketClient client(url(), pem);
  20732. ASSERT_TRUE(client.is_valid());
  20733. client.enable_server_certificate_verification(false);
  20734. ASSERT_TRUE(client.connect());
  20735. ASSERT_TRUE(client.send("hello"));
  20736. std::string msg;
  20737. EXPECT_EQ(ws::Text, client.read(msg));
  20738. EXPECT_EQ("hello", msg);
  20739. client.close();
  20740. }
  20741. std::unique_ptr<SSLServer> server_;
  20742. std::thread server_thread_;
  20743. int port_ = 0;
  20744. };
  20745. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  20746. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  20747. }
  20748. // Control for the tests above: the fixture's server really does require a
  20749. // client certificate, so it is the PEM the constructor installed that decides
  20750. // the outcome.
  20751. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  20752. ws::WebSocketClient client(url());
  20753. ASSERT_TRUE(client.is_valid());
  20754. client.enable_server_certificate_verification(false);
  20755. EXPECT_FALSE(client.connect());
  20756. }
  20757. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  20758. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  20759. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  20760. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  20761. }
  20762. #endif
  20763. #if !defined(_WIN32)
  20764. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  20765. auto secret_dir = std::string("./symlink_test_secret");
  20766. auto served_dir = std::string("./symlink_test_served");
  20767. auto secret_file = secret_dir + "/secret.txt";
  20768. auto symlink_path = served_dir + "/escape";
  20769. // Setup: create directories and files
  20770. mkdir(secret_dir.c_str(), 0755);
  20771. mkdir(served_dir.c_str(), 0755);
  20772. {
  20773. std::ofstream ofs(secret_file);
  20774. ofs << "SECRET_DATA";
  20775. }
  20776. // Create symlink using absolute path so it resolves correctly
  20777. #ifdef PATH_MAX
  20778. char abs_secret[PATH_MAX];
  20779. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  20780. #else
  20781. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  20782. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  20783. ASSERT_NE(nullptr, abs_secret);
  20784. #endif
  20785. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  20786. auto se = detail::scope_exit([&] {
  20787. unlink(symlink_path.c_str());
  20788. unlink(secret_file.c_str());
  20789. rmdir(served_dir.c_str());
  20790. rmdir(secret_dir.c_str());
  20791. });
  20792. Server svr;
  20793. svr.set_mount_point("/", served_dir);
  20794. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  20795. auto se2 = detail::scope_exit([&] {
  20796. svr.stop();
  20797. listen_thread.join();
  20798. });
  20799. svr.wait_until_ready();
  20800. Client cli("localhost", PORT);
  20801. // Symlink pointing outside base dir should be blocked
  20802. auto res = cli.Get("/escape/secret.txt");
  20803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20804. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  20805. }
  20806. #endif
  20807. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  20808. // A GET request with Content-Length to a static file handler must have its
  20809. // body drained before the keep-alive connection is reused. Otherwise the
  20810. // unread body bytes are interpreted as the next HTTP request.
  20811. //
  20812. // The body is sent AFTER receiving the first response (as in the original
  20813. // PoC) so that the stream_line_reader cannot buffer it together with the
  20814. // headers of the first request.
  20815. Server svr;
  20816. svr.set_mount_point("/", "./www");
  20817. std::atomic<int> smuggled_count(0);
  20818. svr.Get("/smuggled", [&](const Request &, Response &res) {
  20819. smuggled_count++;
  20820. res.set_content("oops", "text/plain");
  20821. });
  20822. auto port = svr.bind_to_any_port("localhost");
  20823. thread t = thread([&] { svr.listen_after_bind(); });
  20824. auto se = detail::scope_exit([&] {
  20825. svr.stop();
  20826. t.join();
  20827. });
  20828. svr.wait_until_ready();
  20829. auto error = Error::Success;
  20830. auto sock = detail::create_client_socket(
  20831. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  20832. /*connection_timeout_sec=*/2, 0,
  20833. /*read_timeout_sec=*/2, 0,
  20834. /*write_timeout_sec=*/2, 0, std::string(), error);
  20835. ASSERT_NE(INVALID_SOCKET, sock);
  20836. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20837. // The "smuggled" request will be sent as the body of the outer GET
  20838. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  20839. "Host: localhost\r\n"
  20840. "Connection: close\r\n"
  20841. "\r\n";
  20842. // Step 1: Send only the outer request headers (no body yet)
  20843. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  20844. "Host: localhost\r\n"
  20845. "Content-Length: " +
  20846. std::to_string(smuggled.size()) +
  20847. "\r\n"
  20848. "\r\n";
  20849. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  20850. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  20851. // Step 2: Read the first response (server serves file without reading body)
  20852. std::string first_response;
  20853. char buf[4096];
  20854. for (;;) {
  20855. auto n = recv(sock, buf, sizeof(buf), 0);
  20856. if (n <= 0) break;
  20857. first_response.append(buf, static_cast<size_t>(n));
  20858. // Stop once we have a complete response (headers + body)
  20859. auto hdr_end = first_response.find("\r\n\r\n");
  20860. if (hdr_end != std::string::npos) {
  20861. // Check for Content-Length to know when the body is complete
  20862. auto cl_pos = first_response.find("Content-Length:");
  20863. if (cl_pos != std::string::npos) {
  20864. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  20865. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  20866. auto cl = std::stoul(
  20867. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  20868. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  20869. } else {
  20870. break; // No Content-Length, assume headers-only response
  20871. }
  20872. }
  20873. }
  20874. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  20875. // Step 3: Now send the body, which looks like a new HTTP request.
  20876. // On a vulnerable server the keep-alive loop reads this as a second request.
  20877. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  20878. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  20879. // Step 4: Try to read a second response (should NOT exist after fix)
  20880. std::string second_response;
  20881. for (;;) {
  20882. auto n = recv(sock, buf, sizeof(buf), 0);
  20883. if (n <= 0) break;
  20884. second_response.append(buf, static_cast<size_t>(n));
  20885. }
  20886. // The smuggled request must NOT have been processed
  20887. EXPECT_EQ(0, smuggled_count.load());
  20888. }
  20889. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20890. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  20891. // must be rejected with 400 Bad Request.
  20892. Server svr;
  20893. svr.Post("/test", [&](const Request &, Response &res) {
  20894. res.set_content("ok", "text/plain");
  20895. });
  20896. thread t = thread([&] { svr.listen(HOST, PORT); });
  20897. auto se = detail::scope_exit([&] {
  20898. svr.stop();
  20899. t.join();
  20900. ASSERT_FALSE(svr.is_running());
  20901. });
  20902. svr.wait_until_ready();
  20903. // Exact "chunked"
  20904. {
  20905. auto req = "POST /test HTTP/1.1\r\n"
  20906. "Host: localhost\r\n"
  20907. "Content-Length: 5\r\n"
  20908. "Transfer-Encoding: chunked\r\n"
  20909. "Connection: close\r\n"
  20910. "\r\n"
  20911. "hello";
  20912. std::string response;
  20913. ASSERT_TRUE(send_request(1, req, &response));
  20914. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20915. response.substr(0, response.find("\r\n")));
  20916. }
  20917. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  20918. {
  20919. auto req = "POST /test HTTP/1.1\r\n"
  20920. "Host: localhost\r\n"
  20921. "Content-Length: 5\r\n"
  20922. "Transfer-Encoding: gzip, chunked\r\n"
  20923. "Connection: close\r\n"
  20924. "\r\n"
  20925. "hello";
  20926. std::string response;
  20927. ASSERT_TRUE(send_request(1, req, &response));
  20928. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20929. response.substr(0, response.find("\r\n")));
  20930. }
  20931. }
  20932. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  20933. Server svr;
  20934. svr.Post("/test", [&](const Request &, Response &res) {
  20935. res.set_content("ok", "text/plain");
  20936. });
  20937. thread t = thread([&] { svr.listen(HOST, PORT); });
  20938. auto se = detail::scope_exit([&] {
  20939. svr.stop();
  20940. t.join();
  20941. ASSERT_FALSE(svr.is_running());
  20942. });
  20943. svr.wait_until_ready();
  20944. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  20945. // length cannot be determined, so the server must answer 400 and close
  20946. // rather than treat the request as bodyless and leave the body in the
  20947. // socket for the next request to pick up.
  20948. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  20949. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  20950. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  20951. std::string response;
  20952. ASSERT_TRUE(send_request(1, req, &response));
  20953. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20954. response.substr(0, response.find("\r\n")))
  20955. << transfer_encoding;
  20956. }
  20957. // RFC 9110 5.3: the codings may also be split across several
  20958. // Transfer-Encoding lines, which combine in the order they were received.
  20959. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  20960. // just like the single-line "chunked, gzip" above.
  20961. {
  20962. auto req = "POST /test HTTP/1.1\r\n"
  20963. "Host: localhost\r\n"
  20964. "Transfer-Encoding: chunked\r\n"
  20965. "Transfer-Encoding: gzip\r\n"
  20966. "\r\n"
  20967. "0\r\n\r\n";
  20968. std::string response;
  20969. ASSERT_TRUE(send_request(1, req, &response));
  20970. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20971. response.substr(0, response.find("\r\n")));
  20972. }
  20973. // A sequence ending in chunked stays valid.
  20974. auto req = "POST /test HTTP/1.1\r\n"
  20975. "Host: localhost\r\n"
  20976. "Transfer-Encoding: gzip, chunked\r\n"
  20977. "Connection: close\r\n"
  20978. "\r\n"
  20979. "0\r\n\r\n";
  20980. std::string response;
  20981. ASSERT_TRUE(send_request(1, req, &response));
  20982. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  20983. // ...including when it is spread over several lines.
  20984. auto split_req = "POST /test HTTP/1.1\r\n"
  20985. "Host: localhost\r\n"
  20986. "Transfer-Encoding: gzip\r\n"
  20987. "Transfer-Encoding: chunked\r\n"
  20988. "Connection: close\r\n"
  20989. "\r\n"
  20990. "0\r\n\r\n";
  20991. std::string split_response;
  20992. ASSERT_TRUE(send_request(1, split_req, &split_response));
  20993. EXPECT_EQ("HTTP/1.1 200 OK",
  20994. split_response.substr(0, split_response.find("\r\n")));
  20995. }
  20996. // Regression for issue #2450: a DELETE without Content-Length on a
  20997. // keep-alive connection must not let the post-response drain consume the
  20998. // next request's bytes.
  20999. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21000. Server svr;
  21001. std::atomic<int> delete_count(0);
  21002. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21003. delete_count++;
  21004. res.status = StatusCode::NoContent_204;
  21005. });
  21006. auto port = svr.bind_to_any_port(HOST);
  21007. thread t = thread([&] { svr.listen_after_bind(); });
  21008. auto se = detail::scope_exit([&] {
  21009. svr.stop();
  21010. t.join();
  21011. });
  21012. svr.wait_until_ready();
  21013. auto error = Error::Success;
  21014. auto sock = detail::create_client_socket(
  21015. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21016. /*connection_timeout_sec=*/2, 0,
  21017. /*read_timeout_sec=*/2, 0,
  21018. /*write_timeout_sec=*/2, 0, std::string(), error);
  21019. ASSERT_NE(INVALID_SOCKET, sock);
  21020. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21021. auto send_request_and_read_response = [&](const std::string &req,
  21022. std::string &out) -> bool {
  21023. auto sent = send(sock, req.data(), req.size(), 0);
  21024. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21025. char buf[4096];
  21026. for (;;) {
  21027. auto n = recv(sock, buf, sizeof(buf), 0);
  21028. if (n <= 0) { return !out.empty(); }
  21029. out.append(buf, static_cast<size_t>(n));
  21030. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21031. }
  21032. };
  21033. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21034. "Host: localhost\r\n"
  21035. "\r\n";
  21036. std::string resp1;
  21037. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21038. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21039. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21040. "Host: localhost\r\n"
  21041. "Connection: close\r\n"
  21042. "\r\n";
  21043. std::string resp2;
  21044. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21045. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21046. EXPECT_EQ(2, delete_count.load());
  21047. }
  21048. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21049. Server svr;
  21050. svr.Post("/ingest", [&](const Request &, Response &res,
  21051. const ContentReader &content_reader) {
  21052. auto consumed = content_reader([](const char *, size_t) { return false; });
  21053. EXPECT_FALSE(consumed);
  21054. res.status = StatusCode::Conflict_409;
  21055. res.set_header("Connection", "close");
  21056. });
  21057. auto port = svr.bind_to_any_port(HOST);
  21058. thread t = thread([&] { svr.listen_after_bind(); });
  21059. auto se = detail::scope_exit([&] {
  21060. svr.stop();
  21061. t.join();
  21062. });
  21063. svr.wait_until_ready();
  21064. auto error = Error::Success;
  21065. auto sock = detail::create_client_socket(
  21066. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21067. /*connection_timeout_sec=*/2, 0,
  21068. /*read_timeout_sec=*/1, 0,
  21069. /*write_timeout_sec=*/2, 0, std::string(), error);
  21070. ASSERT_NE(INVALID_SOCKET, sock);
  21071. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21072. std::string request = "POST /ingest HTTP/1.1\r\n"
  21073. "Host: localhost\r\n"
  21074. "Transfer-Encoding: chunked\r\n"
  21075. "\r\n"
  21076. "4\r\n"
  21077. "data\r\n";
  21078. auto sent = send(sock, request.data(), request.size(), 0);
  21079. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21080. std::string response;
  21081. ssize_t received = 0;
  21082. do {
  21083. char buf[4096];
  21084. received = recv(sock, buf, sizeof(buf), 0);
  21085. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21086. } while (received > 0);
  21087. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21088. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21089. EXPECT_EQ(0, received);
  21090. }
  21091. namespace no_proxy_test {
  21092. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21093. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21094. // calling listen().
  21095. class ScopedServer {
  21096. public:
  21097. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21098. ~ScopedServer() {
  21099. svr_.stop();
  21100. if (th_.joinable()) { th_.join(); }
  21101. }
  21102. Server &svr() { return svr_; }
  21103. int port() const { return port_; }
  21104. void listen() {
  21105. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21106. svr_.wait_until_ready();
  21107. }
  21108. private:
  21109. Server svr_;
  21110. std::thread th_;
  21111. int port_ = 0;
  21112. };
  21113. class ProxyAndTargetServers {
  21114. public:
  21115. ProxyAndTargetServers() {
  21116. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21117. proxy_hits_++;
  21118. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21119. res.set_content("via-proxy", "text/plain");
  21120. });
  21121. target_.Get(".*", [this](const Request &req, Response &res) {
  21122. target_hits_++;
  21123. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21124. res.set_content("direct", "text/plain");
  21125. });
  21126. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21127. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21128. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21129. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21130. proxy_mock_.wait_until_ready();
  21131. target_.wait_until_ready();
  21132. }
  21133. ~ProxyAndTargetServers() {
  21134. proxy_mock_.stop();
  21135. target_.stop();
  21136. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21137. if (target_thread_.joinable()) { target_thread_.join(); }
  21138. }
  21139. Server &proxy_mock() { return proxy_mock_; }
  21140. Server &target() { return target_; }
  21141. int proxy_port() const { return proxy_port_; }
  21142. int target_port() const { return target_port_; }
  21143. int proxy_hits() const { return proxy_hits_.load(); }
  21144. int target_hits() const { return target_hits_.load(); }
  21145. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21146. void reset_counters() {
  21147. proxy_hits_ = 0;
  21148. target_hits_ = 0;
  21149. last_had_proxy_authz_ = false;
  21150. }
  21151. private:
  21152. Server proxy_mock_;
  21153. Server target_;
  21154. std::thread proxy_thread_;
  21155. std::thread target_thread_;
  21156. int proxy_port_ = 0;
  21157. int target_port_ = 0;
  21158. std::atomic<int> proxy_hits_{0};
  21159. std::atomic<int> target_hits_{0};
  21160. std::atomic<bool> last_had_proxy_authz_{false};
  21161. };
  21162. inline std::unique_ptr<Client> make_client(const std::string &host,
  21163. ProxyAndTargetServers &s) {
  21164. auto cli = detail::make_unique<Client>(host, s.target_port());
  21165. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21166. cli->set_proxy("127.0.0.1", s.proxy_port());
  21167. return cli;
  21168. }
  21169. } // namespace no_proxy_test
  21170. using no_proxy_test::make_client;
  21171. using no_proxy_test::ProxyAndTargetServers;
  21172. TEST(NoProxyTest, ExactHostnameBypasses) {
  21173. ProxyAndTargetServers s;
  21174. auto cli = make_client("example.com", s);
  21175. cli->set_no_proxy({"example.com"});
  21176. auto res = cli->Get("/");
  21177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21178. EXPECT_EQ(0, s.proxy_hits());
  21179. EXPECT_EQ(1, s.target_hits());
  21180. }
  21181. TEST(NoProxyTest, SubdomainBypasses) {
  21182. ProxyAndTargetServers s;
  21183. auto cli = make_client("foo.example.com", s);
  21184. cli->set_no_proxy({"example.com"});
  21185. auto res = cli->Get("/");
  21186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21187. EXPECT_EQ(0, s.proxy_hits());
  21188. EXPECT_EQ(1, s.target_hits());
  21189. }
  21190. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21191. // Regression guard: "evilexample.com" must not be considered a subdomain
  21192. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21193. // check would let traffic bypass the proxy and leak credentials direct
  21194. // to the attacker host.
  21195. ProxyAndTargetServers s;
  21196. auto cli = make_client("evilexample.com", s);
  21197. cli->set_no_proxy({"example.com"});
  21198. auto res = cli->Get("/");
  21199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21200. EXPECT_GE(s.proxy_hits(), 1);
  21201. EXPECT_EQ(0, s.target_hits());
  21202. }
  21203. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21204. ProxyAndTargetServers s;
  21205. auto cli = make_client("example.com.evil.com", s);
  21206. cli->set_no_proxy({"example.com"});
  21207. auto res = cli->Get("/");
  21208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21209. EXPECT_GE(s.proxy_hits(), 1);
  21210. EXPECT_EQ(0, s.target_hits());
  21211. }
  21212. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21213. ProxyAndTargetServers s;
  21214. auto cli = make_client("example.com", s);
  21215. cli->set_no_proxy({".example.com"});
  21216. auto res = cli->Get("/");
  21217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21218. EXPECT_EQ(0, s.proxy_hits());
  21219. EXPECT_EQ(1, s.target_hits());
  21220. }
  21221. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21222. ProxyAndTargetServers s;
  21223. auto cli = make_client("Example.COM", s);
  21224. cli->set_no_proxy({"EXAMPLE.com"});
  21225. auto res = cli->Get("/");
  21226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21227. EXPECT_EQ(0, s.proxy_hits());
  21228. EXPECT_EQ(1, s.target_hits());
  21229. }
  21230. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21231. ProxyAndTargetServers s;
  21232. auto cli = make_client("example.com.", s);
  21233. cli->set_no_proxy({"example.com"});
  21234. auto res = cli->Get("/");
  21235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21236. EXPECT_EQ(0, s.proxy_hits());
  21237. EXPECT_EQ(1, s.target_hits());
  21238. }
  21239. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21240. // Trailing dots must be normalized on BOTH sides — host and entry.
  21241. // An implementation that only strips the host-side trailing dot would
  21242. // fail to match host "example.com" against entry "example.com." because
  21243. // a literal substring search would compare 11 chars against 12.
  21244. ProxyAndTargetServers s;
  21245. auto cli = make_client("example.com", s);
  21246. cli->set_no_proxy({"example.com."});
  21247. auto res = cli->Get("/");
  21248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21249. EXPECT_EQ(0, s.proxy_hits());
  21250. EXPECT_EQ(1, s.target_hits());
  21251. }
  21252. TEST(NoProxyTest, WildcardBypassesEverything) {
  21253. ProxyAndTargetServers s;
  21254. auto cli = make_client("anything.invalid.test", s);
  21255. cli->set_no_proxy({"*"});
  21256. auto res = cli->Get("/");
  21257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21258. EXPECT_EQ(0, s.proxy_hits());
  21259. EXPECT_EQ(1, s.target_hits());
  21260. }
  21261. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21262. ProxyAndTargetServers s;
  21263. Client cli("127.0.0.1", s.target_port());
  21264. cli.set_proxy("127.0.0.1", s.proxy_port());
  21265. cli.set_no_proxy({"127.0.0.1"});
  21266. auto res = cli.Get("/");
  21267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21268. EXPECT_EQ(0, s.proxy_hits());
  21269. EXPECT_EQ(1, s.target_hits());
  21270. }
  21271. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21272. ProxyAndTargetServers s;
  21273. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21274. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21275. cli.set_proxy("127.0.0.1", s.proxy_port());
  21276. cli.set_no_proxy({"::1"});
  21277. auto res = cli.Get("/");
  21278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21279. EXPECT_EQ(0, s.proxy_hits());
  21280. EXPECT_EQ(1, s.target_hits());
  21281. }
  21282. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21283. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21284. // must still be recognized as IPv6 for CIDR matching. Implementations
  21285. // that detect IPv6 only when the host begins with '[' would parse the
  21286. // host as a hostname and miss the match.
  21287. ProxyAndTargetServers s;
  21288. Client cli("fe80::1", s.target_port());
  21289. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21290. cli.set_proxy("127.0.0.1", s.proxy_port());
  21291. cli.set_no_proxy({"fe80::/10"});
  21292. auto res = cli.Get("/");
  21293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21294. EXPECT_EQ(0, s.proxy_hits());
  21295. EXPECT_EQ(1, s.target_hits());
  21296. }
  21297. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21298. ProxyAndTargetServers s;
  21299. Client cli("::1", s.target_port());
  21300. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21301. cli.set_proxy("127.0.0.1", s.proxy_port());
  21302. cli.set_no_proxy({"[::1]"});
  21303. auto res = cli.Get("/");
  21304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21305. EXPECT_EQ(0, s.proxy_hits());
  21306. EXPECT_EQ(1, s.target_hits());
  21307. }
  21308. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21309. ProxyAndTargetServers s;
  21310. Client cli("fe80::1", s.target_port());
  21311. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21312. cli.set_proxy("127.0.0.1", s.proxy_port());
  21313. cli.set_no_proxy({"[fe80::]/10"});
  21314. auto res = cli.Get("/");
  21315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21316. EXPECT_EQ(0, s.proxy_hits());
  21317. EXPECT_EQ(1, s.target_hits());
  21318. }
  21319. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21320. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21321. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21322. // tricks via address-family conversion.
  21323. ProxyAndTargetServers s;
  21324. Client cli("::ffff:127.0.0.1", s.target_port());
  21325. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21326. cli.set_proxy("127.0.0.1", s.proxy_port());
  21327. cli.set_no_proxy({"127.0.0.1"});
  21328. auto res = cli.Get("/");
  21329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21330. EXPECT_GE(s.proxy_hits(), 1);
  21331. EXPECT_EQ(0, s.target_hits());
  21332. }
  21333. TEST(NoProxyTest, IPv4CidrMatch) {
  21334. ProxyAndTargetServers s;
  21335. Client cli("127.0.0.1", s.target_port());
  21336. cli.set_proxy("127.0.0.1", s.proxy_port());
  21337. cli.set_no_proxy({"127.0.0.0/8"});
  21338. auto res = cli.Get("/");
  21339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21340. EXPECT_EQ(0, s.proxy_hits());
  21341. EXPECT_EQ(1, s.target_hits());
  21342. }
  21343. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21344. ProxyAndTargetServers s;
  21345. Client cli("127.0.0.1", s.target_port());
  21346. cli.set_proxy("127.0.0.1", s.proxy_port());
  21347. cli.set_no_proxy({"10.0.0.0/8"});
  21348. auto res = cli.Get("/");
  21349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21350. EXPECT_GE(s.proxy_hits(), 1);
  21351. EXPECT_EQ(0, s.target_hits());
  21352. }
  21353. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21354. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21355. // IPv4 target matches.
  21356. ProxyAndTargetServers s;
  21357. Client cli("127.0.0.1", s.target_port());
  21358. cli.set_proxy("127.0.0.1", s.proxy_port());
  21359. cli.set_no_proxy({"0.0.0.0/0"});
  21360. auto res = cli.Get("/");
  21361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21362. EXPECT_EQ(0, s.proxy_hits());
  21363. EXPECT_EQ(1, s.target_hits());
  21364. }
  21365. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21366. ProxyAndTargetServers s;
  21367. Client cli("127.0.0.1", s.target_port());
  21368. cli.set_proxy("127.0.0.1", s.proxy_port());
  21369. cli.set_no_proxy({"127.0.0.1"});
  21370. auto res = cli.Get("/");
  21371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21372. EXPECT_EQ(0, s.proxy_hits());
  21373. EXPECT_EQ(1, s.target_hits());
  21374. }
  21375. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21376. ProxyAndTargetServers s;
  21377. Client cli("127.0.0.1", s.target_port());
  21378. cli.set_proxy("127.0.0.1", s.proxy_port());
  21379. cli.set_no_proxy({"127.0.0.0/33"});
  21380. auto res = cli.Get("/");
  21381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21382. EXPECT_GE(s.proxy_hits(), 1);
  21383. EXPECT_EQ(0, s.target_hits());
  21384. }
  21385. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21386. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21387. ProxyAndTargetServers s;
  21388. Client cli("127.0.0.1", s.target_port());
  21389. cli.set_proxy("127.0.0.1", s.proxy_port());
  21390. cli.set_no_proxy({"127.0.0.1/"});
  21391. auto res = cli.Get("/");
  21392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21393. EXPECT_GE(s.proxy_hits(), 1);
  21394. EXPECT_EQ(0, s.target_hits());
  21395. }
  21396. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21397. ProxyAndTargetServers s;
  21398. auto cli = make_client("internal.corp", s);
  21399. cli->set_proxy_basic_auth("u", "p");
  21400. cli->set_no_proxy({"internal.corp"});
  21401. auto res = cli->Get("/");
  21402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21403. EXPECT_EQ(1, s.target_hits());
  21404. EXPECT_EQ(0, s.proxy_hits());
  21405. EXPECT_FALSE(s.last_had_proxy_authz())
  21406. << "Proxy-Authorization must not be sent direct to the target";
  21407. }
  21408. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21409. ProxyAndTargetServers s;
  21410. auto cli = make_client("public.example", s);
  21411. cli->set_proxy_basic_auth("u", "p");
  21412. cli->set_no_proxy({"internal.corp"}); // does not match
  21413. auto res = cli->Get("/");
  21414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21415. EXPECT_GE(s.proxy_hits(), 1);
  21416. EXPECT_TRUE(s.last_had_proxy_authz());
  21417. }
  21418. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21419. ProxyAndTargetServers s;
  21420. auto cli = make_client("anything.test", s);
  21421. auto res = cli->Get("/");
  21422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21423. EXPECT_GE(s.proxy_hits(), 1);
  21424. EXPECT_EQ(0, s.target_hits());
  21425. }
  21426. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21427. ProxyAndTargetServers s;
  21428. auto cli = make_client("example.com", s);
  21429. cli->set_no_proxy({"example.com:8080"});
  21430. auto res = cli->Get("/");
  21431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21432. EXPECT_GE(s.proxy_hits(), 1);
  21433. EXPECT_EQ(0, s.target_hits());
  21434. }
  21435. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21436. ProxyAndTargetServers s;
  21437. auto cli = make_client("anything.test", s);
  21438. cli->set_no_proxy({"", " ", "\t"});
  21439. auto res = cli->Get("/");
  21440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21441. EXPECT_GE(s.proxy_hits(), 1);
  21442. EXPECT_EQ(0, s.target_hits());
  21443. }
  21444. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21445. // An entry with leading/trailing whitespace must still match — env-style
  21446. // values are commonly pasted with stray spaces and an implementation
  21447. // that feeds the raw token directly to inet_pton would fail to match
  21448. // valid CIDRs because of the spaces.
  21449. ProxyAndTargetServers s;
  21450. Client cli("127.0.0.1", s.target_port());
  21451. cli.set_proxy("127.0.0.1", s.proxy_port());
  21452. cli.set_no_proxy({" 127.0.0.0/8 "});
  21453. auto res = cli.Get("/");
  21454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21455. EXPECT_EQ(0, s.proxy_hits());
  21456. EXPECT_EQ(1, s.target_hits());
  21457. }
  21458. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21459. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21460. // go direct and must NOT carry Proxy-Authorization.
  21461. std::atomic<int> proxy_hits{0};
  21462. std::atomic<int> target_hits{0};
  21463. std::atomic<bool> target_saw_authz{false};
  21464. no_proxy_test::ScopedServer proxy_mock, target;
  21465. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21466. proxy_hits++;
  21467. res.status = 302;
  21468. res.set_header("Location", "http://127.0.0.1:" +
  21469. std::to_string(target.port()) + "/landed");
  21470. });
  21471. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21472. target_hits++;
  21473. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21474. res.set_content("direct", "text/plain");
  21475. });
  21476. proxy_mock.listen();
  21477. target.listen();
  21478. Client cli("public.example", target.port());
  21479. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21480. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21481. cli.set_proxy_basic_auth("u", "p");
  21482. cli.set_no_proxy({"127.0.0.1"});
  21483. cli.set_follow_location(true);
  21484. auto res = cli.Get("/redir");
  21485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21486. EXPECT_GE(proxy_hits.load(), 1);
  21487. EXPECT_GE(target_hits.load(), 1);
  21488. EXPECT_FALSE(target_saw_authz.load());
  21489. }
  21490. #ifdef CPPHTTPLIB_SSL_ENABLED
  21491. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21492. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21493. // proxy creds would be sent to the (possibly hostile) origin.
  21494. std::atomic<int> target_hits{0};
  21495. std::atomic<bool> target_saw_proxy_authz{false};
  21496. no_proxy_test::ScopedServer target;
  21497. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21498. target_hits++;
  21499. if (req.has_header("Proxy-Authorization")) {
  21500. target_saw_proxy_authz = true;
  21501. }
  21502. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21503. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21504. "nonce=\"abc\", algorithm=MD5");
  21505. });
  21506. target.listen();
  21507. // The proxy address is set to the target's port: the bypass MUST kick in;
  21508. // if it doesn't, the test still routes "via proxy" to the same server and
  21509. // the Proxy-Authorization assertion below catches the leak.
  21510. Client cli("evil.example", target.port());
  21511. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21512. cli.set_proxy("127.0.0.1", target.port());
  21513. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21514. cli.set_no_proxy({"evil.example"});
  21515. auto res = cli.Get("/x");
  21516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21517. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21518. EXPECT_EQ(1, target_hits.load());
  21519. EXPECT_FALSE(target_saw_proxy_authz.load());
  21520. }
  21521. #endif
  21522. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21523. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21524. std::atomic<int> proxy_hits{0};
  21525. std::atomic<int> bypass_hits{0};
  21526. std::atomic<bool> proxy_saw_c_url{false};
  21527. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21528. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21529. proxy_hits++;
  21530. if (req.path.find("/start") != std::string::npos) {
  21531. res.status = 302;
  21532. res.set_header("Location", "http://127.0.0.1:" +
  21533. std::to_string(bypass_server.port()) +
  21534. "/middle");
  21535. return;
  21536. }
  21537. if (req.path.find("/end") != std::string::npos) {
  21538. proxy_saw_c_url = true;
  21539. res.set_content("c-via-proxy", "text/plain");
  21540. return;
  21541. }
  21542. res.set_content("unexpected", "text/plain");
  21543. });
  21544. // public.example's "advertised" port is arbitrary (the request never lands
  21545. // there — it goes through the proxy), but use a dynamic value to stay
  21546. // friendly with sharded parallel runs.
  21547. int public_port = bypass_server.port();
  21548. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21549. bypass_hits++;
  21550. res.status = 302;
  21551. res.set_header("Location", "http://public.example:" +
  21552. std::to_string(public_port) + "/end");
  21553. });
  21554. proxy_mock.listen();
  21555. bypass_server.listen();
  21556. Client cli("public.example", public_port);
  21557. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21558. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21559. cli.set_no_proxy({"127.0.0.1"});
  21560. cli.set_follow_location(true);
  21561. auto res = cli.Get("/start");
  21562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21563. EXPECT_EQ(StatusCode::OK_200, res->status);
  21564. EXPECT_EQ("c-via-proxy", res->body);
  21565. EXPECT_GE(proxy_hits.load(), 2);
  21566. EXPECT_GE(bypass_hits.load(), 1);
  21567. EXPECT_TRUE(proxy_saw_c_url.load());
  21568. }
  21569. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21570. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21571. // request reconnects to the correct endpoint.
  21572. std::atomic<int> proxy_hits{0};
  21573. std::atomic<int> target_hits{0};
  21574. no_proxy_test::ScopedServer proxy_mock, target;
  21575. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21576. proxy_hits++;
  21577. res.set_content("via-proxy", "text/plain");
  21578. });
  21579. target.svr().Get(".*", [&](const Request &, Response &res) {
  21580. target_hits++;
  21581. res.set_content("direct", "text/plain");
  21582. });
  21583. proxy_mock.listen();
  21584. target.listen();
  21585. Client cli("public.example", target.port());
  21586. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21587. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21588. cli.set_keep_alive(true);
  21589. auto res1 = cli.Get("/a");
  21590. ASSERT_TRUE(res1);
  21591. EXPECT_EQ("via-proxy", res1->body);
  21592. EXPECT_EQ(1, proxy_hits.load());
  21593. EXPECT_EQ(0, target_hits.load());
  21594. cli.set_no_proxy({"public.example"});
  21595. auto res2 = cli.Get("/b");
  21596. ASSERT_TRUE(res2);
  21597. EXPECT_EQ("direct", res2->body);
  21598. EXPECT_EQ(1, proxy_hits.load());
  21599. EXPECT_EQ(1, target_hits.load());
  21600. }
  21601. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21602. namespace proxy_tunnel_test {
  21603. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21604. class ScopedSSLServer {
  21605. public:
  21606. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21607. port_ = svr_.bind_to_any_port("127.0.0.1");
  21608. }
  21609. ~ScopedSSLServer() {
  21610. svr_.stop();
  21611. if (th_.joinable()) { th_.join(); }
  21612. }
  21613. SSLServer &svr() { return svr_; }
  21614. int port() const { return port_; }
  21615. void listen() {
  21616. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21617. svr_.wait_until_ready();
  21618. }
  21619. private:
  21620. SSLServer svr_;
  21621. std::thread th_;
  21622. int port_ = 0;
  21623. };
  21624. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21625. class ScopedConnectProxy {
  21626. public:
  21627. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21628. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21629. if (listen_fd_ < 0) { return; }
  21630. int yes = 1;
  21631. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21632. sockaddr_in a{};
  21633. a.sin_family = AF_INET;
  21634. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21635. a.sin_port = 0;
  21636. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21637. return;
  21638. }
  21639. socklen_t alen = sizeof(a);
  21640. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  21641. 0) {
  21642. return;
  21643. }
  21644. port_ = ntohs(a.sin_port);
  21645. if (::listen(listen_fd_, 1) != 0) { return; }
  21646. th_ = std::thread([this] { run(); });
  21647. }
  21648. ~ScopedConnectProxy() {
  21649. stop_ = true;
  21650. if (listen_fd_ >= 0) {
  21651. ::shutdown(listen_fd_, SHUT_RDWR);
  21652. ::close(listen_fd_);
  21653. }
  21654. if (th_.joinable()) { th_.join(); }
  21655. }
  21656. int port() const { return port_; }
  21657. int connect_hits() const { return connect_hits_.load(); }
  21658. // Head of the last CONNECT request, as the proxy saw it on the wire.
  21659. std::string connect_request() const {
  21660. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21661. return connect_request_;
  21662. }
  21663. private:
  21664. void run() {
  21665. while (!stop_.load()) {
  21666. fd_set rfds;
  21667. FD_ZERO(&rfds);
  21668. FD_SET(listen_fd_, &rfds);
  21669. timeval tv{0, 100 * 1000};
  21670. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  21671. if (sel <= 0) { continue; }
  21672. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  21673. if (client_fd < 0) { continue; }
  21674. std::string req;
  21675. char buf[2048];
  21676. while (req.find("\r\n\r\n") == std::string::npos) {
  21677. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  21678. if (n <= 0) { break; }
  21679. req.append(buf, static_cast<size_t>(n));
  21680. }
  21681. if (req.compare(0, 7, "CONNECT") != 0) {
  21682. ::close(client_fd);
  21683. continue;
  21684. }
  21685. connect_hits_++;
  21686. {
  21687. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21688. connect_request_ = req;
  21689. }
  21690. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  21691. ::send(client_fd, ok, std::strlen(ok), 0);
  21692. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  21693. sockaddr_in o{};
  21694. o.sin_family = AF_INET;
  21695. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21696. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  21697. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  21698. 0) {
  21699. ::close(client_fd);
  21700. ::close(origin_fd);
  21701. continue;
  21702. }
  21703. auto forward = [](int from, int to) {
  21704. char b[8192];
  21705. for (;;) {
  21706. ssize_t n = ::recv(from, b, sizeof(b), 0);
  21707. if (n <= 0) { break; }
  21708. ssize_t off = 0;
  21709. while (off < n) {
  21710. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  21711. if (s <= 0) {
  21712. off = n;
  21713. break;
  21714. }
  21715. off += s;
  21716. }
  21717. }
  21718. ::shutdown(to, SHUT_WR);
  21719. };
  21720. std::thread t1([&] { forward(client_fd, origin_fd); });
  21721. std::thread t2([&] { forward(origin_fd, client_fd); });
  21722. t1.join();
  21723. t2.join();
  21724. ::close(client_fd);
  21725. ::close(origin_fd);
  21726. }
  21727. }
  21728. int forward_port_ = -1;
  21729. int listen_fd_ = -1;
  21730. int port_ = 0;
  21731. std::thread th_;
  21732. std::atomic<bool> stop_{false};
  21733. std::atomic<int> connect_hits_{0};
  21734. mutable std::mutex connect_request_mutex_;
  21735. std::string connect_request_;
  21736. };
  21737. // Sends one request through the CONNECT proxy to the TLS origin with a
  21738. // credential configured for each hop, and checks that each credential reaches
  21739. // only the hop it was configured for: the proxy's on the CONNECT request, the
  21740. // origin's (every header in origin_headers) on the tunnelled request.
  21741. void CredentialsStayWithTheirHop(
  21742. const std::function<void(SSLClient &)> &set_credentials,
  21743. const std::string &scheme,
  21744. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  21745. std::atomic<int> origin_hits{0};
  21746. std::atomic<bool> origin_saw_proxy_authz{false};
  21747. std::atomic<bool> origin_saw_headers{false};
  21748. ScopedSSLServer origin;
  21749. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  21750. origin_hits++;
  21751. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  21752. origin_saw_headers =
  21753. std::all_of(origin_headers.begin(), origin_headers.end(),
  21754. [&](const std::string &h) { return req.has_header(h); });
  21755. res.set_content("ok", "text/plain");
  21756. });
  21757. origin.listen();
  21758. ScopedConnectProxy proxy(origin.port());
  21759. ASSERT_NE(0, proxy.port());
  21760. // Pinned to 127.0.0.1 for the same reason as the test below.
  21761. SSLClient cli("127.0.0.1", origin.port());
  21762. cli.enable_server_certificate_verification(false);
  21763. cli.set_proxy("127.0.0.1", proxy.port());
  21764. set_credentials(cli);
  21765. auto res = cli.Get("/x");
  21766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21767. EXPECT_EQ(StatusCode::OK_200, res->status);
  21768. EXPECT_EQ(1, origin_hits.load());
  21769. EXPECT_EQ(1, proxy.connect_hits());
  21770. EXPECT_TRUE(origin_saw_headers.load());
  21771. EXPECT_FALSE(origin_saw_proxy_authz.load())
  21772. << "Proxy-Authorization must not be sent inside the tunnel";
  21773. auto connect_req = proxy.connect_request();
  21774. EXPECT_NE(std::string::npos,
  21775. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  21776. for (const auto &h : origin_headers) {
  21777. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  21778. << h << " must not be sent to the proxy on CONNECT";
  21779. }
  21780. }
  21781. } // namespace proxy_tunnel_test
  21782. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  21783. proxy_tunnel_test::CredentialsStayWithTheirHop(
  21784. [](SSLClient &cli) {
  21785. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  21786. cli.set_basic_auth("origin-user", "origin-pass");
  21787. },
  21788. "Basic");
  21789. }
  21790. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  21791. proxy_tunnel_test::CredentialsStayWithTheirHop(
  21792. [](SSLClient &cli) {
  21793. cli.set_proxy_bearer_token_auth("proxy-token");
  21794. cli.set_bearer_token_auth("origin-token");
  21795. },
  21796. "Bearer");
  21797. }
  21798. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  21799. proxy_tunnel_test::CredentialsStayWithTheirHop(
  21800. [](SSLClient &cli) {
  21801. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  21802. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  21803. {"Cookie", "sid=origin-session"},
  21804. {"X-Api-Key", "origin-key"}});
  21805. },
  21806. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  21807. }
  21808. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  21809. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  21810. // retry; otherwise proxy creds would be sent to the origin.
  21811. std::atomic<int> origin_hits{0};
  21812. std::atomic<bool> origin_saw_proxy_authz{false};
  21813. proxy_tunnel_test::ScopedSSLServer origin;
  21814. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  21815. origin_hits++;
  21816. if (req.has_header("Proxy-Authorization")) {
  21817. origin_saw_proxy_authz = true;
  21818. }
  21819. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21820. res.set_header("Proxy-Authenticate",
  21821. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  21822. "algorithm=MD5");
  21823. });
  21824. origin.listen();
  21825. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  21826. ASSERT_NE(0, proxy.port());
  21827. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  21828. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  21829. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  21830. // and answer with its own status, making this test flaky.
  21831. SSLClient cli("127.0.0.1", origin.port());
  21832. cli.enable_server_certificate_verification(false);
  21833. cli.set_proxy("127.0.0.1", proxy.port());
  21834. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21835. auto res = cli.Get("/x");
  21836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21837. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21838. EXPECT_EQ(1, origin_hits.load());
  21839. EXPECT_FALSE(origin_saw_proxy_authz.load());
  21840. EXPECT_EQ(1, proxy.connect_hits());
  21841. }
  21842. #endif