test.cc 821 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // Empty quality value
  892. EXPECT_FALSE(
  893. detail::parse_accept_header("text/html;q=,application/json", result));
  894. // Invalid media type format (no slash and not wildcard)
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("invalidtype,application/json", result));
  897. // Valid cases should still work
  898. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  899. EXPECT_EQ(result.size(), 1U);
  900. EXPECT_EQ(result[0], "*/*");
  901. EXPECT_TRUE(detail::parse_accept_header("*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*");
  904. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "text/*");
  907. }
  908. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  909. // elements, so a leading, trailing or doubled comma is a legal Accept value
  910. // and must not be answered with 400 Bad Request.
  911. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  912. struct {
  913. const char *value;
  914. std::vector<std::string> expected;
  915. } cases[] = {
  916. {",application/json", {"application/json"}},
  917. {"text/html,", {"text/html"}},
  918. {"text/html,,*/*", {"text/html", "*/*"}},
  919. // An empty element may be spelled with whitespace in it
  920. {"text/html, , application/json", {"text/html", "application/json"}},
  921. // Nothing but empty elements is an empty list, which means the same
  922. // thing as no Accept header at all
  923. {",,,", {}},
  924. // Quality values still apply across ignored empty elements
  925. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  926. };
  927. for (const auto &c : cases) {
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  930. << "value: " << c.value;
  931. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  932. }
  933. // An invalid entry is still rejected when empty elements surround it
  934. std::vector<std::string> result;
  935. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  936. }
  937. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  938. Server svr;
  939. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  940. EXPECT_EQ(req.accept_content_types.size(), 3U);
  941. EXPECT_EQ(req.accept_content_types[0], "application/json");
  942. EXPECT_EQ(req.accept_content_types[1], "text/html");
  943. EXPECT_EQ(req.accept_content_types[2], "*/*");
  944. res.set_content("ok", "text/plain");
  945. });
  946. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  947. EXPECT_TRUE(false);
  948. res.set_content("bad request", "text/plain");
  949. });
  950. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  951. auto se = detail::scope_exit([&] {
  952. svr.stop();
  953. listen_thread.join();
  954. ASSERT_FALSE(svr.is_running());
  955. });
  956. svr.wait_until_ready();
  957. Client cli("localhost", PORT);
  958. {
  959. auto res = cli.Get(
  960. "/accept_ok",
  961. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  963. EXPECT_EQ(StatusCode::OK_200, res->status);
  964. }
  965. {
  966. auto res = cli.Get("/accept_bad_request",
  967. Headers{{"Accept", "text/html;q=abc,application/json"}});
  968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  970. }
  971. }
  972. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  973. Server svr;
  974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  975. res.set_content("ok", "text/plain");
  976. });
  977. std::atomic<int> start_count{0};
  978. std::atomic<bool> running_when_called{false};
  979. svr.set_start_handler([&]() {
  980. running_when_called = svr.is_running();
  981. start_count++;
  982. });
  983. auto port = svr.bind_to_any_port(HOST);
  984. std::thread t([&]() { svr.listen_after_bind(); });
  985. auto se = detail::scope_exit([&] {
  986. svr.stop();
  987. t.join();
  988. ASSERT_FALSE(svr.is_running());
  989. });
  990. svr.wait_until_ready();
  991. // A successful request proves the accept loop is running, which the start
  992. // handler precedes; so by now the handler must have run exactly once.
  993. Client cli(HOST, port);
  994. cli.set_connection_timeout(std::chrono::seconds(5));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  997. EXPECT_EQ(StatusCode::OK_200, res->status);
  998. EXPECT_EQ(1, start_count.load());
  999. EXPECT_TRUE(running_when_called.load());
  1000. }
  1001. TEST(DivideTest, DivideStringTests) {
  1002. auto divide = [](const std::string &str, char d) {
  1003. std::string lhs;
  1004. std::string rhs;
  1005. detail::divide(str, d,
  1006. [&](const char *lhs_data, std::size_t lhs_size,
  1007. const char *rhs_data, std::size_t rhs_size) {
  1008. lhs.assign(lhs_data, lhs_size);
  1009. rhs.assign(rhs_data, rhs_size);
  1010. });
  1011. return std::make_pair(std::move(lhs), std::move(rhs));
  1012. };
  1013. {
  1014. const auto res = divide("", '=');
  1015. EXPECT_EQ(res.first, "");
  1016. EXPECT_EQ(res.second, "");
  1017. }
  1018. {
  1019. const auto res = divide("=", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide(" ", '=');
  1025. EXPECT_EQ(res.first, " ");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide("a", '=');
  1030. EXPECT_EQ(res.first, "a");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a=", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("=b", '=');
  1040. EXPECT_EQ(res.first, "");
  1041. EXPECT_EQ(res.second, "b");
  1042. }
  1043. {
  1044. const auto res = divide("a=b", '=');
  1045. EXPECT_EQ(res.first, "a");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b=", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b=");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=c", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=c");
  1057. }
  1058. }
  1059. TEST(SplitTest, ParseQueryString) {
  1060. string s = "key1=val1&key2=val2&key3=val3";
  1061. Params dic;
  1062. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1063. [&](const char *b, const char *e) {
  1064. string key, val;
  1065. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1066. if (key.empty()) {
  1067. key.assign(b2, e2);
  1068. } else {
  1069. val.assign(b2, e2);
  1070. }
  1071. });
  1072. dic.emplace(key, val);
  1073. });
  1074. EXPECT_EQ("val1", dic.find("key1")->second);
  1075. EXPECT_EQ("val2", dic.find("key2")->second);
  1076. EXPECT_EQ("val3", dic.find("key3")->second);
  1077. }
  1078. TEST(SplitTest, ParseInvalidQueryTests) {
  1079. {
  1080. string s = " ";
  1081. Params dict;
  1082. detail::parse_query_text(s, dict);
  1083. EXPECT_TRUE(dict.empty());
  1084. }
  1085. {
  1086. string s = " = =";
  1087. Params dict;
  1088. detail::parse_query_text(s, dict);
  1089. EXPECT_TRUE(dict.empty());
  1090. }
  1091. }
  1092. TEST(ParseQueryTest, ParseQueryString) {
  1093. {
  1094. std::string s = "key1=val1&key2=val2&key3=val3";
  1095. Params dic;
  1096. detail::parse_query_text(s, dic);
  1097. EXPECT_EQ("val1", dic.find("key1")->second);
  1098. EXPECT_EQ("val2", dic.find("key2")->second);
  1099. EXPECT_EQ("val3", dic.find("key3")->second);
  1100. }
  1101. {
  1102. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1103. Params dic;
  1104. detail::parse_query_text(s, dic);
  1105. EXPECT_EQ("", dic.find("key1")->second);
  1106. EXPECT_EQ("val1", dic.find("key2")->second);
  1107. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1108. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1109. }
  1110. }
  1111. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1112. Params dic;
  1113. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1114. dic.emplace("key1", "val1");
  1115. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1116. dic.emplace("key2", "val2");
  1117. dic.emplace("key3", "val3");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1119. }
  1120. // Joins every entry of a Headers or Params into "key=value " so a whole
  1121. // traversal can be compared in one assertion. Both are instantiations of the
  1122. // same insertion-ordered container, so one helper serves both.
  1123. template <typename Map> static std::string entries_to_string(const Map &m) {
  1124. std::string s;
  1125. for (const auto &entry : m) {
  1126. s += entry.first + "=" + entry.second + " ";
  1127. }
  1128. return s;
  1129. }
  1130. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1131. // Params used to be a std::multimap, which sorted by name and handed the
  1132. // caller's query back alphabetised. A client signing its query string could
  1133. // not reproduce the order it asked for.
  1134. Params dic;
  1135. dic.emplace("zulu", "1");
  1136. dic.emplace("alpha", "2");
  1137. dic.emplace("mike", "3");
  1138. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1139. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1140. }
  1141. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1142. Params dic;
  1143. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1144. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1145. }
  1146. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1147. Request req;
  1148. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1149. req.params);
  1150. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1151. EXPECT_EQ("first", req.get_param_value("tag"));
  1152. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1153. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1154. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1155. EXPECT_EQ("", req.get_param_value("tag", 3));
  1156. }
  1157. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1158. // Params shares its container with Headers, which matches field names
  1159. // case-insensitively. Parameter names must not pick that up.
  1160. Params dic;
  1161. dic.emplace("Key", "upper");
  1162. dic.emplace("key", "lower");
  1163. EXPECT_EQ(2U, dic.size());
  1164. EXPECT_EQ(1U, dic.count("Key"));
  1165. EXPECT_EQ(1U, dic.count("key"));
  1166. EXPECT_EQ("upper", dic.find("Key")->second);
  1167. EXPECT_EQ("lower", dic.find("key")->second);
  1168. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1169. }
  1170. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1171. Server svr;
  1172. std::string order;
  1173. svr.Get("/order", [&](const Request &req, Response &res) {
  1174. order = entries_to_string(req.params);
  1175. res.set_content("ok", "text/plain");
  1176. });
  1177. auto port = svr.bind_to_any_port(HOST);
  1178. thread t = thread([&] { svr.listen_after_bind(); });
  1179. auto se = detail::scope_exit([&] {
  1180. svr.stop();
  1181. t.join();
  1182. ASSERT_FALSE(svr.is_running());
  1183. });
  1184. svr.wait_until_ready();
  1185. Client cli(HOST, port);
  1186. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1187. ASSERT_TRUE(res);
  1188. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1189. }
  1190. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1191. Server svr;
  1192. std::string field_order, file_order;
  1193. svr.Post("/order", [&](const Request &req, Response &res) {
  1194. for (const auto &field : req.form.fields) {
  1195. field_order += field.first + "=" + field.second.content + " ";
  1196. }
  1197. for (const auto &file : req.form.files) {
  1198. file_order += file.first + "=" + file.second.filename + " ";
  1199. }
  1200. res.set_content("ok", "text/plain");
  1201. });
  1202. auto port = svr.bind_to_any_port(HOST);
  1203. thread t = thread([&] { svr.listen_after_bind(); });
  1204. auto se = detail::scope_exit([&] {
  1205. svr.stop();
  1206. t.join();
  1207. ASSERT_FALSE(svr.is_running());
  1208. });
  1209. svr.wait_until_ready();
  1210. UploadFormDataItems items = {
  1211. {"zulu", "1", "", ""},
  1212. {"alpha", "2", "", ""},
  1213. {"mike", "3", "", ""},
  1214. {"zebra", "z", "z.txt", "text/plain"},
  1215. {"apple", "a", "a.txt", "text/plain"},
  1216. };
  1217. Client cli(HOST, port);
  1218. auto res = cli.Post("/order", items);
  1219. ASSERT_TRUE(res);
  1220. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1221. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1222. }
  1223. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1224. Server svr;
  1225. std::vector<std::string> values;
  1226. std::string first, second, out_of_range, order;
  1227. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1228. values = req.form.get_fields("tag");
  1229. first = req.form.get_field("tag", 0);
  1230. second = req.form.get_field("tag", 1);
  1231. out_of_range = req.form.get_field("tag", 2);
  1232. for (const auto &field : req.form.fields) {
  1233. order += field.first + "=" + field.second.content + " ";
  1234. }
  1235. res.set_content("ok", "text/plain");
  1236. });
  1237. auto port = svr.bind_to_any_port(HOST);
  1238. thread t = thread([&] { svr.listen_after_bind(); });
  1239. auto se = detail::scope_exit([&] {
  1240. svr.stop();
  1241. t.join();
  1242. ASSERT_FALSE(svr.is_running());
  1243. });
  1244. svr.wait_until_ready();
  1245. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1246. // not adjacent in the container.
  1247. UploadFormDataItems items = {
  1248. {"tag", "first", "", ""},
  1249. {"other", "x", "", ""},
  1250. {"tag", "second", "", ""},
  1251. };
  1252. Client cli(HOST, port);
  1253. auto res = cli.Post("/repeated", items);
  1254. ASSERT_TRUE(res);
  1255. ASSERT_EQ(2U, values.size());
  1256. EXPECT_EQ("first", values[0]);
  1257. EXPECT_EQ("second", values[1]);
  1258. EXPECT_EQ("first", first);
  1259. EXPECT_EQ("second", second);
  1260. // std::multimap already kept entries sharing a name in insertion order, so
  1261. // everything above passes without this change too. The whole traversal is
  1262. // what tells the two apart: sorting by name would hoist "other" to the front
  1263. // and the two "tag" parts would end up adjacent.
  1264. EXPECT_EQ("tag=first other=x tag=second ", order);
  1265. // Advancing past the last entry of a name used to run off the container;
  1266. // the container's saturating increment makes it return the default instead.
  1267. EXPECT_EQ("", out_of_range);
  1268. }
  1269. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1270. // Server::read_content() keeps a FormFields::iterator alive across the
  1271. // content callbacks that fill the part it points at. The container is
  1272. // vector-backed, so a later emplace can reallocate and invalidate an older
  1273. // iterator; 64 parts grow the vector through seven reallocations, which
  1274. // checks that every part's content still lands in its own entry.
  1275. const size_t part_count = 64;
  1276. // One formula for both the parts sent and the values expected back, so the
  1277. // two cannot drift apart.
  1278. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1279. auto content_of = [](size_t i) {
  1280. return std::string(64, static_cast<char>('a' + (i % 26)));
  1281. };
  1282. Server svr;
  1283. std::vector<std::pair<std::string, std::string>> received;
  1284. svr.Post("/many", [&](const Request &req, Response &res) {
  1285. for (const auto &field : req.form.fields) {
  1286. received.emplace_back(field.first, field.second.content);
  1287. }
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. auto port = svr.bind_to_any_port(HOST);
  1291. thread t = thread([&] { svr.listen_after_bind(); });
  1292. auto se = detail::scope_exit([&] {
  1293. svr.stop();
  1294. t.join();
  1295. ASSERT_FALSE(svr.is_running());
  1296. });
  1297. svr.wait_until_ready();
  1298. UploadFormDataItems items;
  1299. for (size_t i = 0; i < part_count; i++) {
  1300. items.push_back({name_of(i), content_of(i), "", ""});
  1301. }
  1302. Client cli(HOST, port);
  1303. auto res = cli.Post("/many", items);
  1304. ASSERT_TRUE(res);
  1305. ASSERT_EQ(part_count, received.size());
  1306. for (size_t i = 0; i < part_count; i++) {
  1307. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1308. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1309. }
  1310. }
  1311. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1312. string content_type = "multipart/form-data; boundary=something";
  1313. string boundary;
  1314. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1315. EXPECT_TRUE(ret);
  1316. EXPECT_EQ(boundary, "something");
  1317. }
  1318. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1319. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1320. string boundary;
  1321. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1322. EXPECT_TRUE(ret);
  1323. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1324. }
  1325. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1326. string content_type =
  1327. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1328. string boundary;
  1329. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1330. EXPECT_TRUE(ret);
  1331. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1332. }
  1333. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1334. string content_type =
  1335. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1336. string boundary;
  1337. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1338. EXPECT_TRUE(ret);
  1339. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1340. }
  1341. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1342. const string boundary(70, 'a');
  1343. string content_type = "multipart/form-data; boundary=" + boundary;
  1344. string parsed;
  1345. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1346. EXPECT_TRUE(ret);
  1347. EXPECT_EQ(parsed, boundary);
  1348. }
  1349. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1350. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1351. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1352. string parsed;
  1353. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1354. EXPECT_FALSE(ret);
  1355. }
  1356. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1357. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1358. // is 72 characters on the wire and still valid.
  1359. const string boundary(70, 'a');
  1360. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1361. string parsed;
  1362. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1363. EXPECT_EQ(parsed, boundary);
  1364. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1365. parsed.clear();
  1366. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1367. }
  1368. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1369. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1370. // The parameter parser must not treat that '=' as the key/value separator.
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1373. "charset=UTF-8";
  1374. string parsed;
  1375. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1376. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1379. // A ';' inside the quoted-string is part of the value, not a parameter
  1380. // separator, so it must not truncate the boundary.
  1381. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1382. string parsed;
  1383. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1384. EXPECT_EQ(parsed, "a;b");
  1385. }
  1386. TEST(ParseDispositionParamsTest, QuotedValues) {
  1387. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1388. // ';' and '=' are ordinary characters inside one.
  1389. struct {
  1390. const char *value;
  1391. std::vector<std::pair<const char *, const char *>> expected;
  1392. } cases[] = {
  1393. {"name=\"file1\"; filename=\"a.txt\"",
  1394. {{"name", "file1"}, {"filename", "a.txt"}}},
  1395. // Whitespace around '=' and ';' is still trimmed
  1396. {"name=\"file2\" ;filename = \"a.html\"",
  1397. {{"name", "file2"}, {"filename", "a.html"}}},
  1398. // '=' inside the value used to leave only the text after the last one
  1399. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1400. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1401. {"name=\"x=y\"", {{"name", "x=y"}}},
  1402. // ';' inside the value used to truncate the pair and leave a bogus one
  1403. {"name=\"file3\"; filename=\"a;b.txt\"",
  1404. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1405. // An unquoted value keeps working, and so does filename*
  1406. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1407. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1408. // A parameter with no key is dropped rather than turned into one whose
  1409. // key is the value
  1410. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1411. };
  1412. for (const auto &c : cases) {
  1413. Params params;
  1414. detail::parse_disposition_params(c.value, params);
  1415. for (const auto &kv : c.expected) {
  1416. auto it = params.find(kv.first);
  1417. ASSERT_NE(it, params.end())
  1418. << "value: " << c.value << ", key: " << kv.first;
  1419. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1420. }
  1421. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1422. }
  1423. }
  1424. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1425. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1426. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1427. Server svr;
  1428. std::string field_value, file_name, file_filename;
  1429. bool has_field = false, has_file = false;
  1430. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1431. has_field = req.form.has_field("x=y");
  1432. field_value = req.form.get_field("x=y");
  1433. has_file = req.form.has_file("file1");
  1434. const auto &file = req.form.get_file("file1");
  1435. file_name = file.name;
  1436. file_filename = file.filename;
  1437. res.set_content("ok", "text/plain");
  1438. });
  1439. auto port = svr.bind_to_any_port(HOST);
  1440. thread t = thread([&] { svr.listen_after_bind(); });
  1441. auto se = detail::scope_exit([&] {
  1442. svr.stop();
  1443. t.join();
  1444. ASSERT_FALSE(svr.is_running());
  1445. });
  1446. svr.wait_until_ready();
  1447. UploadFormDataItems items = {
  1448. {"x=y", "field-value", "", ""},
  1449. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1450. };
  1451. Client cli(HOST, port);
  1452. auto res = cli.Post("/quoted", items);
  1453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1454. ASSERT_EQ(StatusCode::OK_200, res->status);
  1455. EXPECT_TRUE(has_field);
  1456. EXPECT_EQ("field-value", field_value);
  1457. EXPECT_TRUE(has_file);
  1458. EXPECT_EQ("file1", file_name);
  1459. EXPECT_EQ("a;b=report.pdf", file_filename);
  1460. }
  1461. TEST(GetHeaderValueTest, DefaultValue) {
  1462. Headers headers = {{"Dummy", "Dummy"}};
  1463. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1464. EXPECT_STREQ("text/plain", val);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValueInt) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1469. EXPECT_EQ(100ull, val);
  1470. }
  1471. TEST(GetHeaderValueTest, RegularValue) {
  1472. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1474. EXPECT_STREQ("text/html", val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, SetContent) {
  1482. Response res;
  1483. res.set_content("html", "text/html");
  1484. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1485. res.set_content("text", "text/plain");
  1486. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1487. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1488. }
  1489. TEST(GetHeaderValueTest, RegularValueInt) {
  1490. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1491. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1492. EXPECT_EQ(100ull, val);
  1493. }
  1494. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1495. Headers headers = {{"Content-Length", "x"}};
  1496. auto is_invalid_value = false;
  1497. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1498. is_invalid_value);
  1499. EXPECT_EQ(0ull, val);
  1500. EXPECT_TRUE(is_invalid_value);
  1501. }
  1502. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1503. // An all-digit value that overflows size_t must be reported as invalid, not
  1504. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1505. // a large length to a small one on 32-bit builds, leaving the framing length
  1506. // wrong while is_invalid_value stayed false.
  1507. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1508. auto is_invalid_value = false;
  1509. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1510. is_invalid_value);
  1511. EXPECT_TRUE(is_invalid_value);
  1512. // A well-formed length is unaffected.
  1513. Headers ok = {{"Content-Length", "1234"}};
  1514. is_invalid_value = false;
  1515. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1516. is_invalid_value);
  1517. EXPECT_EQ(1234ull, val);
  1518. EXPECT_FALSE(is_invalid_value);
  1519. }
  1520. TEST(GetHeaderValueTest, Range) {
  1521. {
  1522. Headers headers = {make_range_header({{1, -1}})};
  1523. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1524. EXPECT_STREQ("bytes=1-", val);
  1525. }
  1526. {
  1527. Headers headers = {make_range_header({{-1, 1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=-1", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{1, 10}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=1-10", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10, 100-", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=0-0, -1", val);
  1550. }
  1551. }
  1552. TEST(BearerTokenAuthTest, SchemeValidation) {
  1553. // A value shorter than "Bearer " must not throw from the fixed-length
  1554. // substr, and a non-Bearer scheme must not be reported as a token.
  1555. struct {
  1556. const char *value;
  1557. const char *expected;
  1558. } cases[] = {
  1559. {"x", ""},
  1560. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1561. {"Bearer abc123", "abc123"},
  1562. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1563. };
  1564. for (const auto &c : cases) {
  1565. Request req;
  1566. req.set_header("Authorization", c.value);
  1567. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1568. }
  1569. }
  1570. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1571. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1572. // to depend on the standard library (libstdc++ handed back duplicates in
  1573. // reverse insertion order, libc++ in insertion order).
  1574. Request req;
  1575. req.set_header("Accept-Encoding", "gzip");
  1576. req.set_header("Accept-Encoding", "deflate");
  1577. req.set_header("Accept-Encoding", "br");
  1578. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1579. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1580. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1581. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1582. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1583. }
  1584. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1585. Request req;
  1586. req.set_header("X-Test", "only");
  1587. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1588. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1589. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1590. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1591. }
  1592. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1593. Headers headers;
  1594. headers.emplace("Host", "example.com");
  1595. headers.emplace("Accept-Encoding", "gzip");
  1596. headers.emplace("User-Agent", "test");
  1597. headers.emplace("Accept-Encoding", "deflate");
  1598. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1599. "Accept-Encoding=deflate ",
  1600. entries_to_string(headers));
  1601. }
  1602. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1603. Headers headers = {{"Content-Type", "text/html"},
  1604. {"CONTENT-TYPE", "text/xml"}};
  1605. EXPECT_EQ(2U, headers.count("content-type"));
  1606. auto it = headers.find("content-type");
  1607. ASSERT_TRUE(it != headers.end());
  1608. EXPECT_EQ("text/html", it->second);
  1609. }
  1610. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1611. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1612. // drop only those fields and leave everything positioned between them.
  1613. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1614. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1615. auto rng = headers.equal_range("a");
  1616. headers.erase(rng.first, rng.second);
  1617. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1618. }
  1619. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1620. Headers headers = {
  1621. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1622. EXPECT_EQ(3U, headers.erase("A"));
  1623. EXPECT_EQ(0U, headers.count("A"));
  1624. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1625. }
  1626. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1627. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1628. headers.emplace_front("Host", "example.com");
  1629. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1630. entries_to_string(headers));
  1631. }
  1632. TEST(ParseHeaderValueTest, Range) {
  1633. {
  1634. Ranges ranges;
  1635. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1636. EXPECT_TRUE(ret);
  1637. EXPECT_EQ(1u, ranges.size());
  1638. EXPECT_EQ(1u, ranges[0].first);
  1639. EXPECT_EQ(-1, ranges[0].second);
  1640. }
  1641. {
  1642. Ranges ranges;
  1643. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1644. EXPECT_TRUE(ret);
  1645. EXPECT_EQ(1u, ranges.size());
  1646. EXPECT_EQ(-1, ranges[0].first);
  1647. EXPECT_EQ(1u, ranges[0].second);
  1648. }
  1649. {
  1650. Ranges ranges;
  1651. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1652. EXPECT_TRUE(ret);
  1653. EXPECT_EQ(1u, ranges.size());
  1654. EXPECT_EQ(1u, ranges[0].first);
  1655. EXPECT_EQ(10u, ranges[0].second);
  1656. }
  1657. {
  1658. Ranges ranges;
  1659. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1660. EXPECT_FALSE(ret);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1665. EXPECT_TRUE(ret);
  1666. EXPECT_EQ(2u, ranges.size());
  1667. EXPECT_EQ(1u, ranges[0].first);
  1668. EXPECT_EQ(10u, ranges[0].second);
  1669. EXPECT_EQ(100u, ranges[1].first);
  1670. EXPECT_EQ(-1, ranges[1].second);
  1671. }
  1672. {
  1673. Ranges ranges;
  1674. auto ret =
  1675. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1676. EXPECT_TRUE(ret);
  1677. EXPECT_EQ(3u, ranges.size());
  1678. EXPECT_EQ(1u, ranges[0].first);
  1679. EXPECT_EQ(10u, ranges[0].second);
  1680. EXPECT_EQ(100u, ranges[1].first);
  1681. EXPECT_EQ(200u, ranges[1].second);
  1682. EXPECT_EQ(300u, ranges[2].first);
  1683. EXPECT_EQ(400u, ranges[2].second);
  1684. }
  1685. {
  1686. Ranges ranges;
  1687. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1688. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1689. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1690. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1700. EXPECT_TRUE(ranges.empty());
  1701. }
  1702. }
  1703. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1704. Request req;
  1705. req.set_header("Accept-Encoding", "gzip");
  1706. Response res;
  1707. res.set_header("Content-Type", "text/plain");
  1708. auto ret = detail::encoding_type(req, res);
  1709. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1710. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1711. #else
  1712. EXPECT_TRUE(ret == detail::EncodingType::None);
  1713. #endif
  1714. }
  1715. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1716. Request req;
  1717. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1718. Response res;
  1719. res.set_header("Content-Type", "text/plain");
  1720. auto ret = detail::encoding_type(req, res);
  1721. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1722. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1723. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1724. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1725. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1726. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1727. #else
  1728. EXPECT_TRUE(ret == detail::EncodingType::None);
  1729. #endif
  1730. }
  1731. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1732. Request req;
  1733. req.set_header("Accept-Encoding",
  1734. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1749. // All supported encodings rejected with q=0 should return None
  1750. Request req;
  1751. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. EXPECT_TRUE(ret == detail::EncodingType::None);
  1756. }
  1757. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1758. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1759. Request req;
  1760. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1761. Response res;
  1762. res.set_header("Content-Type", "text/plain");
  1763. auto ret = detail::encoding_type(req, res);
  1764. EXPECT_TRUE(ret == detail::EncodingType::None);
  1765. }
  1766. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1767. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1768. Request req;
  1769. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1770. Response res;
  1771. res.set_header("Content-Type", "text/plain");
  1772. auto ret = detail::encoding_type(req, res);
  1773. EXPECT_TRUE(ret == detail::EncodingType::None);
  1774. }
  1775. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1776. // RFC 7231: Accept-Encoding values are case-insensitive
  1777. Request req;
  1778. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1779. Response res;
  1780. res.set_header("Content-Type", "text/plain");
  1781. auto ret = detail::encoding_type(req, res);
  1782. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1783. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1784. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1785. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1786. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1787. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1788. #else
  1789. EXPECT_TRUE(ret == detail::EncodingType::None);
  1790. #endif
  1791. }
  1792. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1793. // q value should determine priority, not hardcoded order
  1794. Request req;
  1795. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1796. Response res;
  1797. res.set_header("Content-Type", "text/plain");
  1798. auto ret = detail::encoding_type(req, res);
  1799. // gzip has highest q=1.0, so it should be selected even though
  1800. // br and zstd are also supported
  1801. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1802. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1803. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1804. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1805. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1806. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1807. #else
  1808. EXPECT_TRUE(ret == detail::EncodingType::None);
  1809. #endif
  1810. }
  1811. TEST(BufferStreamTest, read) {
  1812. detail::BufferStream strm1;
  1813. Stream &strm = strm1;
  1814. EXPECT_EQ(5, strm.write("hello"));
  1815. char buf[512];
  1816. EXPECT_EQ(2, strm.read(buf, 2));
  1817. EXPECT_EQ('h', buf[0]);
  1818. EXPECT_EQ('e', buf[1]);
  1819. EXPECT_EQ(2, strm.read(buf, 2));
  1820. EXPECT_EQ('l', buf[0]);
  1821. EXPECT_EQ('l', buf[1]);
  1822. EXPECT_EQ(1, strm.read(buf, 1));
  1823. EXPECT_EQ('o', buf[0]);
  1824. EXPECT_EQ(0, strm.read(buf, 1));
  1825. }
  1826. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1827. auto host = "www.httpwatch.com";
  1828. auto ip = hosted_at(host);
  1829. EXPECT_EQ("23.96.13.243", ip);
  1830. std::vector<std::string> addrs;
  1831. hosted_at(host, addrs);
  1832. EXPECT_EQ(1u, addrs.size());
  1833. }
  1834. #if 0 // It depends on each test environment...
  1835. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1836. auto host = "www.youtube.com";
  1837. std::vector<std::string> addrs;
  1838. hosted_at(host, addrs);
  1839. EXPECT_EQ(20u, addrs.size());
  1840. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1841. EXPECT_TRUE(it != addrs.end());
  1842. }
  1843. #endif
  1844. class ChunkedEncodingTest : public ::testing::Test {
  1845. protected:
  1846. ChunkedEncodingTest()
  1847. : cli_(HOST, PORT)
  1848. #ifdef CPPHTTPLIB_SSL_ENABLED
  1849. ,
  1850. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1851. #endif
  1852. {
  1853. cli_.set_connection_timeout(2);
  1854. #ifdef CPPHTTPLIB_SSL_ENABLED
  1855. cli_.enable_server_certificate_verification(false);
  1856. #endif
  1857. }
  1858. virtual void SetUp() {
  1859. read_file("./image.jpg", image_data_);
  1860. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1861. res.set_content("Hello World!", "text/plain");
  1862. });
  1863. svr_.Get(
  1864. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1865. res.set_chunked_content_provider(
  1866. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1867. size_t remaining = image_data_.size() - offset;
  1868. if (remaining == 0) {
  1869. sink.done();
  1870. } else {
  1871. constexpr size_t CHUNK_SIZE = 1024;
  1872. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1873. sink.write(&image_data_[offset], send_size);
  1874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1875. }
  1876. return true;
  1877. });
  1878. });
  1879. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1880. svr_.wait_until_ready();
  1881. }
  1882. virtual void TearDown() {
  1883. svr_.stop();
  1884. if (!request_threads_.empty()) {
  1885. std::this_thread::sleep_for(std::chrono::seconds(1));
  1886. for (auto &t : request_threads_) {
  1887. t.join();
  1888. }
  1889. }
  1890. t_.join();
  1891. }
  1892. #ifdef CPPHTTPLIB_SSL_ENABLED
  1893. SSLClient cli_;
  1894. SSLServer svr_;
  1895. #else
  1896. Client cli_;
  1897. Server svr_;
  1898. #endif
  1899. thread t_;
  1900. std::vector<thread> request_threads_;
  1901. std::string image_data_;
  1902. };
  1903. TEST_F(ChunkedEncodingTest, NormalGet) {
  1904. auto res = cli_.Get("/chunked");
  1905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1906. std::string out;
  1907. read_file("./image.jpg", out);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. EXPECT_EQ(out, res->body);
  1910. }
  1911. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1912. std::string body;
  1913. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1914. body.append(data, data_length);
  1915. return true;
  1916. });
  1917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1918. std::string out;
  1919. read_file("./image.jpg", out);
  1920. EXPECT_EQ(StatusCode::OK_200, res->status);
  1921. EXPECT_EQ(out, body);
  1922. }
  1923. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1924. std::string body;
  1925. auto res = cli_.Get(
  1926. "/chunked",
  1927. [&](const Response &response) {
  1928. EXPECT_EQ(StatusCode::OK_200, response.status);
  1929. return true;
  1930. },
  1931. [&](const char *data, size_t data_length) {
  1932. body.append(data, data_length);
  1933. return true;
  1934. });
  1935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1936. std::string out;
  1937. read_file("./image.jpg", out);
  1938. EXPECT_EQ(StatusCode::OK_200, res->status);
  1939. EXPECT_EQ(out, body);
  1940. }
  1941. TEST(RangeTest, FromHTTPBin_Online) {
  1942. auto host = "httpbingo.org";
  1943. auto path = std::string{"/range/32"};
  1944. #ifdef CPPHTTPLIB_SSL_ENABLED
  1945. auto port = 443;
  1946. SSLClient cli(host, port);
  1947. #else
  1948. auto port = 80;
  1949. Client cli(host, port);
  1950. #endif
  1951. cli.set_connection_timeout(5);
  1952. {
  1953. auto res = cli.Get(path);
  1954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1955. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1956. EXPECT_EQ(StatusCode::OK_200, res->status);
  1957. }
  1958. {
  1959. Headers headers = {make_range_header({{1, -1}})};
  1960. auto res = cli.Get(path, headers);
  1961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1962. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1964. }
  1965. {
  1966. Headers headers = {make_range_header({{1, 10}})};
  1967. auto res = cli.Get(path, headers);
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("bcdefghijk", res->body);
  1970. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1971. }
  1972. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1973. // entire resource, while the original httpbin returned 200. Both are
  1974. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1975. {
  1976. Headers headers = {make_range_header({{0, 31}})};
  1977. auto res = cli.Get(path, headers);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1981. res->status == StatusCode::PartialContent_206);
  1982. }
  1983. {
  1984. Headers headers = {make_range_header({{0, -1}})};
  1985. auto res = cli.Get(path, headers);
  1986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1987. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1988. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1989. res->status == StatusCode::PartialContent_206);
  1990. }
  1991. // go-httpbin returns 206 with clamped range for over-range requests,
  1992. // while the original httpbin returned 416. Both behaviors are observed
  1993. // in real servers, so we only verify the request succeeds.
  1994. {
  1995. Headers headers = {make_range_header({{0, 32}})};
  1996. auto res = cli.Get(path, headers);
  1997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1998. }
  1999. }
  2000. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2001. auto host = "unresolvableaddress.local";
  2002. auto path = std::string{"/"};
  2003. #ifdef CPPHTTPLIB_SSL_ENABLED
  2004. auto port = 443;
  2005. SSLClient cli(host, port);
  2006. #else
  2007. auto port = 80;
  2008. Client cli(host, port);
  2009. #endif
  2010. cli.set_connection_timeout(1);
  2011. {
  2012. auto res = cli.Get(path);
  2013. ASSERT_FALSE(res);
  2014. }
  2015. std::this_thread::sleep_for(std::chrono::seconds(8));
  2016. }
  2017. #if defined(__linux__) && defined(__GLIBC__) && \
  2018. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2019. // Forward declaration: in split builds split.py strips `inline` and moves the
  2020. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2021. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2022. // against the symbol in both header-only and split builds.
  2023. namespace httplib {
  2024. namespace detail {
  2025. int getaddrinfo_with_timeout(const char *node, const char *service,
  2026. const struct addrinfo *hints,
  2027. struct addrinfo **res, time_t timeout_sec);
  2028. } // namespace detail
  2029. } // namespace httplib
  2030. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2031. //
  2032. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2033. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2034. // gai_suspend() call hits the connection timeout the function calls
  2035. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2036. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2037. // still alive and still references the now-destroyed stack frame.
  2038. //
  2039. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2040. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2041. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2042. // and runs them in a container.
  2043. namespace {
  2044. bool should_run_issue_2431_tests() {
  2045. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2046. return v && *v && std::string(v) != "0";
  2047. }
  2048. std::string unique_unresolvable_host(int n) {
  2049. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2050. // glibc still asks the configured nameserver — which is exactly the path
  2051. // we want to exercise. A unique label per call avoids the resolver cache.
  2052. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2053. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2054. std::to_string(n) + ".invalid";
  2055. }
  2056. } // namespace
  2057. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2058. if (!should_run_issue_2431_tests()) {
  2059. GTEST_SKIP()
  2060. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2061. }
  2062. for (int i = 0; i < 8; ++i) {
  2063. struct addrinfo hints;
  2064. memset(&hints, 0, sizeof(hints));
  2065. hints.ai_family = AF_UNSPEC;
  2066. hints.ai_socktype = SOCK_STREAM;
  2067. auto host = unique_unresolvable_host(i);
  2068. struct addrinfo *result = nullptr;
  2069. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2070. &result, /*timeout_sec=*/1);
  2071. if (rc == 0 && result) { freeaddrinfo(result); }
  2072. }
  2073. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2074. // stack region they still believe holds their gaicb.
  2075. std::this_thread::sleep_for(std::chrono::seconds(3));
  2076. }
  2077. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2078. if (!should_run_issue_2431_tests()) {
  2079. GTEST_SKIP()
  2080. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2081. }
  2082. std::atomic<bool> stop{false};
  2083. std::vector<std::thread> threads;
  2084. for (int t = 0; t < 8; ++t) {
  2085. threads.emplace_back([t, &stop] {
  2086. int i = 0;
  2087. while (!stop.load(std::memory_order_relaxed)) {
  2088. struct addrinfo hints;
  2089. memset(&hints, 0, sizeof(hints));
  2090. hints.ai_family = AF_UNSPEC;
  2091. hints.ai_socktype = SOCK_STREAM;
  2092. auto host = unique_unresolvable_host(t * 100000 + i++);
  2093. struct addrinfo *result = nullptr;
  2094. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2095. &result, /*timeout_sec=*/1);
  2096. if (rc == 0 && result) { freeaddrinfo(result); }
  2097. }
  2098. });
  2099. }
  2100. std::this_thread::sleep_for(std::chrono::seconds(8));
  2101. stop.store(true, std::memory_order_relaxed);
  2102. for (auto &th : threads) {
  2103. th.join();
  2104. }
  2105. std::this_thread::sleep_for(std::chrono::seconds(3));
  2106. }
  2107. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2108. if (!should_run_issue_2431_tests()) {
  2109. GTEST_SKIP()
  2110. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2111. }
  2112. std::atomic<bool> stop{false};
  2113. std::vector<std::thread> threads;
  2114. for (int t = 0; t < 8; ++t) {
  2115. threads.emplace_back([t, &stop] {
  2116. int i = 0;
  2117. while (!stop.load(std::memory_order_relaxed)) {
  2118. auto host = unique_unresolvable_host(t * 100000 + i++);
  2119. Client cli(host, 80);
  2120. cli.set_connection_timeout(1, 0);
  2121. cli.set_read_timeout(1, 0);
  2122. cli.set_write_timeout(1, 0);
  2123. (void)cli.Get("/");
  2124. }
  2125. });
  2126. }
  2127. std::this_thread::sleep_for(std::chrono::seconds(8));
  2128. stop.store(true, std::memory_order_relaxed);
  2129. for (auto &th : threads) {
  2130. th.join();
  2131. }
  2132. std::this_thread::sleep_for(std::chrono::seconds(3));
  2133. }
  2134. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2135. TEST(ConnectionErrorTest, InvalidHost) {
  2136. auto host = "-abcde.com";
  2137. #ifdef CPPHTTPLIB_SSL_ENABLED
  2138. auto port = 443;
  2139. SSLClient cli(host, port);
  2140. #else
  2141. auto port = 80;
  2142. Client cli(host, port);
  2143. #endif
  2144. cli.set_connection_timeout(std::chrono::seconds(2));
  2145. auto res = cli.Get("/");
  2146. ASSERT_TRUE(!res);
  2147. EXPECT_EQ(Error::Connection, res.error());
  2148. }
  2149. TEST(ConnectionErrorTest, InvalidHost2) {
  2150. auto host = "httpcan.org/";
  2151. #ifdef CPPHTTPLIB_SSL_ENABLED
  2152. SSLClient cli(host);
  2153. #else
  2154. Client cli(host);
  2155. #endif
  2156. cli.set_connection_timeout(std::chrono::seconds(2));
  2157. auto res = cli.Get("/");
  2158. ASSERT_TRUE(!res);
  2159. EXPECT_EQ(Error::Connection, res.error());
  2160. }
  2161. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2162. auto host = "httpcan.org/";
  2163. #ifdef CPPHTTPLIB_SSL_ENABLED
  2164. SSLClient cli(host);
  2165. #else
  2166. Client cli(host);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. stringstream s;
  2172. s << "error code: " << res.error();
  2173. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2174. }
  2175. TEST(ConnectionErrorTest, InvalidPort) {
  2176. auto host = "localhost";
  2177. auto port = 44380;
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. SSLClient cli(host, port);
  2180. #else
  2181. Client cli(host, port);
  2182. #endif
  2183. cli.set_connection_timeout(std::chrono::seconds(2));
  2184. auto res = cli.Get("/");
  2185. ASSERT_TRUE(!res);
  2186. EXPECT_TRUE(Error::Connection == res.error() ||
  2187. Error::ConnectionTimeout == res.error());
  2188. }
  2189. TEST(ConnectionErrorTest, Timeout_Online) {
  2190. auto host = "google.com";
  2191. #ifdef CPPHTTPLIB_SSL_ENABLED
  2192. auto port = 44380;
  2193. SSLClient cli(host, port);
  2194. #else
  2195. auto port = 8080;
  2196. Client cli(host, port);
  2197. #endif
  2198. cli.set_connection_timeout(std::chrono::seconds(2));
  2199. // only probe one address type so that the error reason
  2200. // correlates to the timed-out IPv4, not the unsupported
  2201. // IPv6 connection attempt
  2202. cli.set_address_family(AF_INET);
  2203. auto res = cli.Get("/");
  2204. ASSERT_TRUE(!res);
  2205. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2206. }
  2207. TEST(CancelTest, NoCancel_Online) {
  2208. auto host = "httpbingo.org";
  2209. auto path = std::string{"/range/32"};
  2210. #ifdef CPPHTTPLIB_SSL_ENABLED
  2211. auto port = 443;
  2212. SSLClient cli(host, port);
  2213. #else
  2214. auto port = 80;
  2215. Client cli(host, port);
  2216. #endif
  2217. cli.set_connection_timeout(std::chrono::seconds(5));
  2218. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2220. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2221. EXPECT_EQ(StatusCode::OK_200, res->status);
  2222. }
  2223. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2224. // Use /bytes with a large payload so that the DownloadProgress callback
  2225. // (which only fires for Content-Length responses) is invoked before the
  2226. // entire body is received, giving cancellation a chance to fire.
  2227. auto host = "httpbingo.org";
  2228. auto path = std::string{"/bytes/524288"};
  2229. #ifdef CPPHTTPLIB_SSL_ENABLED
  2230. auto port = 443;
  2231. SSLClient cli(host, port);
  2232. #else
  2233. auto port = 80;
  2234. Client cli(host, port);
  2235. #endif
  2236. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2237. cli.set_connection_timeout(std::chrono::seconds(5));
  2238. ASSERT_TRUE(!res);
  2239. EXPECT_EQ(Error::Canceled, res.error());
  2240. }
  2241. TEST(CancelTest, WithCancelLargePayload_Online) {
  2242. auto host = "httpbingo.org";
  2243. auto path = std::string{"/bytes/524288"};
  2244. #ifdef CPPHTTPLIB_SSL_ENABLED
  2245. auto port = 443;
  2246. SSLClient cli(host, port);
  2247. #else
  2248. auto port = 80;
  2249. Client cli(host, port);
  2250. #endif
  2251. cli.set_connection_timeout(std::chrono::seconds(5));
  2252. uint32_t count = 0;
  2253. auto res =
  2254. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2255. ASSERT_TRUE(!res);
  2256. EXPECT_EQ(Error::Canceled, res.error());
  2257. }
  2258. TEST(CancelTest, NoCancelPost) {
  2259. Server svr;
  2260. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2261. res.set_content("Hello World!", "text/plain");
  2262. });
  2263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2264. auto se = detail::scope_exit([&] {
  2265. svr.stop();
  2266. thread.join();
  2267. ASSERT_FALSE(svr.is_running());
  2268. });
  2269. svr.wait_until_ready();
  2270. Client cli(HOST, PORT);
  2271. cli.set_connection_timeout(std::chrono::seconds(5));
  2272. auto res =
  2273. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2274. "application/json", [](uint64_t, uint64_t) { return true; });
  2275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2276. EXPECT_EQ("Hello World!", res->body);
  2277. EXPECT_EQ(StatusCode::OK_200, res->status);
  2278. }
  2279. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2280. Server svr;
  2281. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2282. res.set_content("Hello World!", "text/plain");
  2283. });
  2284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2285. auto se = detail::scope_exit([&] {
  2286. svr.stop();
  2287. thread.join();
  2288. ASSERT_FALSE(svr.is_running());
  2289. });
  2290. svr.wait_until_ready();
  2291. Client cli(HOST, PORT);
  2292. cli.set_connection_timeout(std::chrono::seconds(5));
  2293. auto res =
  2294. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2295. "application/json", [](uint64_t, uint64_t) { return false; });
  2296. ASSERT_TRUE(!res);
  2297. EXPECT_EQ(Error::Canceled, res.error());
  2298. }
  2299. TEST(CancelTest, WithCancelLargePayloadPost) {
  2300. Server svr;
  2301. svr.set_payload_max_length(200 * 1024 * 1024);
  2302. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2303. res.set_content(LARGE_DATA, "text/plain");
  2304. });
  2305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2306. auto se = detail::scope_exit([&] {
  2307. svr.stop();
  2308. thread.join();
  2309. ASSERT_FALSE(svr.is_running());
  2310. });
  2311. svr.wait_until_ready();
  2312. Client cli(HOST, PORT);
  2313. cli.set_payload_max_length(200 * 1024 * 1024);
  2314. cli.set_connection_timeout(std::chrono::seconds(5));
  2315. auto res =
  2316. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2317. "application/json", [](uint64_t, uint64_t) { return false; });
  2318. ASSERT_TRUE(!res);
  2319. EXPECT_EQ(Error::Canceled, res.error());
  2320. }
  2321. TEST(CancelTest, NoCancelPut) {
  2322. Server svr;
  2323. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2324. res.set_content("Hello World!", "text/plain");
  2325. });
  2326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2327. auto se = detail::scope_exit([&] {
  2328. svr.stop();
  2329. thread.join();
  2330. ASSERT_FALSE(svr.is_running());
  2331. });
  2332. svr.wait_until_ready();
  2333. Client cli(HOST, PORT);
  2334. cli.set_connection_timeout(std::chrono::seconds(5));
  2335. auto res =
  2336. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2337. "application/json", [](uint64_t, uint64_t) { return true; });
  2338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2339. EXPECT_EQ("Hello World!", res->body);
  2340. EXPECT_EQ(StatusCode::OK_200, res->status);
  2341. }
  2342. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2343. Server svr;
  2344. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2345. res.set_content("Hello World!", "text/plain");
  2346. });
  2347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2348. auto se = detail::scope_exit([&] {
  2349. svr.stop();
  2350. thread.join();
  2351. ASSERT_FALSE(svr.is_running());
  2352. });
  2353. svr.wait_until_ready();
  2354. Client cli(HOST, PORT);
  2355. cli.set_connection_timeout(std::chrono::seconds(5));
  2356. auto res =
  2357. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2358. "application/json", [](uint64_t, uint64_t) { return false; });
  2359. ASSERT_TRUE(!res);
  2360. EXPECT_EQ(Error::Canceled, res.error());
  2361. }
  2362. TEST(CancelTest, WithCancelLargePayloadPut) {
  2363. Server svr;
  2364. svr.set_payload_max_length(200 * 1024 * 1024);
  2365. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2366. res.set_content(LARGE_DATA, "text/plain");
  2367. });
  2368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2369. auto se = detail::scope_exit([&] {
  2370. svr.stop();
  2371. thread.join();
  2372. ASSERT_FALSE(svr.is_running());
  2373. });
  2374. svr.wait_until_ready();
  2375. Client cli(HOST, PORT);
  2376. cli.set_payload_max_length(200 * 1024 * 1024);
  2377. cli.set_connection_timeout(std::chrono::seconds(5));
  2378. auto res =
  2379. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2380. "application/json", [](uint64_t, uint64_t) { return false; });
  2381. ASSERT_TRUE(!res);
  2382. EXPECT_EQ(Error::Canceled, res.error());
  2383. }
  2384. TEST(CancelTest, NoCancelPatch) {
  2385. Server svr;
  2386. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content("Hello World!", "text/plain");
  2388. });
  2389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. thread.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. Client cli(HOST, PORT);
  2397. cli.set_connection_timeout(std::chrono::seconds(5));
  2398. auto res =
  2399. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2400. "application/json", [](uint64_t, uint64_t) { return true; });
  2401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2402. EXPECT_EQ("Hello World!", res->body);
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. }
  2405. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2406. Server svr;
  2407. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2408. res.set_content("Hello World!", "text/plain");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. Client cli(HOST, PORT);
  2418. cli.set_connection_timeout(std::chrono::seconds(5));
  2419. auto res =
  2420. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2421. "application/json", [](uint64_t, uint64_t) { return false; });
  2422. ASSERT_TRUE(!res);
  2423. EXPECT_EQ(Error::Canceled, res.error());
  2424. }
  2425. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2426. Server svr;
  2427. svr.set_payload_max_length(200 * 1024 * 1024);
  2428. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2429. res.set_content(LARGE_DATA, "text/plain");
  2430. });
  2431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(HOST, PORT);
  2439. cli.set_payload_max_length(200 * 1024 * 1024);
  2440. cli.set_connection_timeout(std::chrono::seconds(5));
  2441. auto res =
  2442. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2443. "application/json", [](uint64_t, uint64_t) { return false; });
  2444. ASSERT_TRUE(!res);
  2445. EXPECT_EQ(Error::Canceled, res.error());
  2446. }
  2447. TEST(CancelTest, NoCancelDelete) {
  2448. Server svr;
  2449. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2450. res.set_content("Hello World!", "text/plain");
  2451. });
  2452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2453. auto se = detail::scope_exit([&] {
  2454. svr.stop();
  2455. thread.join();
  2456. ASSERT_FALSE(svr.is_running());
  2457. });
  2458. svr.wait_until_ready();
  2459. Client cli(HOST, PORT);
  2460. cli.set_connection_timeout(std::chrono::seconds(5));
  2461. auto res =
  2462. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2463. "application/json", [](uint64_t, uint64_t) { return true; });
  2464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2465. EXPECT_EQ("Hello World!", res->body);
  2466. EXPECT_EQ(StatusCode::OK_200, res->status);
  2467. }
  2468. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2469. Server svr;
  2470. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2471. res.set_content("Hello World!", "text/plain");
  2472. });
  2473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2474. auto se = detail::scope_exit([&] {
  2475. svr.stop();
  2476. thread.join();
  2477. ASSERT_FALSE(svr.is_running());
  2478. });
  2479. svr.wait_until_ready();
  2480. Client cli(HOST, PORT);
  2481. cli.set_connection_timeout(std::chrono::seconds(5));
  2482. auto res =
  2483. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2484. "application/json", [](uint64_t, uint64_t) { return false; });
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Canceled, res.error());
  2487. }
  2488. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2489. Server svr;
  2490. svr.set_payload_max_length(200 * 1024 * 1024);
  2491. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2492. res.set_content(LARGE_DATA, "text/plain");
  2493. });
  2494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2495. auto se = detail::scope_exit([&] {
  2496. svr.stop();
  2497. thread.join();
  2498. ASSERT_FALSE(svr.is_running());
  2499. });
  2500. svr.wait_until_ready();
  2501. Client cli(HOST, PORT);
  2502. cli.set_payload_max_length(200 * 1024 * 1024);
  2503. cli.set_connection_timeout(std::chrono::seconds(5));
  2504. auto res =
  2505. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2506. "application/json", [](uint64_t, uint64_t) { return false; });
  2507. ASSERT_TRUE(!res);
  2508. EXPECT_EQ(Error::Canceled, res.error());
  2509. }
  2510. static std::string remove_whitespace(const std::string &input) {
  2511. std::string output;
  2512. output.reserve(input.size());
  2513. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2514. [](unsigned char c) { return !std::isspace(c); });
  2515. return output;
  2516. }
  2517. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2518. auto host = "httpbingo.org";
  2519. auto path = std::string{"/basic-auth/hello/world"};
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 443;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 80;
  2525. Client cli(host, port);
  2526. #endif
  2527. {
  2528. auto res = cli.Get(path);
  2529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2530. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2531. }
  2532. {
  2533. auto res = cli.Get(
  2534. path, Headers{make_basic_authentication_header("hello", "world")});
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. auto body = remove_whitespace(res->body);
  2537. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2538. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2539. EXPECT_EQ(StatusCode::OK_200, res->status);
  2540. }
  2541. {
  2542. cli.set_basic_auth("hello", "world");
  2543. auto res = cli.Get(path);
  2544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2545. auto body = remove_whitespace(res->body);
  2546. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2547. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2548. EXPECT_EQ(StatusCode::OK_200, res->status);
  2549. }
  2550. {
  2551. cli.set_basic_auth("hello", "bad");
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. cli.set_basic_auth("bad", "world");
  2558. auto res = cli.Get(path);
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2561. }
  2562. }
  2563. #ifdef CPPHTTPLIB_SSL_ENABLED
  2564. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2565. auto host = "httpbingo.org";
  2566. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2567. auto paths = std::vector<std::string>{
  2568. "/digest-auth/auth/hello/world/MD5",
  2569. "/digest-auth/auth/hello/world/SHA-256",
  2570. };
  2571. auto port = 443;
  2572. SSLClient cli(host, port);
  2573. {
  2574. auto res = cli.Get(unauth_path);
  2575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2576. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2577. }
  2578. {
  2579. cli.set_digest_auth("hello", "world");
  2580. for (const auto &path : paths) {
  2581. auto res = cli.Get(path.c_str());
  2582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2583. auto body = remove_whitespace(res->body);
  2584. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2585. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2586. EXPECT_EQ(StatusCode::OK_200, res->status);
  2587. }
  2588. cli.set_digest_auth("hello", "bad");
  2589. for (const auto &path : paths) {
  2590. auto res = cli.Get(path.c_str());
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2593. }
  2594. }
  2595. }
  2596. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2597. // comma-separated list of challenges, and each challenge may itself carry a
  2598. // comma-separated auth-param list, so a server can legally offer Basic
  2599. // before Digest, either as two field lines or packed into one. Runs one 401
  2600. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2601. // value() joins them in receipt order) and checks that the retry carries a
  2602. // well-formed Digest Authorization header naming expected_realm.
  2603. static void
  2604. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2605. const std::string &expected_realm) {
  2606. std::atomic<int> hits{0};
  2607. Server svr;
  2608. svr.Get("/x", [&](const Request &req, Response &res) {
  2609. if (++hits == 1) {
  2610. res.status = StatusCode::Unauthorized_401;
  2611. for (const auto &challenge : challenges) {
  2612. res.set_header("WWW-Authenticate", challenge);
  2613. }
  2614. } else {
  2615. auto authorization = req.get_header_value("Authorization");
  2616. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2617. EXPECT_NE(std::string::npos,
  2618. authorization.find("realm=\"" + expected_realm + "\""));
  2619. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2620. res.set_content("ok", "text/plain");
  2621. }
  2622. });
  2623. auto port = svr.bind_to_any_port(HOST);
  2624. std::thread t([&]() { svr.listen_after_bind(); });
  2625. auto se = detail::scope_exit([&] {
  2626. svr.stop();
  2627. t.join();
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, port);
  2631. cli.set_digest_auth("hello", "world");
  2632. auto res = cli.Get("/x");
  2633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2634. EXPECT_EQ(2, hits.load());
  2635. }
  2636. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2637. static const char *kDigestChallenge =
  2638. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2639. "algorithm=MD5";
  2640. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2641. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2642. "testrealm");
  2643. }
  2644. // Same challenge list with the schemes in the opposite order, to make sure
  2645. // the fix above didn't just special-case "Basic first".
  2646. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2647. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2648. "testrealm");
  2649. }
  2650. // A comma inside a quoted auth-param value must not be mistaken for the
  2651. // separator between two challenges (or two auth-params).
  2652. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2653. run_digest_challenge_list_test(
  2654. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2655. "algorithm=MD5"},
  2656. "test,realm");
  2657. }
  2658. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2659. // make_digest_authentication_header() dereferences both unconditionally, so
  2660. // a server sending a challenge missing either one must not be treated as
  2661. // usable -- doing so used to crash the client with std::out_of_range.
  2662. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2663. Server svr;
  2664. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2665. res.status = StatusCode::Unauthorized_401;
  2666. res.set_header("WWW-Authenticate", challenge);
  2667. });
  2668. auto port = svr.bind_to_any_port(HOST);
  2669. std::thread t([&]() { svr.listen_after_bind(); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. t.join();
  2673. });
  2674. svr.wait_until_ready();
  2675. Client cli(HOST, port);
  2676. cli.set_digest_auth("hello", "world");
  2677. auto res = cli.Get("/x");
  2678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2680. }
  2681. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2682. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2683. }
  2684. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2685. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2686. }
  2687. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2688. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2689. }
  2690. #endif
  2691. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2692. auto host = "google.com";
  2693. auto another_host = "example.com";
  2694. auto wrong_ip = "0.0.0.0";
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. SSLClient cli(host);
  2697. #else
  2698. Client cli(host);
  2699. #endif
  2700. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2701. auto res = cli.Get("/");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2704. }
  2705. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2706. auto host = "google.com";
  2707. auto wrong_ip = "0.0.0.0";
  2708. #ifdef CPPHTTPLIB_SSL_ENABLED
  2709. SSLClient cli(host);
  2710. #else
  2711. Client cli(host);
  2712. #endif
  2713. cli.set_hostname_addr_map({{host, wrong_ip}});
  2714. auto res = cli.Get("/");
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_EQ(Error::Connection, res.error());
  2717. }
  2718. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2719. // A mapped value that is not an IP literal must be resolved. "localhost"
  2720. // resolves from the hosts file, so this test needs no external DNS.
  2721. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2722. auto host = "target.invalid";
  2723. Server svr;
  2724. std::string received_host;
  2725. svr.Get("/hi", [&](const Request &req, Response &res) {
  2726. received_host = req.get_header_value("Host");
  2727. res.set_content("Hello World!", "text/plain");
  2728. });
  2729. auto port = svr.bind_to_any_port(HOST);
  2730. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2731. auto se = detail::scope_exit([&] {
  2732. svr.stop();
  2733. thread.join();
  2734. ASSERT_FALSE(svr.is_running());
  2735. });
  2736. svr.wait_until_ready();
  2737. Client cli(host, port);
  2738. cli.set_hostname_addr_map({{host, HOST}});
  2739. auto res = cli.Get("/hi");
  2740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2741. EXPECT_EQ(StatusCode::OK_200, res->status);
  2742. // The mapping only redirects the connection; the identity stays host_.
  2743. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2744. }
  2745. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2746. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2747. auto host = "target.invalid";
  2748. Server svr;
  2749. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2750. res.set_content("Hello World!", "text/plain");
  2751. });
  2752. auto port = svr.bind_to_any_port("127.0.0.1");
  2753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2754. auto se = detail::scope_exit([&] {
  2755. svr.stop();
  2756. thread.join();
  2757. ASSERT_FALSE(svr.is_running());
  2758. });
  2759. svr.wait_until_ready();
  2760. Client cli(host, port);
  2761. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2762. auto res = cli.Get("/hi");
  2763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2764. EXPECT_EQ(StatusCode::OK_200, res->status);
  2765. }
  2766. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2767. // An empty mapped value must leave host_ as the connection target. Without
  2768. // that guard the empty value would become the host argument, getaddrinfo
  2769. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2770. // loopback - silently connecting somewhere the caller never asked for.
  2771. // The server listens on loopback, so such a fallback would succeed and is
  2772. // therefore observable as a failure of this test.
  2773. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2776. res.set_content("Hello World!", "text/plain");
  2777. });
  2778. auto port = svr.bind_to_any_port(HOST);
  2779. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2780. auto se = detail::scope_exit([&] {
  2781. svr.stop();
  2782. thread.join();
  2783. ASSERT_FALSE(svr.is_running());
  2784. });
  2785. svr.wait_until_ready();
  2786. Client cli(blackhole, port);
  2787. cli.set_hostname_addr_map({{blackhole, ""}});
  2788. cli.set_connection_timeout(1);
  2789. auto res = cli.Get("/hi");
  2790. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2791. }
  2792. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2793. auto host = "httpbingo.org";
  2794. auto path = std::string{"/absolute-redirect/3"};
  2795. #ifdef CPPHTTPLIB_SSL_ENABLED
  2796. SSLClient cli(host);
  2797. #else
  2798. Client cli(host);
  2799. #endif
  2800. cli.set_follow_location(true);
  2801. auto res = cli.Get(path);
  2802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2803. EXPECT_EQ(StatusCode::OK_200, res->status);
  2804. }
  2805. TEST(RedirectTest, Redirect_Online) {
  2806. auto host = "httpbingo.org";
  2807. auto path = std::string{"/redirect/3"};
  2808. #ifdef CPPHTTPLIB_SSL_ENABLED
  2809. SSLClient cli(host);
  2810. #else
  2811. Client cli(host);
  2812. #endif
  2813. cli.set_follow_location(true);
  2814. auto res = cli.Get(path);
  2815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2816. EXPECT_EQ(StatusCode::OK_200, res->status);
  2817. }
  2818. TEST(RelativeRedirectTest, Redirect_Online) {
  2819. auto host = "httpbingo.org";
  2820. auto path = std::string{"/relative-redirect/3"};
  2821. #ifdef CPPHTTPLIB_SSL_ENABLED
  2822. SSLClient cli(host);
  2823. #else
  2824. Client cli(host);
  2825. #endif
  2826. cli.set_follow_location(true);
  2827. auto res = cli.Get(path);
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. EXPECT_EQ(StatusCode::OK_200, res->status);
  2830. }
  2831. TEST(TooManyRedirectTest, Redirect_Online) {
  2832. auto host = "httpbingo.org";
  2833. auto path = std::string{"/redirect/21"};
  2834. #ifdef CPPHTTPLIB_SSL_ENABLED
  2835. SSLClient cli(host);
  2836. #else
  2837. Client cli(host);
  2838. #endif
  2839. cli.set_follow_location(true);
  2840. auto res = cli.Get(path);
  2841. ASSERT_TRUE(!res);
  2842. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2843. }
  2844. #ifdef CPPHTTPLIB_SSL_ENABLED
  2845. TEST(YahooRedirectTest, Redirect_Online) {
  2846. Client cli("yahoo.com");
  2847. auto res = cli.Get("/");
  2848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2849. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2850. cli.set_follow_location(true);
  2851. res = cli.Get("/");
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2855. }
  2856. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2857. #define REDIR_HOST "httpbingo.org"
  2858. #define REDIR_PATH "/redirect-to"
  2859. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2860. SSLClient cli(REDIR_HOST);
  2861. cli.set_follow_location(true);
  2862. auto res =
  2863. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. }
  2867. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2868. SSLClient cli(REDIR_HOST);
  2869. cli.set_follow_location(true);
  2870. Params params;
  2871. params.emplace("url", "http://example.com");
  2872. params.emplace("status_code", "302");
  2873. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. }
  2877. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2878. SSLClient cli(REDIR_HOST);
  2879. cli.set_follow_location(true);
  2880. Params params;
  2881. params.emplace("url", "http://example.com");
  2882. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. EXPECT_EQ(StatusCode::OK_200, res->status);
  2885. }
  2886. TEST(UrlWithSpace, Redirect_Online) {
  2887. SSLClient cli("edge.forgecdn.net");
  2888. cli.set_follow_location(true);
  2889. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2893. }
  2894. #endif
  2895. #if !defined(_WIN32) && !defined(_WIN64)
  2896. TEST(ReceiveSignals, Signal) {
  2897. auto setupSignalHandlers = []() {
  2898. struct sigaction act;
  2899. sigemptyset(&act.sa_mask);
  2900. act.sa_flags = SA_SIGINFO;
  2901. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2902. switch (sig) {
  2903. case SIGINT:
  2904. default: break;
  2905. }
  2906. };
  2907. ::sigaction(SIGINT, &act, nullptr);
  2908. };
  2909. Server svr;
  2910. int port = 0;
  2911. auto thread = std::thread([&]() {
  2912. setupSignalHandlers();
  2913. port = svr.bind_to_any_port(HOST);
  2914. svr.listen_after_bind();
  2915. });
  2916. auto se = detail::scope_exit([&] {
  2917. svr.stop();
  2918. thread.join();
  2919. ASSERT_FALSE(svr.is_running());
  2920. });
  2921. svr.wait_until_ready();
  2922. ASSERT_TRUE(svr.is_running());
  2923. pthread_kill(thread.native_handle(), SIGINT);
  2924. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2925. ASSERT_TRUE(svr.is_running());
  2926. }
  2927. #endif
  2928. TEST(RedirectToDifferentPort, Redirect) {
  2929. Server svr1;
  2930. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2931. res.set_content("Hello World!", "text/plain");
  2932. });
  2933. int svr1_port = 0;
  2934. auto thread1 = std::thread([&]() {
  2935. svr1_port = svr1.bind_to_any_port(HOST);
  2936. svr1.listen_after_bind();
  2937. });
  2938. Server svr2;
  2939. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2940. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2941. });
  2942. int svr2_port = 0;
  2943. auto thread2 = std::thread([&]() {
  2944. svr2_port = svr2.bind_to_any_port(HOST);
  2945. svr2.listen_after_bind();
  2946. });
  2947. auto se = detail::scope_exit([&] {
  2948. svr2.stop();
  2949. thread2.join();
  2950. svr1.stop();
  2951. thread1.join();
  2952. ASSERT_FALSE(svr2.is_running());
  2953. ASSERT_FALSE(svr1.is_running());
  2954. });
  2955. svr1.wait_until_ready();
  2956. svr2.wait_until_ready();
  2957. Client cli("localhost", svr2_port);
  2958. cli.set_follow_location(true);
  2959. auto res = cli.Get("/2");
  2960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2961. EXPECT_EQ(StatusCode::OK_200, res->status);
  2962. EXPECT_EQ("Hello World!", res->body);
  2963. }
  2964. static void
  2965. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2966. Server svr1;
  2967. std::string captured_authorization;
  2968. svr1.Get("/target", [&](const Request &req, Response &res) {
  2969. captured_authorization = req.get_header_value("Authorization");
  2970. res.set_content("OK", "text/plain");
  2971. });
  2972. int svr1_port = 0;
  2973. auto thread1 = std::thread([&]() {
  2974. svr1_port = svr1.bind_to_any_port(HOST);
  2975. svr1.listen_after_bind();
  2976. });
  2977. Server svr2;
  2978. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2979. res.set_redirect(
  2980. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2981. });
  2982. int svr2_port = 0;
  2983. auto thread2 = std::thread([&]() {
  2984. svr2_port = svr2.bind_to_any_port(HOST);
  2985. svr2.listen_after_bind();
  2986. });
  2987. auto se = detail::scope_exit([&] {
  2988. svr2.stop();
  2989. thread2.join();
  2990. svr1.stop();
  2991. thread1.join();
  2992. ASSERT_FALSE(svr2.is_running());
  2993. ASSERT_FALSE(svr1.is_running());
  2994. });
  2995. svr1.wait_until_ready();
  2996. svr2.wait_until_ready();
  2997. Client cli("localhost", svr2_port);
  2998. cli.set_follow_location(true);
  2999. set_auth(cli);
  3000. auto res = cli.Get("/redir");
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ(StatusCode::OK_200, res->status);
  3003. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3004. EXPECT_TRUE(captured_authorization.empty());
  3005. }
  3006. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3007. TestDoNotForwardCredentialsOnRedirect(
  3008. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3009. }
  3010. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3011. TestDoNotForwardCredentialsOnRedirect(
  3012. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3013. }
  3014. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3015. Server svr1;
  3016. std::string captured_cookie;
  3017. bool target_hit = false;
  3018. svr1.Get("/target", [&](const Request &req, Response &res) {
  3019. captured_cookie = req.get_header_value("Cookie");
  3020. target_hit = true;
  3021. res.set_content("OK", "text/plain");
  3022. });
  3023. int svr1_port = 0;
  3024. auto thread1 = std::thread([&]() {
  3025. svr1_port = svr1.bind_to_any_port(HOST);
  3026. svr1.listen_after_bind();
  3027. });
  3028. Server svr2;
  3029. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3030. res.set_redirect(
  3031. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3032. });
  3033. int svr2_port = 0;
  3034. auto thread2 = std::thread([&]() {
  3035. svr2_port = svr2.bind_to_any_port(HOST);
  3036. svr2.listen_after_bind();
  3037. });
  3038. auto se = detail::scope_exit([&] {
  3039. svr2.stop();
  3040. thread2.join();
  3041. svr1.stop();
  3042. thread1.join();
  3043. ASSERT_FALSE(svr2.is_running());
  3044. ASSERT_FALSE(svr1.is_running());
  3045. });
  3046. svr1.wait_until_ready();
  3047. svr2.wait_until_ready();
  3048. Client cli("localhost", svr2_port);
  3049. cli.set_follow_location(true);
  3050. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3051. auto res = cli.Get("/redir", headers);
  3052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3053. EXPECT_EQ(StatusCode::OK_200, res->status);
  3054. EXPECT_TRUE(target_hit);
  3055. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3056. EXPECT_TRUE(captured_cookie.empty());
  3057. }
  3058. TEST(RedirectToSamePort, ForwardCookie) {
  3059. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3060. // header so that ordinary session flows keep working.
  3061. Server svr;
  3062. std::string captured_cookie;
  3063. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3064. res.set_redirect("/target", 302);
  3065. });
  3066. svr.Get("/target", [&](const Request &req, Response &res) {
  3067. captured_cookie = req.get_header_value("Cookie");
  3068. res.set_content("OK", "text/plain");
  3069. });
  3070. auto port = svr.bind_to_any_port(HOST);
  3071. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3072. auto se = detail::scope_exit([&] {
  3073. svr.stop();
  3074. thread.join();
  3075. ASSERT_FALSE(svr.is_running());
  3076. });
  3077. svr.wait_until_ready();
  3078. Client cli(HOST, port);
  3079. cli.set_follow_location(true);
  3080. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3081. auto res = cli.Get("/redir", headers);
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(StatusCode::OK_200, res->status);
  3084. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3085. }
  3086. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3087. Server svr;
  3088. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3089. // Port number that overflows int — should not crash
  3090. res.set_redirect("http://localhost:99999999999999999999/target");
  3091. });
  3092. auto port = svr.bind_to_any_port(HOST);
  3093. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3094. auto se = detail::scope_exit([&] {
  3095. svr.stop();
  3096. thread.join();
  3097. ASSERT_FALSE(svr.is_running());
  3098. });
  3099. svr.wait_until_ready();
  3100. Client cli(HOST, port);
  3101. cli.set_follow_location(true);
  3102. auto res = cli.Get("/redir");
  3103. // Should fail gracefully, not crash (no valid response due to bad port)
  3104. EXPECT_FALSE(res);
  3105. }
  3106. TEST(RedirectFromPageWithContent, Redirect) {
  3107. Server svr;
  3108. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3109. res.set_content("___", "text/plain");
  3110. res.set_redirect("/2");
  3111. });
  3112. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3113. res.set_content("Hello World!", "text/plain");
  3114. });
  3115. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3116. auto se = detail::scope_exit([&] {
  3117. svr.stop();
  3118. th.join();
  3119. ASSERT_FALSE(svr.is_running());
  3120. });
  3121. svr.wait_until_ready();
  3122. {
  3123. Client cli("localhost", PORT);
  3124. cli.set_follow_location(true);
  3125. std::string body;
  3126. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3127. body.append(data, data_length);
  3128. return true;
  3129. });
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. EXPECT_EQ("Hello World!", body);
  3133. }
  3134. {
  3135. Client cli("localhost", PORT);
  3136. std::string body;
  3137. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3138. body.append(data, data_length);
  3139. return true;
  3140. });
  3141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3142. EXPECT_EQ(StatusCode::Found_302, res->status);
  3143. EXPECT_EQ("___", body);
  3144. }
  3145. }
  3146. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3147. Server svr;
  3148. auto port_str = std::to_string(PORT);
  3149. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3150. auto expected_host = "[::1]:" + port_str;
  3151. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3152. res.set_content("___", "text/plain");
  3153. // res.set_redirect("/2");
  3154. res.set_redirect(redirect_url);
  3155. });
  3156. svr.Get("/2", [&](const Request &req, Response &res) {
  3157. auto host_header = req.headers.find("Host");
  3158. ASSERT_TRUE(host_header != req.headers.end());
  3159. EXPECT_EQ(expected_host, host_header->second);
  3160. res.set_content("Hello World!", "text/plain");
  3161. });
  3162. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. th.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3169. // actually starts anything, so the condition !svr.is_running() will
  3170. // always remain true, and the loop never stops.
  3171. // This basically counts how many milliseconds have passed since the
  3172. // call to svr.listen(), and if after 5 seconds nothing started yet
  3173. // aborts the test.
  3174. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3175. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3176. ASSERT_LT(milliseconds, 5000U);
  3177. }
  3178. {
  3179. Client cli("::1", PORT);
  3180. cli.set_follow_location(true);
  3181. std::string body;
  3182. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3183. body.append(data, data_length);
  3184. return true;
  3185. });
  3186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3187. EXPECT_EQ(StatusCode::OK_200, res->status);
  3188. EXPECT_EQ("Hello World!", body);
  3189. }
  3190. {
  3191. Client cli("::1", PORT);
  3192. std::string body;
  3193. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3194. body.append(data, data_length);
  3195. return true;
  3196. });
  3197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3198. EXPECT_EQ(StatusCode::Found_302, res->status);
  3199. EXPECT_EQ("___", body);
  3200. }
  3201. }
  3202. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3203. Server svr;
  3204. svr.Get("/foo", [](const Request &req, Response &res) {
  3205. auto a = req.params.find("a");
  3206. if (a != req.params.end()) {
  3207. res.set_content((*a).second, "text/plain");
  3208. res.status = StatusCode::OK_200;
  3209. } else {
  3210. res.status = StatusCode::BadRequest_400;
  3211. }
  3212. });
  3213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3214. auto se = detail::scope_exit([&] {
  3215. svr.stop();
  3216. thread.join();
  3217. ASSERT_FALSE(svr.is_running());
  3218. });
  3219. svr.wait_until_ready();
  3220. {
  3221. Client cli(HOST, PORT);
  3222. cli.set_path_encode(false);
  3223. auto res = cli.Get("/foo?a=explicitly+encoded");
  3224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3225. EXPECT_EQ(StatusCode::OK_200, res->status);
  3226. // This expects it back with a space, as the `+` won't have been
  3227. // url-encoded, and server-side the params get decoded turning `+`
  3228. // into spaces.
  3229. EXPECT_EQ("explicitly encoded", res->body);
  3230. }
  3231. }
  3232. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3233. // When path encoding is disabled the client must transmit the supplied
  3234. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3235. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3236. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3237. // than a space (0x20). Assert on the raw wire target to catch this.
  3238. Server svr;
  3239. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3240. svr.Get("/foo", [&](const Request &req, Response &res) {
  3241. EXPECT_EQ(expected_target, req.target);
  3242. res.status = StatusCode::OK_200;
  3243. });
  3244. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3245. auto se = detail::scope_exit([&] {
  3246. svr.stop();
  3247. thread.join();
  3248. ASSERT_FALSE(svr.is_running());
  3249. });
  3250. svr.wait_until_ready();
  3251. {
  3252. Client cli(HOST, PORT);
  3253. cli.set_path_encode(false);
  3254. auto res = cli.Get(expected_target.c_str());
  3255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3256. EXPECT_EQ(StatusCode::OK_200, res->status);
  3257. }
  3258. }
  3259. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3260. // `open_stream()` used to skip the path encoding that the buffered send
  3261. // path applies, so the same `path` produced different bytes in the request
  3262. // line depending on which API was used. Assert the two agree.
  3263. Server svr;
  3264. std::string target;
  3265. svr.Get(".*", [&](const Request &req, Response &res) {
  3266. target = req.target;
  3267. res.status = StatusCode::OK_200;
  3268. });
  3269. auto port = svr.bind_to_any_port(HOST);
  3270. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3271. auto se = detail::scope_exit([&] {
  3272. svr.stop();
  3273. thread.join();
  3274. ASSERT_FALSE(svr.is_running());
  3275. });
  3276. svr.wait_until_ready();
  3277. struct {
  3278. const char *path;
  3279. const char *expected;
  3280. } cases[] = {
  3281. {"/a b?x=1", "/a%20b?x=1"},
  3282. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3283. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3284. };
  3285. for (const auto &c : cases) {
  3286. Client cli(HOST, port);
  3287. target.clear();
  3288. auto res = cli.Get(c.path);
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3291. auto buffered_target = target;
  3292. target.clear();
  3293. auto handle = cli.open_stream("GET", c.path);
  3294. EXPECT_TRUE(handle.is_valid())
  3295. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3296. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3297. }
  3298. }
  3299. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3300. // The `set_path_encode(false)` contract — transmit the supplied target
  3301. // verbatim — must hold for the streaming API too.
  3302. Server svr;
  3303. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3304. std::string target;
  3305. svr.Get("/foo", [&](const Request &req, Response &res) {
  3306. target = req.target;
  3307. res.status = StatusCode::OK_200;
  3308. });
  3309. auto port = svr.bind_to_any_port(HOST);
  3310. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3311. auto se = detail::scope_exit([&] {
  3312. svr.stop();
  3313. thread.join();
  3314. ASSERT_FALSE(svr.is_running());
  3315. });
  3316. svr.wait_until_ready();
  3317. {
  3318. Client cli(HOST, port);
  3319. cli.set_path_encode(false);
  3320. auto handle = cli.open_stream("GET", expected_target);
  3321. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3322. EXPECT_EQ(expected_target, target);
  3323. }
  3324. }
  3325. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3326. // With path encoding enabled a CR/LF in the target is percent-encoded
  3327. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3328. // write_request_line still backstops `set_path_encode(false)`, which is
  3329. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3330. Server svr;
  3331. // Captured before routing: the decoded path contains a newline, which a
  3332. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3333. std::string target;
  3334. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3335. target = req.target;
  3336. res.status = StatusCode::OK_200;
  3337. return Server::HandlerResponse::Handled;
  3338. });
  3339. auto port = svr.bind_to_any_port(HOST);
  3340. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. {
  3348. Client cli(HOST, port);
  3349. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3350. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3351. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3352. }
  3353. }
  3354. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3355. // Nothing may reach the wire: a raw CR/LF target would split the request
  3356. // line and inject headers.
  3357. Server svr;
  3358. // Pre-routing so that "not called" means nothing reached the server at all,
  3359. // rather than merely failing to match a handler pattern.
  3360. auto handler_called = false;
  3361. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3362. handler_called = true;
  3363. res.status = StatusCode::OK_200;
  3364. return Server::HandlerResponse::Handled;
  3365. });
  3366. auto port = svr.bind_to_any_port(HOST);
  3367. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3368. auto se = detail::scope_exit([&] {
  3369. svr.stop();
  3370. thread.join();
  3371. ASSERT_FALSE(svr.is_running());
  3372. });
  3373. svr.wait_until_ready();
  3374. {
  3375. Client cli(HOST, port);
  3376. cli.set_path_encode(false);
  3377. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3378. EXPECT_FALSE(handle.is_valid());
  3379. EXPECT_EQ(Error::Write, handle.error);
  3380. EXPECT_FALSE(handler_called);
  3381. }
  3382. }
  3383. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3384. // Which of the two branches runs is decided by whether the query component
  3385. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3386. // an empty query and must still fall back to building one from
  3387. // `req.params`, while a non-empty query must win over `req.params`.
  3388. Server svr;
  3389. std::string target;
  3390. svr.Get("/foo", [&](const Request &req, Response &res) {
  3391. target = req.target;
  3392. res.status = StatusCode::OK_200;
  3393. });
  3394. auto port = svr.bind_to_any_port(HOST);
  3395. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3396. auto se = detail::scope_exit([&] {
  3397. svr.stop();
  3398. thread.join();
  3399. ASSERT_FALSE(svr.is_running());
  3400. });
  3401. svr.wait_until_ready();
  3402. {
  3403. // Trailing `?` -> empty query component -> `req.params` is used.
  3404. Client cli(HOST, port);
  3405. Request req;
  3406. req.method = "GET";
  3407. req.path = "/foo?";
  3408. req.params.emplace("a", "1");
  3409. target.clear();
  3410. auto res = cli.send(req);
  3411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3412. EXPECT_EQ("/foo?a=1", target);
  3413. }
  3414. {
  3415. // Non-empty query in `req.path` -> `req.params` is not appended.
  3416. Client cli(HOST, port);
  3417. Request req;
  3418. req.method = "GET";
  3419. req.path = "/foo?b=2";
  3420. req.params.emplace("a", "1");
  3421. target.clear();
  3422. auto res = cli.send(req);
  3423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3424. EXPECT_EQ("/foo?b=2", target);
  3425. }
  3426. }
  3427. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3428. Server svr;
  3429. svr.Get("/", [](const Request &req, Response &) {
  3430. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3431. });
  3432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3433. auto se = detail::scope_exit([&] {
  3434. svr.stop();
  3435. thread.join();
  3436. ASSERT_FALSE(svr.is_running());
  3437. });
  3438. svr.wait_until_ready();
  3439. {
  3440. Client cli(HOST, PORT);
  3441. cli.set_path_encode(false);
  3442. auto res = cli.Get("/?something=%0A");
  3443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3444. EXPECT_EQ(StatusCode::OK_200, res->status);
  3445. }
  3446. }
  3447. TEST(BindServerTest, BindDualStack) {
  3448. Server svr;
  3449. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3450. res.set_content("Hello World!", "text/plain");
  3451. });
  3452. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3453. auto se = detail::scope_exit([&] {
  3454. svr.stop();
  3455. thread.join();
  3456. ASSERT_FALSE(svr.is_running());
  3457. });
  3458. svr.wait_until_ready();
  3459. {
  3460. Client cli("127.0.0.1", PORT);
  3461. auto res = cli.Get("/1");
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("Hello World!", res->body);
  3465. }
  3466. {
  3467. Client cli("::1", PORT);
  3468. auto res = cli.Get("/1");
  3469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3470. EXPECT_EQ(StatusCode::OK_200, res->status);
  3471. EXPECT_EQ("Hello World!", res->body);
  3472. }
  3473. }
  3474. TEST(BindServerTest, BindAndListenSeparately) {
  3475. Server svr;
  3476. int port = svr.bind_to_any_port("0.0.0.0");
  3477. ASSERT_TRUE(svr.is_valid());
  3478. ASSERT_TRUE(port > 0);
  3479. svr.stop();
  3480. }
  3481. // Reports whether anything is still listening on a loopback port. A plain
  3482. // connect() is used instead of a Client request because a socket left bound by
  3483. // mistake accepts the connection into its backlog and never answers, which
  3484. // would hang the test instead of failing it.
  3485. static bool is_loopback_port_accepting(int port) {
  3486. sockaddr_in addr{};
  3487. addr.sin_family = AF_INET;
  3488. addr.sin_port = htons(static_cast<uint16_t>(port));
  3489. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3490. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3491. EXPECT_NE(sock, INVALID_SOCKET);
  3492. if (sock == INVALID_SOCKET) { return false; }
  3493. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3494. static_cast<socklen_t>(sizeof(addr)));
  3495. detail::close_socket(sock);
  3496. return ret == 0;
  3497. }
  3498. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3499. Server svr;
  3500. auto port = svr.bind_to_any_port("127.0.0.1");
  3501. ASSERT_TRUE(port > 0);
  3502. svr.stop();
  3503. // bind_to_any_port() already called listen(2), so until stop() closed the
  3504. // descriptor the port kept accepting connections into the backlog. ASSERT
  3505. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3506. // below blocks forever in the accept loop.
  3507. ASSERT_FALSE(is_loopback_port_accepting(port));
  3508. // Nothing is left to accept on, so listen_after_bind() must report failure
  3509. // instead of returning success without ever serving.
  3510. EXPECT_FALSE(svr.listen_after_bind());
  3511. // The failed listen marks the server decommissioned, so a waiter returns
  3512. // instead of spinning forever.
  3513. svr.wait_until_ready();
  3514. }
  3515. #ifdef CPPHTTPLIB_SSL_ENABLED
  3516. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3518. CLIENT_CA_CERT_DIR);
  3519. int port = svr.bind_to_any_port("0.0.0.0");
  3520. ASSERT_TRUE(svr.is_valid());
  3521. ASSERT_TRUE(port > 0);
  3522. svr.stop();
  3523. }
  3524. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3525. // or a rejected CustomRoute() registration would not stop the server binding.
  3526. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3528. CLIENT_CA_CERT_DIR);
  3529. ASSERT_TRUE(svr.is_valid());
  3530. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3531. EXPECT_FALSE(svr.is_valid());
  3532. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3533. }
  3534. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3535. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3536. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3537. int port = svr.bind_to_any_port("0.0.0.0");
  3538. ASSERT_TRUE(svr.is_valid());
  3539. ASSERT_TRUE(port > 0);
  3540. svr.stop();
  3541. }
  3542. TEST(BindServerTest, UpdateCertsPem) {
  3543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3544. int port = svr.bind_to_any_port("0.0.0.0");
  3545. ASSERT_TRUE(svr.is_valid());
  3546. ASSERT_TRUE(port > 0);
  3547. // Read PEM files
  3548. std::string cert_pem, key_pem, ca_pem;
  3549. read_file(SERVER_CERT_FILE, cert_pem);
  3550. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3551. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3552. // Update server certificates using PEM API
  3553. ASSERT_TRUE(
  3554. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3555. ASSERT_TRUE(svr.is_valid());
  3556. svr.stop();
  3557. }
  3558. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3559. // Start server with client CA (enables client auth)
  3560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3561. ASSERT_TRUE(svr.is_valid());
  3562. bool handler_called = false;
  3563. svr.Get("/test", [&](const Request &req, Response &res) {
  3564. handler_called = true;
  3565. // Verify client certificate is present
  3566. auto cert = req.peer_cert();
  3567. EXPECT_TRUE(static_cast<bool>(cert));
  3568. res.set_content("ok", "text/plain");
  3569. });
  3570. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3571. auto se = detail::scope_exit([&] {
  3572. svr.stop();
  3573. t.join();
  3574. ASSERT_FALSE(svr.is_running());
  3575. });
  3576. svr.wait_until_ready();
  3577. // Read PEM files
  3578. std::string cert_pem, key_pem, ca_pem;
  3579. read_file(SERVER_CERT_FILE, cert_pem);
  3580. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3581. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3582. // Update server certificates and client CA using PEM API while server running
  3583. ASSERT_TRUE(
  3584. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3585. // Connect with client certificate
  3586. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3587. cli.enable_server_certificate_verification(false);
  3588. cli.set_connection_timeout(30);
  3589. auto res = cli.Get("/test");
  3590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3591. ASSERT_EQ(StatusCode::OK_200, res->status);
  3592. ASSERT_TRUE(handler_called);
  3593. EXPECT_EQ("ok", res->body);
  3594. }
  3595. #endif
  3596. TEST(ErrorHandlerTest, ContentLength) {
  3597. Server svr;
  3598. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3599. res.status = StatusCode::OK_200;
  3600. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3601. "text/html"); // <= Content-Length still 13
  3602. });
  3603. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3604. res.set_content("Hello World!\n", "text/plain");
  3605. res.status = 524;
  3606. });
  3607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3608. auto se = detail::scope_exit([&] {
  3609. svr.stop();
  3610. thread.join();
  3611. ASSERT_FALSE(svr.is_running());
  3612. });
  3613. svr.wait_until_ready();
  3614. {
  3615. Client cli(HOST, PORT);
  3616. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3620. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3621. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3622. }
  3623. }
  3624. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3625. TEST(ExceptionTest, WithoutExceptionHandler) {
  3626. Server svr;
  3627. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3628. throw std::runtime_error("exception...");
  3629. });
  3630. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3631. throw std::runtime_error("exception\r\n...");
  3632. });
  3633. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3634. auto se = detail::scope_exit([&] {
  3635. svr.stop();
  3636. listen_thread.join();
  3637. ASSERT_FALSE(svr.is_running());
  3638. });
  3639. svr.wait_until_ready();
  3640. Client cli("localhost", PORT);
  3641. {
  3642. auto res = cli.Get("/exception");
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3645. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3646. }
  3647. {
  3648. auto res = cli.Get("/unknown");
  3649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3650. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3651. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3652. }
  3653. }
  3654. TEST(ExceptionTest, WithExceptionHandler) {
  3655. Server svr;
  3656. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3657. std::exception_ptr ep) {
  3658. EXPECT_FALSE(ep == nullptr);
  3659. try {
  3660. std::rethrow_exception(ep);
  3661. } catch (std::exception &e) {
  3662. EXPECT_EQ("abc", std::string(e.what()));
  3663. } catch (...) {}
  3664. res.status = StatusCode::InternalServerError_500;
  3665. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3666. "text/html"); // <= Content-Length still 13 at this point
  3667. });
  3668. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3669. res.set_content("Hello World!\n", "text/plain");
  3670. throw std::runtime_error("abc");
  3671. });
  3672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. svr.wait_until_ready();
  3679. for (size_t i = 0; i < 10; i++) {
  3680. Client cli(HOST, PORT);
  3681. for (size_t j = 0; j < 100; j++) {
  3682. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3685. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3686. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3687. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3688. }
  3689. cli.set_keep_alive(true);
  3690. for (size_t j = 0; j < 100; j++) {
  3691. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3693. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3694. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3695. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3696. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3697. }
  3698. }
  3699. }
  3700. TEST(ExceptionTest, AndErrorHandler) {
  3701. Server svr;
  3702. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3703. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3704. });
  3705. svr.set_exception_handler(
  3706. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3707. EXPECT_FALSE(ep == nullptr);
  3708. try {
  3709. std::rethrow_exception(ep);
  3710. } catch (std::exception &e) {
  3711. res.set_content(e.what(), "text/html");
  3712. } catch (...) {}
  3713. res.status = StatusCode::InternalServerError_500;
  3714. });
  3715. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3716. throw std::runtime_error("EXCEPTION");
  3717. });
  3718. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3719. res.set_content("ERROR", "text/html");
  3720. res.status = StatusCode::InternalServerError_500;
  3721. });
  3722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3723. auto se = detail::scope_exit([&] {
  3724. svr.stop();
  3725. thread.join();
  3726. ASSERT_FALSE(svr.is_running());
  3727. });
  3728. svr.wait_until_ready();
  3729. Client cli(HOST, PORT);
  3730. {
  3731. auto res = cli.Get("/exception");
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3734. EXPECT_EQ("EXCEPTION", res->body);
  3735. }
  3736. {
  3737. auto res = cli.Get("/error");
  3738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3739. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3740. EXPECT_EQ("ERROR", res->body);
  3741. }
  3742. {
  3743. auto res = cli.Get("/invalid");
  3744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. EXPECT_EQ("NOT_FOUND", res->body);
  3747. }
  3748. }
  3749. #endif
  3750. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3751. // process_request() wraps only routing() in a try/catch, so an exception from
  3752. // any other user callback used to unwind into the task queue - which does not
  3753. // catch - and terminate the process. Each test below runs the server on a
  3754. // single worker thread: a guard that catches the exception but still loses the
  3755. // thread would otherwise be hidden by a spare worker serving the follow-up
  3756. // request. Note that a regression here aborts the whole test binary rather
  3757. // than failing one test.
  3758. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3759. Server svr;
  3760. svr.new_task_queue = [] { return new ThreadPool(1); };
  3761. std::atomic<int> reported{0};
  3762. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3763. if (err == Error::UserCallbackException) { reported++; }
  3764. });
  3765. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3766. res.set_content_provider(
  3767. 1024, "text/plain",
  3768. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3769. sink.write("hello", 5);
  3770. throw std::runtime_error("from the content provider");
  3771. });
  3772. });
  3773. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3774. res.set_content("ok", "text/plain");
  3775. });
  3776. auto port = svr.bind_to_any_port(HOST);
  3777. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. listen_thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. svr.wait_until_ready();
  3784. {
  3785. Client cli(HOST, port);
  3786. cli.set_read_timeout(5, 0);
  3787. EXPECT_FALSE(cli.Get("/throw"));
  3788. }
  3789. EXPECT_TRUE(svr.is_running());
  3790. EXPECT_EQ(1, reported.load());
  3791. // A request on a fresh connection is still served.
  3792. {
  3793. Client cli(HOST, port);
  3794. auto res = cli.Get("/ok");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("ok", res->body);
  3798. }
  3799. }
  3800. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3801. Server svr;
  3802. svr.new_task_queue = [] { return new ThreadPool(1); };
  3803. std::atomic<bool> should_throw{true};
  3804. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3805. res.set_content("hi", "text/plain");
  3806. });
  3807. svr.set_post_routing_handler(
  3808. [&](const Request & /*req*/, Response & /*res*/) {
  3809. if (should_throw) {
  3810. throw std::runtime_error("from the post-routing handler");
  3811. }
  3812. });
  3813. auto port = svr.bind_to_any_port(HOST);
  3814. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3815. auto se = detail::scope_exit([&] {
  3816. svr.stop();
  3817. listen_thread.join();
  3818. ASSERT_FALSE(svr.is_running());
  3819. });
  3820. svr.wait_until_ready();
  3821. {
  3822. Client cli(HOST, port);
  3823. cli.set_read_timeout(5, 0);
  3824. EXPECT_FALSE(cli.Get("/hi"));
  3825. }
  3826. EXPECT_TRUE(svr.is_running());
  3827. should_throw = false;
  3828. {
  3829. Client cli(HOST, port);
  3830. auto res = cli.Get("/hi");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ(StatusCode::OK_200, res->status);
  3833. EXPECT_EQ("hi", res->body);
  3834. }
  3835. }
  3836. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3837. // The guard reports the caught exception through the error logger, which is
  3838. // a user callback too. A logger that throws has to be contained as well, or
  3839. // the process would terminate from inside the catch.
  3840. Server svr;
  3841. svr.new_task_queue = [] { return new ThreadPool(1); };
  3842. std::atomic<int> reported{0};
  3843. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3844. if (err == Error::UserCallbackException) {
  3845. reported++;
  3846. throw std::runtime_error("from the error logger");
  3847. }
  3848. });
  3849. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3850. res.set_content_provider(
  3851. 1024, "text/plain",
  3852. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3853. sink.write("hello", 5);
  3854. throw std::runtime_error("from the content provider");
  3855. });
  3856. });
  3857. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3858. res.set_content("ok", "text/plain");
  3859. });
  3860. auto port = svr.bind_to_any_port(HOST);
  3861. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3862. auto se = detail::scope_exit([&] {
  3863. svr.stop();
  3864. listen_thread.join();
  3865. ASSERT_FALSE(svr.is_running());
  3866. });
  3867. svr.wait_until_ready();
  3868. {
  3869. Client cli(HOST, port);
  3870. cli.set_read_timeout(5, 0);
  3871. EXPECT_FALSE(cli.Get("/throw"));
  3872. }
  3873. EXPECT_TRUE(svr.is_running());
  3874. EXPECT_EQ(1, reported.load());
  3875. {
  3876. Client cli(HOST, port);
  3877. auto res = cli.Get("/ok");
  3878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3879. EXPECT_EQ(StatusCode::OK_200, res->status);
  3880. EXPECT_EQ("ok", res->body);
  3881. }
  3882. }
  3883. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3884. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3885. // so the exception unwinds through the ws::WebSocket object on its way to
  3886. // the guard. None of the HTTP cases above cross that.
  3887. Server svr;
  3888. svr.new_task_queue = [] { return new ThreadPool(1); };
  3889. std::atomic<int> reported{0};
  3890. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3891. if (err == Error::UserCallbackException) { reported++; }
  3892. });
  3893. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3894. throw std::runtime_error("from the WebSocket handler");
  3895. });
  3896. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3897. res.set_content("ok", "text/plain");
  3898. });
  3899. auto port = svr.bind_to_any_port(HOST);
  3900. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3901. auto se = detail::scope_exit([&] {
  3902. svr.stop();
  3903. listen_thread.join();
  3904. ASSERT_FALSE(svr.is_running());
  3905. });
  3906. svr.wait_until_ready();
  3907. {
  3908. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3909. "/ws");
  3910. auto res = client.connect();
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. // The server dropped the connection instead of dying.
  3913. std::string msg;
  3914. EXPECT_FALSE(client.read(msg));
  3915. client.close();
  3916. }
  3917. EXPECT_TRUE(svr.is_running());
  3918. EXPECT_EQ(1, reported.load());
  3919. {
  3920. Client cli(HOST, port);
  3921. auto res = cli.Get("/ok");
  3922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3923. EXPECT_EQ(StatusCode::OK_200, res->status);
  3924. EXPECT_EQ("ok", res->body);
  3925. }
  3926. }
  3927. #ifdef CPPHTTPLIB_SSL_ENABLED
  3928. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3929. // SSLServer::process_and_close_socket() is a separate overload with its own
  3930. // guard, so it is exercised on its own.
  3931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3932. ASSERT_TRUE(svr.is_valid());
  3933. svr.new_task_queue = [] { return new ThreadPool(1); };
  3934. std::atomic<int> reported{0};
  3935. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3936. if (err == Error::UserCallbackException) { reported++; }
  3937. });
  3938. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3939. res.set_content_provider(
  3940. 1024, "text/plain",
  3941. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3942. sink.write("hello", 5);
  3943. throw std::runtime_error("from the content provider");
  3944. });
  3945. });
  3946. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3947. res.set_content("ok", "text/plain");
  3948. });
  3949. auto port = svr.bind_to_any_port(HOST);
  3950. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3951. auto se = detail::scope_exit([&] {
  3952. svr.stop();
  3953. listen_thread.join();
  3954. ASSERT_FALSE(svr.is_running());
  3955. });
  3956. svr.wait_until_ready();
  3957. {
  3958. SSLClient cli(HOST, port);
  3959. cli.enable_server_certificate_verification(false);
  3960. cli.set_read_timeout(5, 0);
  3961. EXPECT_FALSE(cli.Get("/throw"));
  3962. }
  3963. EXPECT_TRUE(svr.is_running());
  3964. EXPECT_EQ(1, reported.load());
  3965. {
  3966. SSLClient cli(HOST, port);
  3967. cli.enable_server_certificate_verification(false);
  3968. auto res = cli.Get("/ok");
  3969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("ok", res->body);
  3972. }
  3973. }
  3974. #endif
  3975. #endif
  3976. TEST(NoContentTest, ContentLength) {
  3977. Server svr;
  3978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3979. res.status = StatusCode::NoContent_204;
  3980. });
  3981. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3982. auto se = detail::scope_exit([&] {
  3983. svr.stop();
  3984. thread.join();
  3985. ASSERT_FALSE(svr.is_running());
  3986. });
  3987. svr.wait_until_ready();
  3988. {
  3989. Client cli(HOST, PORT);
  3990. auto res = cli.Get("/hi");
  3991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3992. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3993. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3994. }
  3995. }
  3996. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3997. #ifdef CPPHTTPLIB_SSL_ENABLED
  3998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3999. ASSERT_TRUE(svr.is_valid());
  4000. #else
  4001. Server svr;
  4002. #endif
  4003. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4004. if (req.path == "/routing_handler") {
  4005. res.set_header("PRE_ROUTING", "on");
  4006. res.set_content("Routing Handler", "text/plain");
  4007. return httplib::Server::HandlerResponse::Handled;
  4008. }
  4009. return httplib::Server::HandlerResponse::Unhandled;
  4010. });
  4011. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4012. res.set_content("Error", "text/html");
  4013. });
  4014. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4015. if (req.path == "/routing_handler") {
  4016. res.set_header("POST_ROUTING", "on");
  4017. }
  4018. });
  4019. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4020. res.set_content("Hello World!\n", "text/plain");
  4021. });
  4022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4023. auto se = detail::scope_exit([&] {
  4024. svr.stop();
  4025. thread.join();
  4026. ASSERT_FALSE(svr.is_running());
  4027. });
  4028. svr.wait_until_ready();
  4029. {
  4030. #ifdef CPPHTTPLIB_SSL_ENABLED
  4031. SSLClient cli(HOST, PORT);
  4032. cli.enable_server_certificate_verification(false);
  4033. #else
  4034. Client cli(HOST, PORT);
  4035. #endif
  4036. auto res = cli.Get("/routing_handler");
  4037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("Routing Handler", res->body);
  4040. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4041. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4042. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4043. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4044. }
  4045. {
  4046. #ifdef CPPHTTPLIB_SSL_ENABLED
  4047. SSLClient cli(HOST, PORT);
  4048. cli.enable_server_certificate_verification(false);
  4049. #else
  4050. Client cli(HOST, PORT);
  4051. #endif
  4052. auto res = cli.Get("/hi");
  4053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4054. EXPECT_EQ(StatusCode::OK_200, res->status);
  4055. EXPECT_EQ("Hello World!\n", res->body);
  4056. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4057. EXPECT_EQ(0U, res->get_header_value_count("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("/aaa");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4069. EXPECT_EQ("Error", 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. TEST(RequestHandlerTest, PreRequestHandler) {
  4075. auto route_path = "/user/:user";
  4076. Server svr;
  4077. svr.Get("/hi", [](const Request &, Response &res) {
  4078. res.set_content("hi", "text/plain");
  4079. });
  4080. svr.Get(route_path, [](const Request &req, Response &res) {
  4081. res.set_content(req.path_params.at("user"), "text/plain");
  4082. });
  4083. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4084. if (req.matched_route == route_path) {
  4085. auto user = req.path_params.at("user");
  4086. if (user != "john") {
  4087. res.status = StatusCode::Forbidden_403;
  4088. res.set_content("error", "text/html");
  4089. return Server::HandlerResponse::Handled;
  4090. }
  4091. }
  4092. return Server::HandlerResponse::Unhandled;
  4093. });
  4094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. thread.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. Client cli(HOST, PORT);
  4102. {
  4103. auto res = cli.Get("/hi");
  4104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4105. EXPECT_EQ(StatusCode::OK_200, res->status);
  4106. EXPECT_EQ("hi", res->body);
  4107. }
  4108. {
  4109. auto res = cli.Get("/user/john");
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::OK_200, res->status);
  4112. EXPECT_EQ("john", res->body);
  4113. }
  4114. {
  4115. auto res = cli.Get("/user/invalid-user");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4118. EXPECT_EQ("error", res->body);
  4119. }
  4120. }
  4121. // The pre-request handler must run before the request body is read, so a
  4122. // rejected request never forces the server to buffer a (potentially large)
  4123. // body. Here the posted body is larger than the payload limit: if the body
  4124. // were read first the server would answer 413, but because the pre-request
  4125. // handler runs first it answers 403 and the body is never read.
  4126. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4127. Server svr;
  4128. svr.set_payload_max_length(8);
  4129. auto handler_ran = false;
  4130. svr.Post("/reject", [&](const Request &req, Response &res) {
  4131. handler_ran = true;
  4132. res.set_content(req.body, "text/plain");
  4133. });
  4134. svr.Post("/accept", [](const Request &req, Response &res) {
  4135. res.set_content(req.body, "text/plain");
  4136. });
  4137. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4138. if (req.matched_route == "/reject") {
  4139. res.status = StatusCode::Forbidden_403;
  4140. res.set_content("denied", "text/plain");
  4141. return Server::HandlerResponse::Handled;
  4142. }
  4143. return Server::HandlerResponse::Unhandled;
  4144. });
  4145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4146. auto se = detail::scope_exit([&] {
  4147. svr.stop();
  4148. thread.join();
  4149. ASSERT_FALSE(svr.is_running());
  4150. });
  4151. svr.wait_until_ready();
  4152. Client cli(HOST, PORT);
  4153. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4154. // rejects with 403 before the body is read, so 413 is never reached.
  4155. {
  4156. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4158. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4159. EXPECT_EQ("denied", res->body);
  4160. EXPECT_FALSE(handler_ran);
  4161. }
  4162. // An approved route still reads the body and enforces the payload limit.
  4163. {
  4164. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4167. }
  4168. }
  4169. TEST(UserDataTest, BasicOperations) {
  4170. httplib::UserData ud;
  4171. // Initially empty
  4172. EXPECT_FALSE(ud.has("key"));
  4173. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4174. // set and get
  4175. ud.set("key", 42);
  4176. EXPECT_TRUE(ud.has("key"));
  4177. auto *p = ud.get<int>("key");
  4178. ASSERT_NE(nullptr, p);
  4179. EXPECT_EQ(42, *p);
  4180. // Type mismatch → nullptr
  4181. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4182. // Overwrite with different type
  4183. ud.set("key", std::string("hello"));
  4184. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4185. auto *s = ud.get<std::string>("key");
  4186. ASSERT_NE(nullptr, s);
  4187. EXPECT_EQ("hello", *s);
  4188. // erase
  4189. ud.erase("key");
  4190. EXPECT_FALSE(ud.has("key"));
  4191. // clear
  4192. ud.set("a", 1);
  4193. ud.set("b", 2);
  4194. ud.clear();
  4195. EXPECT_FALSE(ud.has("a"));
  4196. EXPECT_FALSE(ud.has("b"));
  4197. }
  4198. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4199. struct AuthCtx {
  4200. std::string user_id;
  4201. };
  4202. Server svr;
  4203. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4204. res.user_data.set("auth", AuthCtx{"alice"});
  4205. return Server::HandlerResponse::Unhandled;
  4206. });
  4207. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4208. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4209. ASSERT_NE(nullptr, ctx);
  4210. res.set_content("Hello " + ctx->user_id, "text/plain");
  4211. });
  4212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4213. auto se = detail::scope_exit([&] {
  4214. svr.stop();
  4215. thread.join();
  4216. ASSERT_FALSE(svr.is_running());
  4217. });
  4218. svr.wait_until_ready();
  4219. Client cli(HOST, PORT);
  4220. auto res = cli.Get("/me");
  4221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4222. EXPECT_EQ(StatusCode::OK_200, res->status);
  4223. EXPECT_EQ("Hello alice", res->body);
  4224. }
  4225. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4226. struct RoleCtx {
  4227. std::string role;
  4228. };
  4229. Server svr;
  4230. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4231. res.user_data.set("role", RoleCtx{"admin"});
  4232. return Server::HandlerResponse::Unhandled;
  4233. });
  4234. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4235. auto *ctx = res.user_data.get<RoleCtx>("role");
  4236. ASSERT_NE(nullptr, ctx);
  4237. res.set_content(ctx->role, "text/plain");
  4238. });
  4239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4240. auto se = detail::scope_exit([&] {
  4241. svr.stop();
  4242. thread.join();
  4243. ASSERT_FALSE(svr.is_running());
  4244. });
  4245. svr.wait_until_ready();
  4246. Client cli(HOST, PORT);
  4247. auto res = cli.Get("/role");
  4248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("admin", res->body);
  4251. }
  4252. TEST(InvalidFormatTest, StatusCode) {
  4253. Server svr;
  4254. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4255. res.set_content("Hello World!\n", "text/plain");
  4256. res.status = 9999; // Status should be a three-digit code...
  4257. });
  4258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4259. auto se = detail::scope_exit([&] {
  4260. svr.stop();
  4261. thread.join();
  4262. ASSERT_FALSE(svr.is_running());
  4263. });
  4264. svr.wait_until_ready();
  4265. {
  4266. Client cli(HOST, PORT);
  4267. auto res = cli.Get("/hi");
  4268. ASSERT_FALSE(res);
  4269. }
  4270. }
  4271. TEST(URLFragmentTest, WithFragment) {
  4272. Server svr;
  4273. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4274. EXPECT_TRUE(req.target == "/hi");
  4275. });
  4276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4277. auto se = detail::scope_exit([&] {
  4278. svr.stop();
  4279. thread.join();
  4280. ASSERT_FALSE(svr.is_running());
  4281. });
  4282. svr.wait_until_ready();
  4283. {
  4284. Client cli(HOST, PORT);
  4285. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4286. EXPECT_TRUE(res);
  4287. EXPECT_EQ(StatusCode::OK_200, res->status);
  4288. res = cli.Get("/hi%23key1=val1=key2=val2");
  4289. EXPECT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4291. }
  4292. }
  4293. TEST(HeaderWriter, SetHeaderWriter) {
  4294. Server svr;
  4295. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4296. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4297. return detail::write_headers(strm, hdrs);
  4298. });
  4299. svr.Get("/hi", [](const Request &req, Response &res) {
  4300. auto it = req.headers.find("CustomClientHeader");
  4301. EXPECT_TRUE(it != req.headers.end());
  4302. EXPECT_EQ(it->second, "CustomClientValue");
  4303. res.set_content("Hello World!\n", "text/plain");
  4304. });
  4305. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4306. auto se = detail::scope_exit([&] {
  4307. svr.stop();
  4308. thread.join();
  4309. ASSERT_FALSE(svr.is_running());
  4310. });
  4311. svr.wait_until_ready();
  4312. {
  4313. Client cli(HOST, PORT);
  4314. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4315. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4316. return detail::write_headers(strm, hdrs);
  4317. });
  4318. auto res = cli.Get("/hi");
  4319. EXPECT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. auto it = res->headers.find("CustomServerHeader");
  4322. EXPECT_TRUE(it != res->headers.end());
  4323. EXPECT_EQ(it->second, "CustomServerValue");
  4324. }
  4325. }
  4326. class ServerTest : public ::testing::Test {
  4327. protected:
  4328. ServerTest()
  4329. : cli_(HOST, PORT)
  4330. #ifdef CPPHTTPLIB_SSL_ENABLED
  4331. ,
  4332. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4333. #endif
  4334. {
  4335. #ifdef CPPHTTPLIB_SSL_ENABLED
  4336. cli_.enable_server_certificate_verification(false);
  4337. #endif
  4338. // Allow LARGE_DATA (100MB) responses
  4339. cli_.set_payload_max_length(200 * 1024 * 1024);
  4340. }
  4341. virtual void SetUp() {
  4342. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4343. svr_.set_payload_max_length(200 * 1024 * 1024);
  4344. svr_.set_mount_point("/", "./www");
  4345. svr_.set_mount_point("/mount", "./www2");
  4346. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4347. svr_.Get("/hi",
  4348. [&](const Request & /*req*/, Response &res) {
  4349. res.set_content("Hello World!", "text/plain");
  4350. })
  4351. .Get("/file_content",
  4352. [&](const Request & /*req*/, Response &res) {
  4353. res.set_file_content("./www/dir/test.html");
  4354. })
  4355. .Get("/file_content_with_content_type",
  4356. [&](const Request & /*req*/, Response &res) {
  4357. res.set_file_content("./www/file", "text/plain");
  4358. })
  4359. .Get("/invalid_file_content",
  4360. [&](const Request & /*req*/, Response &res) {
  4361. res.set_file_content("./www/dir/invalid_file_path");
  4362. })
  4363. .Get("/http_response_splitting",
  4364. [&](const Request & /*req*/, Response &res) {
  4365. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4366. EXPECT_EQ(0U, res.headers.size());
  4367. EXPECT_FALSE(res.has_header("a"));
  4368. res.set_header("a", "1\nSet-Cookie: a=1");
  4369. EXPECT_EQ(0U, res.headers.size());
  4370. EXPECT_FALSE(res.has_header("a"));
  4371. res.set_header("a", "1\rSet-Cookie: a=1");
  4372. EXPECT_EQ(0U, res.headers.size());
  4373. EXPECT_FALSE(res.has_header("a"));
  4374. res.set_header("a\r\nb", "0");
  4375. EXPECT_EQ(0U, res.headers.size());
  4376. EXPECT_FALSE(res.has_header("a"));
  4377. res.set_header("a\rb", "0");
  4378. EXPECT_EQ(0U, res.headers.size());
  4379. EXPECT_FALSE(res.has_header("a"));
  4380. res.set_header("a\nb", "0");
  4381. EXPECT_EQ(0U, res.headers.size());
  4382. EXPECT_FALSE(res.has_header("a"));
  4383. res.set_redirect("1\r\nSet-Cookie: a=1");
  4384. EXPECT_EQ(0U, res.headers.size());
  4385. EXPECT_FALSE(res.has_header("Location"));
  4386. })
  4387. .Get("/slow",
  4388. [&](const Request & /*req*/, Response &res) {
  4389. std::this_thread::sleep_for(std::chrono::seconds(4));
  4390. res.set_content("slow", "text/plain");
  4391. })
  4392. #if 0
  4393. .Post("/slowpost",
  4394. [&](const Request & /*req*/, Response &res) {
  4395. std::this_thread::sleep_for(std::chrono::seconds(2));
  4396. res.set_content("slow", "text/plain");
  4397. })
  4398. #endif
  4399. .Get("/remote_addr",
  4400. [&](const Request &req, Response &res) {
  4401. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4402. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4403. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4404. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4405. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4406. #endif
  4407. res.set_content(req.remote_addr, "text/plain");
  4408. })
  4409. .Get("/local_addr",
  4410. [&](const Request &req, Response &res) {
  4411. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4412. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4413. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4414. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4415. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4416. #endif
  4417. auto local_addr = req.local_addr;
  4418. auto local_port = std::to_string(req.local_port);
  4419. res.set_content(local_addr.append(":").append(local_port),
  4420. "text/plain");
  4421. })
  4422. .Get("/endwith%",
  4423. [&](const Request & /*req*/, Response &res) {
  4424. res.set_content("Hello World!", "text/plain");
  4425. })
  4426. .Get("/a\\+\\+b",
  4427. [&](const Request &req, Response &res) {
  4428. ASSERT_TRUE(req.has_param("a +b"));
  4429. auto val = req.get_param_value("a +b");
  4430. res.set_content(val, "text/plain");
  4431. })
  4432. .Get("/", [&](const Request & /*req*/,
  4433. Response &res) { res.set_redirect("/hi"); })
  4434. .Post("/1",
  4435. [](const Request & /*req*/, Response &res) {
  4436. res.set_redirect("/2", StatusCode::SeeOther_303);
  4437. })
  4438. .Get("/2",
  4439. [](const Request & /*req*/, Response &res) {
  4440. res.set_content("redirected.", "text/plain");
  4441. res.status = StatusCode::OK_200;
  4442. })
  4443. .Post("/person",
  4444. [&](const Request &req, Response &res) {
  4445. if (req.has_param("name") && req.has_param("note")) {
  4446. persons_[req.get_param_value("name")] =
  4447. req.get_param_value("note");
  4448. } else {
  4449. res.status = StatusCode::BadRequest_400;
  4450. }
  4451. })
  4452. .Put("/person",
  4453. [&](const Request &req, Response &res) {
  4454. if (req.has_param("name") && req.has_param("note")) {
  4455. persons_[req.get_param_value("name")] =
  4456. req.get_param_value("note");
  4457. } else {
  4458. res.status = StatusCode::BadRequest_400;
  4459. }
  4460. })
  4461. .Get("/person/(.*)",
  4462. [&](const Request &req, Response &res) {
  4463. string name = req.matches[1];
  4464. if (persons_.find(name) != persons_.end()) {
  4465. auto note = persons_[name];
  4466. res.set_content(note, "text/plain");
  4467. } else {
  4468. res.status = StatusCode::NotFound_404;
  4469. }
  4470. })
  4471. .Delete("/person",
  4472. [&](const Request &req, Response &res) {
  4473. if (req.has_param("name")) {
  4474. string name = req.get_param_value("name");
  4475. if (persons_.find(name) != persons_.end()) {
  4476. persons_.erase(name);
  4477. res.set_content("DELETED", "text/plain");
  4478. } else {
  4479. res.status = StatusCode::NotFound_404;
  4480. }
  4481. } else {
  4482. res.status = StatusCode::BadRequest_400;
  4483. }
  4484. })
  4485. .Post("/x-www-form-urlencoded-json",
  4486. [&](const Request &req, Response &res) {
  4487. auto json = req.get_param_value("json");
  4488. ASSERT_EQ(JSON_DATA, json);
  4489. res.set_content(json, "appliation/json");
  4490. res.status = StatusCode::OK_200;
  4491. })
  4492. .Get("/streamed-chunked",
  4493. [&](const Request & /*req*/, Response &res) {
  4494. res.set_chunked_content_provider(
  4495. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4496. sink.os << "123";
  4497. sink.os << "456";
  4498. sink.os << "789";
  4499. sink.done();
  4500. return true;
  4501. });
  4502. })
  4503. .Get("/streamed-chunked-with-prohibited-trailer",
  4504. [&](const Request & /*req*/, Response &res) {
  4505. auto i = new int(0);
  4506. // Declare both a prohibited trailer (Content-Length) and an
  4507. // allowed one
  4508. res.set_header("Trailer", "Content-Length, X-Allowed");
  4509. res.set_chunked_content_provider(
  4510. "text/plain",
  4511. [i](size_t /*offset*/, DataSink &sink) {
  4512. switch (*i) {
  4513. case 0: sink.os << "123"; break;
  4514. case 1: sink.os << "456"; break;
  4515. case 2: sink.os << "789"; break;
  4516. case 3: {
  4517. sink.done_with_trailer(
  4518. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4519. } break;
  4520. }
  4521. (*i)++;
  4522. return true;
  4523. },
  4524. [i](bool success) {
  4525. EXPECT_TRUE(success);
  4526. delete i;
  4527. });
  4528. })
  4529. .Get("/streamed-chunked2",
  4530. [&](const Request & /*req*/, Response &res) {
  4531. auto i = new int(0);
  4532. res.set_chunked_content_provider(
  4533. "text/plain",
  4534. [i](size_t /*offset*/, DataSink &sink) {
  4535. switch (*i) {
  4536. case 0: sink.os << "123"; break;
  4537. case 1: sink.os << "456"; break;
  4538. case 2: sink.os << "789"; break;
  4539. case 3: sink.done(); break;
  4540. }
  4541. (*i)++;
  4542. return true;
  4543. },
  4544. [i](bool success) {
  4545. EXPECT_TRUE(success);
  4546. delete i;
  4547. });
  4548. })
  4549. .Get("/streamed-chunked-with-trailer",
  4550. [&](const Request & /*req*/, Response &res) {
  4551. auto i = new int(0);
  4552. res.set_header("Trailer", "Dummy1, Dummy2");
  4553. res.set_chunked_content_provider(
  4554. "text/plain",
  4555. [i](size_t /*offset*/, DataSink &sink) {
  4556. switch (*i) {
  4557. case 0: sink.os << "123"; break;
  4558. case 1: sink.os << "456"; break;
  4559. case 2: sink.os << "789"; break;
  4560. case 3: {
  4561. sink.done_with_trailer(
  4562. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4563. } break;
  4564. }
  4565. (*i)++;
  4566. return true;
  4567. },
  4568. [i](bool success) {
  4569. EXPECT_TRUE(success);
  4570. delete i;
  4571. });
  4572. })
  4573. .Get("/streamed",
  4574. [&](const Request & /*req*/, Response &res) {
  4575. res.set_content_provider(
  4576. 6, "text/plain",
  4577. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4578. sink.os << (offset < 3 ? "a" : "b");
  4579. return true;
  4580. });
  4581. })
  4582. .Get("/streamed-without-length",
  4583. [&](const Request & /*req*/, Response &res) {
  4584. auto data = new std::string("abcdefg");
  4585. res.set_content_provider(
  4586. "text/plain",
  4587. [data](size_t offset, DataSink &sink) {
  4588. if (offset < data->size()) {
  4589. sink.os << data->substr(offset);
  4590. }
  4591. sink.done();
  4592. return true;
  4593. },
  4594. [data](bool success) {
  4595. EXPECT_TRUE(success);
  4596. delete data;
  4597. });
  4598. })
  4599. .Get("/streamed-with-range",
  4600. [&](const Request &req, Response &res) {
  4601. auto data = new std::string("abcdefg");
  4602. // An explicit status keeps the server from picking the 206 it
  4603. // would otherwise choose for a ranged request, so the response
  4604. // is not a partial representation.
  4605. auto status = req.get_param_value("status");
  4606. if (status == "200") {
  4607. res.status = StatusCode::OK_200;
  4608. } else if (status == "403") {
  4609. res.status = StatusCode::Forbidden_403;
  4610. }
  4611. res.set_content_provider(
  4612. data->size(), "text/plain",
  4613. [data](size_t offset, size_t length, DataSink &sink) {
  4614. size_t DATA_CHUNK_SIZE = 4;
  4615. const auto &d = *data;
  4616. auto out_len =
  4617. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4618. auto ret =
  4619. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4620. EXPECT_TRUE(ret);
  4621. return true;
  4622. },
  4623. [data, &req](bool success) {
  4624. EXPECT_EQ(success, !req.has_param("error"));
  4625. delete data;
  4626. });
  4627. })
  4628. .Get("/streamed-cancel",
  4629. [&](const Request & /*req*/, Response &res) {
  4630. res.set_content_provider(
  4631. size_t(-1), "text/plain",
  4632. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4633. sink.os << "data_chunk";
  4634. return true;
  4635. });
  4636. })
  4637. .Get("/regex-with-delimiter",
  4638. [&](const Request &req, Response & /*res*/) {
  4639. ASSERT_TRUE(req.has_param("key"));
  4640. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4641. })
  4642. .Get("/with-range",
  4643. [&](const Request & /*req*/, Response &res) {
  4644. res.set_content("abcdefg", "text/plain");
  4645. })
  4646. .Get("/test-start-time",
  4647. [&](const Request &req, Response & /*res*/) {
  4648. EXPECT_NE(req.start_time_,
  4649. std::chrono::steady_clock::time_point::min());
  4650. })
  4651. .Get("/with-range-customized-response",
  4652. [&](const Request & /*req*/, Response &res) {
  4653. res.status = StatusCode::BadRequest_400;
  4654. res.set_content(JSON_DATA, "application/json");
  4655. })
  4656. .Post("/chunked",
  4657. [&](const Request &req, Response & /*res*/) {
  4658. EXPECT_EQ(req.body, "dechunked post body");
  4659. })
  4660. .Post("/large-chunked",
  4661. [&](const Request &req, Response & /*res*/) {
  4662. std::string expected(6 * 30 * 1024u, 'a');
  4663. EXPECT_EQ(req.body, expected);
  4664. })
  4665. .Post("/multipart",
  4666. [&](const Request &req, Response & /*res*/) {
  4667. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4668. req.form.get_field_count("text2") +
  4669. req.form.get_field_count("file3") +
  4670. req.form.get_field_count("file4"));
  4671. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4672. req.form.get_file_count("file2"));
  4673. ASSERT_TRUE(!req.form.has_file("???"));
  4674. ASSERT_TRUE(!req.form.has_field("???"));
  4675. ASSERT_TRUE(req.body.empty());
  4676. {
  4677. const auto &text = req.form.get_field("text1");
  4678. EXPECT_EQ("text default", text);
  4679. }
  4680. {
  4681. const auto &text = req.form.get_field("text2");
  4682. EXPECT_EQ("aωb", text);
  4683. }
  4684. {
  4685. const auto &file = req.form.get_file("file1");
  4686. EXPECT_EQ("hello.txt", file.filename);
  4687. EXPECT_EQ("text/plain", file.content_type);
  4688. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4689. }
  4690. {
  4691. const auto &file = req.form.get_file("file2");
  4692. EXPECT_EQ("world.json", file.filename);
  4693. EXPECT_EQ("application/json", file.content_type);
  4694. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4695. }
  4696. {
  4697. const auto &text = req.form.get_field("file3");
  4698. EXPECT_EQ(0u, text.size());
  4699. }
  4700. {
  4701. const auto &text = req.form.get_field("file4");
  4702. EXPECT_EQ(0u, text.size());
  4703. }
  4704. })
  4705. .Post("/multipart/multi_file_values",
  4706. [&](const Request &req, Response & /*res*/) {
  4707. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4708. req.form.get_field_count("multi_text1"));
  4709. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4710. ASSERT_TRUE(!req.form.has_file("???"));
  4711. ASSERT_TRUE(!req.form.has_field("???"));
  4712. ASSERT_TRUE(req.body.empty());
  4713. {
  4714. const auto &text = req.form.get_field("text");
  4715. EXPECT_EQ("default text", text);
  4716. }
  4717. {
  4718. const auto &text1_values = req.form.get_fields("multi_text1");
  4719. EXPECT_EQ(2u, text1_values.size());
  4720. EXPECT_EQ("aaaaa", text1_values[0]);
  4721. EXPECT_EQ("bbbbb", text1_values[1]);
  4722. }
  4723. {
  4724. const auto &file1_values = req.form.get_files("multi_file1");
  4725. EXPECT_EQ(2u, file1_values.size());
  4726. auto file1 = file1_values[0];
  4727. EXPECT_EQ(file1.filename, "hello.txt");
  4728. EXPECT_EQ(file1.content_type, "text/plain");
  4729. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4730. auto file2 = file1_values[1];
  4731. EXPECT_EQ(file2.filename, "world.json");
  4732. EXPECT_EQ(file2.content_type, "application/json");
  4733. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4734. }
  4735. })
  4736. .Post("/empty",
  4737. [&](const Request &req, Response &res) {
  4738. EXPECT_EQ(req.body, "");
  4739. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4740. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4741. res.set_content("empty", "text/plain");
  4742. })
  4743. .Post("/empty-no-content-type",
  4744. [&](const Request &req, Response &res) {
  4745. EXPECT_EQ(req.body, "");
  4746. EXPECT_FALSE(req.has_header("Content-Type"));
  4747. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4748. res.set_content("empty-no-content-type", "text/plain");
  4749. })
  4750. .Post("/path-only",
  4751. [&](const Request &req, Response &res) {
  4752. EXPECT_EQ(req.body, "");
  4753. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4754. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4755. res.set_content("path-only", "text/plain");
  4756. })
  4757. .Post("/path-headers-only",
  4758. [&](const Request &req, Response &res) {
  4759. EXPECT_EQ(req.body, "");
  4760. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4761. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4762. EXPECT_EQ("world", req.get_header_value("hello"));
  4763. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4764. res.set_content("path-headers-only", "text/plain");
  4765. })
  4766. .Post("/post-large",
  4767. [&](const Request &req, Response &res) {
  4768. EXPECT_EQ(req.body, LARGE_DATA);
  4769. res.set_content(req.body, "text/plain");
  4770. })
  4771. .Post("/post-loopback",
  4772. [&](const Request &, Response &res,
  4773. ContentReader const &content_reader) {
  4774. std::string body;
  4775. content_reader([&](const char *data, size_t data_length) {
  4776. body.append(data, data_length);
  4777. return true;
  4778. });
  4779. res.set_content(body, "text/plain");
  4780. })
  4781. .Put("/put-loopback",
  4782. [&](const Request &, Response &res,
  4783. ContentReader const &content_reader) {
  4784. std::string body;
  4785. content_reader([&](const char *data, size_t data_length) {
  4786. body.append(data, data_length);
  4787. return true;
  4788. });
  4789. res.set_content(body, "text/plain");
  4790. })
  4791. .Patch("/patch-loopback",
  4792. [&](const Request &, Response &res,
  4793. ContentReader const &content_reader) {
  4794. std::string body;
  4795. content_reader([&](const char *data, size_t data_length) {
  4796. body.append(data, data_length);
  4797. return true;
  4798. });
  4799. res.set_content(body, "text/plain");
  4800. })
  4801. .Put("/empty-no-content-type",
  4802. [&](const Request &req, Response &res) {
  4803. EXPECT_EQ(req.body, "");
  4804. EXPECT_FALSE(req.has_header("Content-Type"));
  4805. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4806. res.set_content("empty-no-content-type", "text/plain");
  4807. })
  4808. .Put("/put",
  4809. [&](const Request &req, Response &res) {
  4810. EXPECT_EQ(req.body, "PUT");
  4811. res.set_content(req.body, "text/plain");
  4812. })
  4813. .Put("/put-large",
  4814. [&](const Request &req, Response &res) {
  4815. EXPECT_EQ(req.body, LARGE_DATA);
  4816. res.set_content(req.body, "text/plain");
  4817. })
  4818. .Patch("/patch",
  4819. [&](const Request &req, Response &res) {
  4820. EXPECT_EQ(req.body, "PATCH");
  4821. res.set_content(req.body, "text/plain");
  4822. })
  4823. .Delete("/delete",
  4824. [&](const Request & /*req*/, Response &res) {
  4825. res.set_content("DELETE", "text/plain");
  4826. })
  4827. .Delete("/delete-body",
  4828. [&](const Request &req, Response &res) {
  4829. EXPECT_EQ(req.body, "content");
  4830. res.set_content(req.body, "text/plain");
  4831. })
  4832. .Options(R"(\*)",
  4833. [&](const Request & /*req*/, Response &res) {
  4834. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4835. })
  4836. .CustomRoute("PROPFIND", "/dav/:id",
  4837. [&](const Request &req, Response &res) {
  4838. res.set_header("x-body-size",
  4839. std::to_string(req.body.size()));
  4840. res.set_header("x-matched-route", req.matched_route);
  4841. res.set_header("x-dav-id", req.path_params.at("id"));
  4842. res.status = StatusCode::MultiStatus_207;
  4843. res.set_content(req.body, "application/xml");
  4844. })
  4845. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4846. [&](const Request &req, Response &res) {
  4847. res.set_header("x-dav-match", req.matches[1]);
  4848. res.status = StatusCode::MultiStatus_207;
  4849. })
  4850. .CustomRoute("MKCOL", "/dav-mkcol",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_TRUE(req.body.empty());
  4853. res.status = StatusCode::Created_201;
  4854. })
  4855. .CustomRoute(
  4856. "REPORT", "/dav-report",
  4857. [&](const Request & /*req*/, Response &res,
  4858. const ContentReader &content_reader) {
  4859. std::string body;
  4860. content_reader([&](const char *data, size_t data_length) {
  4861. body.append(data, data_length);
  4862. return true;
  4863. });
  4864. res.set_header("x-body-size", std::to_string(body.size()));
  4865. res.status = StatusCode::MultiStatus_207;
  4866. res.set_content(body, "application/xml");
  4867. })
  4868. .Get("/request-target",
  4869. [&](const Request &req, Response & /*res*/) {
  4870. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4871. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4872. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4873. })
  4874. .Get("/long-query-value",
  4875. [&](const Request &req, Response & /*res*/) {
  4876. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4877. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4878. })
  4879. .Get("/too-long-query-value",
  4880. [&](const Request &req, Response & /*res*/) {
  4881. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4882. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4883. })
  4884. .Get("/array-param",
  4885. [&](const Request &req, Response & /*res*/) {
  4886. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4887. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4888. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4889. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4890. })
  4891. .Get("/array-param-values",
  4892. [&](const Request &req, Response & /*res*/) {
  4893. auto values = req.get_param_values("array");
  4894. EXPECT_EQ(3u, values.size());
  4895. EXPECT_EQ("value1", values[0]);
  4896. EXPECT_EQ("value2", values[1]);
  4897. EXPECT_EQ("value3", values[2]);
  4898. auto empty = req.get_param_values("nonexistent");
  4899. EXPECT_TRUE(empty.empty());
  4900. })
  4901. .Post("/validate-no-multiple-headers",
  4902. [&](const Request &req, Response & /*res*/) {
  4903. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4904. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4905. })
  4906. .Post("/content_receiver",
  4907. [&](const Request &req, Response &res,
  4908. const ContentReader &content_reader) {
  4909. if (req.is_multipart_form_data()) {
  4910. std::vector<FormData> items;
  4911. content_reader(
  4912. [&](const FormData &file) {
  4913. items.push_back(file);
  4914. return true;
  4915. },
  4916. [&](const char *data, size_t data_length) {
  4917. items.back().content.append(data, data_length);
  4918. return true;
  4919. });
  4920. EXPECT_EQ(5u, items.size());
  4921. {
  4922. const auto &file = get_file_value(items, "text1");
  4923. EXPECT_TRUE(file.filename.empty());
  4924. EXPECT_EQ("text default", file.content);
  4925. }
  4926. {
  4927. const auto &file = get_file_value(items, "text2");
  4928. EXPECT_TRUE(file.filename.empty());
  4929. EXPECT_EQ("aωb", file.content);
  4930. }
  4931. {
  4932. const auto &file = get_file_value(items, "file1");
  4933. EXPECT_EQ("hello.txt", file.filename);
  4934. EXPECT_EQ("text/plain", file.content_type);
  4935. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4936. }
  4937. {
  4938. const auto &file = get_file_value(items, "file2");
  4939. EXPECT_EQ("world.json", file.filename);
  4940. EXPECT_EQ("application/json", file.content_type);
  4941. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4942. }
  4943. {
  4944. const auto &file = get_file_value(items, "file3");
  4945. EXPECT_TRUE(file.filename.empty());
  4946. EXPECT_EQ("application/octet-stream", file.content_type);
  4947. EXPECT_EQ(0u, file.content.size());
  4948. }
  4949. } else {
  4950. std::string body;
  4951. content_reader([&](const char *data, size_t data_length) {
  4952. EXPECT_EQ(7U, data_length);
  4953. body.append(data, data_length);
  4954. return true;
  4955. });
  4956. EXPECT_EQ(body, "content");
  4957. res.set_content(body, "text/plain");
  4958. }
  4959. })
  4960. .Put("/content_receiver",
  4961. [&](const Request & /*req*/, Response &res,
  4962. const ContentReader &content_reader) {
  4963. std::string body;
  4964. content_reader([&](const char *data, size_t data_length) {
  4965. body.append(data, data_length);
  4966. return true;
  4967. });
  4968. EXPECT_EQ(body, "content");
  4969. res.set_content(body, "text/plain");
  4970. })
  4971. .Patch("/content_receiver",
  4972. [&](const Request & /*req*/, Response &res,
  4973. const ContentReader &content_reader) {
  4974. std::string body;
  4975. content_reader([&](const char *data, size_t data_length) {
  4976. body.append(data, data_length);
  4977. return true;
  4978. });
  4979. EXPECT_EQ(body, "content");
  4980. res.set_content(body, "text/plain");
  4981. })
  4982. .Post("/query-string-and-body",
  4983. [&](const Request &req, Response & /*res*/) {
  4984. ASSERT_TRUE(req.has_param("key"));
  4985. EXPECT_EQ(req.get_param_value("key"), "value");
  4986. EXPECT_EQ(req.body, "content");
  4987. })
  4988. .Get("/last-request",
  4989. [&](const Request &req, Response & /*res*/) {
  4990. EXPECT_EQ("close", req.get_header_value("Connection"));
  4991. })
  4992. .Get(R"(/redirect/(\d+))",
  4993. [&](const Request &req, Response &res) {
  4994. auto num = std::stoi(req.matches[1]) + 1;
  4995. std::string url = "/redirect/" + std::to_string(num);
  4996. res.set_redirect(url);
  4997. })
  4998. .Post("/binary",
  4999. [&](const Request &req, Response &res) {
  5000. EXPECT_EQ(4U, req.body.size());
  5001. EXPECT_EQ("application/octet-stream",
  5002. req.get_header_value("Content-Type"));
  5003. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5004. res.set_content(req.body, "application/octet-stream");
  5005. })
  5006. .Put("/binary",
  5007. [&](const Request &req, Response &res) {
  5008. EXPECT_EQ(4U, req.body.size());
  5009. EXPECT_EQ("application/octet-stream",
  5010. req.get_header_value("Content-Type"));
  5011. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5012. res.set_content(req.body, "application/octet-stream");
  5013. })
  5014. .Patch("/binary",
  5015. [&](const Request &req, Response &res) {
  5016. EXPECT_EQ(4U, req.body.size());
  5017. EXPECT_EQ("application/octet-stream",
  5018. req.get_header_value("Content-Type"));
  5019. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5020. res.set_content(req.body, "application/octet-stream");
  5021. })
  5022. .Delete("/binary",
  5023. [&](const Request &req, Response &res) {
  5024. EXPECT_EQ(4U, req.body.size());
  5025. EXPECT_EQ("application/octet-stream",
  5026. req.get_header_value("Content-Type"));
  5027. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5028. res.set_content(req.body, "application/octet-stream");
  5029. })
  5030. .Get("/issue1772",
  5031. [&](const Request & /*req*/, Response &res) {
  5032. res.status = 401;
  5033. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5034. })
  5035. .Delete("/issue609",
  5036. [](const httplib::Request &, httplib::Response &res,
  5037. const httplib::ContentReader &) {
  5038. res.set_content("ok", "text/plain");
  5039. })
  5040. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5041. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5042. .Get("/compress",
  5043. [&](const Request & /*req*/, Response &res) {
  5044. res.set_content(
  5045. "12345678901234567890123456789012345678901234567890123456789"
  5046. "01234567890123456789012345678901234567890",
  5047. "text/plain");
  5048. })
  5049. .Get("/compress-with-charset",
  5050. [&](const Request & /*req*/, Response &res) {
  5051. res.set_content(
  5052. "12345678901234567890123456789012345678901234567890123456789"
  5053. "01234567890123456789012345678901234567890",
  5054. "application/json; charset=utf-8");
  5055. })
  5056. .Get("/nocompress",
  5057. [&](const Request & /*req*/, Response &res) {
  5058. res.set_content(
  5059. "12345678901234567890123456789012345678901234567890123456789"
  5060. "01234567890123456789012345678901234567890",
  5061. "application/octet-stream");
  5062. })
  5063. .Post("/compress-multipart",
  5064. [&](const Request &req, Response & /*res*/) {
  5065. EXPECT_EQ(2u, req.form.fields.size());
  5066. ASSERT_TRUE(!req.form.has_field("???"));
  5067. {
  5068. const auto &text = req.form.get_field("key1");
  5069. EXPECT_EQ("test", text);
  5070. }
  5071. {
  5072. const auto &text = req.form.get_field("key2");
  5073. EXPECT_EQ("--abcdefg123", text);
  5074. }
  5075. })
  5076. #endif
  5077. ;
  5078. persons_["john"] = "programmer";
  5079. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5080. svr_.wait_until_ready();
  5081. }
  5082. virtual void TearDown() {
  5083. svr_.stop();
  5084. if (!request_threads_.empty()) {
  5085. std::this_thread::sleep_for(std::chrono::seconds(1));
  5086. for (auto &t : request_threads_) {
  5087. t.join();
  5088. }
  5089. }
  5090. t_.join();
  5091. }
  5092. map<string, string> persons_;
  5093. #ifdef CPPHTTPLIB_SSL_ENABLED
  5094. SSLClient cli_;
  5095. SSLServer svr_;
  5096. #else
  5097. Client cli_;
  5098. Server svr_;
  5099. #endif
  5100. thread t_;
  5101. std::vector<thread> request_threads_;
  5102. };
  5103. TEST_F(ServerTest, GetMethod200) {
  5104. auto res = cli_.Get("/hi");
  5105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5106. EXPECT_EQ("HTTP/1.1", res->version);
  5107. EXPECT_EQ(StatusCode::OK_200, res->status);
  5108. EXPECT_EQ("OK", res->reason);
  5109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5110. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5111. EXPECT_EQ("Hello World!", res->body);
  5112. }
  5113. TEST_F(ServerTest, GetEmptyFile) {
  5114. auto res = cli_.Get("/empty_file");
  5115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5118. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5119. EXPECT_EQ("", res->body);
  5120. }
  5121. TEST_F(ServerTest, GetFileContent) {
  5122. auto res = cli_.Get("/file_content");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5127. EXPECT_EQ("test.html", res->body);
  5128. }
  5129. TEST_F(ServerTest, GetFileContentWithRange) {
  5130. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5134. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5135. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5136. EXPECT_EQ("est", res->body);
  5137. }
  5138. TEST_F(ServerTest, GetFileContentWithContentType) {
  5139. auto res = cli_.Get("/file_content_with_content_type");
  5140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5141. EXPECT_EQ(StatusCode::OK_200, res->status);
  5142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5143. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5144. EXPECT_EQ("file\n", res->body);
  5145. }
  5146. TEST_F(ServerTest, GetInvalidFileContent) {
  5147. auto res = cli_.Get("/invalid_file_content");
  5148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5150. }
  5151. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5152. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5154. EXPECT_EQ("HTTP/1.1", res->version);
  5155. EXPECT_EQ(StatusCode::OK_200, res->status);
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5158. EXPECT_EQ("Hello World!", res->body);
  5159. }
  5160. TEST_F(ServerTest, GetMethod302) {
  5161. auto res = cli_.Get("/");
  5162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5163. EXPECT_EQ(StatusCode::Found_302, res->status);
  5164. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5165. }
  5166. TEST_F(ServerTest, GetMethod302Redirect) {
  5167. cli_.set_follow_location(true);
  5168. auto res = cli_.Get("/");
  5169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5170. EXPECT_EQ(StatusCode::OK_200, res->status);
  5171. EXPECT_EQ("Hello World!", res->body);
  5172. EXPECT_EQ("/hi", res->location);
  5173. }
  5174. TEST_F(ServerTest, GetMethod404) {
  5175. auto res = cli_.Get("/invalid");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5178. }
  5179. TEST_F(ServerTest, HeadMethod200) {
  5180. auto res = cli_.Head("/hi");
  5181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5182. EXPECT_EQ(StatusCode::OK_200, res->status);
  5183. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5184. EXPECT_TRUE(res->body.empty());
  5185. }
  5186. TEST_F(ServerTest, HeadMethod200Static) {
  5187. auto res = cli_.Head("/mount/dir/index.html");
  5188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5189. EXPECT_EQ(StatusCode::OK_200, res->status);
  5190. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5191. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5192. EXPECT_TRUE(res->body.empty());
  5193. }
  5194. TEST_F(ServerTest, HeadMethod404) {
  5195. auto res = cli_.Head("/invalid");
  5196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5198. EXPECT_TRUE(res->body.empty());
  5199. }
  5200. TEST_F(ServerTest, GetMethodPersonJohn) {
  5201. auto res = cli_.Get("/person/john");
  5202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5205. EXPECT_EQ("programmer", res->body);
  5206. }
  5207. TEST_F(ServerTest, PostMethod1) {
  5208. auto res = cli_.Get("/person/john1");
  5209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5210. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5211. res = cli_.Post("/person", "name=john1&note=coder",
  5212. "application/x-www-form-urlencoded");
  5213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5214. ASSERT_EQ(StatusCode::OK_200, res->status);
  5215. res = cli_.Get("/person/john1");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. ASSERT_EQ(StatusCode::OK_200, res->status);
  5218. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5219. ASSERT_EQ("coder", res->body);
  5220. }
  5221. TEST_F(ServerTest, PostMethod2) {
  5222. auto res = cli_.Get("/person/john2");
  5223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5225. Params params;
  5226. params.emplace("name", "john2");
  5227. params.emplace("note", "coder");
  5228. res = cli_.Post("/person", params);
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. ASSERT_EQ(StatusCode::OK_200, res->status);
  5231. res = cli_.Get("/person/john2");
  5232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5233. ASSERT_EQ(StatusCode::OK_200, res->status);
  5234. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. ASSERT_EQ("coder", res->body);
  5236. }
  5237. TEST_F(ServerTest, PutMethod3) {
  5238. auto res = cli_.Get("/person/john3");
  5239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5240. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5241. Params params;
  5242. params.emplace("name", "john3");
  5243. params.emplace("note", "coder");
  5244. res = cli_.Put("/person", params);
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. ASSERT_EQ(StatusCode::OK_200, res->status);
  5247. res = cli_.Get("/person/john3");
  5248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5249. ASSERT_EQ(StatusCode::OK_200, res->status);
  5250. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5251. ASSERT_EQ("coder", res->body);
  5252. }
  5253. TEST_F(ServerTest, DeleteMethod1) {
  5254. auto res = cli_.Get("/person/john4");
  5255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5256. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5257. Params params;
  5258. params.emplace("name", "john4");
  5259. params.emplace("note", "coder");
  5260. res = cli_.Post("/person", params);
  5261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5262. ASSERT_EQ(StatusCode::OK_200, res->status);
  5263. res = cli_.Get("/person/john4");
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. ASSERT_EQ(StatusCode::OK_200, res->status);
  5266. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5267. ASSERT_EQ("coder", res->body);
  5268. Params delete_params;
  5269. delete_params.emplace("name", "john4");
  5270. res = cli_.Delete("/person", delete_params);
  5271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5272. ASSERT_EQ(StatusCode::OK_200, res->status);
  5273. ASSERT_EQ("DELETED", res->body);
  5274. res = cli_.Get("/person/john4");
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5277. }
  5278. TEST_F(ServerTest, DeleteMethod2) {
  5279. auto res = cli_.Get("/person/john5");
  5280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5281. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5282. Params params;
  5283. params.emplace("name", "john5");
  5284. params.emplace("note", "developer");
  5285. res = cli_.Post("/person", params);
  5286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5287. ASSERT_EQ(StatusCode::OK_200, res->status);
  5288. res = cli_.Get("/person/john5");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. ASSERT_EQ(StatusCode::OK_200, res->status);
  5291. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5292. ASSERT_EQ("developer", res->body);
  5293. Params delete_params;
  5294. delete_params.emplace("name", "john5");
  5295. Headers headers;
  5296. headers.emplace("Custom-Header", "test-value");
  5297. res = cli_.Delete("/person", headers, delete_params);
  5298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5299. ASSERT_EQ(StatusCode::OK_200, res->status);
  5300. ASSERT_EQ("DELETED", res->body);
  5301. res = cli_.Get("/person/john5");
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5304. }
  5305. TEST_F(ServerTest, DeleteMethod3) {
  5306. auto res = cli_.Get("/person/john6");
  5307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5308. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5309. Params params;
  5310. params.emplace("name", "john6");
  5311. params.emplace("note", "tester");
  5312. res = cli_.Post("/person", params);
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. ASSERT_EQ(StatusCode::OK_200, res->status);
  5315. res = cli_.Get("/person/john6");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. ASSERT_EQ(StatusCode::OK_200, res->status);
  5318. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5319. ASSERT_EQ("tester", res->body);
  5320. Params delete_params;
  5321. delete_params.emplace("name", "john6");
  5322. Headers headers;
  5323. headers.emplace("Custom-Header", "test-value");
  5324. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5326. ASSERT_EQ(StatusCode::OK_200, res->status);
  5327. ASSERT_EQ("DELETED", res->body);
  5328. res = cli_.Get("/person/john6");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5331. }
  5332. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5333. Params params;
  5334. params.emplace("json", JSON_DATA);
  5335. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. ASSERT_EQ(StatusCode::OK_200, res->status);
  5338. ASSERT_EQ(JSON_DATA, res->body);
  5339. }
  5340. TEST_F(ServerTest, PostEmptyContent) {
  5341. auto res = cli_.Post("/empty", "", "text/plain");
  5342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5343. ASSERT_EQ(StatusCode::OK_200, res->status);
  5344. ASSERT_EQ("empty", res->body);
  5345. }
  5346. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5347. auto res = cli_.Post("/empty-no-content-type");
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. ASSERT_EQ(StatusCode::OK_200, res->status);
  5350. ASSERT_EQ("empty-no-content-type", res->body);
  5351. }
  5352. TEST_F(ServerTest, PostPathOnly) {
  5353. auto res = cli_.Post("/path-only");
  5354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5355. ASSERT_EQ(StatusCode::OK_200, res->status);
  5356. ASSERT_EQ("path-only", res->body);
  5357. }
  5358. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5359. auto res = cli_.Post("/path-headers-only",
  5360. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. ASSERT_EQ(StatusCode::OK_200, res->status);
  5363. ASSERT_EQ("path-headers-only", res->body);
  5364. }
  5365. TEST_F(ServerTest, PostLarge) {
  5366. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5368. ASSERT_EQ(StatusCode::OK_200, res->status);
  5369. EXPECT_EQ(LARGE_DATA, res->body);
  5370. }
  5371. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5372. auto res = cli_.Put("/empty-no-content-type");
  5373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5374. ASSERT_EQ(StatusCode::OK_200, res->status);
  5375. ASSERT_EQ("empty-no-content-type", res->body);
  5376. }
  5377. TEST_F(ServerTest, GetMethodDir) {
  5378. auto res = cli_.Get("/dir/");
  5379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5380. EXPECT_EQ(StatusCode::OK_200, res->status);
  5381. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5382. auto body = R"(<html>
  5383. <head>
  5384. </head>
  5385. <body>
  5386. <a href="/dir/test.html">Test</a>
  5387. <a href="/hi">hi</a>
  5388. </body>
  5389. </html>
  5390. )";
  5391. EXPECT_EQ(body, res->body);
  5392. }
  5393. TEST_F(ServerTest, GetMethodDirTest) {
  5394. auto res = cli_.Get("/dir/test.html");
  5395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5396. EXPECT_EQ(StatusCode::OK_200, res->status);
  5397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("test.html", res->body);
  5399. }
  5400. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5401. auto res = cli_.Get("/dir/../dir/test.html");
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5405. EXPECT_EQ("test.html", res->body);
  5406. }
  5407. TEST_F(ServerTest, GetMethodInvalidPath) {
  5408. auto res = cli_.Get("/dir/../test.html");
  5409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5411. }
  5412. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5413. auto res = cli_.Get("/../www/dir/test.html");
  5414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5415. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5416. }
  5417. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5418. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5421. }
  5422. TEST_F(ServerTest, GetMethodDirMountTest) {
  5423. auto res = cli_.Get("/mount/dir/test.html");
  5424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5425. EXPECT_EQ(StatusCode::OK_200, res->status);
  5426. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5427. EXPECT_EQ("test.html", res->body);
  5428. }
  5429. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5430. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5434. EXPECT_EQ("test.html", res->body);
  5435. }
  5436. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5437. auto res = cli_.Get("/mount/dir/../test.html");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5440. }
  5441. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5442. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5447. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5450. }
  5451. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5452. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5455. }
  5456. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5457. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5460. }
  5461. TEST_F(ServerTest, PostMethod303) {
  5462. auto res = cli_.Post("/1", "body", "text/plain");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5465. EXPECT_EQ("/2", res->get_header_value("Location"));
  5466. }
  5467. TEST_F(ServerTest, PostMethod303Redirect) {
  5468. cli_.set_follow_location(true);
  5469. auto res = cli_.Post("/1", "body", "text/plain");
  5470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5471. EXPECT_EQ(StatusCode::OK_200, res->status);
  5472. EXPECT_EQ("redirected.", res->body);
  5473. EXPECT_EQ("/2", res->location);
  5474. }
  5475. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5476. auto res = cli_.Get("/dir/test.abcde");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5480. EXPECT_EQ("abcde", res->body);
  5481. }
  5482. TEST_F(ServerTest, StaticFileRange) {
  5483. auto res =
  5484. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5486. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5487. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5488. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5489. EXPECT_EQ(true, res->has_header("Content-Range"));
  5490. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5491. EXPECT_EQ(std::string("cd"), res->body);
  5492. }
  5493. TEST_F(ServerTest, StaticFileRanges) {
  5494. auto res = cli_.Get("/dir/test.abcde",
  5495. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5497. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5498. EXPECT_TRUE(
  5499. res->get_header_value("Content-Type")
  5500. .find(
  5501. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5502. 0);
  5503. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5504. }
  5505. TEST_F(ServerTest, StaticFileRangeHead) {
  5506. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5509. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5510. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5511. EXPECT_EQ(true, res->has_header("Content-Range"));
  5512. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5513. }
  5514. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5515. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5520. EXPECT_EQ(true, res->has_header("Content-Range"));
  5521. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5522. res->get_header_value("Content-Range"));
  5523. EXPECT_EQ("LAST\n", res->body);
  5524. }
  5525. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5526. auto res =
  5527. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5531. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5532. EXPECT_EQ(true, res->has_header("Content-Range"));
  5533. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5534. }
  5535. TEST_F(ServerTest, StaticFileBigFile) {
  5536. auto res = cli_.Get("/dir/1MB.txt");
  5537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5540. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5541. }
  5542. TEST_F(ServerTest, InvalidBaseDirMount) {
  5543. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5544. }
  5545. TEST_F(ServerTest, Binary) {
  5546. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5547. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5548. "application/octet-stream");
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. ASSERT_EQ(StatusCode::OK_200, res->status);
  5551. ASSERT_EQ(4U, res->body.size());
  5552. res = cli_.Put("/binary", binary.data(), binary.size(),
  5553. "application/octet-stream");
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. ASSERT_EQ(StatusCode::OK_200, res->status);
  5556. ASSERT_EQ(4U, res->body.size());
  5557. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5558. "application/octet-stream");
  5559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5560. ASSERT_EQ(StatusCode::OK_200, res->status);
  5561. ASSERT_EQ(4U, res->body.size());
  5562. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5563. "application/octet-stream");
  5564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5565. ASSERT_EQ(StatusCode::OK_200, res->status);
  5566. ASSERT_EQ(4U, res->body.size());
  5567. }
  5568. TEST_F(ServerTest, BinaryString) {
  5569. auto binary = std::string("\x00\x01\x02\x03", 4);
  5570. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. ASSERT_EQ(StatusCode::OK_200, res->status);
  5573. ASSERT_EQ(4U, res->body.size());
  5574. res = cli_.Put("/binary", binary, "application/octet-stream");
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. ASSERT_EQ(StatusCode::OK_200, res->status);
  5577. ASSERT_EQ(4U, res->body.size());
  5578. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. ASSERT_EQ(StatusCode::OK_200, res->status);
  5581. ASSERT_EQ(4U, res->body.size());
  5582. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. ASSERT_EQ(StatusCode::OK_200, res->status);
  5585. ASSERT_EQ(4U, res->body.size());
  5586. }
  5587. TEST_F(ServerTest, EmptyRequest) {
  5588. auto res = cli_.Get("");
  5589. ASSERT_TRUE(!res);
  5590. EXPECT_EQ(Error::Connection, res.error());
  5591. }
  5592. TEST_F(ServerTest, LongRequest) {
  5593. std::string request;
  5594. for (size_t i = 0; i < 545; i++) {
  5595. request += "/TooLongRequest";
  5596. }
  5597. request += "OK";
  5598. auto res = cli_.Get(request.c_str());
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5601. }
  5602. TEST_F(ServerTest, TooLongRequest) {
  5603. std::string request;
  5604. for (size_t i = 0; i < 546; i++) {
  5605. request += "/TooLongRequest";
  5606. }
  5607. request += "_NG";
  5608. auto start = std::chrono::high_resolution_clock::now();
  5609. cli_.set_keep_alive(true);
  5610. auto res = cli_.Get(request.c_str());
  5611. auto end = std::chrono::high_resolution_clock::now();
  5612. auto elapsed =
  5613. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5614. .count();
  5615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5616. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5617. EXPECT_LE(elapsed, 1000);
  5618. EXPECT_EQ("close", res->get_header_value("Connection"));
  5619. EXPECT_FALSE(cli_.is_socket_open());
  5620. }
  5621. TEST_F(ServerTest, AlmostTooLongRequest) {
  5622. // test for #2046 - URI length check shouldn't include other content on req
  5623. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5624. // leading /, space, HTTP/1.1)
  5625. std::string request =
  5626. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5627. auto res = cli_.Get(request.c_str());
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5630. }
  5631. TEST_F(ServerTest, LongHeader) {
  5632. Request req;
  5633. req.method = "GET";
  5634. req.path = "/hi";
  5635. std::string host_and_port;
  5636. host_and_port += HOST;
  5637. host_and_port += ":";
  5638. host_and_port += std::to_string(PORT);
  5639. req.headers.emplace("Host", host_and_port.c_str());
  5640. req.headers.emplace("Accept", "*/*");
  5641. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5642. req.headers.emplace(
  5643. "Header-Name",
  5644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5672. "@@@@@@@@@@@@@@@@");
  5673. auto res = std::make_shared<Response>();
  5674. auto error = Error::Success;
  5675. auto ret = cli_.send(req, *res, error);
  5676. ASSERT_TRUE(ret);
  5677. EXPECT_EQ(StatusCode::OK_200, res->status);
  5678. }
  5679. TEST_F(ServerTest, LongQueryValue) {
  5680. auto start = std::chrono::high_resolution_clock::now();
  5681. cli_.set_keep_alive(true);
  5682. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5683. auto end = std::chrono::high_resolution_clock::now();
  5684. auto elapsed =
  5685. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5686. .count();
  5687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5688. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5689. EXPECT_LE(elapsed, 1000);
  5690. EXPECT_EQ("close", res->get_header_value("Connection"));
  5691. EXPECT_FALSE(cli_.is_socket_open());
  5692. }
  5693. TEST_F(ServerTest, TooLongQueryValue) {
  5694. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5695. ASSERT_FALSE(res);
  5696. EXPECT_EQ(Error::Read, res.error());
  5697. }
  5698. TEST_F(ServerTest, TooLongHeader) {
  5699. Request req;
  5700. req.method = "GET";
  5701. req.path = "/hi";
  5702. std::string host_and_port;
  5703. host_and_port += HOST;
  5704. host_and_port += ":";
  5705. host_and_port += std::to_string(PORT);
  5706. req.headers.emplace("Host", host_and_port.c_str());
  5707. req.headers.emplace("Accept", "*/*");
  5708. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5709. req.headers.emplace(
  5710. "Header-Name",
  5711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@");
  5740. auto res = std::make_shared<Response>();
  5741. auto error = Error::Success;
  5742. auto ret = cli_.send(req, *res, error);
  5743. ASSERT_TRUE(ret);
  5744. EXPECT_EQ(StatusCode::OK_200, res->status);
  5745. }
  5746. TEST_F(ServerTest, HeaderCountAtLimit) {
  5747. // Test with headers just under the 100 limit
  5748. httplib::Headers headers;
  5749. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5750. // This should keep us just under the 100 header limit
  5751. for (int i = 0; i < 95; i++) {
  5752. std::string name = "X-Test-Header-" + std::to_string(i);
  5753. std::string value = "value" + std::to_string(i);
  5754. headers.emplace(name, value);
  5755. }
  5756. // This should work fine as we're under the limit
  5757. auto res = cli_.Get("/hi", headers);
  5758. EXPECT_TRUE(res);
  5759. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5760. }
  5761. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5762. // Test with many headers to exceed the 100 limit
  5763. httplib::Headers headers;
  5764. // Add 150 headers to definitely exceed the 100 limit
  5765. for (int i = 0; i < 150; 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 fail due to exceeding header count limit
  5771. cli_.set_keep_alive(true);
  5772. auto res = cli_.Get("/hi", headers);
  5773. // The server should respond with 400 Bad Request
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5776. EXPECT_EQ("close", res->get_header_value("Connection"));
  5777. EXPECT_FALSE(cli_.is_socket_open());
  5778. }
  5779. TEST_F(ServerTest, PercentEncoding) {
  5780. auto res = cli_.Get("/e%6edwith%");
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. EXPECT_EQ(StatusCode::OK_200, res->status);
  5783. }
  5784. TEST_F(ServerTest, PercentEncodingUnicode) {
  5785. auto res = cli_.Get("/e%u006edwith%");
  5786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5787. EXPECT_EQ(StatusCode::OK_200, res->status);
  5788. }
  5789. TEST_F(ServerTest, InvalidPercentEncoding) {
  5790. auto res = cli_.Get("/%endwith%");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5793. }
  5794. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5795. auto res = cli_.Get("/%uendwith%");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5798. }
  5799. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5800. auto res = cli_.Get("/hello?aaa=bbb%");
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5803. }
  5804. TEST_F(ServerTest, PlusSignEncoding) {
  5805. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. EXPECT_EQ(StatusCode::OK_200, res->status);
  5808. EXPECT_EQ("a +b", res->body);
  5809. }
  5810. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5811. // This test simulates a potential DoS attack using many headers
  5812. // to verify our security fix prevents memory exhaustion
  5813. httplib::Headers attack_headers;
  5814. // Attempt to add many headers like an attacker would (200 headers to far
  5815. // exceed limit)
  5816. for (int i = 0; i < 200; i++) {
  5817. std::string name = "X-Attack-Header-" + std::to_string(i);
  5818. std::string value = "attack_payload_" + std::to_string(i);
  5819. attack_headers.emplace(name, value);
  5820. }
  5821. // Try to POST with excessive headers
  5822. cli_.set_keep_alive(true);
  5823. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5824. // Should either fail or return 400 Bad Request due to security limit
  5825. if (res) {
  5826. // If we get a response, it should be 400 Bad Request
  5827. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5828. EXPECT_EQ("close", res->get_header_value("Connection"));
  5829. }
  5830. EXPECT_FALSE(cli_.is_socket_open());
  5831. }
  5832. TEST_F(ServerTest, MultipartFormData) {
  5833. UploadFormDataItems items = {
  5834. {"text1", "text default", "", ""},
  5835. {"text2", "aωb", "", ""},
  5836. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5837. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5838. {"file3", "", "", "application/octet-stream"},
  5839. {"file4", "", "", " application/json tmp-string "}};
  5840. auto res = cli_.Post("/multipart", items);
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. EXPECT_EQ(StatusCode::OK_200, res->status);
  5843. }
  5844. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5845. UploadFormDataItems items = {
  5846. {"text", "default text", "", ""},
  5847. {"multi_text1", "aaaaa", "", ""},
  5848. {"multi_text1", "bbbbb", "", ""},
  5849. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5850. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5851. "application/json"},
  5852. };
  5853. auto res = cli_.Post("/multipart/multi_file_values", items);
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. }
  5857. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5858. auto res = cli_.Get("/hi");
  5859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5860. EXPECT_EQ(StatusCode::OK_200, res->status);
  5861. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5862. EXPECT_EQ("Hello World!", res->body);
  5863. }
  5864. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5865. Request req;
  5866. req.method = "POST";
  5867. req.path = "/chunked";
  5868. std::string host_and_port;
  5869. host_and_port += HOST;
  5870. host_and_port += ":";
  5871. host_and_port += std::to_string(PORT);
  5872. req.headers.emplace("Host", host_and_port.c_str());
  5873. req.headers.emplace("Accept", "*/*");
  5874. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5875. req.headers.emplace("Content-Type", "text/plain");
  5876. req.headers.emplace("Content-Length", "0");
  5877. req.headers.emplace(
  5878. "Transfer-Encoding",
  5879. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5880. // Client does not chunk, so make a chunked body manually.
  5881. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5882. auto res = std::make_shared<Response>();
  5883. auto error = Error::Success;
  5884. auto ret = cli_.send(req, *res, error);
  5885. ASSERT_TRUE(ret);
  5886. EXPECT_EQ(StatusCode::OK_200, res->status);
  5887. }
  5888. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5889. // rather than treat them as valid lengths.
  5890. template <typename ClientT>
  5891. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5892. Request req;
  5893. req.method = "POST";
  5894. req.path = "/chunked";
  5895. std::string host_and_port;
  5896. host_and_port += HOST;
  5897. host_and_port += ":";
  5898. host_and_port += std::to_string(PORT);
  5899. req.headers.emplace("Host", host_and_port.c_str());
  5900. req.headers.emplace("Content-Length", "0");
  5901. req.headers.emplace("Transfer-Encoding", "chunked");
  5902. req.body = body;
  5903. auto res = std::make_shared<Response>();
  5904. auto error = Error::Success;
  5905. ASSERT_TRUE(cli.send(req, *res, error));
  5906. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5907. }
  5908. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5909. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5910. }
  5911. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5912. expect_chunked_body_rejected(
  5913. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5914. }
  5915. TEST_F(ServerTest, GetStreamed2) {
  5916. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5919. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5920. EXPECT_EQ(true, res->has_header("Content-Range"));
  5921. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5922. EXPECT_EQ(std::string("ab"), res->body);
  5923. }
  5924. TEST_F(ServerTest, GetStreamed) {
  5925. auto res = cli_.Get("/streamed");
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::OK_200, res->status);
  5928. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5929. EXPECT_EQ(std::string("aaabbb"), res->body);
  5930. }
  5931. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5932. auto res = cli_.Get("/streamed-without-length",
  5933. Headers{make_range_header({{0, -1}})});
  5934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. EXPECT_EQ(false, res->has_header("Content-Length"));
  5937. EXPECT_EQ(false, res->has_header("Content-Range"));
  5938. EXPECT_EQ(std::string("abcdefg"), res->body);
  5939. }
  5940. TEST_F(ServerTest, GetStreamedWithRange1) {
  5941. auto res =
  5942. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5945. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5946. EXPECT_EQ(true, res->has_header("Content-Range"));
  5947. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5948. EXPECT_EQ(std::string("def"), res->body);
  5949. }
  5950. TEST_F(ServerTest, GetStreamedWithRange2) {
  5951. auto res =
  5952. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5954. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5955. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5956. EXPECT_EQ(true, res->has_header("Content-Range"));
  5957. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5958. EXPECT_EQ(std::string("bcdefg"), res->body);
  5959. }
  5960. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5961. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5963. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5964. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5965. EXPECT_EQ(true, res->has_header("Content-Range"));
  5966. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5967. EXPECT_EQ(std::string("efg"), res->body);
  5968. }
  5969. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5970. auto res =
  5971. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5974. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5975. EXPECT_EQ(false, res->has_header("Content-Range"));
  5976. EXPECT_EQ(0U, res->body.size());
  5977. }
  5978. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5979. // Only a 206 is served as a partial representation. Under any other status
  5980. // `apply_ranges()` reported the full content length, so the body must match
  5981. // that header, and the content provider must never be asked for an offset
  5982. // outside the representation.
  5983. auto check = [&](int status, const char *range) {
  5984. auto path =
  5985. std::string("/streamed-with-range?status=") + std::to_string(status);
  5986. auto ctx = path + " Range: " + range;
  5987. auto res = cli_.Get(path, Headers{{"Range", range}});
  5988. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5989. EXPECT_EQ(status, res->status) << ctx;
  5990. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5992. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5993. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5994. };
  5995. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5996. check(403, "bytes=3-5");
  5997. // The offset is far past the representation.
  5998. check(403, "bytes=100000-100200");
  5999. // `first_pos` is still -1 here, and the bounds asserts in
  6000. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6001. check(403, "bytes=-3");
  6002. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6003. // multipart branch would have written one that is empty.
  6004. check(403, "bytes=1-2, 4-5");
  6005. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6006. // covers the whole representation.
  6007. check(200, "bytes=3-5");
  6008. check(200, "bytes=1-2, 4-5");
  6009. }
  6010. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6011. auto res =
  6012. cli_.Get("/streamed-with-range",
  6013. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6014. "92233720368547758079223372036854775807"}});
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6017. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6018. EXPECT_EQ(false, res->has_header("Content-Range"));
  6019. EXPECT_EQ(0U, res->body.size());
  6020. }
  6021. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6022. auto res = cli_.Get(
  6023. "/with-range",
  6024. Headers{{"Range",
  6025. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6026. {"Accept-Encoding", ""}});
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6029. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6030. EXPECT_EQ(true, res->has_header("Content-Range"));
  6031. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6032. EXPECT_EQ(std::string("abcdefg"), res->body);
  6033. }
  6034. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6035. auto res = cli_.Get("/with-range", Headers{
  6036. {"Range", "bytes=0-"},
  6037. {"Accept-Encoding", ""},
  6038. });
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6041. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6042. EXPECT_EQ(true, res->has_header("Content-Range"));
  6043. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6044. EXPECT_EQ(std::string("abcdefg"), res->body);
  6045. }
  6046. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6047. auto res = cli_.Get("/streamed-with-range",
  6048. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6050. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6051. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6052. EXPECT_EQ(false, res->has_header("Content-Range"));
  6053. EXPECT_EQ(267U, res->body.size());
  6054. // Check that both range contents are present
  6055. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6056. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6057. // Check that Content-Range headers are present for both ranges
  6058. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6059. std::string::npos);
  6060. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6061. std::string::npos);
  6062. }
  6063. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6064. Ranges ranges;
  6065. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6066. ranges.emplace_back(0, -1);
  6067. }
  6068. auto res = cli_.Get("/streamed-with-range?error",
  6069. Headers{{make_range_header(ranges)}});
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6072. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6073. EXPECT_EQ(false, res->has_header("Content-Range"));
  6074. EXPECT_EQ(0U, res->body.size());
  6075. }
  6076. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6077. auto res = cli_.Get("/streamed-with-range",
  6078. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6081. EXPECT_EQ(5U, res->body.size());
  6082. // Check that overlapping ranges are coalesced into a single range
  6083. EXPECT_EQ("bcdef", res->body);
  6084. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6085. // Should be single range, not multipart
  6086. EXPECT_TRUE(res->has_header("Content-Range"));
  6087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6088. }
  6089. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6090. auto res = cli_.Get("/streamed-with-range",
  6091. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6094. EXPECT_EQ(268U, res->body.size());
  6095. // Check that both range contents are present
  6096. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6097. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6098. // Check that Content-Range headers are present for both ranges
  6099. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6100. std::string::npos);
  6101. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6102. std::string::npos);
  6103. }
  6104. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6105. auto res = cli_.Get("/streamed-with-range",
  6106. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6109. EXPECT_EQ(269U, res->body.size());
  6110. // Check that both duplicate range contents are present
  6111. size_t first_abc = res->body.find("abc\r\n");
  6112. EXPECT_TRUE(first_abc != std::string::npos);
  6113. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6114. EXPECT_TRUE(second_abc != std::string::npos);
  6115. // Check that Content-Range headers are present for both ranges
  6116. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6117. EXPECT_TRUE(first_range != std::string::npos);
  6118. size_t second_range =
  6119. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6120. EXPECT_TRUE(second_range != std::string::npos);
  6121. }
  6122. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6123. auto res =
  6124. cli_.Get("/streamed-with-range?error",
  6125. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6128. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6129. EXPECT_EQ(false, res->has_header("Content-Range"));
  6130. EXPECT_EQ(0U, res->body.size());
  6131. }
  6132. TEST_F(ServerTest, GetStreamedEndless) {
  6133. uint64_t offset = 0;
  6134. auto res = cli_.Get("/streamed-cancel",
  6135. [&](const char * /*data*/, uint64_t data_length) {
  6136. if (offset < 100) {
  6137. offset += data_length;
  6138. return true;
  6139. }
  6140. return false;
  6141. });
  6142. ASSERT_TRUE(!res);
  6143. EXPECT_EQ(Error::Canceled, res.error());
  6144. }
  6145. TEST_F(ServerTest, ClientStop) {
  6146. std::atomic_size_t count{4};
  6147. std::vector<std::thread> threads;
  6148. for (auto i = count.load(); i != 0; --i) {
  6149. threads.emplace_back([&]() {
  6150. auto res = cli_.Get("/streamed-cancel",
  6151. [&](const char *, uint64_t) { return true; });
  6152. --count;
  6153. ASSERT_TRUE(!res);
  6154. EXPECT_TRUE(res.error() == Error::Canceled ||
  6155. res.error() == Error::Read || res.error() == Error::Write);
  6156. });
  6157. }
  6158. std::this_thread::sleep_for(std::chrono::seconds(2));
  6159. while (count != 0) {
  6160. cli_.stop();
  6161. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6162. }
  6163. for (auto &t : threads) {
  6164. t.join();
  6165. }
  6166. }
  6167. TEST_F(ServerTest, GetWithRange1) {
  6168. auto res = cli_.Get("/with-range", Headers{
  6169. make_range_header({{3, 5}}),
  6170. {"Accept-Encoding", ""},
  6171. });
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6174. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6175. EXPECT_EQ(true, res->has_header("Content-Range"));
  6176. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6177. EXPECT_EQ(std::string("def"), res->body);
  6178. }
  6179. TEST_F(ServerTest, GetWithRange2) {
  6180. auto res = cli_.Get("/with-range", Headers{
  6181. make_range_header({{1, -1}}),
  6182. {"Accept-Encoding", ""},
  6183. });
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6186. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6187. EXPECT_EQ(true, res->has_header("Content-Range"));
  6188. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6189. EXPECT_EQ(std::string("bcdefg"), res->body);
  6190. }
  6191. TEST_F(ServerTest, GetWithRange3) {
  6192. auto res = cli_.Get("/with-range", Headers{
  6193. make_range_header({{0, 0}}),
  6194. {"Accept-Encoding", ""},
  6195. });
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6198. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6199. EXPECT_EQ(true, res->has_header("Content-Range"));
  6200. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6201. EXPECT_EQ(std::string("a"), res->body);
  6202. }
  6203. TEST_F(ServerTest, GetWithRange4) {
  6204. auto res = cli_.Get("/with-range", Headers{
  6205. make_range_header({{-1, 2}}),
  6206. {"Accept-Encoding", ""},
  6207. });
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6210. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6211. EXPECT_EQ(true, res->has_header("Content-Range"));
  6212. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6213. EXPECT_EQ(std::string("fg"), res->body);
  6214. }
  6215. TEST_F(ServerTest, GetWithRange5) {
  6216. auto res = cli_.Get("/with-range", Headers{
  6217. make_range_header({{0, 5}}),
  6218. {"Accept-Encoding", ""},
  6219. });
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6222. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6223. EXPECT_EQ(true, res->has_header("Content-Range"));
  6224. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6225. EXPECT_EQ(std::string("abcdef"), res->body);
  6226. }
  6227. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6228. auto res =
  6229. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6232. }
  6233. TEST_F(ServerTest, GetWithRangeMultipart) {
  6234. auto res =
  6235. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6238. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6239. EXPECT_EQ(false, res->has_header("Content-Range"));
  6240. EXPECT_EQ(267U, res->body.size());
  6241. }
  6242. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6243. auto res = cli_.Get("/with-range",
  6244. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6247. }
  6248. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6249. auto res = cli_.Get("/with-range-customized-response",
  6250. Headers{{make_range_header({{1, 2}})}});
  6251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6253. EXPECT_EQ(true, res->has_header("Content-Length"));
  6254. EXPECT_EQ(false, res->has_header("Content-Range"));
  6255. EXPECT_EQ(JSON_DATA, res->body);
  6256. }
  6257. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6258. auto res = cli_.Get("/with-range-customized-response",
  6259. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6262. EXPECT_EQ(true, res->has_header("Content-Length"));
  6263. EXPECT_EQ(false, res->has_header("Content-Range"));
  6264. EXPECT_EQ(JSON_DATA, res->body);
  6265. }
  6266. TEST_F(ServerTest, Issue1772) {
  6267. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6270. }
  6271. TEST_F(ServerTest, Issue609) {
  6272. auto res = cli_.Delete("/issue609");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. EXPECT_EQ(std::string("ok"), res->body);
  6276. }
  6277. TEST_F(ServerTest, GetStreamedChunked) {
  6278. auto res = cli_.Get("/streamed-chunked");
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. EXPECT_EQ(std::string("123456789"), res->body);
  6282. }
  6283. TEST_F(ServerTest, GetStreamedChunked2) {
  6284. auto res = cli_.Get("/streamed-chunked2");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. EXPECT_EQ(std::string("123456789"), res->body);
  6288. }
  6289. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6290. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::OK_200, res->status);
  6293. EXPECT_EQ(std::string("123456789"), res->body);
  6294. EXPECT_TRUE(res->has_header("Trailer"));
  6295. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6296. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6297. // Trailers are now stored separately from headers (security fix)
  6298. EXPECT_EQ(2U, res->trailers.size());
  6299. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6300. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6301. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6302. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6303. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6304. // Verify trailers are NOT in headers (security verification)
  6305. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6306. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6307. }
  6308. TEST_F(ServerTest, LargeChunkedPost) {
  6309. Request req;
  6310. req.method = "POST";
  6311. req.path = "/large-chunked";
  6312. std::string host_and_port;
  6313. host_and_port += HOST;
  6314. host_and_port += ":";
  6315. host_and_port += std::to_string(PORT);
  6316. req.headers.emplace("Host", host_and_port.c_str());
  6317. req.headers.emplace("Accept", "*/*");
  6318. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6319. req.headers.emplace("Content-Type", "text/plain");
  6320. req.headers.emplace("Content-Length", "0");
  6321. req.headers.emplace("Transfer-Encoding", "chunked");
  6322. std::string long_string(30 * 1024u, 'a');
  6323. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6324. // Attempt to make a large enough post to exceed OS buffers, to test that
  6325. // the server handles short reads if the full chunk data isn't available.
  6326. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6327. auto res = std::make_shared<Response>();
  6328. auto error = Error::Success;
  6329. auto ret = cli_.send(req, *res, error);
  6330. ASSERT_TRUE(ret);
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6334. auto res = cli_.Get("/remote_addr");
  6335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6336. EXPECT_EQ(StatusCode::OK_200, res->status);
  6337. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6338. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6339. }
  6340. TEST_F(ServerTest, GetMethodLocalAddr) {
  6341. auto res = cli_.Get("/local_addr");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6345. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6346. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6347. }
  6348. TEST_F(ServerTest, HTTPResponseSplitting) {
  6349. auto res = cli_.Get("/http_response_splitting");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. }
  6353. TEST_F(ServerTest, SlowRequest) {
  6354. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6355. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6356. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6357. }
  6358. #if 0
  6359. TEST_F(ServerTest, SlowPost) {
  6360. char buffer[64 * 1024];
  6361. memset(buffer, 0x42, sizeof(buffer));
  6362. auto res = cli_.Post(
  6363. "/slowpost", 64 * 1024 * 1024,
  6364. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6365. auto ret = sink.write(buffer, sizeof(buffer));
  6366. EXPECT_TRUE(ret);
  6367. return true;
  6368. },
  6369. "text/plain");
  6370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6371. EXPECT_EQ(StatusCode::OK_200, res->status);
  6372. }
  6373. TEST_F(ServerTest, SlowPostFail) {
  6374. char buffer[64 * 1024];
  6375. memset(buffer, 0x42, sizeof(buffer));
  6376. cli_.set_write_timeout(std::chrono::seconds(0));
  6377. auto res = cli_.Post(
  6378. "/slowpost", 64 * 1024 * 1024,
  6379. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6380. sink.write(buffer, sizeof(buffer));
  6381. return true;
  6382. },
  6383. "text/plain");
  6384. ASSERT_TRUE(!res);
  6385. EXPECT_EQ(Error::Write, res.error());
  6386. }
  6387. #endif
  6388. TEST_F(ServerTest, Put) {
  6389. auto res = cli_.Put("/put", "PUT", "text/plain");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("PUT", res->body);
  6393. }
  6394. TEST_F(ServerTest, PutWithContentProvider) {
  6395. auto res = cli_.Put(
  6396. "/put", 3,
  6397. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6398. sink.os << "PUT";
  6399. return true;
  6400. },
  6401. "text/plain");
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. EXPECT_EQ("PUT", res->body);
  6405. }
  6406. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6407. auto res = cli_.Post(
  6408. "/post", 42,
  6409. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6410. return false;
  6411. },
  6412. "text/plain");
  6413. ASSERT_TRUE(!res);
  6414. EXPECT_EQ(Error::Canceled, res.error());
  6415. }
  6416. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6417. auto res = cli_.Put(
  6418. "/put",
  6419. [](size_t /*offset*/, DataSink &sink) {
  6420. sink.os << "PUT";
  6421. sink.done();
  6422. return true;
  6423. },
  6424. "text/plain");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("PUT", res->body);
  6428. }
  6429. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6430. auto res = cli_.Post(
  6431. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6432. "text/plain");
  6433. ASSERT_TRUE(!res);
  6434. EXPECT_EQ(Error::Canceled, res.error());
  6435. }
  6436. TEST_F(ServerTest, PostLoopBack) {
  6437. std::string body;
  6438. auto res = cli_.Post(
  6439. "/post-loopback", 9,
  6440. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6441. EXPECT_EQ(9u, length);
  6442. sink.write("123", 3);
  6443. sink.write("456", 3);
  6444. sink.write("789", 3);
  6445. return true;
  6446. },
  6447. "text/plain",
  6448. [&body](const char *data, size_t data_length) {
  6449. body.append(data, data_length);
  6450. return true;
  6451. });
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::OK_200, res->status);
  6454. EXPECT_EQ("123456789", body);
  6455. }
  6456. TEST_F(ServerTest, PutLoopBack) {
  6457. std::string body;
  6458. auto res = cli_.Put(
  6459. "/put-loopback", 9,
  6460. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6461. EXPECT_EQ(9u, length);
  6462. sink.write("123", 3);
  6463. sink.write("456", 3);
  6464. sink.write("789", 3);
  6465. return true;
  6466. },
  6467. "text/plain",
  6468. [&body](const char *data, size_t data_length) {
  6469. body.append(data, data_length);
  6470. return true;
  6471. });
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("123456789", body);
  6475. }
  6476. TEST_F(ServerTest, PatchLoopBack) {
  6477. std::string body;
  6478. auto res = cli_.Patch(
  6479. "/patch-loopback", 9,
  6480. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6481. EXPECT_EQ(9u, length);
  6482. sink.write("123", 3);
  6483. sink.write("456", 3);
  6484. sink.write("789", 3);
  6485. return true;
  6486. },
  6487. "text/plain",
  6488. [&body](const char *data, size_t data_length) {
  6489. body.append(data, data_length);
  6490. return true;
  6491. });
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. EXPECT_EQ(StatusCode::OK_200, res->status);
  6494. EXPECT_EQ("123456789", body);
  6495. }
  6496. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6497. std::string body;
  6498. auto res = cli_.Post(
  6499. "/post-loopback",
  6500. [](size_t /*offset*/, DataSink &sink) {
  6501. sink.write("123", 3);
  6502. sink.write("456", 3);
  6503. sink.write("789", 3);
  6504. sink.done();
  6505. return true;
  6506. },
  6507. "text/plain",
  6508. [&body](const char *data, size_t data_length) {
  6509. body.append(data, data_length);
  6510. return true;
  6511. });
  6512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. EXPECT_EQ("123456789", body);
  6515. }
  6516. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6517. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6518. cli_.set_compress(true);
  6519. auto res = cli_.Put(
  6520. "/put", 3,
  6521. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6522. sink.os << "PUT";
  6523. return true;
  6524. },
  6525. "text/plain");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(StatusCode::OK_200, res->status);
  6528. EXPECT_EQ("PUT", res->body);
  6529. }
  6530. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6531. cli_.set_compress(true);
  6532. auto res = cli_.Post(
  6533. "/post", 42,
  6534. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6535. return false;
  6536. },
  6537. "text/plain");
  6538. ASSERT_TRUE(!res);
  6539. EXPECT_EQ(Error::Canceled, res.error());
  6540. }
  6541. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6542. cli_.set_compress(true);
  6543. auto res = cli_.Put(
  6544. "/put",
  6545. [](size_t /*offset*/, DataSink &sink) {
  6546. sink.os << "PUT";
  6547. sink.done();
  6548. return true;
  6549. },
  6550. "text/plain");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. EXPECT_EQ("PUT", res->body);
  6554. }
  6555. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6556. cli_.set_compress(true);
  6557. auto res = cli_.Post(
  6558. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6559. "text/plain");
  6560. ASSERT_TRUE(!res);
  6561. EXPECT_EQ(Error::Canceled, res.error());
  6562. }
  6563. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6564. cli_.set_compress(true);
  6565. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ(StatusCode::OK_200, res->status);
  6568. EXPECT_EQ(LARGE_DATA, res->body);
  6569. }
  6570. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6571. #ifdef CPPHTTPLIB_SSL_ENABLED
  6572. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6573. Client cli(s.c_str());
  6574. cli.enable_server_certificate_verification(false);
  6575. #else
  6576. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6577. Client cli(s.c_str());
  6578. #endif
  6579. cli.set_compress(true);
  6580. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ(StatusCode::OK_200, res->status);
  6583. EXPECT_EQ(LARGE_DATA, res->body);
  6584. // The compressed size should be less than a 10th of the original. May vary
  6585. // depending on the zlib library.
  6586. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6587. static_cast<uint64_t>(10 * 1024 * 1024));
  6588. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6589. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6590. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6591. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6592. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6593. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6594. #endif
  6595. }
  6596. TEST_F(ServerTest, PutContentWithDeflate) {
  6597. cli_.set_compress(false);
  6598. Headers headers;
  6599. headers.emplace("Content-Encoding", "deflate");
  6600. // PUT in deflate format:
  6601. auto res = cli_.Put("/put", headers,
  6602. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. EXPECT_EQ("PUT", res->body);
  6606. }
  6607. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6608. Headers headers;
  6609. headers.emplace("Accept-Encoding", "gzip, deflate");
  6610. auto res = cli_.Get("/streamed-chunked", headers);
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. EXPECT_EQ(StatusCode::OK_200, res->status);
  6613. EXPECT_EQ(std::string("123456789"), res->body);
  6614. }
  6615. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6616. Headers headers;
  6617. headers.emplace("Accept-Encoding", "gzip, deflate");
  6618. auto res = cli_.Get("/streamed-chunked2", headers);
  6619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. EXPECT_EQ(std::string("123456789"), res->body);
  6622. }
  6623. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6624. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6626. EXPECT_EQ(StatusCode::OK_200, res->status);
  6627. }
  6628. TEST(GzipDecompressor, ChunkedDecompression) {
  6629. std::string data;
  6630. for (size_t i = 0; i < 32 * 1024; ++i) {
  6631. data.push_back(static_cast<char>('a' + i % 26));
  6632. }
  6633. std::string compressed_data;
  6634. {
  6635. httplib::detail::gzip_compressor compressor;
  6636. bool result = compressor.compress(
  6637. data.data(), data.size(),
  6638. /*last=*/true,
  6639. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6640. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6641. compressed_data_size);
  6642. return true;
  6643. });
  6644. ASSERT_TRUE(result);
  6645. }
  6646. std::string decompressed_data;
  6647. {
  6648. httplib::detail::gzip_decompressor decompressor;
  6649. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6650. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6651. size_t chunk_size = 130;
  6652. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6653. chunk_begin += chunk_size) {
  6654. size_t current_chunk_size =
  6655. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6656. bool result = decompressor.decompress(
  6657. compressed_data.data() + chunk_begin, current_chunk_size,
  6658. [&](const char *decompressed_data_chunk,
  6659. size_t decompressed_data_chunk_size) {
  6660. decompressed_data.insert(decompressed_data.size(),
  6661. decompressed_data_chunk,
  6662. decompressed_data_chunk_size);
  6663. return true;
  6664. });
  6665. ASSERT_TRUE(result);
  6666. }
  6667. }
  6668. ASSERT_EQ(data, decompressed_data);
  6669. }
  6670. TEST(GzipDecompressor, DeflateDecompression) {
  6671. std::string original_text = "Raw deflate without gzip";
  6672. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6673. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6674. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6675. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6676. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6677. std::string decompressed_data;
  6678. {
  6679. httplib::detail::gzip_decompressor decompressor;
  6680. bool result = decompressor.decompress(
  6681. compressed_data.data(), compressed_data.size(),
  6682. [&](const char *decompressed_data_chunk,
  6683. size_t decompressed_data_chunk_size) {
  6684. decompressed_data.insert(decompressed_data.size(),
  6685. decompressed_data_chunk,
  6686. decompressed_data_chunk_size);
  6687. return true;
  6688. });
  6689. ASSERT_TRUE(result);
  6690. }
  6691. ASSERT_EQ(original_text, decompressed_data);
  6692. }
  6693. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6694. std::string original_text = "Raw deflate without gzip";
  6695. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6696. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6697. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6698. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6699. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6700. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6701. std::string decompressed_data;
  6702. {
  6703. httplib::detail::gzip_decompressor decompressor;
  6704. bool result = decompressor.decompress(
  6705. compressed_data.data(), compressed_data.size(),
  6706. [&](const char *decompressed_data_chunk,
  6707. size_t decompressed_data_chunk_size) {
  6708. decompressed_data.insert(decompressed_data.size(),
  6709. decompressed_data_chunk,
  6710. decompressed_data_chunk_size);
  6711. return true;
  6712. });
  6713. ASSERT_TRUE(result);
  6714. }
  6715. ASSERT_EQ(original_text, decompressed_data);
  6716. }
  6717. #endif
  6718. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6719. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6720. Headers headers;
  6721. headers.emplace("Accept-Encoding", "br");
  6722. auto res = cli_.Get("/streamed-chunked", headers);
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. EXPECT_EQ(std::string("123456789"), res->body);
  6726. }
  6727. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6728. Headers headers;
  6729. headers.emplace("Accept-Encoding", "br");
  6730. auto res = cli_.Get("/streamed-chunked2", headers);
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::OK_200, res->status);
  6733. EXPECT_EQ(std::string("123456789"), res->body);
  6734. }
  6735. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6736. cli_.set_compress(true);
  6737. auto res = cli_.Put(
  6738. "/put", 3,
  6739. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6740. sink.os << "PUT";
  6741. return true;
  6742. },
  6743. "text/plain");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. EXPECT_EQ("PUT", res->body);
  6747. }
  6748. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6749. cli_.set_compress(true);
  6750. auto res = cli_.Put(
  6751. "/put",
  6752. [](size_t /*offset*/, DataSink &sink) {
  6753. sink.os << "PUT";
  6754. sink.done();
  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, PutLargeFileWithBrotli) {
  6763. cli_.set_compress(true);
  6764. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ(LARGE_DATA, res->body);
  6768. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6769. }
  6770. #endif
  6771. TEST_F(ServerTest, Patch) {
  6772. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. EXPECT_EQ("PATCH", res->body);
  6776. }
  6777. TEST_F(ServerTest, Delete) {
  6778. auto res = cli_.Delete("/delete");
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ("DELETE", res->body);
  6782. }
  6783. TEST_F(ServerTest, DeleteContentReceiver) {
  6784. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6786. EXPECT_EQ(StatusCode::OK_200, res->status);
  6787. EXPECT_EQ("content", res->body);
  6788. }
  6789. TEST_F(ServerTest, Options) {
  6790. auto res = cli_.Options("*");
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6794. EXPECT_TRUE(res->body.empty());
  6795. }
  6796. TEST_F(ServerTest, URL) {
  6797. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. EXPECT_EQ(StatusCode::OK_200, res->status);
  6800. }
  6801. TEST_F(ServerTest, ArrayParam) {
  6802. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::OK_200, res->status);
  6805. }
  6806. TEST_F(ServerTest, ArrayParamValues) {
  6807. auto res =
  6808. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(StatusCode::OK_200, res->status);
  6811. }
  6812. TEST_F(ServerTest, NoMultipleHeaders) {
  6813. Headers headers = {{"Content-Length", "5"}};
  6814. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6815. "text/plain");
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. }
  6819. TEST_F(ServerTest, PostContentReceiver) {
  6820. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. ASSERT_EQ(StatusCode::OK_200, res->status);
  6823. ASSERT_EQ("content", res->body);
  6824. }
  6825. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6826. UploadFormDataItems items = {
  6827. {"text1", "text default", "", ""},
  6828. {"text2", "aωb", "", ""},
  6829. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6830. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6831. {"file3", "", "", "application/octet-stream"},
  6832. };
  6833. auto res = cli_.Post("/content_receiver", items);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. }
  6837. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6838. UploadFormDataItems items = {
  6839. {"text1", "text default", "", ""},
  6840. {"text2", "aωb", "", ""},
  6841. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6842. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6843. {"file3", "", "", "application/octet-stream"},
  6844. };
  6845. auto boundary = std::string("+++++");
  6846. std::string body;
  6847. for (const auto &item : items) {
  6848. body += "--" + boundary + "\r\n";
  6849. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6850. if (!item.filename.empty()) {
  6851. body += "; filename=\"" + item.filename + "\"";
  6852. }
  6853. body += "\r\n";
  6854. if (!item.content_type.empty()) {
  6855. body += "Content-Type: " + item.content_type + "\r\n";
  6856. }
  6857. body += "\r\n";
  6858. body += item.content + "\r\n";
  6859. }
  6860. body += "--" + boundary + "--\r\n";
  6861. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6862. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6864. EXPECT_EQ(StatusCode::OK_200, res->status);
  6865. }
  6866. TEST(MultipartFormDataTest, FieldEscaping) {
  6867. Server svr;
  6868. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6869. const ContentReader &content_reader) {
  6870. ASSERT_TRUE(req.is_multipart_form_data());
  6871. std::vector<FormData> received;
  6872. content_reader(
  6873. [&](const FormData &file) {
  6874. received.push_back(file);
  6875. return true;
  6876. },
  6877. [&](const char *data, size_t data_length) {
  6878. received.back().content.append(data, data_length);
  6879. return true;
  6880. });
  6881. // '"', CR and LF in names and filenames are escaped following the
  6882. // WHATWG HTML standard, so each part still parses as a single part
  6883. // with no injected headers. Content types get CR/LF escaped too,
  6884. // while '"' (legal there, e.g. quoted charset) is preserved.
  6885. ASSERT_EQ(4U, received.size());
  6886. EXPECT_EQ("na%22me", received[0].name);
  6887. EXPECT_EQ("quoted name", received[0].content);
  6888. EXPECT_EQ("file", received[1].name);
  6889. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6890. received[1].filename);
  6891. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6892. EXPECT_EQ("injected", received[1].content);
  6893. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6894. EXPECT_EQ("my%22file.txt", received[2].filename);
  6895. EXPECT_EQ("cr lf name", received[2].content);
  6896. EXPECT_EQ("typed", received[3].name);
  6897. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6898. received[3].content_type);
  6899. EXPECT_EQ("typed content", received[3].content);
  6900. });
  6901. auto port = svr.bind_to_any_port("localhost");
  6902. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6903. auto se = detail::scope_exit([&] {
  6904. svr.stop();
  6905. t.join();
  6906. ASSERT_FALSE(svr.is_running());
  6907. });
  6908. svr.wait_until_ready();
  6909. Client cli("localhost", port);
  6910. UploadFormDataItems items = {
  6911. {"na\"me", "quoted name", "", ""},
  6912. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6913. "application/octet-stream"},
  6914. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6915. {"typed", "typed content", "",
  6916. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6917. };
  6918. auto res = cli.Post("/post", items);
  6919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6920. EXPECT_EQ(StatusCode::OK_200, res->status);
  6921. }
  6922. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6923. const UploadFormDataItems items = {
  6924. {"name1", "Content 1", "", ""},
  6925. {"name2", "Content 2", "file2.txt", "text/plain"},
  6926. };
  6927. Server svr;
  6928. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6929. const ContentReader &content_reader) {
  6930. ASSERT_TRUE(req.is_multipart_form_data());
  6931. std::vector<FormData> received;
  6932. content_reader(
  6933. [&](const FormData &file) {
  6934. received.push_back(file);
  6935. return true;
  6936. },
  6937. [&](const char *data, size_t data_length) {
  6938. received.back().content.append(data, data_length);
  6939. return true;
  6940. });
  6941. ASSERT_EQ(2U, received.size());
  6942. EXPECT_EQ("name1", received[0].name);
  6943. EXPECT_EQ("Content 1", received[0].content);
  6944. EXPECT_EQ("name2", received[1].name);
  6945. EXPECT_EQ("Content 2", received[1].content);
  6946. EXPECT_EQ("file2.txt", received[1].filename);
  6947. EXPECT_EQ("text/plain", received[1].content_type);
  6948. });
  6949. auto port = svr.bind_to_any_port("localhost");
  6950. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6951. auto se = detail::scope_exit([&] {
  6952. svr.stop();
  6953. t.join();
  6954. ASSERT_FALSE(svr.is_running());
  6955. });
  6956. svr.wait_until_ready();
  6957. Client cli("localhost", port);
  6958. // Whole-body serialization with a generated boundary
  6959. {
  6960. MultipartFormDataWriter writer;
  6961. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6962. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6963. writer.content_type());
  6964. auto body = writer.serialize(items);
  6965. EXPECT_EQ(body.size(), writer.content_length(items));
  6966. auto res = cli.Post("/post", body, writer.content_type());
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::OK_200, res->status);
  6969. }
  6970. // Per-part framing with a custom boundary via a content provider
  6971. {
  6972. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6973. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6974. MultipartFormDataWriter writer("custom-boundary_123");
  6975. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6976. std::string body;
  6977. for (const auto &item : items) {
  6978. body += writer.item_begin(item);
  6979. body += item.content;
  6980. body += MultipartFormDataWriter::item_end();
  6981. }
  6982. body += writer.finish();
  6983. EXPECT_EQ(body.size(), writer.content_length(items));
  6984. auto res = cli.Post(
  6985. "/post", body.size(),
  6986. [&](size_t offset, size_t length, DataSink &sink) {
  6987. sink.write(body.data() + offset, length);
  6988. return true;
  6989. },
  6990. writer.content_type());
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. }
  6994. }
  6995. TEST_F(ServerTest, PostContentReceiverGzip) {
  6996. cli_.set_compress(true);
  6997. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. ASSERT_EQ(StatusCode::OK_200, res->status);
  7000. ASSERT_EQ("content", res->body);
  7001. }
  7002. TEST_F(ServerTest, PutContentReceiver) {
  7003. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. ASSERT_EQ(StatusCode::OK_200, res->status);
  7006. ASSERT_EQ("content", res->body);
  7007. }
  7008. TEST_F(ServerTest, PatchContentReceiver) {
  7009. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. ASSERT_EQ(StatusCode::OK_200, res->status);
  7012. ASSERT_EQ("content", res->body);
  7013. }
  7014. template <typename ClientType>
  7015. void TestWithHeadersAndContentReceiver(
  7016. ClientType &cli,
  7017. std::function<Result(ClientType &, const std::string &, const Headers &,
  7018. const std::string &, const std::string &,
  7019. ContentReceiver, DownloadProgress)>
  7020. request_func) {
  7021. Headers headers;
  7022. headers.emplace("X-Custom-Header", "test-value");
  7023. std::string received_body;
  7024. auto res = request_func(
  7025. cli, "/content_receiver", headers, "content", "application/json",
  7026. [&](const char *data, size_t data_length) {
  7027. received_body.append(data, data_length);
  7028. return true;
  7029. },
  7030. nullptr);
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. EXPECT_EQ("content", received_body);
  7034. }
  7035. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7036. #ifdef CPPHTTPLIB_SSL_ENABLED
  7037. using ClientT = SSLClient;
  7038. #else
  7039. using ClientT = Client;
  7040. #endif
  7041. TestWithHeadersAndContentReceiver<ClientT>(
  7042. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7043. const std::string &body, const std::string &content_type,
  7044. ContentReceiver receiver, DownloadProgress progress) {
  7045. return cli.Post(path, headers, body, content_type, receiver, progress);
  7046. });
  7047. }
  7048. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7049. #ifdef CPPHTTPLIB_SSL_ENABLED
  7050. using ClientT = SSLClient;
  7051. #else
  7052. using ClientT = Client;
  7053. #endif
  7054. TestWithHeadersAndContentReceiver<ClientT>(
  7055. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7056. const std::string &body, const std::string &content_type,
  7057. ContentReceiver receiver, DownloadProgress progress) {
  7058. return cli.Put(path, headers, body, content_type, receiver, progress);
  7059. });
  7060. }
  7061. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7062. #ifdef CPPHTTPLIB_SSL_ENABLED
  7063. using ClientT = SSLClient;
  7064. #else
  7065. using ClientT = Client;
  7066. #endif
  7067. TestWithHeadersAndContentReceiver<ClientT>(
  7068. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7069. const std::string &body, const std::string &content_type,
  7070. ContentReceiver receiver, DownloadProgress progress) {
  7071. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7072. });
  7073. }
  7074. template <typename ClientType>
  7075. void TestWithHeadersAndContentReceiverWithProgress(
  7076. ClientType &cli,
  7077. std::function<Result(ClientType &, const std::string &, const Headers &,
  7078. const std::string &, const std::string &,
  7079. ContentReceiver, DownloadProgress)>
  7080. request_func) {
  7081. Headers headers;
  7082. headers.emplace("X-Test-Header", "progress-test");
  7083. std::string received_body;
  7084. auto progress_called = false;
  7085. auto res = request_func(
  7086. cli, "/content_receiver", headers, "content", "text/plain",
  7087. [&](const char *data, size_t data_length) {
  7088. received_body.append(data, data_length);
  7089. return true;
  7090. },
  7091. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7092. progress_called = true;
  7093. return true;
  7094. });
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. EXPECT_EQ("content", received_body);
  7098. EXPECT_TRUE(progress_called);
  7099. }
  7100. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7101. #ifdef CPPHTTPLIB_SSL_ENABLED
  7102. using ClientT = SSLClient;
  7103. #else
  7104. using ClientT = Client;
  7105. #endif
  7106. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7107. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7108. const std::string &body, const std::string &content_type,
  7109. ContentReceiver receiver, DownloadProgress progress) {
  7110. return cli.Post(path, headers, body, content_type, receiver, progress);
  7111. });
  7112. }
  7113. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7114. #ifdef CPPHTTPLIB_SSL_ENABLED
  7115. using ClientT = SSLClient;
  7116. #else
  7117. using ClientT = Client;
  7118. #endif
  7119. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7120. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7121. const std::string &body, const std::string &content_type,
  7122. ContentReceiver receiver, DownloadProgress progress) {
  7123. return cli.Put(path, headers, body, content_type, receiver, progress);
  7124. });
  7125. }
  7126. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7127. #ifdef CPPHTTPLIB_SSL_ENABLED
  7128. using ClientT = SSLClient;
  7129. #else
  7130. using ClientT = Client;
  7131. #endif
  7132. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7133. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7134. const std::string &body, const std::string &content_type,
  7135. ContentReceiver receiver, DownloadProgress progress) {
  7136. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7137. });
  7138. }
  7139. template <typename ClientType>
  7140. void TestWithHeadersAndContentReceiverError(
  7141. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7142. const Headers &, const std::string &,
  7143. const std::string &, ContentReceiver)>
  7144. request_func) {
  7145. Headers headers;
  7146. headers.emplace("X-Error-Test", "true");
  7147. std::string received_body;
  7148. auto receiver_failed = false;
  7149. auto res =
  7150. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7151. [&](const char *data, size_t data_length) {
  7152. received_body.append(data, data_length);
  7153. receiver_failed = true;
  7154. return false;
  7155. });
  7156. ASSERT_FALSE(res);
  7157. EXPECT_TRUE(receiver_failed);
  7158. }
  7159. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7160. #ifdef CPPHTTPLIB_SSL_ENABLED
  7161. using ClientT = SSLClient;
  7162. #else
  7163. using ClientT = Client;
  7164. #endif
  7165. TestWithHeadersAndContentReceiverError<ClientT>(
  7166. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7167. const std::string &body, const std::string &content_type,
  7168. ContentReceiver receiver) {
  7169. return cli.Post(path, headers, body, content_type, receiver);
  7170. });
  7171. }
  7172. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7173. #ifdef CPPHTTPLIB_SSL_ENABLED
  7174. using ClientT = SSLClient;
  7175. #else
  7176. using ClientT = Client;
  7177. #endif
  7178. TestWithHeadersAndContentReceiverError<ClientT>(
  7179. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7180. const std::string &body, const std::string &content_type,
  7181. ContentReceiver receiver) {
  7182. return cli.Put(path, headers, body, content_type, receiver);
  7183. });
  7184. }
  7185. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7186. #ifdef CPPHTTPLIB_SSL_ENABLED
  7187. using ClientT = SSLClient;
  7188. #else
  7189. using ClientT = Client;
  7190. #endif
  7191. TestWithHeadersAndContentReceiverError<ClientT>(
  7192. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7193. const std::string &body, const std::string &content_type,
  7194. ContentReceiver receiver) {
  7195. return cli.Patch(path, headers, body, content_type, receiver);
  7196. });
  7197. }
  7198. TEST_F(ServerTest, PostQueryStringAndBody) {
  7199. auto res =
  7200. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. ASSERT_EQ(StatusCode::OK_200, res->status);
  7203. }
  7204. TEST_F(ServerTest, HTTP2Magic) {
  7205. Request req;
  7206. req.method = "PRI";
  7207. req.path = "*";
  7208. req.body = "SM";
  7209. auto res = std::make_shared<Response>();
  7210. auto error = Error::Success;
  7211. auto ret = cli_.send(req, *res, error);
  7212. ASSERT_TRUE(ret);
  7213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7214. }
  7215. TEST_F(ServerTest, KeepAlive) {
  7216. auto res = cli_.Get("/hi");
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7220. EXPECT_EQ("Hello World!", res->body);
  7221. res = cli_.Get("/hi");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7225. EXPECT_EQ("Hello World!", res->body);
  7226. res = cli_.Get("/hi");
  7227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7228. EXPECT_EQ(StatusCode::OK_200, res->status);
  7229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7230. EXPECT_EQ("Hello World!", res->body);
  7231. res = cli_.Get("/not-exist");
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7234. res = cli_.Post("/empty", "", "text/plain");
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. EXPECT_EQ(StatusCode::OK_200, res->status);
  7237. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7238. EXPECT_EQ("empty", res->body);
  7239. EXPECT_EQ("close", res->get_header_value("Connection"));
  7240. res = cli_.Post(
  7241. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7242. "text/plain");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7246. EXPECT_EQ("empty", res->body);
  7247. cli_.set_keep_alive(false);
  7248. res = cli_.Get("/last-request");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ("close", res->get_header_value("Connection"));
  7252. }
  7253. TEST_F(ServerTest, TooManyRedirect) {
  7254. cli_.set_follow_location(true);
  7255. auto res = cli_.Get("/redirect/0");
  7256. ASSERT_TRUE(!res);
  7257. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7258. }
  7259. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7260. Request req;
  7261. req.method = "FOOBAR";
  7262. req.path = "/hi";
  7263. cli_.set_keep_alive(true);
  7264. auto res = cli_.send(req);
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7267. EXPECT_EQ("close", res->get_header_value("Connection"));
  7268. EXPECT_FALSE(cli_.is_socket_open());
  7269. }
  7270. TEST_F(ServerTest, CustomRouteReadsBody) {
  7271. const std::string xml =
  7272. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7273. Request req;
  7274. req.method = "PROPFIND";
  7275. req.path = "/dav/dir";
  7276. req.set_header("Depth", "1");
  7277. req.body = xml;
  7278. auto res = cli_.send(req);
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7281. EXPECT_EQ(xml, res->body);
  7282. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7283. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7284. }
  7285. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7286. Request req;
  7287. req.method = "PROPFIND";
  7288. req.path = "/dav/42";
  7289. auto res = cli_.send(req);
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7292. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7293. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7294. }
  7295. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7296. Request req;
  7297. req.method = "PROPFIND";
  7298. req.path = "/dav-re/123";
  7299. auto res = cli_.send(req);
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7302. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7303. }
  7304. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7305. Request req;
  7306. req.method = "MKCOL";
  7307. req.path = "/dav-mkcol";
  7308. auto res = cli_.send(req);
  7309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7310. EXPECT_EQ(StatusCode::Created_201, res->status);
  7311. }
  7312. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7313. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7314. Request req;
  7315. req.method = "REPORT";
  7316. req.path = "/dav-report";
  7317. req.body = xml;
  7318. auto res = cli_.send(req);
  7319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7320. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7321. EXPECT_EQ(xml, res->body);
  7322. }
  7323. // A content reader route must fire even when the request carries no body,
  7324. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7325. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7326. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7327. Request req;
  7328. req.method = "REPORT";
  7329. req.path = "/dav-report";
  7330. auto res = cli_.send(req);
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7333. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7334. }
  7335. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7336. Request req;
  7337. req.method = "PROPFIND";
  7338. req.path = "/not-dav";
  7339. auto res = cli_.send(req);
  7340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7341. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7342. }
  7343. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7344. Request req;
  7345. req.method = "UNLOCK";
  7346. req.path = "/dav/dir";
  7347. cli_.set_keep_alive(true);
  7348. auto res = cli_.send(req);
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7351. EXPECT_EQ("close", res->get_header_value("Connection"));
  7352. EXPECT_FALSE(cli_.is_socket_open());
  7353. }
  7354. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7355. // The mount point serves this path, but only for GET and HEAD.
  7356. auto get_res = cli_.Get("/dir/index.html");
  7357. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7358. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7359. Request req;
  7360. req.method = "PROPFIND";
  7361. req.path = "/dir/index.html";
  7362. auto res = cli_.send(req);
  7363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7365. }
  7366. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7367. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7368. cli_.set_keep_alive(true);
  7369. for (auto i = 0; i < 2; i++) {
  7370. Request req;
  7371. req.method = "PROPFIND";
  7372. req.path = "/dav/dir";
  7373. req.body = xml;
  7374. auto res = cli_.send(req);
  7375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7376. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7377. EXPECT_EQ(xml, res->body);
  7378. EXPECT_TRUE(cli_.is_socket_open());
  7379. }
  7380. // A built-in method must still be served on the same connection.
  7381. cli_.set_keep_alive(false);
  7382. auto res = cli_.Get("/hi");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("close", res->get_header_value("Connection"));
  7386. }
  7387. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7388. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7389. Request req;
  7390. req.method = "PROPFIND";
  7391. req.path = "/dav/dir";
  7392. req.set_header("Expect", "100-continue");
  7393. req.body = xml;
  7394. auto res = cli_.send(req);
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7397. EXPECT_EQ(xml, res->body);
  7398. }
  7399. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7400. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7401. TEST_F(ServerTest, Gzip) {
  7402. Headers headers;
  7403. headers.emplace("Accept-Encoding", "gzip, deflate");
  7404. auto res = cli_.Get("/compress", headers);
  7405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7406. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7408. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7410. "7890123456789012345678901234567890",
  7411. res->body);
  7412. EXPECT_EQ(StatusCode::OK_200, res->status);
  7413. }
  7414. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7415. Headers headers;
  7416. headers.emplace("Accept-Encoding", "gzip, deflate");
  7417. auto res = cli_.Get("/compress-with-charset", headers);
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7420. EXPECT_EQ("application/json; charset=utf-8",
  7421. res->get_header_value("Content-Type"));
  7422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7423. "7890123456789012345678901234567890",
  7424. res->body);
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. }
  7427. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7428. Headers headers;
  7429. headers.emplace("Accept-Encoding", "");
  7430. auto res = cli_.Get("/compress", headers);
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7434. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7435. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7436. "7890123456789012345678901234567890",
  7437. res->body);
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. }
  7440. TEST_F(ServerTest, GzipWithContentReceiver) {
  7441. Headers headers;
  7442. headers.emplace("Accept-Encoding", "gzip, deflate");
  7443. std::string body;
  7444. auto res = cli_.Get("/compress", headers,
  7445. [&](const char *data, uint64_t data_length) {
  7446. EXPECT_EQ(100U, data_length);
  7447. body.append(data, data_length);
  7448. return true;
  7449. });
  7450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7451. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7453. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7454. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7455. "7890123456789012345678901234567890",
  7456. body);
  7457. EXPECT_EQ(StatusCode::OK_200, res->status);
  7458. }
  7459. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7460. Headers headers;
  7461. headers.emplace("Accept-Encoding", "gzip, deflate");
  7462. cli_.set_decompress(false);
  7463. auto res = cli_.Get("/compress", headers);
  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(33U, res->body.size());
  7469. EXPECT_EQ(StatusCode::OK_200, res->status);
  7470. }
  7471. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7472. Headers headers;
  7473. headers.emplace("Accept-Encoding", "");
  7474. std::string body;
  7475. auto res = cli_.Get("/compress", headers,
  7476. [&](const char *data, uint64_t data_length) {
  7477. EXPECT_EQ(100U, data_length);
  7478. body.append(data, data_length);
  7479. return true;
  7480. });
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7484. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7485. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7486. "7890123456789012345678901234567890",
  7487. body);
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, NoGzip) {
  7491. Headers headers;
  7492. headers.emplace("Accept-Encoding", "gzip, deflate");
  7493. auto res = cli_.Get("/nocompress", headers);
  7494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7495. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7496. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7497. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7498. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7499. "7890123456789012345678901234567890",
  7500. res->body);
  7501. EXPECT_EQ(StatusCode::OK_200, res->status);
  7502. }
  7503. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7504. Headers headers;
  7505. headers.emplace("Accept-Encoding", "gzip, deflate");
  7506. std::string body;
  7507. auto res = cli_.Get("/nocompress", headers,
  7508. [&](const char *data, uint64_t data_length) {
  7509. EXPECT_EQ(100U, data_length);
  7510. body.append(data, data_length);
  7511. return true;
  7512. });
  7513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7514. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7515. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7516. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7517. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7518. "7890123456789012345678901234567890",
  7519. body);
  7520. EXPECT_EQ(StatusCode::OK_200, res->status);
  7521. }
  7522. TEST_F(ServerTest, MultipartFormDataGzip) {
  7523. UploadFormDataItems items = {
  7524. {"key1", "test", "", ""},
  7525. {"key2", "--abcdefg123", "", ""},
  7526. };
  7527. cli_.set_compress(true);
  7528. auto res = cli_.Post("/compress-multipart", items);
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. }
  7532. #endif
  7533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7534. // Static file compression is opt-in, so these run their own server rather than
  7535. // flipping it on for the shared ServerTest fixture, which would silently
  7536. // rewrite what every other static file test is asserting.
  7537. class StaticFileCompressionTest : public ::testing::Test {
  7538. protected:
  7539. void TearDown() override {
  7540. if (t_.joinable()) {
  7541. svr_.stop();
  7542. t_.join();
  7543. }
  7544. }
  7545. int start(const std::function<void(Server &)> &configure = nullptr) {
  7546. // Serves the same tree as a directory of build-time compressed assets
  7547. // would be served: the mount point names the coding the files are already
  7548. // stored in. Registered before "/" so it is the one that matches.
  7549. svr_.set_mount_point("/pre-encoded", "./www",
  7550. {{"Content-Encoding", "gzip"}});
  7551. svr_.set_mount_point("/", "./www");
  7552. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7553. res.set_file_content("./www/dir/index.html", "text/html");
  7554. });
  7555. svr_.Get("/pre-encoded-file-content",
  7556. [](const Request & /*req*/, Response &res) {
  7557. res.set_header("Content-Encoding", "gzip");
  7558. res.set_file_content("./www/dir/index.html", "text/html");
  7559. });
  7560. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7561. res.set_content_provider(
  7562. 6, "text/plain",
  7563. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7564. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7565. return true;
  7566. });
  7567. });
  7568. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7569. res.set_content_provider(
  7570. 1000, "text/plain",
  7571. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7572. if (offset < 100) {
  7573. std::string data(100, 'A');
  7574. sink.write(data.data(), data.size());
  7575. return true;
  7576. }
  7577. std::this_thread::sleep_for(std::chrono::seconds(2));
  7578. std::string data(900, 'B');
  7579. sink.write(data.data(), data.size());
  7580. return true;
  7581. });
  7582. });
  7583. if (configure) { configure(svr_); }
  7584. auto port = svr_.bind_to_any_port(HOST);
  7585. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7586. svr_.wait_until_ready();
  7587. return port;
  7588. }
  7589. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7590. // Every file under ./www except 1MB.txt is smaller than the default
  7591. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7592. // it out of the way.
  7593. static void enable_without_floor(Server &svr) {
  7594. svr.set_static_file_compression(true);
  7595. svr.set_static_file_compression_min_length(0);
  7596. }
  7597. Server svr_;
  7598. std::thread t_;
  7599. };
  7600. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7601. auto port = start();
  7602. Client cli(HOST, port);
  7603. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7605. EXPECT_EQ(StatusCode::OK_200, res->status);
  7606. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7607. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7608. EXPECT_EQ(1048576U, res->body.size());
  7609. }
  7610. TEST_F(StaticFileCompressionTest, MountPoint) {
  7611. auto port = start(enable);
  7612. Client cli(HOST, port);
  7613. cli.set_decompress(false);
  7614. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7616. EXPECT_EQ(StatusCode::OK_200, res->status);
  7617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7618. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7619. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7620. // The response stays self-delimiting: a length, not a chunked body.
  7621. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7622. EXPECT_EQ(std::to_string(res->body.size()),
  7623. res->get_header_value("Content-Length"));
  7624. EXPECT_LT(res->body.size(), 1048576U);
  7625. EXPECT_FALSE(res->body.empty());
  7626. }
  7627. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7628. auto port = start(enable);
  7629. Client cli(HOST, port);
  7630. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7632. EXPECT_EQ(StatusCode::OK_200, res->status);
  7633. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7634. EXPECT_EQ(1048576U, res->body.size());
  7635. }
  7636. TEST_F(StaticFileCompressionTest, FileContent) {
  7637. auto port = start(enable_without_floor);
  7638. Client cli(HOST, port);
  7639. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7641. EXPECT_EQ(StatusCode::OK_200, res->status);
  7642. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7643. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7644. EXPECT_EQ(104U, res->body.size());
  7645. }
  7646. // A handler that serves an already-encoded file names the coding itself. The
  7647. // file-backed path decided its coding from Accept-Encoding and the content
  7648. // type alone, so it compressed the stored bytes a second time and appended a
  7649. // second Content-Encoding field line.
  7650. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7651. auto port = start(enable_without_floor);
  7652. Client cli(HOST, port);
  7653. cli.set_decompress(false);
  7654. auto res = cli.Get("/pre-encoded-file-content",
  7655. Headers{{"Accept-Encoding", "gzip"}});
  7656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7657. EXPECT_EQ(StatusCode::OK_200, res->status);
  7658. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7659. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7660. // Vary belongs to a coding the server chose, and it chose none here.
  7661. EXPECT_FALSE(res->has_header("Vary"));
  7662. // The file travels exactly as it is stored on disk.
  7663. EXPECT_EQ(104U, res->body.size());
  7664. }
  7665. // The 1MB file clears the default floor, so this one runs the configuration a
  7666. // deployment would actually have.
  7667. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7668. auto port = start(enable);
  7669. Client cli(HOST, port);
  7670. cli.set_decompress(false);
  7671. auto res =
  7672. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7676. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7677. EXPECT_FALSE(res->has_header("Vary"));
  7678. EXPECT_EQ(1048576U, res->body.size());
  7679. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7680. }
  7681. TEST_F(StaticFileCompressionTest, Head) {
  7682. auto port = start(enable);
  7683. Client cli(HOST, port);
  7684. cli.set_decompress(false);
  7685. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7686. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7687. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7691. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7692. // HEAD still reports the size a GET would return.
  7693. EXPECT_EQ(get->get_header_value("Content-Length"),
  7694. res->get_header_value("Content-Length"));
  7695. EXPECT_TRUE(res->body.empty());
  7696. }
  7697. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7698. auto port = start(enable);
  7699. Client cli(HOST, port);
  7700. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7701. {"Accept-Encoding", "gzip"}});
  7702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7703. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7704. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7705. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7706. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7707. EXPECT_EQ("cd", res->body);
  7708. }
  7709. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7710. auto port = start(enable);
  7711. Client cli(HOST, port);
  7712. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_EQ(StatusCode::OK_200, res->status);
  7715. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7716. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7717. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7718. }
  7719. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7720. auto port = start(enable);
  7721. Client cli(HOST, port);
  7722. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7726. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7727. EXPECT_TRUE(res->body.empty());
  7728. }
  7729. TEST_F(StaticFileCompressionTest, MinLength) {
  7730. auto port = start(enable);
  7731. Client cli(HOST, port);
  7732. // 104 bytes, well under the default floor. Compressing it would add the
  7733. // gzip header and trailer to a body that already fits in one packet.
  7734. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7736. EXPECT_EQ(StatusCode::OK_200, res->status);
  7737. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7738. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7739. }
  7740. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7741. auto port = start([](Server &svr) {
  7742. svr.set_static_file_compression(true);
  7743. svr.set_static_file_compression_min_length(1);
  7744. });
  7745. Client cli(HOST, port);
  7746. cli.set_decompress(false);
  7747. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7749. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7750. // A 9-byte file comes back larger than it went in, because gzip's header and
  7751. // trailer outweigh anything deflate can save. That is the end of the range
  7752. // the floor exists to keep out.
  7753. EXPECT_GT(res->body.size(), 9U);
  7754. }
  7755. TEST_F(StaticFileCompressionTest, MaxLength) {
  7756. auto port = start([](Server &svr) {
  7757. svr.set_static_file_compression(true);
  7758. svr.set_static_file_compression_min_length(0);
  7759. svr.set_static_file_compression_max_length(1024);
  7760. });
  7761. Client cli(HOST, port);
  7762. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7763. // defines `small` as a macro on Windows.
  7764. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7765. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7766. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7767. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7768. // Under it: compressed.
  7769. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7770. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7771. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7772. }
  7773. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7774. auto port = start(enable_without_floor);
  7775. Client cli(HOST, port);
  7776. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7777. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7778. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7779. auto identity_etag = identity->get_header_value("ETag");
  7780. ASSERT_FALSE(identity_etag.empty());
  7781. auto gzipped =
  7782. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7783. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7784. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7785. auto gzip_etag = gzipped->get_header_value("ETag");
  7786. ASSERT_FALSE(gzip_etag.empty());
  7787. // Two representations, two validators.
  7788. EXPECT_NE(identity_etag, gzip_etag);
  7789. // Each one revalidates against the request that would produce it...
  7790. auto fresh =
  7791. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7792. {"If-None-Match", gzip_etag}});
  7793. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7794. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7795. auto fresh_identity =
  7796. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7797. {"If-None-Match", identity_etag}});
  7798. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7799. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7800. // ...and not against the other representation.
  7801. auto crossed =
  7802. cli.Get("/dir/index.html",
  7803. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7804. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7805. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7806. }
  7807. // The opt-in covers responses the server reads off disk itself. A caller's own
  7808. // known-length provider keeps its Content-Length and, more importantly, keeps
  7809. // delivering incrementally: routing it through a compressor would hold every
  7810. // write back until zlib's window filled.
  7811. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7812. auto port = start(enable);
  7813. Client cli(HOST, port);
  7814. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7818. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7819. EXPECT_EQ("aaabbb", res->body);
  7820. }
  7821. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7822. auto port = start(enable);
  7823. Client cli(HOST, port);
  7824. cli.set_read_timeout(1, 0);
  7825. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7826. Headers{{"Accept-Encoding", "gzip"}});
  7827. ASSERT_TRUE(handle.is_valid());
  7828. // The provider writes 100 bytes and then stalls for longer than the read
  7829. // timeout. Those first bytes have to arrive anyway: run the response through
  7830. // a compressor and zlib holds them until its window fills, so the read would
  7831. // come back empty instead.
  7832. char buf[256];
  7833. auto n = handle.read(buf, sizeof(buf));
  7834. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7835. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7836. }
  7837. #endif
  7838. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7839. TEST_F(ServerTest, Brotli) {
  7840. Headers headers;
  7841. headers.emplace("Accept-Encoding", "br");
  7842. auto res = cli_.Get("/compress", headers);
  7843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7844. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7846. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7847. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7848. "7890123456789012345678901234567890",
  7849. res->body);
  7850. EXPECT_EQ(StatusCode::OK_200, res->status);
  7851. }
  7852. #endif
  7853. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7854. TEST_F(ServerTest, Zstd) {
  7855. Headers headers;
  7856. headers.emplace("Accept-Encoding", "zstd");
  7857. auto res = cli_.Get("/compress", headers);
  7858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7859. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7860. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7861. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7862. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7863. "7890123456789012345678901234567890",
  7864. res->body);
  7865. EXPECT_EQ(StatusCode::OK_200, res->status);
  7866. }
  7867. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7868. Headers headers;
  7869. headers.emplace("Accept-Encoding", "");
  7870. auto res = cli_.Get("/compress", headers);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7873. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7874. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7875. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7876. "7890123456789012345678901234567890",
  7877. res->body);
  7878. EXPECT_EQ(StatusCode::OK_200, res->status);
  7879. }
  7880. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7881. Headers headers;
  7882. headers.emplace("Accept-Encoding", "zstd");
  7883. std::string body;
  7884. auto res = cli_.Get("/compress", headers,
  7885. [&](const char *data, uint64_t data_length) {
  7886. EXPECT_EQ(100U, data_length);
  7887. body.append(data, data_length);
  7888. return true;
  7889. });
  7890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7891. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7892. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7893. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7894. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7895. "7890123456789012345678901234567890",
  7896. body);
  7897. EXPECT_EQ(StatusCode::OK_200, res->status);
  7898. }
  7899. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7900. Headers headers;
  7901. headers.emplace("Accept-Encoding", "zstd");
  7902. cli_.set_decompress(false);
  7903. auto res = cli_.Get("/compress", headers);
  7904. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7905. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7906. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7907. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7909. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7911. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7912. EXPECT_EQ(StatusCode::OK_200, res->status);
  7913. ASSERT_EQ(26U, res->body.size());
  7914. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7915. 0);
  7916. }
  7917. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7918. Headers headers;
  7919. headers.emplace("Accept-Encoding", "");
  7920. std::string body;
  7921. auto res = cli_.Get("/compress", headers,
  7922. [&](const char *data, uint64_t data_length) {
  7923. EXPECT_EQ(100U, data_length);
  7924. body.append(data, data_length);
  7925. return true;
  7926. });
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7929. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7930. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7931. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7932. "7890123456789012345678901234567890",
  7933. body);
  7934. EXPECT_EQ(StatusCode::OK_200, res->status);
  7935. }
  7936. TEST_F(ServerTest, NoZstd) {
  7937. Headers headers;
  7938. headers.emplace("Accept-Encoding", "zstd");
  7939. auto res = cli_.Get("/nocompress", headers);
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7942. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7943. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7944. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7945. "7890123456789012345678901234567890",
  7946. res->body);
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  7950. Headers headers;
  7951. headers.emplace("Accept-Encoding", "zstd");
  7952. std::string body;
  7953. auto res = cli_.Get("/nocompress", headers,
  7954. [&](const char *data, uint64_t data_length) {
  7955. EXPECT_EQ(100U, data_length);
  7956. body.append(data, data_length);
  7957. return true;
  7958. });
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7961. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7962. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7963. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7964. "7890123456789012345678901234567890",
  7965. body);
  7966. EXPECT_EQ(StatusCode::OK_200, res->status);
  7967. }
  7968. // TODO: How to enable zstd ??
  7969. TEST_F(ServerTest, MultipartFormDataZstd) {
  7970. UploadFormDataItems items = {
  7971. {"key1", "test", "", ""},
  7972. {"key2", "--abcdefg123", "", ""},
  7973. };
  7974. Headers headers;
  7975. headers.emplace("Accept-Encoding", "zstd");
  7976. cli_.set_compress(true);
  7977. auto res = cli_.Post("/compress-multipart", headers, items);
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. EXPECT_EQ(StatusCode::OK_200, res->status);
  7980. }
  7981. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  7982. Headers headers;
  7983. headers.emplace("Accept-Encoding", "zstd");
  7984. cli_.set_compress(true);
  7985. auto res = cli_.Put(
  7986. "/put", headers, 3,
  7987. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7988. sink.os << "PUT";
  7989. return true;
  7990. },
  7991. "text/plain");
  7992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7993. EXPECT_EQ(StatusCode::OK_200, res->status);
  7994. EXPECT_EQ("PUT", res->body);
  7995. }
  7996. // Pre-compression logging tests
  7997. TEST_F(ServerTest, PreCompressionLogging) {
  7998. // Test data for compression (matches the actual /compress endpoint content)
  7999. const std::string test_content =
  8000. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8001. "3456789012345678901234567890";
  8002. // Variables to capture logging data
  8003. std::string pre_compression_body;
  8004. std::string pre_compression_content_type;
  8005. std::string pre_compression_content_encoding;
  8006. std::string post_compression_body;
  8007. std::string post_compression_content_type;
  8008. std::string post_compression_content_encoding;
  8009. // Set up pre-compression logger
  8010. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8011. const Response &res) {
  8012. pre_compression_body = res.body;
  8013. pre_compression_content_type = res.get_header_value("Content-Type");
  8014. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8015. });
  8016. // Set up post-compression logger
  8017. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8018. post_compression_body = res.body;
  8019. post_compression_content_type = res.get_header_value("Content-Type");
  8020. post_compression_content_encoding =
  8021. res.get_header_value("Content-Encoding");
  8022. });
  8023. // Test with gzip compression
  8024. Headers headers;
  8025. headers.emplace("Accept-Encoding", "gzip");
  8026. auto res = cli_.Get("/compress", headers);
  8027. // Verify response was compressed
  8028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8029. EXPECT_EQ(StatusCode::OK_200, res->status);
  8030. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8031. // Verify pre-compression logger captured uncompressed content
  8032. EXPECT_EQ(test_content, pre_compression_body);
  8033. EXPECT_EQ("text/plain", pre_compression_content_type);
  8034. EXPECT_TRUE(pre_compression_content_encoding
  8035. .empty()); // No encoding header before compression
  8036. // Verify post-compression logger captured compressed content
  8037. EXPECT_NE(test_content,
  8038. post_compression_body); // Should be different after compression
  8039. EXPECT_EQ("text/plain", post_compression_content_type);
  8040. EXPECT_EQ("gzip", post_compression_content_encoding);
  8041. // Verify compressed content is smaller
  8042. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8043. }
  8044. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8045. const std::string test_content =
  8046. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8047. "3456789012345678901234567890";
  8048. std::string pre_compression_body;
  8049. std::string post_compression_body;
  8050. svr_.set_pre_compression_logger(
  8051. [&](const Request & /*req*/, const Response &res) {
  8052. pre_compression_body = res.body;
  8053. });
  8054. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8055. post_compression_body = res.body;
  8056. });
  8057. Headers headers;
  8058. headers.emplace("Accept-Encoding", "br");
  8059. auto res = cli_.Get("/compress", headers);
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8063. // Verify pre-compression content is uncompressed
  8064. EXPECT_EQ(test_content, pre_compression_body);
  8065. // Verify post-compression content is compressed
  8066. EXPECT_NE(test_content, post_compression_body);
  8067. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8068. }
  8069. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8070. const std::string test_content =
  8071. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8072. "3456789012345678901234567890";
  8073. std::string pre_compression_body;
  8074. std::string post_compression_body;
  8075. svr_.set_pre_compression_logger(
  8076. [&](const Request & /*req*/, const Response &res) {
  8077. pre_compression_body = res.body;
  8078. });
  8079. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8080. post_compression_body = res.body;
  8081. });
  8082. // Request without compression (use /nocompress endpoint)
  8083. Headers headers;
  8084. auto res = cli_.Get("/nocompress", headers);
  8085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8086. EXPECT_EQ(StatusCode::OK_200, res->status);
  8087. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8088. // Pre-compression logger should not be called when no compression is applied
  8089. EXPECT_TRUE(
  8090. pre_compression_body.empty()); // Pre-compression logger not called
  8091. EXPECT_EQ(
  8092. test_content,
  8093. post_compression_body); // Post-compression logger captures final content
  8094. }
  8095. TEST_F(ServerTest, LoggerSeesContentLength) {
  8096. size_t logged_content_length = 0;
  8097. std::string logged_content_length_header;
  8098. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8099. logged_content_length = res.content_length_;
  8100. logged_content_length_header = res.get_header_value("Content-Length");
  8101. });
  8102. auto res = cli_.Get("/nocompress");
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. EXPECT_EQ(res->body.size(), logged_content_length);
  8106. EXPECT_EQ(std::to_string(logged_content_length),
  8107. logged_content_length_header);
  8108. }
  8109. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8110. const std::string test_content =
  8111. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8112. "3456789012345678901234567890";
  8113. std::string pre_compression_body;
  8114. bool pre_logger_called = false;
  8115. // Set only pre-compression logger
  8116. svr_.set_pre_compression_logger(
  8117. [&](const Request & /*req*/, const Response &res) {
  8118. pre_compression_body = res.body;
  8119. pre_logger_called = true;
  8120. });
  8121. Headers headers;
  8122. headers.emplace("Accept-Encoding", "gzip");
  8123. auto res = cli_.Get("/compress", headers);
  8124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8125. EXPECT_EQ(StatusCode::OK_200, res->status);
  8126. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8127. // Verify pre-compression logger was called
  8128. EXPECT_TRUE(pre_logger_called);
  8129. EXPECT_EQ(test_content, pre_compression_body);
  8130. }
  8131. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8132. {
  8133. // Test with Expect: 100-continue header - success case
  8134. // Server returns 100 Continue, client sends body, server returns 200 OK
  8135. Request req;
  8136. req.method = "POST";
  8137. req.path = "/post-large";
  8138. req.set_header("Expect", "100-continue");
  8139. req.body = LARGE_DATA;
  8140. Response res;
  8141. auto error = Error::Success;
  8142. cli_.set_keep_alive(true);
  8143. auto ret = cli_.send(req, res, error);
  8144. EXPECT_TRUE(ret);
  8145. EXPECT_EQ(StatusCode::OK_200, res.status);
  8146. EXPECT_EQ(LARGE_DATA, res.body);
  8147. }
  8148. {
  8149. // Test with Expect: 100-continue header - error case
  8150. // Client should not send the body when server returns an error
  8151. Request req;
  8152. req.method = "POST";
  8153. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8154. req.set_header("Expect", "100-continue");
  8155. req.body = LARGE_DATA;
  8156. Response res;
  8157. auto error = Error::Success;
  8158. auto start = std::chrono::high_resolution_clock::now();
  8159. cli_.set_keep_alive(true);
  8160. auto ret = cli_.send(req, res, error);
  8161. auto end = std::chrono::high_resolution_clock::now();
  8162. auto elapsed =
  8163. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8164. .count();
  8165. // With Expect: 100-continue, request completes successfully but with error
  8166. EXPECT_TRUE(ret);
  8167. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8168. EXPECT_EQ("close", res.get_header_value("Connection"));
  8169. EXPECT_FALSE(cli_.is_socket_open());
  8170. EXPECT_LE(elapsed, 2000);
  8171. }
  8172. {
  8173. // Send an extra GET request to ensure error recovery without hanging
  8174. Request req;
  8175. req.method = "GET";
  8176. req.path = "/hi";
  8177. auto start = std::chrono::high_resolution_clock::now();
  8178. auto res = cli_.send(req);
  8179. auto end = std::chrono::high_resolution_clock::now();
  8180. auto elapsed =
  8181. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8182. .count();
  8183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8184. EXPECT_EQ(StatusCode::OK_200, res->status);
  8185. EXPECT_EQ("Hello World!", res->body);
  8186. EXPECT_LE(elapsed, 500);
  8187. }
  8188. }
  8189. TEST(ZstdDecompressor, ChunkedDecompression) {
  8190. std::string data;
  8191. for (size_t i = 0; i < 32 * 1024; ++i) {
  8192. data.push_back(static_cast<char>('a' + i % 26));
  8193. }
  8194. std::string compressed_data;
  8195. {
  8196. httplib::detail::zstd_compressor compressor;
  8197. bool result = compressor.compress(
  8198. data.data(), data.size(),
  8199. /*last=*/true,
  8200. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8201. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8202. compressed_data_size);
  8203. return true;
  8204. });
  8205. ASSERT_TRUE(result);
  8206. }
  8207. std::string decompressed_data;
  8208. {
  8209. httplib::detail::zstd_decompressor decompressor;
  8210. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8211. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8212. size_t chunk_size = 130;
  8213. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8214. chunk_begin += chunk_size) {
  8215. size_t current_chunk_size =
  8216. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8217. bool result = decompressor.decompress(
  8218. compressed_data.data() + chunk_begin, current_chunk_size,
  8219. [&](const char *decompressed_data_chunk,
  8220. size_t decompressed_data_chunk_size) {
  8221. decompressed_data.insert(decompressed_data.size(),
  8222. decompressed_data_chunk,
  8223. decompressed_data_chunk_size);
  8224. return true;
  8225. });
  8226. ASSERT_TRUE(result);
  8227. }
  8228. }
  8229. ASSERT_EQ(data, decompressed_data);
  8230. }
  8231. TEST(ZstdDecompressor, Decompress) {
  8232. std::string original_text = "Compressed with ZSTD";
  8233. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8234. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8235. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8236. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8237. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8238. std::string decompressed_data;
  8239. {
  8240. httplib::detail::zstd_decompressor decompressor;
  8241. bool result = decompressor.decompress(
  8242. compressed_data.data(), compressed_data.size(),
  8243. [&](const char *decompressed_data_chunk,
  8244. size_t decompressed_data_chunk_size) {
  8245. decompressed_data.insert(decompressed_data.size(),
  8246. decompressed_data_chunk,
  8247. decompressed_data_chunk_size);
  8248. return true;
  8249. });
  8250. ASSERT_TRUE(result);
  8251. }
  8252. ASSERT_EQ(original_text, decompressed_data);
  8253. }
  8254. #endif
  8255. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8256. // separate chunks so that the server sees each part in its own read(). Used to
  8257. // place a read boundary at a specific offset of a request body.
  8258. static bool send_request_in_parts(time_t read_timeout_sec,
  8259. const std::vector<std::string> &parts,
  8260. std::string *resp = nullptr,
  8261. int port = PORT) {
  8262. auto error = Error::Success;
  8263. auto client_sock = detail::create_client_socket(
  8264. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8265. /*connection_timeout_sec=*/5, 0,
  8266. /*read_timeout_sec=*/5, 0,
  8267. /*write_timeout_sec=*/5, 0, std::string(), error);
  8268. if (client_sock == INVALID_SOCKET) { return false; }
  8269. auto ret = detail::process_client_socket(
  8270. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8271. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8272. for (size_t i = 0; i < parts.size(); i++) {
  8273. const auto &part = parts[i];
  8274. if (part.size() !=
  8275. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8276. return false;
  8277. }
  8278. if (i + 1 < parts.size()) {
  8279. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8280. }
  8281. }
  8282. char buf[512];
  8283. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8284. while (line_reader.getline()) {
  8285. if (resp) { *resp += line_reader.ptr(); }
  8286. }
  8287. return true;
  8288. });
  8289. detail::close_socket(client_sock);
  8290. return ret;
  8291. }
  8292. // Sends a raw request to a server listening at HOST:PORT.
  8293. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8294. std::string *resp = nullptr, int port = PORT) {
  8295. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8296. }
  8297. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8298. Server svr;
  8299. std::string header_value;
  8300. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8301. header_value = req.get_header_value("foo");
  8302. res.set_content("ok", "text/plain");
  8303. });
  8304. thread t = thread([&] { svr.listen(HOST, PORT); });
  8305. auto se = detail::scope_exit([&] {
  8306. svr.stop();
  8307. t.join();
  8308. ASSERT_FALSE(svr.is_running());
  8309. });
  8310. svr.wait_until_ready();
  8311. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8312. // like characters are not treated the same - use vertical tab and escape.
  8313. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8314. "foo: \t \v bar \x1B\t \r\n"
  8315. "Connection: close\r\n"
  8316. "\r\n";
  8317. std::string res;
  8318. ASSERT_TRUE(send_request(5, req, &res));
  8319. EXPECT_EQ(header_value, "");
  8320. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8321. }
  8322. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8323. Server svr;
  8324. std::string received;
  8325. svr.Get("/order", [&](const Request &req, Response &res) {
  8326. received = entries_to_string(req.headers);
  8327. res.set_content("ok", "text/plain");
  8328. });
  8329. auto port = svr.bind_to_any_port(HOST);
  8330. thread t = thread([&] { svr.listen_after_bind(); });
  8331. auto se = detail::scope_exit([&] {
  8332. svr.stop();
  8333. t.join();
  8334. ASSERT_FALSE(svr.is_running());
  8335. });
  8336. svr.wait_until_ready();
  8337. const std::string req = "GET /order HTTP/1.1\r\n"
  8338. "X-First: 1\r\n"
  8339. "X-Dup: a\r\n"
  8340. "X-Second: 2\r\n"
  8341. "X-Dup: b\r\n"
  8342. "Connection: close\r\n"
  8343. "\r\n";
  8344. std::string res;
  8345. ASSERT_TRUE(send_request(5, req, &res, port));
  8346. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8347. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8348. }
  8349. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8350. Server svr;
  8351. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8352. res.set_header("Set-Cookie", "first=1");
  8353. res.set_header("X-Between", "y");
  8354. res.set_header("Set-Cookie", "second=2");
  8355. res.set_content("ok", "text/plain");
  8356. });
  8357. auto port = svr.bind_to_any_port(HOST);
  8358. thread t = thread([&] { svr.listen_after_bind(); });
  8359. auto se = detail::scope_exit([&] {
  8360. svr.stop();
  8361. t.join();
  8362. ASSERT_FALSE(svr.is_running());
  8363. });
  8364. svr.wait_until_ready();
  8365. Client cli(HOST, port);
  8366. auto res = cli.Get("/cookies");
  8367. ASSERT_TRUE(res);
  8368. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8369. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8370. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8371. }
  8372. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8373. Server svr;
  8374. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8375. auto i = new int(0);
  8376. res.set_header("Trailer", "X-Safe, X-Reflected");
  8377. res.set_chunked_content_provider(
  8378. "text/plain",
  8379. [i](size_t /*offset*/, DataSink &sink) {
  8380. if (*i == 0) {
  8381. sink.os << "body";
  8382. } else {
  8383. Headers trailer;
  8384. // A valid trailer that must survive.
  8385. trailer.emplace("X-Safe", "safe");
  8386. // Attacker-controlled value carrying CR/LF (response splitting).
  8387. trailer.emplace("X-Reflected",
  8388. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8389. // Attacker-controlled name carrying CR/LF.
  8390. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8391. sink.done_with_trailer(trailer);
  8392. }
  8393. (*i)++;
  8394. return true;
  8395. },
  8396. [i](bool /*success*/) { delete i; });
  8397. });
  8398. thread t = thread([&] { svr.listen(HOST, PORT); });
  8399. auto se = detail::scope_exit([&] {
  8400. svr.stop();
  8401. t.join();
  8402. ASSERT_FALSE(svr.is_running());
  8403. });
  8404. svr.wait_until_ready();
  8405. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8406. "Host: " + HOST +
  8407. "\r\n"
  8408. "Connection: close\r\n"
  8409. "\r\n";
  8410. std::string res;
  8411. ASSERT_TRUE(send_request(5, req, &res));
  8412. // The injected fields must not appear anywhere in the raw response.
  8413. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8414. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8415. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8416. // Invalid trailers are dropped entirely, matching set_header().
  8417. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8418. // The valid trailer still passes through.
  8419. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8420. }
  8421. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8422. Server svr;
  8423. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8424. // res.headers is a public field an application can populate directly,
  8425. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8426. // A valid header that must survive.
  8427. res.headers.emplace("X-Safe", "safe");
  8428. // Attacker-controlled value carrying CR/LF (response splitting).
  8429. res.headers.emplace("X-Reflected",
  8430. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8431. // Attacker-controlled name carrying CR/LF.
  8432. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8433. res.set_content("body", "text/plain");
  8434. });
  8435. thread t = thread([&] { svr.listen(HOST, PORT); });
  8436. auto se = detail::scope_exit([&] {
  8437. svr.stop();
  8438. t.join();
  8439. ASSERT_FALSE(svr.is_running());
  8440. });
  8441. svr.wait_until_ready();
  8442. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8443. "Host: " + HOST +
  8444. "\r\n"
  8445. "Connection: close\r\n"
  8446. "\r\n";
  8447. std::string res;
  8448. ASSERT_TRUE(send_request(5, req, &res));
  8449. // The injected fields must not appear anywhere in the raw response.
  8450. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8451. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8452. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8453. // Invalid headers are dropped entirely, matching set_header().
  8454. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8455. // The valid header still passes through.
  8456. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8457. }
  8458. // Forward declaration: in split builds split.py strips `inline` and moves the
  8459. // definition into httplib.cc, so detail::write_request_line is not visible from
  8460. // the public httplib.h. Re-declaring it here lets the tests link against the
  8461. // symbol in both header-only and split builds.
  8462. namespace httplib {
  8463. namespace detail {
  8464. ssize_t write_request_line(Stream &strm, const std::string &method,
  8465. const std::string &path);
  8466. } // namespace detail
  8467. } // namespace httplib
  8468. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8469. // A well-formed target is written verbatim.
  8470. {
  8471. detail::BufferStream strm;
  8472. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8473. EXPECT_GT(n, 0);
  8474. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8475. }
  8476. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8477. // otherwise it splits the request line and injects a header or a whole
  8478. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8479. // when path encoding is disabled.
  8480. const std::string evil_targets[] = {
  8481. "/a\r\nInjected: pwned",
  8482. "/a\rInjected",
  8483. "/a\nInjected",
  8484. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8485. };
  8486. for (const auto &evil : evil_targets) {
  8487. detail::BufferStream strm;
  8488. auto n = detail::write_request_line(strm, "GET", evil);
  8489. EXPECT_LT(n, 0);
  8490. EXPECT_TRUE(strm.get_buffer().empty());
  8491. }
  8492. }
  8493. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8494. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8495. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8496. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8497. // client must fail cleanly with Error::Write instead of putting a
  8498. // request-line-less, header-injecting request on the wire.
  8499. Server svr;
  8500. svr.Get("/a", [](const Request &, Response &res) {
  8501. res.set_content("ok", "text/plain");
  8502. });
  8503. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8504. auto se = detail::scope_exit([&] {
  8505. svr.stop();
  8506. thread.join();
  8507. ASSERT_FALSE(svr.is_running());
  8508. });
  8509. svr.wait_until_ready();
  8510. {
  8511. Client cli(HOST, PORT);
  8512. cli.set_path_encode(false);
  8513. // The request is rejected before anything is written, so the connection
  8514. // stays silent and the subsequent response read would otherwise block for
  8515. // the full default read timeout. Shorten it -- the assertion is on the
  8516. // error, not the timeout.
  8517. cli.set_read_timeout(1, 0);
  8518. auto res = cli.Get("/a\r\nInjected: pwned");
  8519. EXPECT_FALSE(res);
  8520. EXPECT_EQ(Error::Write, res.error());
  8521. }
  8522. }
  8523. // Sends a raw request and verifies that there isn't a crash or exception.
  8524. static void test_raw_request(const std::string &req,
  8525. std::string *out = nullptr) {
  8526. Server svr;
  8527. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8528. res.set_content("ok", "text/plain");
  8529. });
  8530. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8531. res.set_content("ok", "text/plain");
  8532. });
  8533. svr.Get("/header_field_value_check",
  8534. [&](const Request & /*req*/, Response &res) {
  8535. res.set_content("ok", "text/plain");
  8536. });
  8537. svr.CustomRoute("PROPFIND", "/dav",
  8538. [&](const Request & /*req*/, Response &res) {
  8539. res.status = StatusCode::MultiStatus_207;
  8540. });
  8541. // Server read timeout must be longer than the client read timeout for the
  8542. // bug to reproduce, probably to force the server to process a request
  8543. // without a trailing blank line.
  8544. const time_t client_read_timeout_sec = 1;
  8545. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8546. bool listen_thread_ok = false;
  8547. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8548. auto se = detail::scope_exit([&] {
  8549. svr.stop();
  8550. t.join();
  8551. ASSERT_FALSE(svr.is_running());
  8552. EXPECT_TRUE(listen_thread_ok);
  8553. });
  8554. svr.wait_until_ready();
  8555. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8556. }
  8557. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8558. // A certain header line causes an exception if the header property is parsed
  8559. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8560. test_raw_request(
  8561. "GET /hi HTTP/1.1\r\n"
  8562. " : "
  8563. " "
  8564. " ");
  8565. }
  8566. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8567. // A certain header line causes an exception if the header property *name* is
  8568. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8569. // greedy matcher and requires backtracking when there are a lot of ":"
  8570. // characters.
  8571. // This occurs with libc++ but not libstdc++.
  8572. test_raw_request(
  8573. "GET /hi HTTP/1.1\r\n"
  8574. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8575. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8576. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8577. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8578. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8579. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8580. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8581. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8582. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8583. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8584. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8585. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8586. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8587. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8588. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8589. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8590. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8591. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8592. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8593. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8594. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8595. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8596. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8597. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8598. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8599. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8600. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8601. "&&&%%%");
  8602. }
  8603. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8604. // Make sure this doesn't crash the server.
  8605. // In a previous version of the header line regex, the "\r" rendered the line
  8606. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8607. // a new position where the leading white space ended and the field value
  8608. // began.
  8609. // The crash occurs with libc++ but not libstdc++.
  8610. test_raw_request("GET /hi HTTP/1.1\r\n"
  8611. "a:" +
  8612. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8613. "\r\n"
  8614. "\r\n");
  8615. }
  8616. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8617. std::string out;
  8618. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8619. "Content-Type: text/plain\r\n"
  8620. "Transfer-Encoding: chunked\r\n"
  8621. "\r\n"
  8622. "nothex\r\n",
  8623. &out);
  8624. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8625. }
  8626. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8627. std::string out;
  8628. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8629. "Content-Type: text/plain\r\n"
  8630. "Transfer-Encoding: chunked\r\n"
  8631. "\r\n"
  8632. "3\r\n"
  8633. "xyz\r\n"
  8634. "NaN\r\n",
  8635. &out);
  8636. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8637. }
  8638. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8639. std::string out;
  8640. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8641. "Content-Type: text/plain\r\n"
  8642. "Transfer-Encoding: chunked\r\n"
  8643. "\r\n"
  8644. // Length is too large for 64 bits.
  8645. "1ffffffffffffffff\r\n"
  8646. "xyz\r\n",
  8647. &out);
  8648. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8649. }
  8650. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8651. test_raw_request("GET /hi HTTP/1.1\r\n"
  8652. "Content-Type: text/plain\r\n\r");
  8653. }
  8654. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8655. std::string out;
  8656. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8657. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8658. }
  8659. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8660. Server svr;
  8661. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8662. EXPECT_TRUE(!req.remote_addr.empty());
  8663. });
  8664. thread t = thread([&] { svr.listen(HOST, PORT); });
  8665. auto se = detail::scope_exit([&] {
  8666. svr.stop();
  8667. t.join();
  8668. ASSERT_FALSE(svr.is_running());
  8669. });
  8670. svr.wait_until_ready();
  8671. // Send an invalid request line to trigger Bad Request
  8672. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8673. std::string out;
  8674. ASSERT_TRUE(send_request(5, bad_req, &out));
  8675. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8676. }
  8677. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8678. // answered right away rather than blocking on a read that waits for EOF.
  8679. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8680. std::string out;
  8681. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8682. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8683. }
  8684. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8685. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8686. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8687. for (const auto *method : methods) {
  8688. Server svr;
  8689. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8690. EXPECT_FALSE(svr.is_valid()) << method;
  8691. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8692. }
  8693. }
  8694. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8695. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8696. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8697. for (const auto *method : methods) {
  8698. Server svr;
  8699. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8700. EXPECT_FALSE(svr.is_valid()) << method;
  8701. }
  8702. }
  8703. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8704. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8705. "COPY", "MOVE", "LOCK",
  8706. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8707. Server svr;
  8708. for (const auto *method : methods) {
  8709. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8710. }
  8711. EXPECT_TRUE(svr.is_valid());
  8712. }
  8713. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8714. Server svr;
  8715. svr.CustomRoute("POST", "/x",
  8716. [](const Request &, Response &, const ContentReader &) {});
  8717. EXPECT_FALSE(svr.is_valid());
  8718. }
  8719. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8720. Server svr;
  8721. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8722. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8723. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8724. EXPECT_FALSE(svr.is_valid());
  8725. }
  8726. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8727. Server svr;
  8728. auto captured = Error::Success;
  8729. svr.set_error_logger(
  8730. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8731. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8732. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8733. }
  8734. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8735. std::string out;
  8736. std::string request(
  8737. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8738. test_raw_request(request, &out);
  8739. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8740. }
  8741. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8742. std::string out;
  8743. std::string request(
  8744. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8745. test_raw_request(request, &out);
  8746. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8747. }
  8748. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8749. std::string out;
  8750. std::string request(
  8751. "GET /header_field_value_check HTTP/1.1\r\n Test: val\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, EmptyFieldValue) {
  8756. std::string out;
  8757. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8758. "Test: \r\n\r\n",
  8759. &out);
  8760. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8761. }
  8762. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8763. Server svr;
  8764. std::string x_custom;
  8765. std::string cookie;
  8766. std::string xff;
  8767. std::string x_unicode;
  8768. std::string x_iis;
  8769. svr.Get("/check", [&](const Request &req, Response &res) {
  8770. x_custom = req.get_header_value("X-Custom");
  8771. cookie = req.get_header_value("Cookie");
  8772. xff = req.get_header_value("X-Forwarded-For");
  8773. x_unicode = req.get_header_value("X-Unicode");
  8774. x_iis = req.get_header_value("X-IIS");
  8775. res.set_content("ok", "text/plain");
  8776. });
  8777. thread t = thread([&] { svr.listen(HOST, PORT); });
  8778. auto se = detail::scope_exit([&] {
  8779. svr.stop();
  8780. t.join();
  8781. ASSERT_FALSE(svr.is_running());
  8782. });
  8783. svr.wait_until_ready();
  8784. const std::string req = "GET /check HTTP/1.1\r\n"
  8785. "Host: localhost\r\n"
  8786. "X-Custom: a%0D%0AInjected: b\r\n"
  8787. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8788. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8789. "X-Unicode: %E3%81%82\r\n"
  8790. "X-IIS: %u00E9\r\n"
  8791. "Connection: close\r\n"
  8792. "\r\n";
  8793. std::string res;
  8794. ASSERT_TRUE(send_request(5, req, &res));
  8795. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8796. // Every value must be returned verbatim (wire form), with no decoding.
  8797. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8798. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8799. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8800. EXPECT_EQ("%E3%81%82", x_unicode);
  8801. EXPECT_EQ("%u00E9", x_iis);
  8802. }
  8803. // Applications that previously relied on automatic percent-decoding can
  8804. // reproduce the old behavior by explicitly calling decode_path_component()
  8805. // or, for RFC 3986 conformance, decode_uri_component().
  8806. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8807. Server svr;
  8808. std::string decoded;
  8809. svr.Get("/check", [&](const Request &req, Response &res) {
  8810. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8811. res.set_content("ok", "text/plain");
  8812. });
  8813. thread t = thread([&] { svr.listen(HOST, PORT); });
  8814. auto se = detail::scope_exit([&] {
  8815. svr.stop();
  8816. t.join();
  8817. ASSERT_FALSE(svr.is_running());
  8818. });
  8819. svr.wait_until_ready();
  8820. const std::string req = "GET /check HTTP/1.1\r\n"
  8821. "Host: localhost\r\n"
  8822. "X-Custom: hello%20world\r\n"
  8823. "Connection: close\r\n"
  8824. "\r\n";
  8825. std::string res;
  8826. ASSERT_TRUE(send_request(5, req, &res));
  8827. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8828. EXPECT_EQ("hello world", decoded);
  8829. }
  8830. // Regression test for #2033. Browsers send Referer values that include
  8831. // percent-encoded characters such as %0A inside the URL. Decoding the
  8832. // header value would either trip the post-decode CR/LF/NUL guard (the
  8833. // original bug, returning 400) or, after that guard was relaxed, silently
  8834. // store a literal LF — both unacceptable. The wire form must round-trip.
  8835. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8836. Server svr;
  8837. std::string referer;
  8838. svr.Get("/check", [&](const Request &req, Response &res) {
  8839. referer = req.get_header_value("Referer");
  8840. res.set_content("ok", "text/plain");
  8841. });
  8842. thread t = thread([&] { svr.listen(HOST, PORT); });
  8843. auto se = detail::scope_exit([&] {
  8844. svr.stop();
  8845. t.join();
  8846. ASSERT_FALSE(svr.is_running());
  8847. });
  8848. svr.wait_until_ready();
  8849. const std::string req = "GET /check HTTP/1.1\r\n"
  8850. "Host: localhost\r\n"
  8851. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8852. "Connection: close\r\n"
  8853. "\r\n";
  8854. std::string res;
  8855. ASSERT_TRUE(send_request(5, req, &res));
  8856. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8857. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  8858. }
  8859. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  8860. Server svr;
  8861. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  8862. res.set_header("Cache-Control", "no-cache");
  8863. res.set_chunked_content_provider(
  8864. "text/event-stream", [](size_t offset, DataSink &sink) {
  8865. std::string s = "data:";
  8866. s += std::to_string(offset);
  8867. s += "\n\n";
  8868. auto ret = sink.write(s.data(), s.size());
  8869. EXPECT_TRUE(ret);
  8870. std::this_thread::sleep_for(std::chrono::seconds(1));
  8871. return true;
  8872. });
  8873. });
  8874. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8875. svr.wait_until_ready();
  8876. Client client(HOST, PORT);
  8877. const Headers headers = {{"Accept", "text/event-stream"}};
  8878. auto get_thread = std::thread([&client, &headers]() {
  8879. auto res = client.Get(
  8880. "/events", headers,
  8881. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  8882. });
  8883. auto se = detail::scope_exit([&] {
  8884. svr.stop();
  8885. get_thread.join();
  8886. listen_thread.join();
  8887. ASSERT_FALSE(svr.is_running());
  8888. });
  8889. // Give GET time to get a few messages.
  8890. std::this_thread::sleep_for(std::chrono::seconds(2));
  8891. }
  8892. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  8893. httplib::Server svr;
  8894. svr.Post("/hi",
  8895. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8896. res.status = StatusCode::OK_200;
  8897. });
  8898. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8899. svr.wait_until_ready();
  8900. Client cli(HOST, PORT);
  8901. auto res = cli.Post("/hi", "data", "text/plain");
  8902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8903. EXPECT_EQ(StatusCode::OK_200, res->status);
  8904. svr.stop();
  8905. thread.join();
  8906. ASSERT_FALSE(svr.is_running());
  8907. res = cli.Post("/hi", "data", "text/plain");
  8908. ASSERT_FALSE(res);
  8909. }
  8910. TEST(ServerStopTest, ListenFailure) {
  8911. Server svr;
  8912. auto t = thread([&]() {
  8913. auto ret = svr.listen("????", PORT);
  8914. EXPECT_FALSE(ret);
  8915. });
  8916. svr.wait_until_ready();
  8917. svr.stop();
  8918. t.join();
  8919. }
  8920. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8921. TEST(ServerStopTest, Decommision) {
  8922. Server svr;
  8923. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  8924. for (int i = 0; i < 4; i++) {
  8925. auto is_even = !(i % 2);
  8926. std::thread t{[&] {
  8927. try {
  8928. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8929. if (is_even) {
  8930. throw std::runtime_error("Some thing that happens to go wrong.");
  8931. }
  8932. svr.listen(HOST, PORT);
  8933. } catch (...) { svr.decommission(); }
  8934. }};
  8935. svr.wait_until_ready();
  8936. // Server is up
  8937. {
  8938. Client cli(HOST, PORT);
  8939. auto res = cli.Get("/hi");
  8940. if (is_even) {
  8941. EXPECT_FALSE(res);
  8942. } else {
  8943. EXPECT_TRUE(res);
  8944. EXPECT_EQ("hi...", res->body);
  8945. }
  8946. }
  8947. svr.stop();
  8948. t.join();
  8949. // Server is down...
  8950. {
  8951. Client cli(HOST, PORT);
  8952. auto res = cli.Get("/hi");
  8953. EXPECT_FALSE(res);
  8954. }
  8955. }
  8956. }
  8957. #endif
  8958. // Helper function for string body upload progress tests
  8959. template <typename SetupHandler, typename ClientCall>
  8960. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  8961. ClientCall &&client_call,
  8962. const string &body) {
  8963. Server svr;
  8964. setup_handler(svr);
  8965. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8966. auto se = detail::scope_exit([&] {
  8967. svr.stop();
  8968. t.join();
  8969. });
  8970. svr.wait_until_ready();
  8971. Client cli(HOST, PORT);
  8972. vector<uint64_t> progress_values;
  8973. bool progress_called = false;
  8974. auto res =
  8975. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  8976. progress_values.push_back(current);
  8977. progress_called = true;
  8978. return true;
  8979. });
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ(200, res->status);
  8982. EXPECT_TRUE(progress_called);
  8983. }
  8984. TEST(UploadProgressTest, PostStringBodyBasic) {
  8985. TestStringBodyUploadProgress(
  8986. [](Server &svr) {
  8987. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  8988. res.set_content("received", "text/plain");
  8989. });
  8990. },
  8991. [](Client &cli, const string &body, UploadProgress progress_callback) {
  8992. return cli.Post("/test", body, "text/plain", progress_callback);
  8993. },
  8994. "test data for upload progress");
  8995. }
  8996. TEST(UploadProgressTest, PutStringBodyBasic) {
  8997. TestStringBodyUploadProgress(
  8998. [](Server &svr) {
  8999. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9000. res.set_content("put received", "text/plain");
  9001. });
  9002. },
  9003. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9004. return cli.Put("/test", body, "text/plain", progress_callback);
  9005. },
  9006. "put test data for upload progress");
  9007. }
  9008. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9009. TestStringBodyUploadProgress(
  9010. [](Server &svr) {
  9011. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9012. res.set_content("patch received", "text/plain");
  9013. });
  9014. },
  9015. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9016. return cli.Patch("/test", body, "text/plain", progress_callback);
  9017. },
  9018. "patch test data for upload progress");
  9019. }
  9020. // Helper function for content provider upload progress tests
  9021. template <typename SetupHandler, typename ClientCall>
  9022. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9023. ClientCall &&client_call) {
  9024. Server svr;
  9025. setup_handler(svr);
  9026. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9027. auto se = detail::scope_exit([&] {
  9028. svr.stop();
  9029. t.join();
  9030. });
  9031. svr.wait_until_ready();
  9032. Client cli(HOST, PORT);
  9033. vector<uint64_t> progress_values;
  9034. auto res =
  9035. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9036. progress_values.push_back(current);
  9037. return true;
  9038. });
  9039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9040. EXPECT_EQ(200, res->status);
  9041. EXPECT_FALSE(progress_values.empty());
  9042. }
  9043. TEST(UploadProgressTest, PostContentProviderProgress) {
  9044. TestContentProviderUploadProgress(
  9045. [](Server &svr) {
  9046. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9047. res.set_content("provider received", "text/plain");
  9048. });
  9049. },
  9050. [](Client &cli, UploadProgress progress_callback) {
  9051. return cli.Post(
  9052. "/test", 10,
  9053. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9054. sink.os << "test data";
  9055. return true;
  9056. },
  9057. "text/plain", progress_callback);
  9058. });
  9059. }
  9060. // Helper function for multipart upload progress tests
  9061. template <typename SetupHandler, typename ClientCall>
  9062. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9063. ClientCall &&client_call,
  9064. const string &endpoint) {
  9065. Server svr;
  9066. setup_handler(svr);
  9067. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9068. auto se = detail::scope_exit([&] {
  9069. svr.stop();
  9070. t.join();
  9071. });
  9072. svr.wait_until_ready();
  9073. Client cli(HOST, PORT);
  9074. vector<uint64_t> progress_values;
  9075. UploadFormDataItems items = {
  9076. {"field1", "value1", "", ""},
  9077. {"field2", "longer value for progress tracking test", "", ""},
  9078. {"file1", "file content data for upload progress", "test.txt",
  9079. "text/plain"}};
  9080. auto res = client_call(cli, endpoint, items,
  9081. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9082. progress_values.push_back(current);
  9083. return true;
  9084. });
  9085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9086. EXPECT_EQ(200, res->status);
  9087. EXPECT_FALSE(progress_values.empty());
  9088. }
  9089. TEST(UploadProgressTest, PostMultipartProgress) {
  9090. TestMultipartUploadProgress(
  9091. [](Server &svr) {
  9092. svr.Post("/multipart", [](const Request &req, Response &res) {
  9093. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9094. res.set_content("multipart received", "text/plain");
  9095. });
  9096. },
  9097. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9098. UploadProgress progress_callback) {
  9099. return cli.Post(endpoint, items, progress_callback);
  9100. },
  9101. "/multipart");
  9102. }
  9103. // Helper function for basic download progress tests
  9104. template <typename SetupHandler, typename ClientCall>
  9105. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9106. ClientCall &&client_call, const string &endpoint,
  9107. size_t expected_content_size) {
  9108. Server svr;
  9109. setup_handler(svr);
  9110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9111. auto se = detail::scope_exit([&] {
  9112. svr.stop();
  9113. t.join();
  9114. });
  9115. svr.wait_until_ready();
  9116. Client cli(HOST, PORT);
  9117. vector<uint64_t> progress_values;
  9118. auto res = client_call(cli, endpoint,
  9119. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9120. progress_values.push_back(current);
  9121. return true;
  9122. });
  9123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9124. EXPECT_EQ(200, res->status);
  9125. EXPECT_FALSE(progress_values.empty());
  9126. EXPECT_EQ(expected_content_size, res->body.size());
  9127. }
  9128. TEST(DownloadProgressTest, GetBasic) {
  9129. TestBasicDownloadProgress(
  9130. [](Server &svr) {
  9131. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9132. string content(1000, 'D');
  9133. res.set_content(content, "text/plain");
  9134. });
  9135. },
  9136. [](Client &cli, const string &endpoint,
  9137. DownloadProgress progress_callback) {
  9138. return cli.Get(endpoint, progress_callback);
  9139. },
  9140. "/download", 1000u);
  9141. }
  9142. // Helper function for content receiver download progress tests
  9143. template <typename SetupHandler, typename ClientCall>
  9144. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9145. ClientCall &&client_call,
  9146. const string &endpoint,
  9147. size_t expected_content_size) {
  9148. Server svr;
  9149. setup_handler(svr);
  9150. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9151. auto se = detail::scope_exit([&] {
  9152. svr.stop();
  9153. t.join();
  9154. });
  9155. svr.wait_until_ready();
  9156. Client cli(HOST, PORT);
  9157. vector<uint64_t> progress_values;
  9158. string received_body;
  9159. auto res = client_call(
  9160. cli, endpoint,
  9161. [&](const char *data, size_t data_length) -> bool {
  9162. received_body.append(data, data_length);
  9163. return true;
  9164. },
  9165. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9166. progress_values.push_back(current);
  9167. return true;
  9168. });
  9169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9170. EXPECT_EQ(200, res->status);
  9171. EXPECT_FALSE(progress_values.empty());
  9172. EXPECT_EQ(expected_content_size, received_body.size());
  9173. EXPECT_TRUE(res->body.empty());
  9174. }
  9175. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9176. TestContentReceiverDownloadProgress(
  9177. [](Server &svr) {
  9178. svr.Get("/download-receiver",
  9179. [](const Request & /*req*/, Response &res) {
  9180. string content(2000, 'R');
  9181. res.set_content(content, "text/plain");
  9182. });
  9183. },
  9184. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9185. DownloadProgress progress_callback) {
  9186. return cli.Get(endpoint, content_receiver, progress_callback);
  9187. },
  9188. "/download-receiver", 2000u);
  9189. }
  9190. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9191. // A provider reaching a pass with nothing to hand over - an empty buffer
  9192. // popped off a queue, say - must not be taken to mean the body is finished.
  9193. // It used to end the loop with the terminating chunk unwritten while the
  9194. // server still considered the response complete, so the peer waited for an
  9195. // end that never arrived.
  9196. Server svr;
  9197. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9198. auto step = std::make_shared<int>(0);
  9199. res.set_chunked_content_provider("text/plain",
  9200. [step](size_t /*offset*/, DataSink &sink) {
  9201. switch ((*step)++) {
  9202. case 0: sink.write("", 0); break;
  9203. case 1: sink.write("hello", 5); break;
  9204. default: sink.done(); break;
  9205. }
  9206. return true;
  9207. });
  9208. });
  9209. auto port = svr.bind_to_any_port(HOST);
  9210. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9211. auto listen_se = detail::scope_exit([&] {
  9212. svr.stop();
  9213. listen_thread.join();
  9214. ASSERT_FALSE(svr.is_running());
  9215. });
  9216. svr.wait_until_ready();
  9217. Client cli(HOST, port);
  9218. // Without the fix the body is never terminated, so bound the wait rather
  9219. // than letting the test hang on the default read timeout.
  9220. cli.set_read_timeout(5, 0);
  9221. auto res = cli.Get("/stream");
  9222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9223. EXPECT_EQ(StatusCode::OK_200, res->status);
  9224. EXPECT_EQ("hello", res->body);
  9225. }
  9226. TEST(StreamingTest, NoContentLengthStreaming) {
  9227. Server svr;
  9228. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9229. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9230. if (offset < 6) {
  9231. sink.os << (offset < 3 ? "a" : "b");
  9232. } else {
  9233. sink.done();
  9234. }
  9235. return true;
  9236. });
  9237. });
  9238. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9239. auto listen_se = detail::scope_exit([&] {
  9240. svr.stop();
  9241. listen_thread.join();
  9242. ASSERT_FALSE(svr.is_running());
  9243. });
  9244. svr.wait_until_ready();
  9245. Client client(HOST, PORT);
  9246. auto get_thread = std::thread([&client]() {
  9247. std::string s;
  9248. auto res =
  9249. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9250. s += std::string(data, len);
  9251. return true;
  9252. });
  9253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9254. EXPECT_EQ(StatusCode::OK_200, res->status);
  9255. EXPECT_EQ("aaabbb", s);
  9256. });
  9257. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9258. // Give GET time to get a few messages.
  9259. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9260. }
  9261. TEST(MountTest, Unmount) {
  9262. Server svr;
  9263. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9264. auto se = detail::scope_exit([&] {
  9265. svr.stop();
  9266. listen_thread.join();
  9267. ASSERT_FALSE(svr.is_running());
  9268. });
  9269. svr.wait_until_ready();
  9270. Client cli("localhost", PORT);
  9271. svr.set_mount_point("/mount2", "./www2");
  9272. auto res = cli.Get("/");
  9273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9274. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9275. res = cli.Get("/mount2/dir/test.html");
  9276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9277. EXPECT_EQ(StatusCode::OK_200, res->status);
  9278. svr.set_mount_point("/", "./www");
  9279. res = cli.Get("/dir/");
  9280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9281. EXPECT_EQ(StatusCode::OK_200, res->status);
  9282. svr.remove_mount_point("/");
  9283. res = cli.Get("/dir/");
  9284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9286. svr.remove_mount_point("/mount2");
  9287. res = cli.Get("/mount2/dir/test.html");
  9288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9290. }
  9291. TEST(MountTest, PathSegmentBoundary) {
  9292. Server svr;
  9293. svr.set_mount_point("/mount2", "./www2");
  9294. svr.set_mount_point("/", "./www");
  9295. auto port = svr.bind_to_any_port(HOST);
  9296. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9297. auto se = detail::scope_exit([&] {
  9298. svr.stop();
  9299. listen_thread.join();
  9300. ASSERT_FALSE(svr.is_running());
  9301. });
  9302. svr.wait_until_ready();
  9303. Client cli(HOST, port);
  9304. auto res = cli.Get("/mount2/dir/test.html");
  9305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9306. EXPECT_EQ(StatusCode::OK_200, res->status);
  9307. // "/mount2" must not match part-way through a path segment.
  9308. res = cli.Get("/mount2dir/test.html");
  9309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9310. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9311. // A mount point ending in '/' keeps matching every path below it.
  9312. res = cli.Get("/dir/test.html");
  9313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9314. EXPECT_EQ(StatusCode::OK_200, res->status);
  9315. }
  9316. TEST(MountTest, Redicect) {
  9317. Server svr;
  9318. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9319. auto se = detail::scope_exit([&] {
  9320. svr.stop();
  9321. listen_thread.join();
  9322. ASSERT_FALSE(svr.is_running());
  9323. });
  9324. svr.set_mount_point("/", "./www");
  9325. svr.wait_until_ready();
  9326. Client cli("localhost", PORT);
  9327. auto res = cli.Get("/dir/");
  9328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9329. EXPECT_EQ(StatusCode::OK_200, res->status);
  9330. res = cli.Get("/dir");
  9331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9332. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9333. res = cli.Get("/file");
  9334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9335. EXPECT_EQ(StatusCode::OK_200, res->status);
  9336. res = cli.Get("/file/");
  9337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9339. cli.set_follow_location(true);
  9340. res = cli.Get("/dir");
  9341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9342. EXPECT_EQ(StatusCode::OK_200, res->status);
  9343. }
  9344. TEST(MountTest, MultibytesPathName) {
  9345. Server svr;
  9346. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9347. auto se = detail::scope_exit([&] {
  9348. svr.stop();
  9349. listen_thread.join();
  9350. ASSERT_FALSE(svr.is_running());
  9351. });
  9352. svr.set_mount_point("/", "./www");
  9353. svr.wait_until_ready();
  9354. Client cli("localhost", PORT);
  9355. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9357. EXPECT_EQ(StatusCode::OK_200, res->status);
  9358. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9359. }
  9360. #ifdef _WIN32
  9361. // Issue #2435: mmap::open() must succeed even when another handle holds
  9362. // the file open for writing (e.g. an active log file).
  9363. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9364. const char *path = "mmap_concurrent_writer_test.txt";
  9365. const char *content = "hello";
  9366. {
  9367. std::ofstream f(path, std::ios::binary);
  9368. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9369. }
  9370. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9371. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9372. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9373. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9374. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9375. detail::mmap m(path);
  9376. ASSERT_TRUE(m.is_open());
  9377. EXPECT_EQ(strlen(content), m.size());
  9378. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9379. }
  9380. #endif
  9381. #ifndef _WIN32
  9382. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9383. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9384. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9385. TEST(MmapTest, FailedMappingIsNotOpen) {
  9386. const char *path = "./mmap_failed_mapping_test_dir";
  9387. ASSERT_EQ(0, ::mkdir(path, 0755));
  9388. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9389. detail::mmap m(path);
  9390. EXPECT_FALSE(m.is_open());
  9391. EXPECT_EQ(0U, m.size());
  9392. EXPECT_NE(static_cast<const void *>(m.data()),
  9393. static_cast<const void *>(MAP_FAILED));
  9394. }
  9395. #endif
  9396. TEST(KeepAliveTest, ReadTimeout) {
  9397. Server svr;
  9398. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9399. std::this_thread::sleep_for(std::chrono::seconds(2));
  9400. res.set_content("a", "text/plain");
  9401. });
  9402. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9403. res.set_content("b", "text/plain");
  9404. });
  9405. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9406. auto se = detail::scope_exit([&] {
  9407. svr.stop();
  9408. listen_thread.join();
  9409. ASSERT_FALSE(svr.is_running());
  9410. });
  9411. svr.wait_until_ready();
  9412. Client cli("localhost", PORT);
  9413. cli.set_keep_alive(true);
  9414. cli.set_read_timeout(std::chrono::seconds(1));
  9415. auto resa = cli.Get("/a");
  9416. ASSERT_FALSE(resa);
  9417. EXPECT_EQ(Error::Read, resa.error());
  9418. auto resb = cli.Get("/b");
  9419. ASSERT_TRUE(resb);
  9420. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9421. EXPECT_EQ("b", resb->body);
  9422. }
  9423. TEST(KeepAliveTest, MaxCount) {
  9424. size_t keep_alive_max_count = 3;
  9425. Server svr;
  9426. svr.set_keep_alive_max_count(keep_alive_max_count);
  9427. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9428. res.set_content("Hello World!", "text/plain");
  9429. });
  9430. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9431. auto se = detail::scope_exit([&] {
  9432. svr.stop();
  9433. listen_thread.join();
  9434. ASSERT_FALSE(svr.is_running());
  9435. });
  9436. svr.wait_until_ready();
  9437. Client cli(HOST, PORT);
  9438. cli.set_keep_alive(true);
  9439. for (size_t i = 0; i < 5; i++) {
  9440. auto result = cli.Get("/hi");
  9441. ASSERT_TRUE(result);
  9442. EXPECT_EQ(StatusCode::OK_200, result->status);
  9443. if (i == keep_alive_max_count - 1) {
  9444. EXPECT_EQ("close", result->get_header_value("Connection"));
  9445. } else {
  9446. EXPECT_FALSE(result->has_header("Connection"));
  9447. }
  9448. }
  9449. }
  9450. TEST(KeepAliveTest, Issue1041) {
  9451. Server svr;
  9452. svr.set_keep_alive_timeout(3);
  9453. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9454. res.set_content("Hello World!", "text/plain");
  9455. });
  9456. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9457. auto se = detail::scope_exit([&] {
  9458. svr.stop();
  9459. listen_thread.join();
  9460. ASSERT_FALSE(svr.is_running());
  9461. });
  9462. svr.wait_until_ready();
  9463. Client cli(HOST, PORT);
  9464. cli.set_keep_alive(true);
  9465. auto result = cli.Get("/hi");
  9466. ASSERT_TRUE(result);
  9467. EXPECT_EQ(StatusCode::OK_200, result->status);
  9468. std::this_thread::sleep_for(std::chrono::seconds(5));
  9469. result = cli.Get("/hi");
  9470. ASSERT_TRUE(result);
  9471. EXPECT_EQ(StatusCode::OK_200, result->status);
  9472. }
  9473. TEST(KeepAliveTest, Issue1959) {
  9474. Server svr;
  9475. svr.set_keep_alive_timeout(5);
  9476. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9477. res.set_content("a", "text/plain");
  9478. });
  9479. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9480. auto se = detail::scope_exit([&] {
  9481. if (!svr.is_running()) return;
  9482. svr.stop();
  9483. listen_thread.join();
  9484. ASSERT_FALSE(svr.is_running());
  9485. });
  9486. svr.wait_until_ready();
  9487. Client cli("localhost", PORT);
  9488. cli.set_keep_alive(true);
  9489. using namespace std::chrono;
  9490. auto start = steady_clock::now();
  9491. cli.Get("/a");
  9492. svr.stop();
  9493. listen_thread.join();
  9494. auto end = steady_clock::now();
  9495. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9496. EXPECT_LT(elapsed, 5000);
  9497. }
  9498. #ifdef CPPHTTPLIB_SSL_ENABLED
  9499. TEST(KeepAliveTest, SSLClientReconnection) {
  9500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9501. ASSERT_TRUE(svr.is_valid());
  9502. svr.set_keep_alive_timeout(1);
  9503. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9504. res.set_content("Hello World!", "text/plain");
  9505. });
  9506. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9507. auto se = detail::scope_exit([&] {
  9508. svr.stop();
  9509. listen_thread.join();
  9510. ASSERT_FALSE(svr.is_running());
  9511. });
  9512. svr.wait_until_ready();
  9513. SSLClient cli(HOST, PORT);
  9514. cli.enable_server_certificate_verification(false);
  9515. cli.set_keep_alive(true);
  9516. auto result = cli.Get("/hi");
  9517. ASSERT_TRUE(result);
  9518. EXPECT_EQ(StatusCode::OK_200, result->status);
  9519. result = cli.Get("/hi");
  9520. ASSERT_TRUE(result);
  9521. EXPECT_EQ(StatusCode::OK_200, result->status);
  9522. std::this_thread::sleep_for(std::chrono::seconds(2));
  9523. // Recoonect
  9524. result = cli.Get("/hi");
  9525. ASSERT_TRUE(result);
  9526. EXPECT_EQ(StatusCode::OK_200, result->status);
  9527. result = cli.Get("/hi");
  9528. ASSERT_TRUE(result);
  9529. EXPECT_EQ(StatusCode::OK_200, result->status);
  9530. }
  9531. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9533. ASSERT_TRUE(svr.is_valid());
  9534. svr.set_keep_alive_timeout(1);
  9535. std::string content = "reconnect";
  9536. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9537. res.set_content("Hello World!", "text/plain");
  9538. });
  9539. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9540. auto se = detail::scope_exit([&] {
  9541. svr.stop();
  9542. listen_thread.join();
  9543. ASSERT_FALSE(svr.is_running());
  9544. });
  9545. svr.wait_until_ready();
  9546. SSLClient cli(HOST, PORT);
  9547. cli.enable_server_certificate_verification(false);
  9548. cli.set_keep_alive(true);
  9549. auto result = cli.Post(
  9550. "/hi", content.size(),
  9551. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9552. sink.write(content.c_str(), content.size());
  9553. return true;
  9554. },
  9555. "text/plain");
  9556. ASSERT_TRUE(result);
  9557. EXPECT_EQ(200, result->status);
  9558. std::this_thread::sleep_for(std::chrono::seconds(2));
  9559. // Recoonect
  9560. result = cli.Post(
  9561. "/hi", content.size(),
  9562. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9563. sink.write(content.c_str(), content.size());
  9564. return true;
  9565. },
  9566. "text/plain");
  9567. ASSERT_TRUE(result);
  9568. EXPECT_EQ(200, result->status);
  9569. result = cli.Post(
  9570. "/hi", content.size(),
  9571. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9572. sink.write(content.c_str(), content.size());
  9573. return true;
  9574. },
  9575. "text/plain");
  9576. ASSERT_TRUE(result);
  9577. EXPECT_EQ(200, result->status);
  9578. }
  9579. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9580. using namespace httplib::tls;
  9581. {
  9582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9583. ASSERT_TRUE(svr.is_valid());
  9584. svr.Get("/sni", [&](const Request &req, Response &res) {
  9585. std::string expected = req.sni();
  9586. EXPECT_EQ(expected, req.get_param_value("expected"));
  9587. res.set_content("ok", "text/plain");
  9588. });
  9589. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9590. auto se = detail::scope_exit([&] {
  9591. svr.stop();
  9592. listen_thread.join();
  9593. ASSERT_FALSE(svr.is_running());
  9594. });
  9595. svr.wait_until_ready();
  9596. {
  9597. SSLClient cli("localhost", PORT);
  9598. cli.enable_server_certificate_verification(false);
  9599. auto res = cli.Get("/sni?expected=localhost");
  9600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9601. }
  9602. {
  9603. SSLClient cli("::1", PORT);
  9604. cli.enable_server_certificate_verification(false);
  9605. auto res = cli.Get("/sni?expected=");
  9606. // NOTE: This may fail if the server is listening on IPv4 only
  9607. // (e.g., when localhost resolves to 127.0.0.1 only)
  9608. if (res) {
  9609. EXPECT_EQ(StatusCode::OK_200, res->status);
  9610. } else {
  9611. EXPECT_EQ(Error::Connection, res.error());
  9612. }
  9613. }
  9614. }
  9615. }
  9616. #endif
  9617. TEST(ClientProblemDetectionTest, ContentProvider) {
  9618. Server svr;
  9619. size_t content_length = 1024 * 1024;
  9620. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9621. res.set_content_provider(
  9622. content_length, "text/plain",
  9623. [&](size_t offset, size_t length, DataSink &sink) {
  9624. auto out_len = std::min(length, static_cast<size_t>(1024));
  9625. std::string out(out_len, '@');
  9626. sink.write(out.data(), out_len);
  9627. return offset < 4096;
  9628. },
  9629. [](bool success) { ASSERT_FALSE(success); });
  9630. });
  9631. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9632. res.set_content_provider(
  9633. 0, "text/plain",
  9634. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9635. EXPECT_TRUE(false);
  9636. return true;
  9637. },
  9638. [](bool success) { ASSERT_FALSE(success); });
  9639. });
  9640. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9641. auto se = detail::scope_exit([&] {
  9642. svr.stop();
  9643. listen_thread.join();
  9644. ASSERT_FALSE(svr.is_running());
  9645. });
  9646. svr.wait_until_ready();
  9647. Client cli("localhost", PORT);
  9648. {
  9649. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9650. size_t /*data_length*/) { return false; });
  9651. ASSERT_FALSE(res);
  9652. }
  9653. {
  9654. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9655. size_t /*data_length*/) { return false; });
  9656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9657. }
  9658. }
  9659. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9660. // A provider that reports success without writing anything and without
  9661. // calling done() used to be handed the same offset and length again on every
  9662. // pass, so it spun for as long as the peer stayed connected.
  9663. Server svr;
  9664. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9665. res.set_content("ok", "text/plain");
  9666. });
  9667. auto port = svr.bind_to_any_port(HOST);
  9668. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9669. auto se = detail::scope_exit([&] {
  9670. svr.stop();
  9671. listen_thread.join();
  9672. ASSERT_FALSE(svr.is_running());
  9673. });
  9674. svr.wait_until_ready();
  9675. std::atomic<int> call_count{0};
  9676. Client cli(HOST, port);
  9677. auto res = cli.Post(
  9678. "/", 1024,
  9679. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9680. // Give up after enough passes to show the spin, so that losing the
  9681. // check below fails this test instead of hanging it.
  9682. return ++call_count < 100;
  9683. },
  9684. "text/plain");
  9685. ASSERT_FALSE(res);
  9686. EXPECT_EQ(Error::Write, res.error());
  9687. EXPECT_EQ(1, call_count.load());
  9688. }
  9689. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9690. // A writer only has to assign `write`. The other three used to be left as
  9691. // empty std::functions, so a provider calling one threw
  9692. // std::bad_function_call out of the thread running it and took the whole
  9693. // process down.
  9694. DataSink sink;
  9695. std::string written;
  9696. sink.write = [&](const char *data, size_t data_len) {
  9697. written.append(data, data_len);
  9698. return true;
  9699. };
  9700. EXPECT_TRUE(sink.is_writable());
  9701. sink.done();
  9702. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9703. EXPECT_TRUE(written.empty());
  9704. }
  9705. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9706. // A sink that cannot carry trailers still has to finish.
  9707. DataSink sink;
  9708. auto done_count = 0;
  9709. sink.done = [&]() { done_count++; };
  9710. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9711. EXPECT_EQ(1, done_count);
  9712. }
  9713. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9714. Server svr;
  9715. const std::string body(4096, 'x');
  9716. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9717. res.set_content_provider(body.size(), "text/plain",
  9718. [&](size_t offset, size_t length, DataSink &sink) {
  9719. sink.write(body.data() + offset, length);
  9720. sink.done();
  9721. return true;
  9722. });
  9723. });
  9724. auto port = svr.bind_to_any_port(HOST);
  9725. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9726. auto se = detail::scope_exit([&] {
  9727. svr.stop();
  9728. listen_thread.join();
  9729. ASSERT_FALSE(svr.is_running());
  9730. });
  9731. svr.wait_until_ready();
  9732. Client cli(HOST, port);
  9733. auto res = cli.Get("/");
  9734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9735. EXPECT_EQ(StatusCode::OK_200, res->status);
  9736. EXPECT_EQ(body, res->body);
  9737. }
  9738. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9739. Server svr;
  9740. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9741. res.set_content_provider(
  9742. 1024, "text/plain",
  9743. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9744. sink.write("hello", 5);
  9745. sink.done(); // short of the 1024 bytes the response promised
  9746. return true;
  9747. });
  9748. });
  9749. auto port = svr.bind_to_any_port(HOST);
  9750. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. listen_thread.join();
  9754. ASSERT_FALSE(svr.is_running());
  9755. });
  9756. svr.wait_until_ready();
  9757. Client cli(HOST, port);
  9758. cli.set_read_timeout(5, 0);
  9759. // The response is short of its Content-Length, so the client cannot read a
  9760. // complete body. What matters is that this returns at all: a no-op done()
  9761. // would leave the writer looping over a provider that never makes progress.
  9762. auto res = cli.Get("/");
  9763. EXPECT_FALSE(res);
  9764. }
  9765. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9766. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9767. // The compressed path builds the whole body before connecting, so this
  9768. // fails client-side and never reaches a server.
  9769. Client cli(HOST, PORT);
  9770. cli.set_compress(true);
  9771. auto res = cli.Post(
  9772. "/", 1024,
  9773. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9774. sink.write("hello", 5);
  9775. sink.done(); // short of the 1024 bytes the request announced
  9776. return true;
  9777. },
  9778. "text/plain");
  9779. ASSERT_FALSE(res);
  9780. EXPECT_EQ(Error::Write, res.error());
  9781. }
  9782. #endif
  9783. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9784. Server svr;
  9785. svr.set_error_handler([](Request const &, Response &res) -> void {
  9786. res.set_chunked_content_provider(
  9787. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9788. sink.os << "hello";
  9789. sink.os << "world";
  9790. sink.done();
  9791. return true;
  9792. });
  9793. });
  9794. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9795. auto se = detail::scope_exit([&] {
  9796. svr.stop();
  9797. listen_thread.join();
  9798. ASSERT_FALSE(svr.is_running());
  9799. });
  9800. svr.wait_until_ready();
  9801. Client cli("localhost", PORT);
  9802. auto res = cli.Get("/");
  9803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9804. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9805. EXPECT_EQ("helloworld", res->body);
  9806. }
  9807. TEST(LongPollingTest, ClientCloseDetection) {
  9808. Server svr;
  9809. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9810. res.set_chunked_content_provider(
  9811. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9812. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9813. sink.os << "hello";
  9814. auto count = 10;
  9815. while (count > 0 && sink.is_writable()) {
  9816. this_thread::sleep_for(chrono::milliseconds(10));
  9817. count--;
  9818. }
  9819. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9820. return true;
  9821. });
  9822. });
  9823. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9824. auto se = detail::scope_exit([&] {
  9825. svr.stop();
  9826. listen_thread.join();
  9827. ASSERT_FALSE(svr.is_running());
  9828. });
  9829. svr.wait_until_ready();
  9830. Client cli("localhost", PORT);
  9831. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9832. EXPECT_EQ("hello", string(data, data_length));
  9833. return false; // close the socket immediately.
  9834. });
  9835. ASSERT_FALSE(res);
  9836. }
  9837. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9838. Server svr;
  9839. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9840. res.set_chunked_content_provider(
  9841. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9842. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9843. sink.os << "hello";
  9844. EXPECT_TRUE(sink.os.good());
  9845. // Wait for the client to close the connection
  9846. auto count = 10;
  9847. while (count > 0 && sink.is_writable()) {
  9848. this_thread::sleep_for(chrono::milliseconds(10));
  9849. count--;
  9850. }
  9851. // After client disconnect, write repeatedly until the socket
  9852. // write actually fails (small writes may be absorbed by the
  9853. // kernel buffer)
  9854. std::string chunk(1024, 'x');
  9855. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  9856. sink.os << chunk;
  9857. }
  9858. EXPECT_TRUE(sink.os.fail());
  9859. return true;
  9860. });
  9861. });
  9862. auto port = svr.bind_to_any_port("localhost");
  9863. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9864. auto se = detail::scope_exit([&] {
  9865. svr.stop();
  9866. listen_thread.join();
  9867. ASSERT_FALSE(svr.is_running());
  9868. });
  9869. svr.wait_until_ready();
  9870. Client cli("localhost", port);
  9871. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9872. EXPECT_EQ("hello", string(data, data_length));
  9873. return false; // close the socket immediately.
  9874. });
  9875. ASSERT_FALSE(res);
  9876. }
  9877. TEST(GetWithParametersTest, GetWithParameters) {
  9878. Server svr;
  9879. svr.Get("/", [&](const Request &req, Response &) {
  9880. EXPECT_EQ("world", req.get_param_value("hello"));
  9881. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9882. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9883. });
  9884. svr.Get("/params", [&](const Request &req, Response &) {
  9885. EXPECT_EQ("world", req.get_param_value("hello"));
  9886. EXPECT_EQ("world2", req.get_param_value("hello2"));
  9887. EXPECT_EQ("world3", req.get_param_value("hello3"));
  9888. });
  9889. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  9890. EXPECT_EQ("resource-id", req.matches[1]);
  9891. EXPECT_EQ("foo", req.get_param_value("param1"));
  9892. EXPECT_EQ("bar", req.get_param_value("param2"));
  9893. });
  9894. svr.Get("/users/:id", [&](const Request &req, Response &) {
  9895. EXPECT_EQ("user-id", req.path_params.at("id"));
  9896. EXPECT_EQ("foo", req.get_param_value("param1"));
  9897. EXPECT_EQ("bar", req.get_param_value("param2"));
  9898. });
  9899. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9900. auto se = detail::scope_exit([&] {
  9901. svr.stop();
  9902. listen_thread.join();
  9903. ASSERT_FALSE(svr.is_running());
  9904. });
  9905. svr.wait_until_ready();
  9906. {
  9907. Client cli(HOST, PORT);
  9908. Params params;
  9909. params.emplace("hello", "world");
  9910. params.emplace("hello2", "world2");
  9911. params.emplace("hello3", "world3");
  9912. auto res = cli.Get("/", params, Headers{});
  9913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9914. EXPECT_EQ(StatusCode::OK_200, res->status);
  9915. }
  9916. {
  9917. Client cli(HOST, PORT);
  9918. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  9919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9920. EXPECT_EQ(StatusCode::OK_200, res->status);
  9921. }
  9922. {
  9923. Client cli(HOST, PORT);
  9924. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  9925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9926. EXPECT_EQ(StatusCode::OK_200, res->status);
  9927. }
  9928. {
  9929. Client cli(HOST, PORT);
  9930. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  9931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9932. EXPECT_EQ(StatusCode::OK_200, res->status);
  9933. }
  9934. }
  9935. TEST(GetWithParametersTest, GetWithParameters2) {
  9936. Server svr;
  9937. svr.Get("/", [&](const Request &req, Response &res) {
  9938. auto text = req.get_param_value("hello");
  9939. res.set_content(text, "text/plain");
  9940. });
  9941. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. listen_thread.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. Client cli("localhost", PORT);
  9949. Params params;
  9950. params.emplace("hello", "world");
  9951. std::string body;
  9952. auto res = cli.Get("/", params, Headers{},
  9953. [&](const char *data, size_t data_length) {
  9954. body.append(data, data_length);
  9955. return true;
  9956. });
  9957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9958. EXPECT_EQ(StatusCode::OK_200, res->status);
  9959. EXPECT_EQ("world", body);
  9960. }
  9961. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  9962. Server svr;
  9963. svr.Get("/search", [&](const Request &req, Response &res) {
  9964. auto q = req.get_param_value("q");
  9965. res.set_content(q, "text/plain");
  9966. });
  9967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. listen_thread.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. });
  9973. svr.wait_until_ready();
  9974. Client cli("localhost", PORT);
  9975. // Verify that Get(path, params) works without requiring Headers argument
  9976. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  9977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9978. EXPECT_EQ(StatusCode::OK_200, res->status);
  9979. EXPECT_EQ("cpp-httplib", res->body);
  9980. }
  9981. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  9982. auto host = "httpbingo.org";
  9983. auto path = std::string{"/range/32"};
  9984. #ifdef CPPHTTPLIB_SSL_ENABLED
  9985. SSLClient cli(host);
  9986. #else
  9987. Client cli(host);
  9988. #endif
  9989. cli.set_default_headers({make_range_header({{1, 10}})});
  9990. cli.set_connection_timeout(5);
  9991. {
  9992. auto res = cli.Get(path);
  9993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9994. EXPECT_EQ("bcdefghijk", res->body);
  9995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9996. }
  9997. {
  9998. auto res = cli.Get(path);
  9999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10000. EXPECT_EQ("bcdefghijk", res->body);
  10001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10002. }
  10003. }
  10004. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10005. Server svr;
  10006. svr.set_default_headers({{"Hello", "World"}});
  10007. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10008. res.set_content("ok", "text/plain");
  10009. });
  10010. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. listen_thread.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. Client cli("localhost", PORT);
  10018. auto res = cli.Get("/");
  10019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10020. EXPECT_EQ(StatusCode::OK_200, res->status);
  10021. EXPECT_EQ("ok", res->body);
  10022. EXPECT_EQ("World", res->get_header_value("Hello"));
  10023. }
  10024. #ifdef CPPHTTPLIB_SSL_ENABLED
  10025. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10026. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10027. ASSERT_TRUE(svr.is_valid());
  10028. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10029. std::this_thread::sleep_for(std::chrono::seconds(2));
  10030. res.set_content("a", "text/plain");
  10031. });
  10032. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10033. res.set_content("b", "text/plain");
  10034. });
  10035. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10036. auto se = detail::scope_exit([&] {
  10037. svr.stop();
  10038. listen_thread.join();
  10039. ASSERT_FALSE(svr.is_running());
  10040. });
  10041. svr.wait_until_ready();
  10042. SSLClient cli("localhost", PORT);
  10043. cli.enable_server_certificate_verification(false);
  10044. cli.set_keep_alive(true);
  10045. cli.set_read_timeout(std::chrono::seconds(1));
  10046. auto resa = cli.Get("/a");
  10047. ASSERT_TRUE(!resa);
  10048. EXPECT_EQ(Error::Read, resa.error());
  10049. auto resb = cli.Get("/b");
  10050. ASSERT_TRUE(resb);
  10051. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10052. EXPECT_EQ("b", resb->body);
  10053. }
  10054. #endif
  10055. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10056. protected:
  10057. ServerTestWithAI_PASSIVE()
  10058. : cli_(HOST, PORT)
  10059. #ifdef CPPHTTPLIB_SSL_ENABLED
  10060. ,
  10061. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10062. #endif
  10063. {
  10064. #ifdef CPPHTTPLIB_SSL_ENABLED
  10065. cli_.enable_server_certificate_verification(false);
  10066. #endif
  10067. }
  10068. virtual void SetUp() {
  10069. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10070. res.set_content("Hello World!", "text/plain");
  10071. });
  10072. t_ = thread(
  10073. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10074. svr_.wait_until_ready();
  10075. }
  10076. virtual void TearDown() {
  10077. svr_.stop();
  10078. t_.join();
  10079. }
  10080. #ifdef CPPHTTPLIB_SSL_ENABLED
  10081. SSLClient cli_;
  10082. SSLServer svr_;
  10083. #else
  10084. Client cli_;
  10085. Server svr_;
  10086. #endif
  10087. thread t_;
  10088. };
  10089. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10090. auto res = cli_.Get("/hi");
  10091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10092. EXPECT_EQ(StatusCode::OK_200, res->status);
  10093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10094. EXPECT_EQ("Hello World!", res->body);
  10095. }
  10096. class ServerUpDownTest : public ::testing::Test {
  10097. protected:
  10098. ServerUpDownTest() : cli_(HOST, PORT) {}
  10099. virtual void SetUp() {
  10100. t_ = thread([&]() {
  10101. svr_.bind_to_any_port(HOST);
  10102. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10103. ASSERT_TRUE(svr_.listen_after_bind());
  10104. });
  10105. svr_.wait_until_ready();
  10106. }
  10107. virtual void TearDown() {
  10108. svr_.stop();
  10109. t_.join();
  10110. }
  10111. Client cli_;
  10112. Server svr_;
  10113. thread t_;
  10114. };
  10115. TEST_F(ServerUpDownTest, QuickStartStop) {
  10116. // Should not crash, especially when run with
  10117. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10118. }
  10119. class PayloadMaxLengthTest : public ::testing::Test {
  10120. protected:
  10121. PayloadMaxLengthTest()
  10122. : cli_(HOST, PORT)
  10123. #ifdef CPPHTTPLIB_SSL_ENABLED
  10124. ,
  10125. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10126. #endif
  10127. {
  10128. #ifdef CPPHTTPLIB_SSL_ENABLED
  10129. cli_.enable_server_certificate_verification(false);
  10130. #endif
  10131. }
  10132. virtual void SetUp() {
  10133. svr_.set_payload_max_length(8);
  10134. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10135. res.set_content("test", "text/plain");
  10136. });
  10137. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10138. svr_.wait_until_ready();
  10139. }
  10140. virtual void TearDown() {
  10141. svr_.stop();
  10142. t_.join();
  10143. }
  10144. #ifdef CPPHTTPLIB_SSL_ENABLED
  10145. SSLClient cli_;
  10146. SSLServer svr_;
  10147. #else
  10148. Client cli_;
  10149. Server svr_;
  10150. #endif
  10151. thread t_;
  10152. };
  10153. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10154. auto res = cli_.Post("/test", "123456789", "text/plain");
  10155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10156. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10157. res = cli_.Post("/test", "12345678", "text/plain");
  10158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10159. EXPECT_EQ(StatusCode::OK_200, res->status);
  10160. }
  10161. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10162. // Test chunked encoding with payload exceeding the 8-byte limit
  10163. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10164. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10167. }
  10168. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10169. // Test chunked encoding with payload within the 8-byte limit
  10170. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10171. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10173. EXPECT_EQ(StatusCode::OK_200, res->status);
  10174. }
  10175. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10176. // Test using send_request to send chunked data exceeding payload limit
  10177. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10178. "Host: " +
  10179. std::string(HOST) + ":" + std::to_string(PORT) +
  10180. "\r\n"
  10181. "Transfer-Encoding: chunked\r\n"
  10182. "Connection: close\r\n"
  10183. "\r\n"
  10184. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10185. "0123456789\r\n"
  10186. "0\r\n" // End chunk
  10187. "\r\n";
  10188. std::string response;
  10189. bool result = send_request(1, chunked_request, &response);
  10190. if (!result) {
  10191. // If send_request fails, it might be because the server closed the
  10192. // connection due to payload limit enforcement, which is acceptable
  10193. SUCCEED()
  10194. << "Server rejected oversized chunked request (connection closed)";
  10195. } else {
  10196. // If we got a response, check if it's an error response or connection was
  10197. // closed early Short response length indicates connection was closed due to
  10198. // payload limit
  10199. if (response.length() <= 10) {
  10200. SUCCEED() << "Server closed connection for oversized chunked request";
  10201. } else {
  10202. // Check for error status codes
  10203. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10204. response.find("Payload Too Large") != std::string::npos ||
  10205. response.find("400") != std::string::npos);
  10206. }
  10207. }
  10208. }
  10209. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10210. // Test request without Content-Length header exceeding payload limit
  10211. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10212. "Host: " +
  10213. std::string(HOST) + ":" +
  10214. std::to_string(PORT) +
  10215. "\r\n"
  10216. "Connection: close\r\n"
  10217. "\r\n";
  10218. // Add payload exceeding the 8-byte limit
  10219. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10220. request_without_content_length += large_payload;
  10221. std::string response;
  10222. bool result = send_request(1, request_without_content_length, &response);
  10223. if (!result) {
  10224. // If send_request fails, server likely closed connection due to payload
  10225. // limit
  10226. SUCCEED() << "Server rejected oversized request without Content-Length "
  10227. "(connection closed)";
  10228. } else {
  10229. // Check if server responded with error or closed connection early
  10230. if (response.length() <= 10) {
  10231. SUCCEED() << "Server closed connection for oversized request without "
  10232. "Content-Length";
  10233. } else {
  10234. // Check for error status codes
  10235. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10236. response.find("Payload Too Large") != std::string::npos ||
  10237. response.find("400") != std::string::npos);
  10238. }
  10239. }
  10240. }
  10241. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10242. // Test request without Content-Length header within payload limit
  10243. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10244. "Host: " +
  10245. std::string(HOST) + ":" +
  10246. std::to_string(PORT) +
  10247. "\r\n"
  10248. "Connection: close\r\n"
  10249. "\r\n";
  10250. // Add payload within the 8-byte limit
  10251. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10252. request_without_content_length += small_payload;
  10253. std::string response;
  10254. bool result = send_request(1, request_without_content_length, &response);
  10255. // For requests without Content-Length, the server may have different behavior
  10256. // The key is that it should not reject due to payload limit for small
  10257. // payloads
  10258. if (result) {
  10259. // Check for any HTTP response (success or error, but not connection closed)
  10260. if (response.length() > 10) {
  10261. SUCCEED()
  10262. << "Server processed request without Content-Length within limit";
  10263. } else {
  10264. // Short response might indicate connection closed, which is acceptable
  10265. SUCCEED() << "Server closed connection for request without "
  10266. "Content-Length (acceptable behavior)";
  10267. }
  10268. } else {
  10269. // Connection failure might be due to protocol requirements
  10270. SUCCEED() << "Connection issue with request without Content-Length "
  10271. "(environment-specific)";
  10272. }
  10273. }
  10274. class LargePayloadMaxLengthTest : public ::testing::Test {
  10275. protected:
  10276. LargePayloadMaxLengthTest()
  10277. : cli_(HOST, PORT)
  10278. #ifdef CPPHTTPLIB_SSL_ENABLED
  10279. ,
  10280. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10281. #endif
  10282. {
  10283. #ifdef CPPHTTPLIB_SSL_ENABLED
  10284. cli_.enable_server_certificate_verification(false);
  10285. #endif
  10286. }
  10287. virtual void SetUp() {
  10288. // Set 10MB payload limit
  10289. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10290. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10291. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10292. res.set_content("Large payload test", "text/plain");
  10293. });
  10294. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10295. svr_.wait_until_ready();
  10296. }
  10297. virtual void TearDown() {
  10298. svr_.stop();
  10299. t_.join();
  10300. }
  10301. #ifdef CPPHTTPLIB_SSL_ENABLED
  10302. SSLClient cli_;
  10303. SSLServer svr_;
  10304. #else
  10305. Client cli_;
  10306. Server svr_;
  10307. #endif
  10308. thread t_;
  10309. };
  10310. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10311. // Test chunked encoding with payload within 10MB limit
  10312. std::string medium_payload(5 * 1024 * 1024,
  10313. 'A'); // 5MB payload, within 10MB limit
  10314. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10316. EXPECT_EQ(StatusCode::OK_200, res->status);
  10317. }
  10318. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10319. // Test chunked encoding with payload exceeding 10MB limit
  10320. std::string large_payload(12 * 1024 * 1024,
  10321. 'B'); // 12MB payload, exceeds 10MB limit
  10322. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10323. // Server may either return 413 or close the connection
  10324. if (res) {
  10325. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10326. } else {
  10327. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10328. }
  10329. }
  10330. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10331. // Test request without Content-Length header within 10MB limit
  10332. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10333. "Host: " +
  10334. std::string(HOST) + ":" +
  10335. std::to_string(PORT) +
  10336. "\r\n"
  10337. "Connection: close\r\n"
  10338. "\r\n";
  10339. // Add 1MB payload (within 10MB limit)
  10340. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10341. request_without_content_length += medium_payload;
  10342. std::string response;
  10343. bool result = send_request(5, request_without_content_length, &response);
  10344. if (result) {
  10345. // Should get a proper HTTP response for payloads within limit
  10346. if (response.length() > 10) {
  10347. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10348. "10MB limit";
  10349. } else {
  10350. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10351. "Content-Length)";
  10352. }
  10353. } else {
  10354. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10355. }
  10356. }
  10357. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10358. // Test request without Content-Length header exceeding 10MB limit
  10359. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10360. "Host: " +
  10361. std::string(HOST) + ":" +
  10362. std::to_string(PORT) +
  10363. "\r\n"
  10364. "Connection: close\r\n"
  10365. "\r\n";
  10366. // Add 12MB payload (exceeds 10MB limit)
  10367. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10368. request_without_content_length += large_payload;
  10369. std::string response;
  10370. bool result = send_request(10, request_without_content_length, &response);
  10371. if (!result) {
  10372. // Server should close connection due to payload limit
  10373. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10374. "(connection closed)";
  10375. } else {
  10376. // Check for error response
  10377. if (response.length() <= 10) {
  10378. SUCCEED()
  10379. << "Server closed connection for 12MB request exceeding 10MB limit";
  10380. } else {
  10381. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10382. response.find("Payload Too Large") != std::string::npos ||
  10383. response.find("400") != std::string::npos);
  10384. }
  10385. }
  10386. }
  10387. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10388. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10389. // path.
  10390. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10391. Server svr;
  10392. const size_t LIMIT = 64 * 1024; // 64KB
  10393. svr.set_payload_max_length(LIMIT);
  10394. size_t total = 0;
  10395. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10396. const ContentReader &content_reader) {
  10397. content_reader([&](const char * /*data*/, size_t len) {
  10398. total += len;
  10399. return true;
  10400. });
  10401. res.status = 200;
  10402. res.set_content("stream_ok", "text/plain");
  10403. });
  10404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10405. auto se = detail::scope_exit([&] {
  10406. svr.stop();
  10407. thread.join();
  10408. ASSERT_FALSE(svr.is_running());
  10409. });
  10410. svr.wait_until_ready();
  10411. // Prepare 256KB raw data and gzip-compress it
  10412. std::string raw(256 * 1024, 'A');
  10413. std::string gz;
  10414. {
  10415. z_stream zs{};
  10416. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10417. Z_DEFAULT_STRATEGY);
  10418. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10419. zs.avail_in = static_cast<uInt>(raw.size());
  10420. char outbuf[4096];
  10421. int ret;
  10422. do {
  10423. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10424. zs.avail_out = sizeof(outbuf);
  10425. ret = deflate(&zs, Z_FINISH);
  10426. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10427. } while (ret != Z_STREAM_END);
  10428. deflateEnd(&zs);
  10429. }
  10430. Client cli(HOST, PORT);
  10431. cli.set_connection_timeout(std::chrono::seconds(5));
  10432. Headers headers = {{"Content-Encoding", "gzip"}};
  10433. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10434. "application/octet-stream");
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. // Server must reject oversized decompressed payloads with 413.
  10437. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10438. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10439. EXPECT_LE(total, LIMIT);
  10440. }
  10441. #ifndef CPPHTTPLIB_SSL_ENABLED
  10442. // For a request with neither Content-Length nor Transfer-Encoding, the
  10443. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10444. // compressed wire bytes straight to the ContentReader without ever routing
  10445. // them through the decompressor, so payload_max_length_ only bounded the
  10446. // compressed size on the wire, not the decompressed size.
  10447. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10448. Server svr;
  10449. const size_t LIMIT = 64 * 1024; // 64KB
  10450. svr.set_payload_max_length(LIMIT);
  10451. size_t total = 0;
  10452. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10453. const ContentReader &content_reader) {
  10454. content_reader([&](const char * /*data*/, size_t len) {
  10455. total += len;
  10456. return true;
  10457. });
  10458. res.status = 200;
  10459. res.set_content("stream_ok", "text/plain");
  10460. });
  10461. auto port = svr.bind_to_any_port(HOST);
  10462. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10463. auto se = detail::scope_exit([&] {
  10464. svr.stop();
  10465. thread.join();
  10466. ASSERT_FALSE(svr.is_running());
  10467. });
  10468. svr.wait_until_ready();
  10469. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10470. // StreamingGzipDecompression test above.
  10471. std::string raw(256 * 1024, 'A');
  10472. std::string gz;
  10473. {
  10474. httplib::detail::gzip_compressor compressor;
  10475. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10476. [&](const char *chunk, size_t len) {
  10477. gz.append(chunk, len);
  10478. return true;
  10479. });
  10480. ASSERT_TRUE(result);
  10481. }
  10482. // Send the gzip body over raw TCP with neither Content-Length nor
  10483. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10484. // kicks in.
  10485. std::string req = "POST /stream HTTP/1.1\r\n"
  10486. "Host: " +
  10487. std::string(HOST) + ":" + std::to_string(port) +
  10488. "\r\n"
  10489. "Content-Encoding: gzip\r\n"
  10490. "Connection: close\r\n"
  10491. "\r\n" +
  10492. gz;
  10493. std::string response;
  10494. ASSERT_TRUE(send_request(5, req, &response, port));
  10495. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10496. EXPECT_LE(total, LIMIT);
  10497. }
  10498. #endif
  10499. #endif
  10500. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10501. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10502. // the payload must be passed through untouched instead of being rejected.
  10503. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10504. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10505. Server svr;
  10506. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10507. res.set_content(body, "image/jpeg");
  10508. res.set_header("Content-Encoding", "UTF-8");
  10509. });
  10510. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10511. res.set_content(body, "image/jpeg");
  10512. res.set_header("Content-Encoding", "identity");
  10513. });
  10514. svr.Post("/echo", [](const Request &req, Response &res) {
  10515. res.set_content(req.body, "image/jpeg");
  10516. });
  10517. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10518. auto se = detail::scope_exit([&] {
  10519. svr.stop();
  10520. t.join();
  10521. ASSERT_FALSE(svr.is_running());
  10522. });
  10523. svr.wait_until_ready();
  10524. Client cli(HOST, PORT);
  10525. {
  10526. auto res = cli.Get("/image");
  10527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10528. EXPECT_EQ(StatusCode::OK_200, res->status);
  10529. EXPECT_EQ(body, res->body);
  10530. }
  10531. {
  10532. auto res = cli.Get("/identity");
  10533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10534. EXPECT_EQ(StatusCode::OK_200, res->status);
  10535. EXPECT_EQ(body, res->body);
  10536. }
  10537. {
  10538. // The same applies to a request body reaching the server.
  10539. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10540. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10542. EXPECT_EQ(StatusCode::OK_200, res->status);
  10543. EXPECT_EQ(body, res->body);
  10544. }
  10545. }
  10546. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10547. // gzip-encoded response even when the build has no zlib support.
  10548. static const char GZIPPED_HELLO_WORLD[] = {
  10549. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10550. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10551. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10552. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10553. // A content coding is a whole token, not something the field value merely
  10554. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10555. // as "fibre" look like Brotli, and turned a multi-coding value like
  10556. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10557. // it was never meant to see.
  10558. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10559. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10560. Server svr;
  10561. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10562. res.set_content(body, "image/jpeg");
  10563. res.set_header("Content-Encoding", "fibre");
  10564. });
  10565. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10566. res.set_content(body, "image/jpeg");
  10567. res.set_header("Content-Encoding", "gzip, br");
  10568. });
  10569. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10570. res.set_content(body, "image/jpeg");
  10571. res.set_header("Content-Encoding", "x-zstd-ish");
  10572. });
  10573. auto port = svr.bind_to_any_port(HOST);
  10574. thread t = thread([&]() { svr.listen_after_bind(); });
  10575. auto se = detail::scope_exit([&] {
  10576. svr.stop();
  10577. t.join();
  10578. ASSERT_FALSE(svr.is_running());
  10579. });
  10580. svr.wait_until_ready();
  10581. Client cli(HOST, port);
  10582. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10583. auto res = cli.Get(path);
  10584. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10585. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10586. // Not a coding we recognize, so the payload comes back untouched
  10587. EXPECT_EQ(body, res->body) << path;
  10588. }
  10589. }
  10590. // A content coding cpp-httplib recognizes but was not built with must be
  10591. // reported as such. Handing the still-compressed payload back to the caller
  10592. // would silently corrupt it.
  10593. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10594. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10595. Server svr;
  10596. // "image/jpeg" keeps the server from applying a content coding of its own,
  10597. // so the hand-crafted Content-Encoding below survives.
  10598. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10599. res.set_content(gzipped, "image/jpeg");
  10600. res.set_header("Content-Encoding", "gzip");
  10601. });
  10602. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10603. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10604. res.set_content(gzipped, "image/jpeg");
  10605. res.set_header("Content-Encoding", "GZIP");
  10606. });
  10607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10608. auto se = detail::scope_exit([&] {
  10609. svr.stop();
  10610. t.join();
  10611. ASSERT_FALSE(svr.is_running());
  10612. });
  10613. svr.wait_until_ready();
  10614. Client cli(HOST, PORT);
  10615. {
  10616. auto res = cli.Get("/gzipped");
  10617. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. EXPECT_EQ("Hello World!", res->body);
  10620. #else
  10621. ASSERT_FALSE(res);
  10622. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10623. #endif
  10624. }
  10625. {
  10626. // open_stream() must behave the same way.
  10627. auto handle = cli.open_stream("GET", "/gzipped");
  10628. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10629. ASSERT_TRUE(handle.is_valid());
  10630. std::string received;
  10631. char buf[256];
  10632. ssize_t n;
  10633. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10634. received.append(buf, static_cast<size_t>(n));
  10635. }
  10636. EXPECT_EQ("Hello World!", received);
  10637. #else
  10638. EXPECT_FALSE(handle.is_valid());
  10639. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10640. #endif
  10641. }
  10642. {
  10643. // A differently-cased coding must not be mistaken for an unknown one, or
  10644. // the body would be handed back still compressed.
  10645. auto res = cli.Get("/gzipped-uppercase");
  10646. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10648. EXPECT_EQ("Hello World!", res->body);
  10649. #else
  10650. ASSERT_FALSE(res);
  10651. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10652. #endif
  10653. }
  10654. }
  10655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10656. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10657. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10658. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10659. // body a second time and appending a second Content-Encoding field line, so
  10660. // clients that decode one coding per listed value handed back raw gzip bytes.
  10661. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10662. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10663. Server svr;
  10664. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10665. // keeps the server from applying a coding of its own.
  10666. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10667. res.set_content(gzipped, "text/plain");
  10668. res.set_header("Content-Encoding", "gzip");
  10669. });
  10670. auto port = svr.bind_to_any_port(HOST);
  10671. thread t = thread([&]() { svr.listen_after_bind(); });
  10672. auto se = detail::scope_exit([&] {
  10673. svr.stop();
  10674. t.join();
  10675. ASSERT_FALSE(svr.is_running());
  10676. });
  10677. svr.wait_until_ready();
  10678. Client cli(HOST, port);
  10679. Headers headers = {{"Accept-Encoding", "gzip"}};
  10680. auto res = cli.Get("/pre-gzipped", headers);
  10681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10682. EXPECT_EQ(StatusCode::OK_200, res->status);
  10683. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10684. EXPECT_EQ("Hello World!", res->body);
  10685. }
  10686. // A chunked provider settles its coding where the headers are written and
  10687. // reuses it at write time. Both ends of that have to hold: a handler's own
  10688. // Content-Encoding suppresses the coding, and a response without one is still
  10689. // compressed as it always was.
  10690. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10691. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10692. const std::string plain = "Hello World! Hello World! Hello World!";
  10693. Server svr;
  10694. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10695. res.set_header("Content-Encoding", "gzip");
  10696. res.set_chunked_content_provider(
  10697. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10698. sink.write(gzipped.data(), gzipped.size());
  10699. sink.done();
  10700. return true;
  10701. });
  10702. });
  10703. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10704. res.set_chunked_content_provider(
  10705. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10706. sink.write(plain.data(), plain.size());
  10707. sink.done();
  10708. return true;
  10709. });
  10710. });
  10711. auto port = svr.bind_to_any_port(HOST);
  10712. thread t = thread([&]() { svr.listen_after_bind(); });
  10713. auto se = detail::scope_exit([&] {
  10714. svr.stop();
  10715. t.join();
  10716. ASSERT_FALSE(svr.is_running());
  10717. });
  10718. svr.wait_until_ready();
  10719. Client cli(HOST, port);
  10720. Headers headers = {{"Accept-Encoding", "gzip"}};
  10721. {
  10722. auto res = cli.Get("/pre-gzipped", headers);
  10723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10724. EXPECT_EQ(StatusCode::OK_200, res->status);
  10725. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10726. EXPECT_EQ("Hello World!", res->body);
  10727. }
  10728. {
  10729. auto res = cli.Get("/negotiated", headers);
  10730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10731. EXPECT_EQ(StatusCode::OK_200, res->status);
  10732. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10733. EXPECT_EQ(plain, res->body);
  10734. }
  10735. }
  10736. #endif
  10737. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10738. // the same message as the comma-joined one, so both have to be read the same
  10739. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10740. // single gzip coding, and a body the sender says was encoded twice was handed
  10741. // back after one pass, still compressed but presented as decoded.
  10742. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10743. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10744. Server svr;
  10745. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10746. res.set_content(body, "image/jpeg");
  10747. res.headers.emplace("Content-Encoding", "gzip");
  10748. res.headers.emplace("Content-Encoding", "gzip");
  10749. });
  10750. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10751. res.set_content(body, "image/jpeg");
  10752. res.set_header("Content-Encoding", "gzip, gzip");
  10753. });
  10754. auto port = svr.bind_to_any_port(HOST);
  10755. thread t = thread([&]() { svr.listen_after_bind(); });
  10756. auto se = detail::scope_exit([&] {
  10757. svr.stop();
  10758. t.join();
  10759. ASSERT_FALSE(svr.is_running());
  10760. });
  10761. svr.wait_until_ready();
  10762. Client cli(HOST, port);
  10763. // Two codings is not something cpp-httplib decodes, so both representations
  10764. // take the pass-through path rather than one of them being gunzipped once.
  10765. for (const char *path : {"/split", "/joined"}) {
  10766. auto res = cli.Get(path);
  10767. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10768. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10769. EXPECT_EQ(body, res->body) << path;
  10770. }
  10771. }
  10772. // Regression test for DoS vulnerability: a malicious server sending a response
  10773. // without Content-Length header must not cause unbounded memory consumption on
  10774. // the client side. The client should stop reading after a reasonable limit,
  10775. // similar to the server-side set_payload_max_length protection.
  10776. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10777. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10778. #ifndef _WIN32
  10779. signal(SIGPIPE, SIG_IGN);
  10780. #endif
  10781. auto server_thread = std::thread([] {
  10782. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10783. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10784. default_socket_options(srv);
  10785. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10787. sockaddr_in addr{};
  10788. addr.sin_family = AF_INET;
  10789. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10790. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10791. int opt = 1;
  10792. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10793. #ifdef _WIN32
  10794. reinterpret_cast<const char *>(&opt),
  10795. #else
  10796. &opt,
  10797. #endif
  10798. sizeof(opt));
  10799. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10800. ::listen(srv, 1);
  10801. sockaddr_in cli_addr{};
  10802. socklen_t cli_len = sizeof(cli_addr);
  10803. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10804. if (cli != INVALID_SOCKET) {
  10805. char buf[4096];
  10806. ::recv(cli, buf, sizeof(buf), 0);
  10807. // Malicious response: no Content-Length, no chunked encoding
  10808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10809. "Connection: close\r\n"
  10810. "\r\n";
  10811. ::send(cli,
  10812. #ifdef _WIN32
  10813. static_cast<const char *>(response_header.c_str()),
  10814. static_cast<int>(response_header.size()),
  10815. #else
  10816. response_header.c_str(), response_header.size(),
  10817. #endif
  10818. 0);
  10819. // Send 10MB of data
  10820. std::string chunk(64 * 1024, 'A');
  10821. size_t total_sent = 0;
  10822. while (total_sent < MALICIOUS_DATA_SIZE) {
  10823. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  10824. auto sent = ::send(cli,
  10825. #ifdef _WIN32
  10826. static_cast<const char *>(chunk.c_str()),
  10827. static_cast<int>(to_send),
  10828. #else
  10829. chunk.c_str(), to_send,
  10830. #endif
  10831. 0);
  10832. if (sent <= 0) break;
  10833. total_sent += static_cast<size_t>(sent);
  10834. }
  10835. detail::close_socket(cli);
  10836. }
  10837. detail::close_socket(srv);
  10838. });
  10839. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10840. size_t total_read = 0;
  10841. {
  10842. Client cli("127.0.0.1", PORT + 2);
  10843. cli.set_read_timeout(5, 0);
  10844. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  10845. auto stream = cli.open_stream("GET", "/malicious");
  10846. ASSERT_TRUE(stream.is_valid());
  10847. char buffer[64 * 1024];
  10848. ssize_t n;
  10849. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10850. total_read += static_cast<size_t>(n);
  10851. }
  10852. } // StreamHandle and Client destroyed here, closing the socket
  10853. server_thread.join();
  10854. // With set_payload_max_length, the client must stop reading before consuming
  10855. // all 10MB. The read loop should be cut off at or near the configured limit.
  10856. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  10857. << "Client read " << total_read << " bytes, exceeding the configured "
  10858. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  10859. }
  10860. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  10861. // the entire response body without truncation.
  10862. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  10863. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  10864. #ifndef _WIN32
  10865. signal(SIGPIPE, SIG_IGN);
  10866. #endif
  10867. auto server_thread = std::thread([] {
  10868. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10869. default_socket_options(srv);
  10870. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10871. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10872. sockaddr_in addr{};
  10873. addr.sin_family = AF_INET;
  10874. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10875. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10876. int opt = 1;
  10877. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10878. #ifdef _WIN32
  10879. reinterpret_cast<const char *>(&opt),
  10880. #else
  10881. &opt,
  10882. #endif
  10883. sizeof(opt));
  10884. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10885. ::listen(srv, 1);
  10886. sockaddr_in cli_addr{};
  10887. socklen_t cli_len = sizeof(cli_addr);
  10888. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10889. if (cli != INVALID_SOCKET) {
  10890. char buf[4096];
  10891. ::recv(cli, buf, sizeof(buf), 0);
  10892. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10893. "Connection: close\r\n"
  10894. "\r\n";
  10895. ::send(cli,
  10896. #ifdef _WIN32
  10897. static_cast<const char *>(response_header.c_str()),
  10898. static_cast<int>(response_header.size()),
  10899. #else
  10900. response_header.c_str(), response_header.size(),
  10901. #endif
  10902. 0);
  10903. std::string chunk(64 * 1024, 'A');
  10904. size_t total_sent = 0;
  10905. while (total_sent < DATA_SIZE) {
  10906. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  10907. auto sent = ::send(cli,
  10908. #ifdef _WIN32
  10909. static_cast<const char *>(chunk.c_str()),
  10910. static_cast<int>(to_send),
  10911. #else
  10912. chunk.c_str(), to_send,
  10913. #endif
  10914. 0);
  10915. if (sent <= 0) break;
  10916. total_sent += static_cast<size_t>(sent);
  10917. }
  10918. #ifdef _WIN32
  10919. ::shutdown(cli, SD_SEND);
  10920. #else
  10921. ::shutdown(cli, SHUT_WR);
  10922. #endif
  10923. // Drain until the client closes its end, ensuring all data is delivered
  10924. char drain[1024];
  10925. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  10926. detail::close_socket(cli);
  10927. }
  10928. detail::close_socket(srv);
  10929. });
  10930. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10931. size_t total_read = 0;
  10932. {
  10933. Client cli("127.0.0.1", PORT + 2);
  10934. cli.set_read_timeout(5, 0);
  10935. cli.set_payload_max_length(0); // 0 means no limit
  10936. auto stream = cli.open_stream("GET", "/data");
  10937. ASSERT_TRUE(stream.is_valid());
  10938. char buffer[64 * 1024];
  10939. ssize_t n;
  10940. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  10941. total_read += static_cast<size_t>(n);
  10942. }
  10943. }
  10944. server_thread.join();
  10945. EXPECT_EQ(total_read, DATA_SIZE)
  10946. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  10947. << " bytes without truncation, but only read " << total_read << " bytes.";
  10948. }
  10949. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  10950. // enormous Content-Length must not cause the client to pre-allocate a huge
  10951. // response body buffer. The reservation is capped at payload_max_length_, and
  10952. // the read itself fails when the body exceeds the limit.
  10953. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  10954. #ifndef _WIN32
  10955. signal(SIGPIPE, SIG_IGN);
  10956. #endif
  10957. auto server_thread = std::thread([] {
  10958. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10959. default_socket_options(srv);
  10960. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10961. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10962. sockaddr_in addr{};
  10963. addr.sin_family = AF_INET;
  10964. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10965. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10966. int opt = 1;
  10967. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10968. #ifdef _WIN32
  10969. reinterpret_cast<const char *>(&opt),
  10970. #else
  10971. &opt,
  10972. #endif
  10973. sizeof(opt));
  10974. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10975. ::listen(srv, 1);
  10976. sockaddr_in cli_addr{};
  10977. socklen_t cli_len = sizeof(cli_addr);
  10978. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10979. if (cli != INVALID_SOCKET) {
  10980. char buf[4096];
  10981. ::recv(cli, buf, sizeof(buf), 0);
  10982. // Malicious response: claim a 20GB body but send only a tiny payload.
  10983. std::string response = "HTTP/1.1 200 OK\r\n"
  10984. "Content-Length: 20000000000\r\n"
  10985. "\r\n"
  10986. "abc";
  10987. ::send(cli,
  10988. #ifdef _WIN32
  10989. static_cast<const char *>(response.c_str()),
  10990. static_cast<int>(response.size()),
  10991. #else
  10992. response.c_str(), response.size(),
  10993. #endif
  10994. 0);
  10995. detail::close_socket(cli);
  10996. }
  10997. detail::close_socket(srv);
  10998. });
  10999. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11000. {
  11001. Client cli("127.0.0.1", PORT + 2);
  11002. cli.set_read_timeout(5, 0);
  11003. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11004. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11005. // (server claims more bytes than payload_max_length permits), but it must
  11006. // not exhaust memory before getting there.
  11007. auto res = cli.Get("/malicious");
  11008. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11009. }
  11010. server_thread.join();
  11011. }
  11012. // Verify that content_receiver bypasses the default payload_max_length,
  11013. // allowing streaming downloads larger than 100MB without requiring an explicit
  11014. // set_payload_max_length call.
  11015. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11016. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11017. #ifndef _WIN32
  11018. signal(SIGPIPE, SIG_IGN);
  11019. #endif
  11020. auto server_thread = std::thread([] {
  11021. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11022. default_socket_options(srv);
  11023. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11024. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11025. sockaddr_in addr{};
  11026. addr.sin_family = AF_INET;
  11027. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11028. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11029. int opt = 1;
  11030. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11031. #ifdef _WIN32
  11032. reinterpret_cast<const char *>(&opt),
  11033. #else
  11034. &opt,
  11035. #endif
  11036. sizeof(opt));
  11037. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11038. ::listen(srv, 1);
  11039. sockaddr_in cli_addr{};
  11040. socklen_t cli_len = sizeof(cli_addr);
  11041. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11042. if (cli != INVALID_SOCKET) {
  11043. char buf[4096];
  11044. ::recv(cli, buf, sizeof(buf), 0);
  11045. // Response with Content-Length larger than default 100MB limit
  11046. auto content_length = std::to_string(DATA_SIZE);
  11047. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11048. "Content-Length: " +
  11049. content_length +
  11050. "\r\n"
  11051. "Connection: close\r\n"
  11052. "\r\n";
  11053. ::send(cli,
  11054. #ifdef _WIN32
  11055. static_cast<const char *>(response_header.c_str()),
  11056. static_cast<int>(response_header.size()),
  11057. #else
  11058. response_header.c_str(), response_header.size(),
  11059. #endif
  11060. 0);
  11061. std::string chunk(64 * 1024, 'A');
  11062. size_t total_sent = 0;
  11063. while (total_sent < DATA_SIZE) {
  11064. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11065. auto sent = ::send(cli,
  11066. #ifdef _WIN32
  11067. static_cast<const char *>(chunk.c_str()),
  11068. static_cast<int>(to_send),
  11069. #else
  11070. chunk.c_str(), to_send,
  11071. #endif
  11072. 0);
  11073. if (sent <= 0) break;
  11074. total_sent += static_cast<size_t>(sent);
  11075. }
  11076. detail::close_socket(cli);
  11077. }
  11078. detail::close_socket(srv);
  11079. });
  11080. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11081. size_t total_received = 0;
  11082. {
  11083. Client cli("127.0.0.1", PORT + 2);
  11084. cli.set_read_timeout(10, 0);
  11085. // Do NOT call set_payload_max_length — use the default 100MB limit
  11086. auto res =
  11087. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11088. total_received += data_length;
  11089. return true;
  11090. });
  11091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11092. EXPECT_EQ(StatusCode::OK_200, res->status);
  11093. }
  11094. server_thread.join();
  11095. EXPECT_EQ(total_received, DATA_SIZE)
  11096. << "With content_receiver, the client should read all " << DATA_SIZE
  11097. << " bytes despite the default 100MB payload_max_length, but only read "
  11098. << total_received << " bytes.";
  11099. }
  11100. // Verify that an explicit set_payload_max_length smaller than the response is
  11101. // enforced even when a content_receiver is used.
  11102. TEST(ClientVulnerabilityTest,
  11103. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11104. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11105. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11106. #ifndef _WIN32
  11107. signal(SIGPIPE, SIG_IGN);
  11108. #endif
  11109. auto server_thread = std::thread([] {
  11110. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11111. default_socket_options(srv);
  11112. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11113. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11114. sockaddr_in addr{};
  11115. addr.sin_family = AF_INET;
  11116. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11117. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11118. int opt = 1;
  11119. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11120. #ifdef _WIN32
  11121. reinterpret_cast<const char *>(&opt),
  11122. #else
  11123. &opt,
  11124. #endif
  11125. sizeof(opt));
  11126. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11127. ::listen(srv, 1);
  11128. sockaddr_in cli_addr{};
  11129. socklen_t cli_len = sizeof(cli_addr);
  11130. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11131. if (cli != INVALID_SOCKET) {
  11132. char buf[4096];
  11133. ::recv(cli, buf, sizeof(buf), 0);
  11134. auto content_length = std::to_string(DATA_SIZE);
  11135. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11136. "Content-Length: " +
  11137. content_length +
  11138. "\r\n"
  11139. "Connection: close\r\n"
  11140. "\r\n";
  11141. ::send(cli,
  11142. #ifdef _WIN32
  11143. static_cast<const char *>(response_header.c_str()),
  11144. static_cast<int>(response_header.size()),
  11145. #else
  11146. response_header.c_str(), response_header.size(),
  11147. #endif
  11148. 0);
  11149. std::string chunk(64 * 1024, 'A');
  11150. size_t total_sent = 0;
  11151. while (total_sent < DATA_SIZE) {
  11152. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11153. auto sent = ::send(cli,
  11154. #ifdef _WIN32
  11155. static_cast<const char *>(chunk.c_str()),
  11156. static_cast<int>(to_send),
  11157. #else
  11158. chunk.c_str(), to_send,
  11159. #endif
  11160. 0);
  11161. if (sent <= 0) break;
  11162. total_sent += static_cast<size_t>(sent);
  11163. }
  11164. detail::close_socket(cli);
  11165. }
  11166. detail::close_socket(srv);
  11167. });
  11168. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11169. size_t total_received = 0;
  11170. {
  11171. Client cli("127.0.0.1", PORT + 2);
  11172. cli.set_read_timeout(10, 0);
  11173. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11174. auto res =
  11175. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11176. total_received += data_length;
  11177. return true;
  11178. });
  11179. // Should fail because 200MB exceeds the explicit 150MB limit
  11180. EXPECT_FALSE(res);
  11181. }
  11182. server_thread.join();
  11183. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11184. << "Client with content_receiver should respect the explicit "
  11185. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11186. << total_received << " bytes.";
  11187. }
  11188. // Verify that an explicit set_payload_max_length larger than the response
  11189. // allows the content_receiver to read all data successfully.
  11190. TEST(ClientVulnerabilityTest,
  11191. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11192. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11193. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11194. #ifndef _WIN32
  11195. signal(SIGPIPE, SIG_IGN);
  11196. #endif
  11197. auto server_thread = std::thread([] {
  11198. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11199. default_socket_options(srv);
  11200. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11201. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11202. sockaddr_in addr{};
  11203. addr.sin_family = AF_INET;
  11204. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11205. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11206. int opt = 1;
  11207. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11208. #ifdef _WIN32
  11209. reinterpret_cast<const char *>(&opt),
  11210. #else
  11211. &opt,
  11212. #endif
  11213. sizeof(opt));
  11214. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11215. ::listen(srv, 1);
  11216. sockaddr_in cli_addr{};
  11217. socklen_t cli_len = sizeof(cli_addr);
  11218. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11219. if (cli != INVALID_SOCKET) {
  11220. char buf[4096];
  11221. ::recv(cli, buf, sizeof(buf), 0);
  11222. auto content_length = std::to_string(DATA_SIZE);
  11223. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11224. "Content-Length: " +
  11225. content_length +
  11226. "\r\n"
  11227. "Connection: close\r\n"
  11228. "\r\n";
  11229. ::send(cli,
  11230. #ifdef _WIN32
  11231. static_cast<const char *>(response_header.c_str()),
  11232. static_cast<int>(response_header.size()),
  11233. #else
  11234. response_header.c_str(), response_header.size(),
  11235. #endif
  11236. 0);
  11237. std::string chunk(64 * 1024, 'A');
  11238. size_t total_sent = 0;
  11239. while (total_sent < DATA_SIZE) {
  11240. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11241. auto sent = ::send(cli,
  11242. #ifdef _WIN32
  11243. static_cast<const char *>(chunk.c_str()),
  11244. static_cast<int>(to_send),
  11245. #else
  11246. chunk.c_str(), to_send,
  11247. #endif
  11248. 0);
  11249. if (sent <= 0) break;
  11250. total_sent += static_cast<size_t>(sent);
  11251. }
  11252. #ifdef _WIN32
  11253. ::shutdown(cli, SD_SEND);
  11254. #else
  11255. ::shutdown(cli, SHUT_WR);
  11256. #endif
  11257. char drain[1024];
  11258. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11259. detail::close_socket(cli);
  11260. }
  11261. detail::close_socket(srv);
  11262. });
  11263. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11264. size_t total_received = 0;
  11265. {
  11266. Client cli("127.0.0.1", PORT + 2);
  11267. cli.set_read_timeout(10, 0);
  11268. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11269. auto res =
  11270. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11271. total_received += data_length;
  11272. return true;
  11273. });
  11274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11275. EXPECT_EQ(StatusCode::OK_200, res->status);
  11276. }
  11277. server_thread.join();
  11278. EXPECT_EQ(total_received, DATA_SIZE)
  11279. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11280. << " bytes (larger than " << DATA_SIZE
  11281. << " bytes response), content_receiver should read all data, but only "
  11282. "read "
  11283. << total_received << " bytes.";
  11284. }
  11285. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11286. // Regression test for "zip bomb" attack on the client side: a malicious server
  11287. // sends a small gzip-compressed response that decompresses to a huge payload.
  11288. // The client must enforce payload_max_length on the decompressed size.
  11289. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11290. constexpr size_t DECOMPRESSED_SIZE =
  11291. 10 * 1024 * 1024; // 10MB after decompression
  11292. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11293. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11294. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11295. std::string compressed;
  11296. {
  11297. httplib::detail::gzip_compressor compressor;
  11298. bool ok =
  11299. compressor.compress(uncompressed.data(), uncompressed.size(),
  11300. /*last=*/true, [&](const char *buf, size_t len) {
  11301. compressed.append(buf, len);
  11302. return true;
  11303. });
  11304. ASSERT_TRUE(ok);
  11305. }
  11306. // Sanity: compressed data should be much smaller than the decompressed size
  11307. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11308. #ifndef _WIN32
  11309. signal(SIGPIPE, SIG_IGN);
  11310. #endif
  11311. // Set up the listening socket in the main thread so the server is guaranteed
  11312. // to be ready before the client connects (eliminates race condition).
  11313. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11314. default_socket_options(srv);
  11315. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11316. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11317. sockaddr_in addr{};
  11318. addr.sin_family = AF_INET;
  11319. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11320. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11321. int opt = 1;
  11322. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11323. #ifdef _WIN32
  11324. reinterpret_cast<const char *>(&opt),
  11325. #else
  11326. &opt,
  11327. #endif
  11328. sizeof(opt));
  11329. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11330. ASSERT_EQ(0, ::listen(srv, 1));
  11331. auto server_thread = std::thread([&compressed, srv] {
  11332. sockaddr_in cli_addr{};
  11333. socklen_t cli_len = sizeof(cli_addr);
  11334. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11335. if (cli != INVALID_SOCKET) {
  11336. // Read the full HTTP request (until \r\n\r\n)
  11337. char buf[4096];
  11338. size_t total = 0;
  11339. while (total < sizeof(buf)) {
  11340. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11341. if (n <= 0) break;
  11342. total += static_cast<size_t>(n);
  11343. // Check for end of headers
  11344. if (total >= 4) {
  11345. std::string req(buf, total);
  11346. if (req.find("\r\n\r\n") != std::string::npos) break;
  11347. }
  11348. }
  11349. // Malicious response: gzip-compressed body, no Content-Length
  11350. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11351. "Content-Encoding: gzip\r\n"
  11352. "Connection: close\r\n"
  11353. "\r\n";
  11354. ::send(cli,
  11355. #ifdef _WIN32
  11356. static_cast<const char *>(response_header.c_str()),
  11357. static_cast<int>(response_header.size()),
  11358. #else
  11359. response_header.c_str(), response_header.size(),
  11360. #endif
  11361. 0);
  11362. // Send the compressed payload (small on the wire, huge when decompressed)
  11363. size_t total_sent = 0;
  11364. while (total_sent < compressed.size()) {
  11365. auto to_send = std::min(compressed.size() - total_sent,
  11366. static_cast<size_t>(64 * 1024));
  11367. auto sent =
  11368. ::send(cli,
  11369. #ifdef _WIN32
  11370. static_cast<const char *>(compressed.c_str() + total_sent),
  11371. static_cast<int>(to_send),
  11372. #else
  11373. compressed.c_str() + total_sent, to_send,
  11374. #endif
  11375. 0);
  11376. if (sent <= 0) break;
  11377. total_sent += static_cast<size_t>(sent);
  11378. }
  11379. detail::close_socket(cli);
  11380. }
  11381. });
  11382. auto se = detail::scope_exit([&] {
  11383. detail::close_socket(srv);
  11384. server_thread.join();
  11385. });
  11386. size_t total_decompressed = 0;
  11387. {
  11388. Client cli("127.0.0.1", PORT + 3);
  11389. cli.set_read_timeout(5, 0);
  11390. cli.set_decompress(true);
  11391. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11392. auto stream = cli.open_stream("GET", "/zipbomb");
  11393. ASSERT_TRUE(stream.is_valid());
  11394. char buffer[64 * 1024];
  11395. ssize_t n;
  11396. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11397. total_decompressed += static_cast<size_t>(n);
  11398. }
  11399. }
  11400. // The decompressed size must be capped by payload_max_length. Without
  11401. // protection, the client would decompress the full 10MB from a tiny
  11402. // compressed payload, enabling a zip bomb DoS attack.
  11403. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11404. << "Client decompressed " << total_decompressed
  11405. << " bytes from a gzip response. The decompressed size should be "
  11406. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11407. }
  11408. #endif
  11409. TEST(HostAndPortPropertiesTest, NoSSL) {
  11410. httplib::Client cli("www.google.com", 1234);
  11411. ASSERT_EQ("www.google.com", cli.host());
  11412. ASSERT_EQ(1234, cli.port());
  11413. }
  11414. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11415. httplib::Client cli("www.google.com:1234");
  11416. ASSERT_EQ("www.google.com", cli.host());
  11417. ASSERT_EQ(1234, cli.port());
  11418. }
  11419. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11420. // Port number that overflows int — should not crash, client becomes invalid
  11421. httplib::Client cli("http://www.google.com:99999999999999999999");
  11422. ASSERT_FALSE(cli.is_valid());
  11423. }
  11424. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11425. // Port 99999 exceeds valid range (1-65535) — should not crash
  11426. httplib::Client cli("http://www.google.com:99999");
  11427. ASSERT_FALSE(cli.is_valid());
  11428. }
  11429. #ifdef CPPHTTPLIB_SSL_ENABLED
  11430. TEST(HostAndPortPropertiesTest, SSL) {
  11431. httplib::SSLClient cli("www.google.com");
  11432. ASSERT_EQ("www.google.com", cli.host());
  11433. ASSERT_EQ(443, cli.port());
  11434. }
  11435. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11436. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11437. std::string cert;
  11438. read_file(CA_CERT_FILE, cert);
  11439. httplib::SSLClient httplib_client("www.google.com");
  11440. // Load CA store first time
  11441. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11442. // Load CA store second time (update)
  11443. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11444. // Verify client is still valid and can make connections
  11445. httplib_client.enable_server_certificate_verification(true);
  11446. auto res = httplib_client.Get("/");
  11447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11448. // Google may return 200 or 301 depending on various factors
  11449. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11450. res->status == StatusCode::MovedPermanently_301);
  11451. }
  11452. TEST(SSLClientTest, ServerNameIndication_Online) {
  11453. auto host = "httpbingo.org";
  11454. auto path = std::string{"/get"};
  11455. SSLClient cli(host, 443);
  11456. auto res = cli.Get(path);
  11457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11458. ASSERT_EQ(StatusCode::OK_200, res->status);
  11459. }
  11460. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11461. // Use a site that will cause SSL verification failure due to self-signed cert
  11462. SSLClient cli("self-signed.badssl.com", 443);
  11463. cli.enable_server_certificate_verification(true);
  11464. auto res = cli.Get("/");
  11465. ASSERT_TRUE(!res);
  11466. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11467. // Verify backend error is captured for SSLServerVerification
  11468. // This occurs when certificate verification fails
  11469. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11470. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11471. EXPECT_NE(0UL, res.ssl_backend_error());
  11472. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11473. // For OpenSSL, ssl_error is 0 for verification errors
  11474. EXPECT_EQ(0, res.ssl_error());
  11475. #if !defined(_WIN32) || \
  11476. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11477. // On non-Windows or when Windows Schannel is disabled, the error comes
  11478. // from OpenSSL's verification
  11479. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11480. res.ssl_backend_error());
  11481. #endif
  11482. #endif
  11483. }
  11484. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11485. // Use a site where hostname doesn't match the certificate
  11486. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11487. SSLClient cli("wrong.host.badssl.com", 443);
  11488. cli.enable_server_certificate_verification(true);
  11489. cli.enable_server_hostname_verification(true);
  11490. auto res = cli.Get("/");
  11491. ASSERT_TRUE(!res);
  11492. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11493. // Verify backend error is captured for hostname verification failure
  11494. EXPECT_NE(0UL, res.ssl_backend_error());
  11495. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11496. // For OpenSSL, ssl_error is 0 for verification errors
  11497. EXPECT_EQ(0, res.ssl_error());
  11498. #if !defined(_WIN32) || \
  11499. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11500. // On non-Windows or when Windows Schannel is disabled, the error comes
  11501. // from OpenSSL's hostname verification
  11502. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11503. res.ssl_backend_error());
  11504. #endif
  11505. #endif
  11506. }
  11507. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11508. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11509. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11510. SSLClient cli("www.google.com", 443);
  11511. cli.enable_server_certificate_verification(true);
  11512. auto res = cli.Get("/");
  11513. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11514. }
  11515. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11516. SSLClient cli("www.google.com", 443);
  11517. cli.enable_server_certificate_verification(true);
  11518. cli.enable_windows_certificate_verification(false);
  11519. auto res = cli.Get("/");
  11520. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11521. }
  11522. #endif
  11523. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11524. Client cli("https://google.com");
  11525. auto res = cli.Get("/");
  11526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11527. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11528. }
  11529. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11530. SSLClient cli("google.com");
  11531. cli.set_ca_cert_path(CA_CERT_FILE);
  11532. auto res = cli.Get("/");
  11533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11534. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11535. }
  11536. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11537. SSLClient cli("google.com");
  11538. cli.enable_server_certificate_verification(true);
  11539. cli.set_ca_cert_path("hello");
  11540. auto res = cli.Get("/");
  11541. ASSERT_TRUE(!res);
  11542. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11543. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11544. // should be set
  11545. EXPECT_EQ(0, res.ssl_error());
  11546. // Verify backend error is captured for SSLLoadingCerts
  11547. // This error occurs when loading CA certificates fails
  11548. EXPECT_NE(0UL, res.ssl_backend_error());
  11549. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11550. // OpenSSL specific error codes:
  11551. // > openssl errstr 0x80000002
  11552. // error:80000002:system library::No such file or directory
  11553. // > openssl errstr 0xA000126
  11554. // error:0A000126:SSL routines::unexpected eof while reading
  11555. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11556. res.ssl_backend_error() == 0xA000126);
  11557. #endif
  11558. }
  11559. TEST(SSLClientTest, ServerCertificateVerification4) {
  11560. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11561. ASSERT_TRUE(svr.is_valid());
  11562. svr.Get("/test", [&](const Request &, Response &res) {
  11563. res.set_content("test", "text/plain");
  11564. svr.stop();
  11565. ASSERT_TRUE(true);
  11566. });
  11567. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11568. auto se = detail::scope_exit([&] {
  11569. t.join();
  11570. ASSERT_FALSE(svr.is_running());
  11571. });
  11572. svr.wait_until_ready();
  11573. SSLClient cli("127.0.0.1", PORT);
  11574. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11575. cli.enable_server_certificate_verification(true);
  11576. cli.set_connection_timeout(30);
  11577. auto res = cli.Get("/test");
  11578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11579. ASSERT_EQ(StatusCode::OK_200, res->status);
  11580. }
  11581. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11582. std::string cert;
  11583. read_file(CA_CERT_FILE, cert);
  11584. SSLClient cli("google.com");
  11585. cli.load_ca_cert_store(cert.data(), cert.size());
  11586. const auto res = cli.Get("/");
  11587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11588. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11589. }
  11590. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11591. // clang-format off
  11592. static constexpr char cert[] =
  11593. "GlobalSign Root CA\n"
  11594. "==================\n"
  11595. "-----BEGIN CERTIFICATE-----\n"
  11596. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11597. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11598. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11599. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11600. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11601. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11602. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11603. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11604. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11605. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11606. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11607. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11608. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11609. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11610. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11611. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11612. "-----END CERTIFICATE-----\n";
  11613. // clang-format on
  11614. SSLClient cli("google.com");
  11615. cli.load_ca_cert_store(cert, sizeof(cert));
  11616. const auto res = cli.Get("/");
  11617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11618. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11619. }
  11620. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11621. SSLClient cli("www.youtube.com");
  11622. cli.set_ca_cert_path(CA_CERT_FILE);
  11623. cli.enable_server_certificate_verification(true);
  11624. cli.set_follow_location(true);
  11625. auto res = cli.Get("/");
  11626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11627. ASSERT_EQ(StatusCode::OK_200, res->status);
  11628. }
  11629. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11630. SSLClient cli("wWw.YouTube.Com");
  11631. cli.set_ca_cert_path(CA_CERT_FILE);
  11632. cli.enable_server_certificate_verification(true);
  11633. cli.enable_server_hostname_verification(true);
  11634. cli.set_follow_location(true);
  11635. auto res = cli.Get("/");
  11636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11637. ASSERT_EQ(StatusCode::OK_200, res->status);
  11638. }
  11639. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11640. SSLClient cli("gOoGlE.COm");
  11641. cli.enable_server_certificate_verification(true);
  11642. cli.enable_server_hostname_verification(true);
  11643. cli.set_follow_location(true);
  11644. auto res = cli.Get("/");
  11645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11646. ASSERT_EQ(StatusCode::OK_200, res->status);
  11647. }
  11648. TEST(SSLClientTest, Issue2004_Online) {
  11649. Client client("https://google.com");
  11650. client.set_follow_location(true);
  11651. auto res = client.Get("/");
  11652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11653. ASSERT_EQ(StatusCode::OK_200, res->status);
  11654. auto body = res->body;
  11655. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11656. }
  11657. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11658. // Create SSLClient with invalid cert/key to make is_valid() return false
  11659. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11660. "nonexistent_key.pem");
  11661. // is_valid() should be false due to cert loading failure
  11662. ASSERT_FALSE(cli.is_valid());
  11663. auto res = cli.Get("/");
  11664. ASSERT_FALSE(res);
  11665. EXPECT_EQ(Error::SSLConnection, res.error());
  11666. }
  11667. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11668. // Test for Issue #2251: SSL error not properly reported when client cert
  11669. // and key paths are swapped or mismatched
  11670. // This simulates the scenario where user accidentally swaps the cert and key
  11671. // files
  11672. // Using client cert file as private key and vice versa (completely wrong)
  11673. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11674. // Should fail validation due to cert/key mismatch
  11675. ASSERT_FALSE(cli.is_valid());
  11676. // Attempt to make a request should fail with proper error
  11677. auto res = cli.Get("/");
  11678. ASSERT_FALSE(res);
  11679. EXPECT_EQ(Error::SSLConnection, res.error());
  11680. // SSL error should be recorded in the Result object (this is the key fix for
  11681. // Issue #2251)
  11682. auto backend_error = res.ssl_backend_error();
  11683. EXPECT_NE(0u, backend_error);
  11684. }
  11685. // Tests cert/key mismatch detection at the TLS context level
  11686. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11687. // Test that using mismatched cert/key causes connection failure.
  11688. // We verify this at the SSLClient level rather than through internal
  11689. // TLS API functions.
  11690. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11691. cli.enable_server_certificate_verification(false);
  11692. cli.set_connection_timeout(2);
  11693. // The mismatch should cause a connection or handshake error
  11694. auto res = cli.Get("/test");
  11695. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11696. // Either way, the request should fail
  11697. EXPECT_FALSE(res);
  11698. }
  11699. #endif
  11700. #if 0
  11701. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11702. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11703. ASSERT_TRUE(cli != nullptr);
  11704. cli->set_address_family(AF_INET6);
  11705. cli->set_interface("en0");
  11706. auto res = cli->Get("/get");
  11707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11708. ASSERT_EQ(StatusCode::OK_200, res->status);
  11709. }
  11710. #endif
  11711. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11712. #ifdef CPPHTTPLIB_SSL_ENABLED
  11713. void ClientCertPresent(
  11714. const std::string &client_cert_file,
  11715. const std::string &client_private_key_file,
  11716. const std::string &client_encrypted_private_key_pass = std::string()) {
  11717. using namespace httplib::tls;
  11718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11719. CLIENT_CA_CERT_DIR);
  11720. ASSERT_TRUE(svr.is_valid());
  11721. svr.Get("/test", [&](const Request &req, Response &res) {
  11722. res.set_content("test", "text/plain");
  11723. auto cert = req.peer_cert();
  11724. ASSERT_TRUE(static_cast<bool>(cert));
  11725. std::string common_name = cert.subject_cn();
  11726. EXPECT_EQ("Common Name", common_name);
  11727. });
  11728. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11729. auto se = detail::scope_exit([&] {
  11730. svr.stop();
  11731. t.join();
  11732. ASSERT_FALSE(svr.is_running());
  11733. });
  11734. svr.wait_until_ready();
  11735. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11736. client_encrypted_private_key_pass);
  11737. cli.enable_server_certificate_verification(false);
  11738. cli.set_connection_timeout(30);
  11739. auto res = cli.Get("/test");
  11740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11741. ASSERT_EQ(StatusCode::OK_200, res->status);
  11742. }
  11743. TEST(SSLClientServerTest, ClientCertPresent) {
  11744. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11745. }
  11746. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11747. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11748. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11749. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11750. }
  11751. // PEM memory-based constructor tests (works with all TLS backends)
  11752. void PemMemoryClientCertPresent(
  11753. const std::string &client_cert_file,
  11754. const std::string &client_private_key_file,
  11755. const std::string &client_encrypted_private_key_pass = std::string()) {
  11756. // Read PEM files into memory
  11757. std::string server_cert_pem, server_key_pem;
  11758. std::string client_ca_pem;
  11759. std::string client_cert_pem, client_key_pem;
  11760. read_file(SERVER_CERT_FILE, server_cert_pem);
  11761. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11762. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11763. read_file(client_cert_file, client_cert_pem);
  11764. read_file(client_private_key_file, client_key_pem);
  11765. // Create server with PEM memory
  11766. SSLServer::PemMemory server_pem = {
  11767. server_cert_pem.c_str(),
  11768. server_cert_pem.size(),
  11769. server_key_pem.c_str(),
  11770. server_key_pem.size(),
  11771. client_ca_pem.c_str(),
  11772. client_ca_pem.size(),
  11773. nullptr // no password for server key
  11774. };
  11775. SSLServer svr(server_pem);
  11776. ASSERT_TRUE(svr.is_valid());
  11777. svr.Get("/test", [&](const Request &, Response &res) {
  11778. res.set_content("test", "text/plain");
  11779. });
  11780. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11781. auto se = detail::scope_exit([&] {
  11782. svr.stop();
  11783. t.join();
  11784. ASSERT_FALSE(svr.is_running());
  11785. });
  11786. svr.wait_until_ready();
  11787. // Create client with PEM memory
  11788. const char *password = client_encrypted_private_key_pass.empty()
  11789. ? nullptr
  11790. : client_encrypted_private_key_pass.c_str();
  11791. SSLClient::PemMemory client_pem = {
  11792. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11793. client_key_pem.size(), password};
  11794. SSLClient cli(HOST, PORT, client_pem);
  11795. cli.enable_server_certificate_verification(false);
  11796. cli.set_connection_timeout(30);
  11797. auto res = cli.Get("/test");
  11798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11799. ASSERT_EQ(StatusCode::OK_200, res->status);
  11800. }
  11801. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11802. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11803. }
  11804. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11805. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11806. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11807. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11808. }
  11809. TEST(SSLClientServerTest, ClientCertMissing) {
  11810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11811. CLIENT_CA_CERT_DIR);
  11812. ASSERT_TRUE(svr.is_valid());
  11813. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11815. auto se = detail::scope_exit([&] {
  11816. svr.stop();
  11817. t.join();
  11818. ASSERT_FALSE(svr.is_running());
  11819. });
  11820. svr.wait_until_ready();
  11821. SSLClient cli(HOST, PORT);
  11822. cli.set_connection_timeout(30);
  11823. auto res = cli.Get("/test");
  11824. ASSERT_TRUE(!res);
  11825. // When client cert is missing and server requires it, connection fails
  11826. // Error type depends on backend implementation
  11827. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11828. res.error() == Error::SSLConnection);
  11829. // Verify backend error is captured
  11830. // Note: This test may have different error codes depending on the exact
  11831. // verification failure
  11832. EXPECT_NE(0UL, res.ssl_backend_error());
  11833. }
  11834. TEST(SSLClientServerTest, TrustDirOptional) {
  11835. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  11836. ASSERT_TRUE(svr.is_valid());
  11837. svr.Get("/test", [&](const Request &, Response &res) {
  11838. res.set_content("test", "text/plain");
  11839. });
  11840. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11841. auto se = detail::scope_exit([&] {
  11842. svr.stop();
  11843. t.join();
  11844. ASSERT_FALSE(svr.is_running());
  11845. });
  11846. svr.wait_until_ready();
  11847. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11848. cli.enable_server_certificate_verification(false);
  11849. cli.set_connection_timeout(30);
  11850. auto res = cli.Get("/test");
  11851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11852. ASSERT_EQ(StatusCode::OK_200, res->status);
  11853. }
  11854. TEST(SSLClientServerTest, SSLConnectTimeout) {
  11855. class NoListenSSLServer : public SSLServer {
  11856. public:
  11857. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  11858. const char *client_ca_cert_file_path,
  11859. const char *client_ca_cert_dir_path = nullptr)
  11860. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  11861. client_ca_cert_dir_path),
  11862. stop_(false) {}
  11863. std::atomic_bool stop_;
  11864. private:
  11865. bool process_and_close_socket(socket_t /*sock*/) override {
  11866. // Don't create SSL context
  11867. while (!stop_.load()) {
  11868. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11869. }
  11870. return true;
  11871. }
  11872. };
  11873. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11874. CLIENT_CA_CERT_FILE);
  11875. ASSERT_TRUE(svr.is_valid());
  11876. svr.Get("/test", [&](const Request &, Response &res) {
  11877. res.set_content("test", "text/plain");
  11878. });
  11879. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11880. auto se = detail::scope_exit([&] {
  11881. svr.stop_ = true;
  11882. svr.stop();
  11883. t.join();
  11884. ASSERT_FALSE(svr.is_running());
  11885. });
  11886. svr.wait_until_ready();
  11887. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11888. cli.enable_server_certificate_verification(false);
  11889. cli.set_connection_timeout(1);
  11890. auto res = cli.Get("/test");
  11891. ASSERT_TRUE(!res);
  11892. EXPECT_EQ(Error::SSLConnection, res.error());
  11893. // Timeout results in WantRead error code (maps to backend-specific value)
  11894. EXPECT_NE(0, res.ssl_error());
  11895. }
  11896. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  11897. // Test SSLServer with client certificate verification using the standard
  11898. // constructor (ContextSetupCallback is tested by backend-specific tests)
  11899. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11900. CLIENT_CA_CERT_DIR);
  11901. ASSERT_TRUE(svr.is_valid());
  11902. svr.Get("/test", [&](const Request &req, Response &res) {
  11903. res.set_content("test", "text/plain");
  11904. auto cert = req.peer_cert();
  11905. ASSERT_TRUE(static_cast<bool>(cert));
  11906. auto common_name = cert.subject_cn();
  11907. EXPECT_EQ("Common Name", common_name);
  11908. });
  11909. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11910. auto se = detail::scope_exit([&] {
  11911. svr.stop();
  11912. t.join();
  11913. ASSERT_FALSE(svr.is_running());
  11914. });
  11915. svr.wait_until_ready();
  11916. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11917. cli.enable_server_certificate_verification(false);
  11918. cli.set_connection_timeout(30);
  11919. auto res = cli.Get("/test");
  11920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11921. ASSERT_EQ(StatusCode::OK_200, res->status);
  11922. }
  11923. // Test verify_hostname for both OpenSSL and MbedTLS backends
  11924. // Verifies that wildcard matching and exact matching work consistently
  11925. TEST(SSLClientServerTest, TlsVerifyHostname) {
  11926. using namespace httplib::tls;
  11927. // We need a running server to test against
  11928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11929. ASSERT_TRUE(svr.is_valid());
  11930. svr.Get("/test", [](const Request &, Response &res) {
  11931. res.set_content("ok", "text/plain");
  11932. });
  11933. thread t([&]() { svr.listen(HOST, PORT); });
  11934. auto se = detail::scope_exit([&] {
  11935. svr.stop();
  11936. t.join();
  11937. });
  11938. svr.wait_until_ready();
  11939. bool verify_callback_called = false;
  11940. bool verify_result_wrong = false;
  11941. SSLClient cli(HOST, PORT);
  11942. cli.enable_server_certificate_verification(true);
  11943. cli.set_ca_cert_path(CA_CERT_FILE);
  11944. cli.set_connection_timeout(5);
  11945. // Note: Test certificate has CN="Common Name", not "localhost"
  11946. bool verify_result_cn = false;
  11947. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  11948. verify_callback_called = true;
  11949. if (!ctx.cert) return false;
  11950. // Test 1: "Common Name" should match (our test server cert CN)
  11951. verify_result_cn = ctx.check_hostname("Common Name");
  11952. // Test 2: wrong hostname should not match
  11953. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  11954. return true; // Accept for the purpose of this test
  11955. });
  11956. auto res = cli.Get("/test");
  11957. // The request may succeed or fail depending on cert configuration
  11958. // but the callback should have been called
  11959. ASSERT_TRUE(verify_callback_called)
  11960. << "Verify callback should have been called";
  11961. // CN="Common Name" should match our test certificate
  11962. //
  11963. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  11964. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  11965. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  11966. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  11967. // <openssl/base.h>, which is included transitively when
  11968. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  11969. #if defined(OPENSSL_IS_BORINGSSL)
  11970. EXPECT_FALSE(verify_result_cn)
  11971. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  11972. #else
  11973. EXPECT_TRUE(verify_result_cn)
  11974. << "verify_hostname should match 'Common Name' (certificate CN)";
  11975. #endif
  11976. // Wrong hostname should not match
  11977. EXPECT_FALSE(verify_result_wrong)
  11978. << "verify_hostname should not match 'wronghost.example.com'";
  11979. }
  11980. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  11981. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  11982. // X509_check_ip behavior and must hold for every backend.
  11983. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  11984. using namespace httplib::tls;
  11985. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  11986. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  11987. ASSERT_TRUE(svr.is_valid());
  11988. svr.Get("/test", [](const Request &, Response &res) {
  11989. res.set_content("ok", "text/plain");
  11990. });
  11991. thread t([&]() { svr.listen(HOST, PORT); });
  11992. auto se = detail::scope_exit([&] {
  11993. svr.stop();
  11994. t.join();
  11995. });
  11996. svr.wait_until_ready();
  11997. bool verify_callback_called = false;
  11998. bool ip_matched_via_cn = true;
  11999. SSLClient cli(HOST, PORT);
  12000. cli.enable_server_certificate_verification(true);
  12001. cli.set_ca_cert_path(CA_CERT_FILE);
  12002. cli.set_connection_timeout(5);
  12003. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12004. verify_callback_called = true;
  12005. if (!ctx.cert) return false;
  12006. // The IP appears only in the CN, so it must NOT be accepted.
  12007. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12008. return true; // Accept for the purpose of this test
  12009. });
  12010. cli.Get("/test");
  12011. ASSERT_TRUE(verify_callback_called)
  12012. << "Verify callback should have been called";
  12013. EXPECT_FALSE(ip_matched_via_cn)
  12014. << "An IP host must not be authenticated via the certificate CN";
  12015. }
  12016. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12017. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12018. using namespace httplib::tls;
  12019. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12020. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12021. ASSERT_TRUE(svr.is_valid());
  12022. svr.Get("/test", [](const Request &, Response &res) {
  12023. res.set_content("ok", "text/plain");
  12024. });
  12025. thread t([&]() { svr.listen(HOST, PORT); });
  12026. auto se = detail::scope_exit([&] {
  12027. svr.stop();
  12028. t.join();
  12029. });
  12030. svr.wait_until_ready();
  12031. bool verify_callback_called = false;
  12032. bool san_matched = false;
  12033. bool wrong_ipv6_matched = true;
  12034. bool cn_ipv6_matched = true;
  12035. SSLClient cli(HOST, PORT);
  12036. cli.enable_server_certificate_verification(true);
  12037. cli.set_ca_cert_path(CA_CERT_FILE);
  12038. cli.set_connection_timeout(5);
  12039. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12040. verify_callback_called = true;
  12041. if (!ctx.cert) return false;
  12042. // Matches the IPv6 iPAddress SAN.
  12043. san_matched = ctx.check_hostname("2001:db8::1");
  12044. // A different IPv6 address must not match.
  12045. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12046. // "::1" lives only in the CN, so it must not be accepted.
  12047. cn_ipv6_matched = ctx.check_hostname("::1");
  12048. return true; // Accept for the purpose of this test
  12049. });
  12050. cli.Get("/test");
  12051. ASSERT_TRUE(verify_callback_called)
  12052. << "Verify callback should have been called";
  12053. EXPECT_TRUE(san_matched)
  12054. << "verify_hostname should match an IPv6 iPAddress SAN";
  12055. EXPECT_FALSE(wrong_ipv6_matched)
  12056. << "verify_hostname should not match a non-matching IPv6 address";
  12057. EXPECT_FALSE(cn_ipv6_matched)
  12058. << "An IPv6 host must not be authenticated via the certificate CN";
  12059. }
  12060. #endif
  12061. // mbedTLS-specific callback constructor test
  12062. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12063. #ifdef CPPHTTPLIB_SSL_ENABLED
  12064. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12066. ASSERT_TRUE(svr.is_valid());
  12067. // Set up a handler to verify client certificate is present
  12068. bool client_cert_verified = false;
  12069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12070. // Verify that client certificate was provided
  12071. client_cert_verified = true;
  12072. res.set_content("success", "text/plain");
  12073. });
  12074. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12075. auto se = detail::scope_exit([&] {
  12076. svr.stop();
  12077. t.join();
  12078. ASSERT_FALSE(svr.is_running());
  12079. });
  12080. svr.wait_until_ready();
  12081. // Client with certificate
  12082. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12083. cli.enable_server_certificate_verification(false);
  12084. cli.set_connection_timeout(30);
  12085. auto res = cli.Get("/test");
  12086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12087. ASSERT_EQ(StatusCode::OK_200, res->status);
  12088. ASSERT_TRUE(client_cert_verified);
  12089. EXPECT_EQ("success", res->body);
  12090. }
  12091. #endif
  12092. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12093. // backends
  12094. #ifdef CPPHTTPLIB_SSL_ENABLED
  12095. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12096. using namespace httplib::tls;
  12097. // Test that when client CA cert file is provided,
  12098. // the server properly requests and validates client certificates
  12099. // Create a server with client authentication
  12100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12101. ASSERT_TRUE(svr.is_valid());
  12102. bool handler_called = false;
  12103. svr.Get("/test", [&](const Request &req, Response &res) {
  12104. handler_called = true;
  12105. // Verify that a client certificate was provided
  12106. auto cert = req.peer_cert();
  12107. ASSERT_TRUE(static_cast<bool>(cert));
  12108. // Get the issuer name
  12109. std::string issuer_str = cert.issuer_name();
  12110. ASSERT_FALSE(issuer_str.empty());
  12111. // The client certificate should be issued by our test CA
  12112. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12113. res.set_content("authenticated", "text/plain");
  12114. });
  12115. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12116. auto se = detail::scope_exit([&] {
  12117. svr.stop();
  12118. t.join();
  12119. ASSERT_FALSE(svr.is_running());
  12120. });
  12121. svr.wait_until_ready();
  12122. // Connect with a client certificate issued by the CA
  12123. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12124. cli.enable_server_certificate_verification(false);
  12125. cli.set_connection_timeout(30);
  12126. auto res = cli.Get("/test");
  12127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12128. ASSERT_EQ(StatusCode::OK_200, res->status);
  12129. ASSERT_TRUE(handler_called);
  12130. EXPECT_EQ("authenticated", res->body);
  12131. }
  12132. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12133. using namespace httplib::tls;
  12134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12135. ASSERT_TRUE(svr.is_valid());
  12136. svr.Get("/test", [](const Request &, Response &res) {
  12137. res.set_content("ok", "text/plain");
  12138. });
  12139. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12140. auto se = detail::scope_exit([&] {
  12141. svr.stop();
  12142. t.join();
  12143. });
  12144. svr.wait_until_ready();
  12145. SSLClient cli(HOST, PORT);
  12146. cli.enable_server_certificate_verification(false);
  12147. cli.set_connection_timeout(30);
  12148. bool cert_checked = false;
  12149. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12150. if (ctx.cert) {
  12151. auto sans = ctx.sans();
  12152. // Test certificate may or may not have SANs - just verify the API
  12153. // works If SANs exist, verify the types are valid
  12154. for (const auto &san : sans) {
  12155. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12156. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12157. san.type == SanType::OTHER);
  12158. EXPECT_FALSE(san.value.empty());
  12159. }
  12160. cert_checked = true;
  12161. }
  12162. return true;
  12163. });
  12164. auto res = cli.Get("/test");
  12165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12166. EXPECT_TRUE(cert_checked);
  12167. }
  12168. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12169. using namespace httplib::tls;
  12170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12171. ASSERT_TRUE(svr.is_valid());
  12172. svr.Get("/test", [](const Request &, Response &res) {
  12173. res.set_content("ok", "text/plain");
  12174. });
  12175. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12176. auto se = detail::scope_exit([&] {
  12177. svr.stop();
  12178. t.join();
  12179. });
  12180. svr.wait_until_ready();
  12181. SSLClient cli(HOST, PORT);
  12182. cli.enable_server_certificate_verification(false);
  12183. cli.set_connection_timeout(30);
  12184. bool validity_checked = false;
  12185. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12186. if (ctx.cert) {
  12187. time_t not_before = 0, not_after = 0;
  12188. bool result = ctx.validity(not_before, not_after);
  12189. EXPECT_TRUE(result);
  12190. // Verify that not_before < now < not_after for a valid cert
  12191. time_t now = time(nullptr);
  12192. EXPECT_LT(not_before, now);
  12193. EXPECT_GT(not_after, now);
  12194. validity_checked = true;
  12195. }
  12196. return true;
  12197. });
  12198. auto res = cli.Get("/test");
  12199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12200. EXPECT_TRUE(validity_checked);
  12201. }
  12202. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12203. using namespace httplib::tls;
  12204. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12205. ASSERT_TRUE(svr.is_valid());
  12206. svr.Get("/test", [](const Request &, Response &res) {
  12207. res.set_content("ok", "text/plain");
  12208. });
  12209. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12210. auto se = detail::scope_exit([&] {
  12211. svr.stop();
  12212. t.join();
  12213. });
  12214. svr.wait_until_ready();
  12215. SSLClient cli(HOST, PORT);
  12216. cli.enable_server_certificate_verification(false);
  12217. cli.set_connection_timeout(30);
  12218. bool serial_checked = false;
  12219. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12220. if (ctx.cert) {
  12221. std::string serial = ctx.serial();
  12222. EXPECT_FALSE(serial.empty());
  12223. // Serial should be a hex string
  12224. for (char c : serial) {
  12225. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12226. (c >= 'a' && c <= 'f'));
  12227. }
  12228. serial_checked = true;
  12229. }
  12230. return true;
  12231. });
  12232. auto res = cli.Get("/test");
  12233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12234. EXPECT_TRUE(serial_checked);
  12235. }
  12236. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12237. // Test 1: Valid CA file - no error should be recorded
  12238. {
  12239. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12240. CLIENT_CA_CERT_FILE);
  12241. ASSERT_TRUE(svr.is_valid());
  12242. // With valid setup, last_ssl_error should be 0
  12243. EXPECT_EQ(0, svr.ssl_last_error());
  12244. }
  12245. // Test 2: Invalid CA file content
  12246. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12247. {
  12248. // Create a temporary file with completely invalid content
  12249. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12250. {
  12251. std::ofstream ofs(temp_invalid_ca);
  12252. ofs << "This is not a certificate file at all\n";
  12253. ofs << "Just plain text content\n";
  12254. }
  12255. // Create server with invalid CA file
  12256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12257. // Clean up temporary file
  12258. std::remove(temp_invalid_ca);
  12259. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12260. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12261. // Note: SSL_CTX_load_verify_locations typically fails first,
  12262. // but our error handling code path is still exercised
  12263. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12264. }
  12265. }
  12266. TEST(VerifyCallbackTest, VerifyContextFields) {
  12267. using namespace httplib::tls;
  12268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12269. ASSERT_TRUE(svr.is_valid());
  12270. svr.Get("/test", [](const Request &, Response &res) {
  12271. res.set_content("ok", "text/plain");
  12272. });
  12273. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12274. auto se = detail::scope_exit([&] {
  12275. svr.stop();
  12276. t.join();
  12277. });
  12278. svr.wait_until_ready();
  12279. SSLClient cli(HOST, PORT);
  12280. cli.enable_server_certificate_verification(false);
  12281. cli.set_connection_timeout(30);
  12282. int callback_count = 0;
  12283. bool saw_leaf_cert = false;
  12284. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12285. if (ctx.cert) {
  12286. callback_count++;
  12287. // We should see at least one certificate (the leaf)
  12288. std::string cn = ctx.subject_cn();
  12289. if (!cn.empty()) { saw_leaf_cert = true; }
  12290. // Verify context fields are populated
  12291. EXPECT_NE(ctx.session, nullptr);
  12292. EXPECT_GE(ctx.depth, 0);
  12293. }
  12294. return true;
  12295. });
  12296. auto res = cli.Get("/test");
  12297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12298. EXPECT_GT(callback_count, 0);
  12299. EXPECT_TRUE(saw_leaf_cert);
  12300. }
  12301. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12302. using httplib::tls::TlsError;
  12303. // Test that verify_error_to_string returns empty for success
  12304. std::string success_str = TlsError::verify_error_to_string(0);
  12305. EXPECT_TRUE(success_str.empty());
  12306. // Test that verify_error_to_string returns non-empty for error codes
  12307. // Using a common error code (certificate expired)
  12308. std::string error_str =
  12309. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12310. EXPECT_FALSE(error_str.empty());
  12311. }
  12312. TEST(SessionVerifierTest, CertificateAccepted) {
  12313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12314. ASSERT_TRUE(svr.is_valid());
  12315. svr.Get("/test", [](const Request &, Response &res) {
  12316. res.set_content("ok", "text/plain");
  12317. });
  12318. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12319. auto se = detail::scope_exit([&] {
  12320. svr.stop();
  12321. t.join();
  12322. });
  12323. svr.wait_until_ready();
  12324. SSLClient cli(HOST, PORT);
  12325. cli.enable_server_certificate_verification(false);
  12326. cli.set_connection_timeout(30);
  12327. bool callback_called = false;
  12328. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12329. EXPECT_NE(session, nullptr);
  12330. callback_called = true;
  12331. return SSLVerifierResponse::CertificateAccepted;
  12332. });
  12333. auto res = cli.Get("/test");
  12334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12335. EXPECT_EQ(200, res->status);
  12336. EXPECT_TRUE(callback_called);
  12337. }
  12338. TEST(SessionVerifierTest, CertificateRejected) {
  12339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12340. ASSERT_TRUE(svr.is_valid());
  12341. svr.Get("/test", [](const Request &, Response &res) {
  12342. res.set_content("ok", "text/plain");
  12343. });
  12344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12345. auto se = detail::scope_exit([&] {
  12346. svr.stop();
  12347. t.join();
  12348. });
  12349. svr.wait_until_ready();
  12350. SSLClient cli(HOST, PORT);
  12351. cli.enable_server_certificate_verification(false);
  12352. cli.set_connection_timeout(30);
  12353. bool callback_called = false;
  12354. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12355. EXPECT_NE(session, nullptr);
  12356. callback_called = true;
  12357. return SSLVerifierResponse::CertificateRejected;
  12358. });
  12359. auto res = cli.Get("/test");
  12360. EXPECT_FALSE(res);
  12361. EXPECT_TRUE(callback_called);
  12362. }
  12363. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  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. // NoDecisionMade with verification disabled should succeed (no default check)
  12376. SSLClient cli(HOST, PORT);
  12377. cli.enable_server_certificate_verification(false);
  12378. cli.set_connection_timeout(30);
  12379. bool callback_called = false;
  12380. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12381. EXPECT_NE(session, nullptr);
  12382. callback_called = true;
  12383. return SSLVerifierResponse::NoDecisionMade;
  12384. });
  12385. auto res = cli.Get("/test");
  12386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12387. EXPECT_EQ(200, res->status);
  12388. EXPECT_TRUE(callback_called);
  12389. }
  12390. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12392. ASSERT_TRUE(svr.is_valid());
  12393. svr.Get("/test", [](const Request &, Response &res) {
  12394. res.set_content("ok", "text/plain");
  12395. });
  12396. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12397. auto se = detail::scope_exit([&] {
  12398. svr.stop();
  12399. t.join();
  12400. });
  12401. svr.wait_until_ready();
  12402. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12403. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12404. // so we only check that the request fails, not whether the callback was
  12405. // called.
  12406. SSLClient cli(HOST, PORT);
  12407. cli.enable_server_certificate_verification(true);
  12408. cli.set_connection_timeout(30);
  12409. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12410. EXPECT_NE(session, nullptr);
  12411. return SSLVerifierResponse::NoDecisionMade;
  12412. });
  12413. auto res = cli.Get("/test");
  12414. EXPECT_FALSE(res);
  12415. }
  12416. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12417. // Test SSL server using PemMemory constructor with client CA certificates
  12418. // Read PEM files
  12419. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12420. read_file(SERVER_CERT_FILE, server_cert_pem);
  12421. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12422. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12423. // Create SSLServer with PemMemory constructor including client CA
  12424. SSLServer::PemMemory server_pem = {
  12425. server_cert_pem.c_str(),
  12426. server_cert_pem.size(),
  12427. server_key_pem.c_str(),
  12428. server_key_pem.size(),
  12429. client_ca_pem.c_str(),
  12430. client_ca_pem.size(),
  12431. nullptr // no password for server key
  12432. };
  12433. SSLServer svr(server_pem);
  12434. ASSERT_TRUE(svr.is_valid());
  12435. // No SSL error should be recorded for valid setup
  12436. EXPECT_EQ(0, svr.ssl_last_error());
  12437. // Set up server endpoints
  12438. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12439. res.set_content("ok", "text/plain");
  12440. });
  12441. // Start server in a thread
  12442. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12443. svr.wait_until_ready();
  12444. // Connect with client certificate (using constructor with paths)
  12445. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12446. cli.enable_server_certificate_verification(false);
  12447. auto res = cli.Get("/test-pem-ca");
  12448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12449. EXPECT_EQ(200, res->status);
  12450. EXPECT_EQ("ok", res->body);
  12451. svr.stop();
  12452. server_thread.join();
  12453. }
  12454. #endif
  12455. #ifdef _WIN32
  12456. TEST(CleanupTest, WSACleanup) {
  12457. int ret = WSACleanup();
  12458. ASSERT_EQ(0, ret);
  12459. }
  12460. #endif
  12461. #ifndef CPPHTTPLIB_SSL_ENABLED
  12462. TEST(NoSSLSupport, SimpleInterface) {
  12463. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12464. }
  12465. #endif
  12466. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12467. TEST(InvalidScheme, SimpleInterface) {
  12468. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12469. }
  12470. #endif
  12471. TEST(NoScheme, SimpleInterface) {
  12472. Client cli("yahoo.com:80");
  12473. ASSERT_TRUE(cli.is_valid());
  12474. }
  12475. TEST(SendAPI, SimpleInterface_Online) {
  12476. Client cli("http://yahoo.com");
  12477. Request req;
  12478. req.method = "GET";
  12479. req.path = "/";
  12480. auto res = cli.send(req);
  12481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12482. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12483. }
  12484. TEST(SendAPI, WithParamsInRequest) {
  12485. Server svr;
  12486. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12487. EXPECT_TRUE(req.has_param("test"));
  12488. EXPECT_EQ("test_value", req.get_param_value("test"));
  12489. });
  12490. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12491. auto se = detail::scope_exit([&] {
  12492. svr.stop();
  12493. t.join();
  12494. ASSERT_FALSE(svr.is_running());
  12495. });
  12496. svr.wait_until_ready();
  12497. Client cli(HOST, PORT);
  12498. {
  12499. Request req;
  12500. req.method = "GET";
  12501. req.path = "/";
  12502. req.params.emplace("test", "test_value");
  12503. auto res = cli.send(req);
  12504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12505. }
  12506. {
  12507. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12509. }
  12510. }
  12511. TEST(ClientImplMethods, GetSocketTest) {
  12512. httplib::Server svr;
  12513. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12514. res.status = StatusCode::OK_200;
  12515. });
  12516. auto port = svr.bind_to_any_port("127.0.0.1");
  12517. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12518. auto se = detail::scope_exit([&] {
  12519. svr.stop();
  12520. thread.join();
  12521. ASSERT_FALSE(svr.is_running());
  12522. });
  12523. svr.wait_until_ready();
  12524. {
  12525. httplib::Client cli("127.0.0.1", port);
  12526. cli.set_keep_alive(true);
  12527. // Use the behavior of cpp-httplib of opening the connection
  12528. // only when the first request happens. If that changes,
  12529. // this test would be obsolete.
  12530. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12531. // This also implicitly tests the server. But other tests would fail much
  12532. // earlier than this one to be considered.
  12533. auto res = cli.Get("/");
  12534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12535. EXPECT_EQ(StatusCode::OK_200, res->status);
  12536. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12537. }
  12538. }
  12539. #ifdef CPPHTTPLIB_SSL_ENABLED
  12540. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12541. Client cli("http://yahoo.com");
  12542. auto res = cli.Get("/");
  12543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12544. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12545. cli.set_follow_location(true);
  12546. res = cli.Get("/");
  12547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12548. EXPECT_EQ(StatusCode::OK_200, res->status);
  12549. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12550. }
  12551. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12552. Client cli("https://yahoo.com");
  12553. auto res = cli.Get("/");
  12554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12555. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12556. cli.set_follow_location(true);
  12557. res = cli.Get("/");
  12558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12559. EXPECT_EQ(StatusCode::OK_200, res->status);
  12560. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12561. }
  12562. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12563. Client cli("https://yahoo.com");
  12564. auto res = cli.Get("/");
  12565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12566. ASSERT_FALSE(!res);
  12567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12568. ASSERT_FALSE(res == nullptr);
  12569. ASSERT_TRUE(res != nullptr);
  12570. EXPECT_EQ(Error::Success, res.error());
  12571. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12572. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12573. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12574. cli.set_follow_location(true);
  12575. res = cli.Get("/");
  12576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12577. EXPECT_EQ(Error::Success, res.error());
  12578. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12579. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12580. EXPECT_EQ(StatusCode::OK_200, res->status);
  12581. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12582. }
  12583. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12584. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12585. Client cli("https://cdnjs.cloudflare.com");
  12586. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12587. Headers{{"Accept-Encoding", "br"}});
  12588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12589. EXPECT_EQ(StatusCode::OK_200, res->status);
  12590. EXPECT_EQ(287630U, res->body.size());
  12591. EXPECT_EQ("application/javascript; charset=utf-8",
  12592. res->get_header_value("Content-Type"));
  12593. }
  12594. #endif
  12595. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12596. #undef REDIR_HOST // Silence compiler warning
  12597. #define REDIR_HOST "https://httpbingo.org"
  12598. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12599. Client cli(REDIR_HOST);
  12600. cli.set_follow_location(true);
  12601. auto res =
  12602. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12604. EXPECT_EQ(StatusCode::OK_200, res->status);
  12605. }
  12606. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12607. Client cli(REDIR_HOST);
  12608. cli.set_follow_location(true);
  12609. Params params;
  12610. params.emplace("url", "http://example.com");
  12611. params.emplace("status_code", "302");
  12612. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12614. EXPECT_EQ(StatusCode::OK_200, res->status);
  12615. }
  12616. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12617. Client cli(REDIR_HOST);
  12618. cli.set_follow_location(true);
  12619. Params params;
  12620. params.emplace("url", "http://example.com");
  12621. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12623. EXPECT_EQ(StatusCode::OK_200, res->status);
  12624. }
  12625. TEST(HttpToHttpsRedirectTest, CertFile) {
  12626. auto ssl_port = PORT + 1;
  12627. Server svr;
  12628. ASSERT_TRUE(svr.is_valid());
  12629. svr.Get("/index", [&](const Request &, Response &res) {
  12630. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12631. "/index");
  12632. svr.stop();
  12633. });
  12634. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12635. ASSERT_TRUE(ssl_svr.is_valid());
  12636. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12637. res.set_content("test", "text/plain");
  12638. ssl_svr.stop();
  12639. });
  12640. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12641. thread t2 =
  12642. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12643. auto se = detail::scope_exit([&] {
  12644. t2.join();
  12645. t.join();
  12646. ASSERT_FALSE(svr.is_running());
  12647. });
  12648. svr.wait_until_ready();
  12649. ssl_svr.wait_until_ready();
  12650. Client cli("127.0.0.1", PORT);
  12651. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12652. cli.enable_server_certificate_verification(true);
  12653. cli.set_follow_location(true);
  12654. cli.set_connection_timeout(30);
  12655. auto res = cli.Get("/index");
  12656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12657. ASSERT_EQ(StatusCode::OK_200, res->status);
  12658. }
  12659. TEST(SSLClientRedirectTest, CertFile) {
  12660. auto ssl_port = PORT + 1;
  12661. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12662. ASSERT_TRUE(ssl_svr1.is_valid());
  12663. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12664. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12665. "/index");
  12666. ssl_svr1.stop();
  12667. });
  12668. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12669. ASSERT_TRUE(ssl_svr2.is_valid());
  12670. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12671. res.set_content("test", "text/plain");
  12672. ssl_svr2.stop();
  12673. });
  12674. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12675. thread t2 =
  12676. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12677. auto se = detail::scope_exit([&] {
  12678. t2.join();
  12679. t.join();
  12680. ASSERT_FALSE(ssl_svr1.is_running());
  12681. });
  12682. ssl_svr1.wait_until_ready();
  12683. ssl_svr2.wait_until_ready();
  12684. SSLClient cli("127.0.0.1", PORT);
  12685. std::string cert;
  12686. read_file(SERVER_CERT2_FILE, cert);
  12687. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12688. cli.enable_server_certificate_verification(true);
  12689. cli.set_follow_location(true);
  12690. cli.set_connection_timeout(30);
  12691. auto res = cli.Get("/index");
  12692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12693. ASSERT_EQ(StatusCode::OK_200, res->status);
  12694. }
  12695. #endif
  12696. #ifdef CPPHTTPLIB_SSL_ENABLED
  12697. // Test that set_ca_cert_store() skips system certs (consistent with
  12698. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12699. // should be trusted - system certs should NOT be loaded.
  12700. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12701. // Load a specific cert that is NOT a system CA cert
  12702. std::string cert;
  12703. read_file(SERVER_CERT2_FILE, cert);
  12704. SSLClient cli("google.com");
  12705. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12706. cli.enable_server_certificate_verification(true);
  12707. // This should FAIL because:
  12708. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12709. // 2. System certs should NOT be loaded when custom store is set
  12710. // If system certs WERE loaded, this would succeed
  12711. auto res = cli.Get("/");
  12712. ASSERT_FALSE(res);
  12713. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12714. }
  12715. // Same as above, but through the native store handle path. Regression test:
  12716. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12717. // merged system certs into the user-provided store.
  12718. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12719. std::string cert;
  12720. read_file(SERVER_CERT2_FILE, cert);
  12721. SSLClient cli("google.com");
  12722. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12723. cli.enable_server_certificate_verification(true);
  12724. auto res = cli.Get("/");
  12725. ASSERT_FALSE(res);
  12726. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12727. }
  12728. // A custom store set via the native handle must still verify a server whose
  12729. // cert it does contain.
  12730. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12731. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12732. ASSERT_TRUE(svr.is_valid());
  12733. svr.Get("/test", [&](const Request &, Response &res) {
  12734. res.set_content("test", "text/plain");
  12735. });
  12736. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12737. auto se = detail::scope_exit([&] {
  12738. svr.stop();
  12739. t.join();
  12740. ASSERT_FALSE(svr.is_running());
  12741. });
  12742. svr.wait_until_ready();
  12743. SSLClient cli("127.0.0.1", PORT);
  12744. std::string cert;
  12745. read_file(SERVER_CERT2_FILE, cert);
  12746. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12747. cli.enable_server_certificate_verification(true);
  12748. cli.set_connection_timeout(30);
  12749. auto res = cli.Get("/test");
  12750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12751. ASSERT_EQ(StatusCode::OK_200, res->status);
  12752. }
  12753. // CA certs loaded through the universal Client must be transferred to the
  12754. // client created internally for following an HTTPS redirect. Regression test:
  12755. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12756. // the CA data for redirect transfer.
  12757. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12758. auto ssl_port = PORT + 1;
  12759. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12760. ASSERT_TRUE(ssl_svr1.is_valid());
  12761. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12762. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12763. "/index");
  12764. });
  12765. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12766. ASSERT_TRUE(ssl_svr2.is_valid());
  12767. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12768. res.set_content("test", "text/plain");
  12769. });
  12770. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12771. thread t2 =
  12772. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12773. auto se = detail::scope_exit([&] {
  12774. ssl_svr2.stop();
  12775. ssl_svr1.stop();
  12776. t2.join();
  12777. t.join();
  12778. ASSERT_FALSE(ssl_svr1.is_running());
  12779. });
  12780. ssl_svr1.wait_until_ready();
  12781. ssl_svr2.wait_until_ready();
  12782. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12783. std::string cert;
  12784. read_file(SERVER_CERT2_FILE, cert);
  12785. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12786. cli.enable_server_certificate_verification(true);
  12787. cli.set_follow_location(true);
  12788. cli.set_connection_timeout(30);
  12789. auto res = cli.Get("/index");
  12790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12791. ASSERT_EQ(StatusCode::OK_200, res->status);
  12792. }
  12793. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12794. // so a host signed by a system CA verifies even though a custom CA is set
  12795. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12796. std::string cert;
  12797. read_file(SERVER_CERT2_FILE, cert);
  12798. SSLClient cli("google.com");
  12799. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12800. cli.enable_system_ca(true);
  12801. cli.enable_server_certificate_verification(true);
  12802. auto res = cli.Get("/");
  12803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12804. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12805. }
  12806. // The custom CA remains effective when combined with the system CA
  12807. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12808. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12809. ASSERT_TRUE(svr.is_valid());
  12810. svr.Get("/test", [&](const Request &, Response &res) {
  12811. res.set_content("test", "text/plain");
  12812. });
  12813. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop();
  12816. t.join();
  12817. ASSERT_FALSE(svr.is_running());
  12818. });
  12819. svr.wait_until_ready();
  12820. SSLClient cli("127.0.0.1", PORT);
  12821. std::string cert;
  12822. read_file(SERVER_CERT2_FILE, cert);
  12823. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12824. cli.enable_system_ca(true);
  12825. cli.enable_server_certificate_verification(true);
  12826. cli.set_connection_timeout(30);
  12827. auto res = cli.Get("/test");
  12828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12829. ASSERT_EQ(StatusCode::OK_200, res->status);
  12830. }
  12831. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  12832. // skip chain verification entirely (only the certificate identity was
  12833. // checked), so a server presenting an untrusted certificate with a matching
  12834. // IP SAN was accepted. The chain must be validated for IP hosts too.
  12835. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  12836. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12837. ASSERT_TRUE(svr.is_valid());
  12838. svr.Get("/test", [&](const Request &, Response &res) {
  12839. res.set_content("test", "text/plain");
  12840. });
  12841. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12842. auto se = detail::scope_exit([&] {
  12843. svr.stop();
  12844. t.join();
  12845. ASSERT_FALSE(svr.is_running());
  12846. });
  12847. svr.wait_until_ready();
  12848. SSLClient cli("127.0.0.1", PORT);
  12849. std::string cert;
  12850. // A trusted CA that did not sign the server certificate. The server cert
  12851. // (cert2) carries the matching IP SAN, so only chain validation can reject
  12852. // this connection.
  12853. read_file(CLIENT_CA_CERT_FILE, cert);
  12854. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12855. cli.enable_server_certificate_verification(true);
  12856. cli.set_connection_timeout(30);
  12857. auto res = cli.Get("/test");
  12858. ASSERT_FALSE(res);
  12859. }
  12860. // enable_system_ca(false) prevents system CA loading entirely
  12861. TEST(SSLClientTest, DisableSystemCa_Online) {
  12862. SSLClient cli("google.com");
  12863. cli.enable_system_ca(false);
  12864. cli.enable_server_certificate_verification(true);
  12865. auto res = cli.Get("/");
  12866. ASSERT_FALSE(res);
  12867. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  12868. // itself when the CA chain is empty
  12869. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12870. res.error() == Error::SSLConnection);
  12871. }
  12872. // The universal Client forwards enable_system_ca()
  12873. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  12874. std::string cert;
  12875. read_file(SERVER_CERT2_FILE, cert);
  12876. Client cli("https://google.com");
  12877. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12878. cli.enable_system_ca(true);
  12879. cli.enable_server_certificate_verification(true);
  12880. auto res = cli.Get("/");
  12881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12882. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12883. }
  12884. // The system CA policy must carry over to the client created internally for
  12885. // following a cross-host HTTPS redirect
  12886. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  12887. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12888. ASSERT_TRUE(svr.is_valid());
  12889. svr.Get("/index", [&](const Request &, Response &res) {
  12890. res.set_redirect("https://www.google.com/");
  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. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12900. std::string cert;
  12901. read_file(SERVER_CERT2_FILE, cert);
  12902. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12903. cli.enable_system_ca(true);
  12904. cli.enable_server_certificate_verification(true);
  12905. cli.set_follow_location(true);
  12906. cli.set_connection_timeout(30);
  12907. // Receiving any response proves the redirect client completed the TLS
  12908. // handshake with a system-CA-signed host
  12909. auto res = cli.Get("/index");
  12910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12911. }
  12912. TEST(MultipartFormDataTest, LargeData) {
  12913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12914. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  12915. const ContentReader &content_reader) {
  12916. if (req.is_multipart_form_data()) {
  12917. std::vector<FormData> items;
  12918. content_reader(
  12919. [&](const FormData &file) {
  12920. items.push_back(file);
  12921. return true;
  12922. },
  12923. [&](const char *data, size_t data_length) {
  12924. items.back().content.append(data, data_length);
  12925. return true;
  12926. });
  12927. EXPECT_TRUE(std::string(items[0].name) == "document");
  12928. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  12929. EXPECT_TRUE(items[0].filename == "2MB_data");
  12930. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  12931. EXPECT_TRUE(items[1].name == "hello");
  12932. EXPECT_TRUE(items[1].content == "world");
  12933. EXPECT_TRUE(items[1].filename == "");
  12934. EXPECT_TRUE(items[1].content_type == "");
  12935. } else {
  12936. std::string body;
  12937. content_reader([&](const char *data, size_t data_length) {
  12938. body.append(data, data_length);
  12939. return true;
  12940. });
  12941. }
  12942. });
  12943. auto port = svr.bind_to_any_port(HOST);
  12944. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12945. auto se = detail::scope_exit([&] {
  12946. svr.stop();
  12947. t.join();
  12948. ASSERT_FALSE(svr.is_running());
  12949. });
  12950. svr.wait_until_ready();
  12951. {
  12952. std::string data(1024 * 1024 * 2, '.');
  12953. std::stringstream buffer;
  12954. buffer << data;
  12955. SSLClient cli(HOST, port);
  12956. cli.enable_server_certificate_verification(false);
  12957. UploadFormDataItems items{
  12958. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  12959. {"hello", "world", "", ""},
  12960. };
  12961. auto res = cli.Post("/post", items);
  12962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12963. ASSERT_EQ(StatusCode::OK_200, res->status);
  12964. }
  12965. }
  12966. TEST(MultipartFormDataTest, DataProviderItems) {
  12967. std::random_device seed_gen;
  12968. std::mt19937 random(seed_gen());
  12969. std::string rand1;
  12970. rand1.resize(1000);
  12971. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  12972. std::string rand2;
  12973. rand2.resize(3000);
  12974. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  12975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12976. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  12977. const ContentReader &content_reader) {
  12978. ASSERT_FALSE(req.is_multipart_form_data());
  12979. std::string body;
  12980. content_reader([&](const char *data, size_t data_length) {
  12981. body.append(data, data_length);
  12982. return true;
  12983. });
  12984. EXPECT_EQ(body, "");
  12985. });
  12986. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  12987. const ContentReader &content_reader) {
  12988. ASSERT_TRUE(req.is_multipart_form_data());
  12989. std::vector<FormData> items;
  12990. content_reader(
  12991. [&](const FormData &file) {
  12992. items.push_back(file);
  12993. return true;
  12994. },
  12995. [&](const char *data, size_t data_length) {
  12996. items.back().content.append(data, data_length);
  12997. return true;
  12998. });
  12999. ASSERT_TRUE(items.size() == 2);
  13000. EXPECT_EQ(std::string(items[0].name), "name1");
  13001. EXPECT_EQ(items[0].content, "Testing123");
  13002. EXPECT_EQ(items[0].filename, "filename1");
  13003. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13004. EXPECT_EQ(items[1].name, "name2");
  13005. EXPECT_EQ(items[1].content, "Testing456");
  13006. EXPECT_EQ(items[1].filename, "");
  13007. EXPECT_EQ(items[1].content_type, "");
  13008. });
  13009. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13010. const ContentReader &content_reader) {
  13011. ASSERT_TRUE(req.is_multipart_form_data());
  13012. std::vector<FormData> items;
  13013. content_reader(
  13014. [&](const FormData &file) {
  13015. items.push_back(file);
  13016. return true;
  13017. },
  13018. [&](const char *data, size_t data_length) {
  13019. items.back().content.append(data, data_length);
  13020. return true;
  13021. });
  13022. ASSERT_TRUE(items.size() == 2);
  13023. EXPECT_EQ(items[0].name, "name3");
  13024. EXPECT_EQ(items[0].content, rand1);
  13025. EXPECT_EQ(items[0].filename, "filename3");
  13026. EXPECT_EQ(items[0].content_type, "");
  13027. EXPECT_EQ(items[1].name, "name4");
  13028. EXPECT_EQ(items[1].content, rand2);
  13029. EXPECT_EQ(items[1].filename, "filename4");
  13030. EXPECT_EQ(items[1].content_type, "");
  13031. });
  13032. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13033. const ContentReader &content_reader) {
  13034. ASSERT_TRUE(req.is_multipart_form_data());
  13035. std::vector<FormData> items;
  13036. content_reader(
  13037. [&](const FormData &file) {
  13038. items.push_back(file);
  13039. return true;
  13040. },
  13041. [&](const char *data, size_t data_length) {
  13042. items.back().content.append(data, data_length);
  13043. return true;
  13044. });
  13045. ASSERT_TRUE(items.size() == 4);
  13046. EXPECT_EQ(std::string(items[0].name), "name1");
  13047. EXPECT_EQ(items[0].content, "Testing123");
  13048. EXPECT_EQ(items[0].filename, "filename1");
  13049. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13050. EXPECT_EQ(items[1].name, "name2");
  13051. EXPECT_EQ(items[1].content, "Testing456");
  13052. EXPECT_EQ(items[1].filename, "");
  13053. EXPECT_EQ(items[1].content_type, "");
  13054. EXPECT_EQ(items[2].name, "name3");
  13055. EXPECT_EQ(items[2].content, rand1);
  13056. EXPECT_EQ(items[2].filename, "filename3");
  13057. EXPECT_EQ(items[2].content_type, "");
  13058. EXPECT_EQ(items[3].name, "name4");
  13059. EXPECT_EQ(items[3].content, rand2);
  13060. EXPECT_EQ(items[3].filename, "filename4");
  13061. EXPECT_EQ(items[3].content_type, "");
  13062. });
  13063. auto port = svr.bind_to_any_port("localhost");
  13064. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13065. auto se = detail::scope_exit([&] {
  13066. svr.stop();
  13067. t.join();
  13068. ASSERT_FALSE(svr.is_running());
  13069. });
  13070. svr.wait_until_ready();
  13071. {
  13072. SSLClient cli("localhost", port);
  13073. cli.enable_server_certificate_verification(false);
  13074. UploadFormDataItems items{
  13075. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13076. {"name2", "Testing456", "", ""}, // not a file
  13077. };
  13078. {
  13079. auto res = cli.Post("/post-none", {}, {}, {});
  13080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13081. ASSERT_EQ(StatusCode::OK_200, res->status);
  13082. }
  13083. FormDataProviderItems providers;
  13084. {
  13085. auto res =
  13086. cli.Post("/post-items", {}, items, providers); // empty providers
  13087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13088. ASSERT_EQ(StatusCode::OK_200, res->status);
  13089. }
  13090. providers.push_back({"name3",
  13091. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13092. // test the offset is given correctly at each step
  13093. if (!offset)
  13094. sink.os.write(rand1.data(), 30);
  13095. else if (offset == 30)
  13096. sink.os.write(rand1.data() + 30, 300);
  13097. else if (offset == 330)
  13098. sink.os.write(rand1.data() + 330, 670);
  13099. else if (offset == rand1.size())
  13100. sink.done();
  13101. return true;
  13102. },
  13103. "filename3",
  13104. {}});
  13105. providers.push_back({"name4",
  13106. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13107. // test the offset is given correctly at each step
  13108. if (!offset)
  13109. sink.os.write(rand2.data(), 2000);
  13110. else if (offset == 2000)
  13111. sink.os.write(rand2.data() + 2000, 1);
  13112. else if (offset == 2001)
  13113. sink.os.write(rand2.data() + 2001, 999);
  13114. else if (offset == rand2.size())
  13115. sink.done();
  13116. return true;
  13117. },
  13118. "filename4",
  13119. {}});
  13120. {
  13121. auto res = cli.Post("/post-providers", {}, {}, providers);
  13122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13123. ASSERT_EQ(StatusCode::OK_200, res->status);
  13124. }
  13125. {
  13126. auto res = cli.Post("/post-both", {}, items, providers);
  13127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13128. ASSERT_EQ(StatusCode::OK_200, res->status);
  13129. }
  13130. }
  13131. }
  13132. TEST(MultipartFormDataTest, BadHeader) {
  13133. Server svr;
  13134. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13135. res.set_content("ok", "text/plain");
  13136. });
  13137. thread t = thread([&] { svr.listen(HOST, PORT); });
  13138. auto se = detail::scope_exit([&] {
  13139. svr.stop();
  13140. t.join();
  13141. ASSERT_FALSE(svr.is_running());
  13142. });
  13143. svr.wait_until_ready();
  13144. const std::string body =
  13145. "This is the preamble. It is to be ignored, though it\r\n"
  13146. "is a handy place for composition agents to include an\r\n"
  13147. "explanatory note to non-MIME conformant readers.\r\n"
  13148. "\r\n"
  13149. "\r\n"
  13150. "--simple boundary\r\n"
  13151. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13152. ": BAD...\r\n"
  13153. "\r\n"
  13154. "value1\r\n"
  13155. "--simple boundary\r\n"
  13156. "Content-Disposition: form-data; name=\"field2\"; "
  13157. "filename=\"example.txt\"\r\n"
  13158. "\r\n"
  13159. "value2\r\n"
  13160. "--simple boundary--\r\n"
  13161. "This is the epilogue. It is also to be ignored.\r\n";
  13162. std::string content_type =
  13163. R"(multipart/form-data; boundary="simple boundary")";
  13164. Client cli(HOST, PORT);
  13165. auto res = cli.Post("/post", body, content_type.c_str());
  13166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13167. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13168. }
  13169. TEST(MultipartFormDataTest, WithPreamble) {
  13170. Server svr;
  13171. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13172. res.set_content("ok", "text/plain");
  13173. });
  13174. thread t = thread([&] { svr.listen(HOST, PORT); });
  13175. auto se = detail::scope_exit([&] {
  13176. svr.stop();
  13177. t.join();
  13178. ASSERT_FALSE(svr.is_running());
  13179. });
  13180. svr.wait_until_ready();
  13181. const std::string body =
  13182. "This is the preamble. It is to be ignored, though it\r\n"
  13183. "is a handy place for composition agents to include an\r\n"
  13184. "explanatory note to non-MIME conformant readers.\r\n"
  13185. "\r\n"
  13186. "\r\n"
  13187. "--simple boundary\r\n"
  13188. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13189. "\r\n"
  13190. "value1\r\n"
  13191. "--simple boundary\r\n"
  13192. "Content-Disposition: form-data; name=\"field2\"; "
  13193. "filename=\"example.txt\"\r\n"
  13194. "\r\n"
  13195. "value2\r\n"
  13196. "--simple boundary--\r\n"
  13197. "This is the epilogue. It is also to be ignored.\r\n";
  13198. std::string content_type =
  13199. R"(multipart/form-data; boundary="simple boundary")";
  13200. Client cli(HOST, PORT);
  13201. auto res = cli.Post("/post", body, content_type.c_str());
  13202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13203. EXPECT_EQ(StatusCode::OK_200, res->status);
  13204. }
  13205. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13207. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13208. const ContentReader &content_reader) {
  13209. if (req.is_multipart_form_data()) {
  13210. std::vector<FormData> items;
  13211. content_reader(
  13212. [&](const FormData &file) {
  13213. items.push_back(file);
  13214. return true;
  13215. },
  13216. [&](const char *data, size_t data_length) {
  13217. items.back().content.append(data, data_length);
  13218. return true;
  13219. });
  13220. EXPECT_TRUE(std::string(items[0].name) == "document");
  13221. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13222. EXPECT_TRUE(items[0].filename == "2MB_data");
  13223. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13224. EXPECT_TRUE(items[1].name == "hello");
  13225. EXPECT_TRUE(items[1].content == "world");
  13226. EXPECT_TRUE(items[1].filename == "");
  13227. EXPECT_TRUE(items[1].content_type == "");
  13228. } else {
  13229. std::string body;
  13230. content_reader([&](const char *data, size_t data_length) {
  13231. body.append(data, data_length);
  13232. return true;
  13233. });
  13234. }
  13235. });
  13236. auto port = svr.bind_to_any_port("localhost");
  13237. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13238. auto se = detail::scope_exit([&] {
  13239. svr.stop();
  13240. t.join();
  13241. ASSERT_FALSE(svr.is_running());
  13242. });
  13243. svr.wait_until_ready();
  13244. {
  13245. std::string data(1024 * 1024 * 2, '.');
  13246. std::stringstream buffer;
  13247. buffer << data;
  13248. SSLClient cli("localhost", port);
  13249. cli.enable_server_certificate_verification(false);
  13250. UploadFormDataItems items{
  13251. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13252. {"hello", "world", "", ""},
  13253. };
  13254. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13256. ASSERT_EQ(StatusCode::OK_200, res->status);
  13257. }
  13258. }
  13259. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13260. std::string data(1024 * 1024 * 2, '&');
  13261. std::stringstream buffer;
  13262. buffer << data;
  13263. Client cli("https://localhost:8080");
  13264. UploadFormDataItems items{
  13265. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13266. {"hello", "world", "", ""},
  13267. };
  13268. for (const char &c : " \t\r\n") {
  13269. auto res =
  13270. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13271. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13272. ASSERT_FALSE(res);
  13273. }
  13274. }
  13275. TEST(MultipartFormDataTest, PutFormData) {
  13276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13277. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13278. const ContentReader &content_reader) {
  13279. if (req.is_multipart_form_data()) {
  13280. std::vector<FormData> items;
  13281. content_reader(
  13282. [&](const FormData &file) {
  13283. items.push_back(file);
  13284. return true;
  13285. },
  13286. [&](const char *data, size_t data_length) {
  13287. items.back().content.append(data, data_length);
  13288. return true;
  13289. });
  13290. EXPECT_TRUE(std::string(items[0].name) == "document");
  13291. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13292. EXPECT_TRUE(items[0].filename == "2MB_data");
  13293. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13294. EXPECT_TRUE(items[1].name == "hello");
  13295. EXPECT_TRUE(items[1].content == "world");
  13296. EXPECT_TRUE(items[1].filename == "");
  13297. EXPECT_TRUE(items[1].content_type == "");
  13298. } else {
  13299. std::string body;
  13300. content_reader([&](const char *data, size_t data_length) {
  13301. body.append(data, data_length);
  13302. return true;
  13303. });
  13304. }
  13305. });
  13306. auto port = svr.bind_to_any_port("localhost");
  13307. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13308. auto se = detail::scope_exit([&] {
  13309. svr.stop();
  13310. t.join();
  13311. ASSERT_FALSE(svr.is_running());
  13312. });
  13313. svr.wait_until_ready();
  13314. {
  13315. std::string data(1024 * 1024 * 2, '&');
  13316. std::stringstream buffer;
  13317. buffer << data;
  13318. SSLClient cli("localhost", port);
  13319. cli.enable_server_certificate_verification(false);
  13320. UploadFormDataItems items{
  13321. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13322. {"hello", "world", "", ""},
  13323. };
  13324. auto res = cli.Put("/put", items);
  13325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13326. ASSERT_EQ(StatusCode::OK_200, res->status);
  13327. }
  13328. }
  13329. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13331. svr.Put("/put_customboundary",
  13332. [&](const Request &req, const Response & /*res*/,
  13333. const ContentReader &content_reader) {
  13334. if (req.is_multipart_form_data()) {
  13335. std::vector<FormData> items;
  13336. content_reader(
  13337. [&](const FormData &file) {
  13338. items.push_back(file);
  13339. return true;
  13340. },
  13341. [&](const char *data, size_t data_length) {
  13342. items.back().content.append(data, data_length);
  13343. return true;
  13344. });
  13345. EXPECT_TRUE(std::string(items[0].name) == "document");
  13346. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13347. EXPECT_TRUE(items[0].filename == "2MB_data");
  13348. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13349. EXPECT_TRUE(items[1].name == "hello");
  13350. EXPECT_TRUE(items[1].content == "world");
  13351. EXPECT_TRUE(items[1].filename == "");
  13352. EXPECT_TRUE(items[1].content_type == "");
  13353. } else {
  13354. std::string body;
  13355. content_reader([&](const char *data, size_t data_length) {
  13356. body.append(data, data_length);
  13357. return true;
  13358. });
  13359. }
  13360. });
  13361. auto port = svr.bind_to_any_port("localhost");
  13362. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13363. auto se = detail::scope_exit([&] {
  13364. svr.stop();
  13365. t.join();
  13366. ASSERT_FALSE(svr.is_running());
  13367. });
  13368. svr.wait_until_ready();
  13369. {
  13370. std::string data(1024 * 1024 * 2, '&');
  13371. std::stringstream buffer;
  13372. buffer << data;
  13373. SSLClient cli("localhost", port);
  13374. cli.enable_server_certificate_verification(false);
  13375. UploadFormDataItems items{
  13376. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13377. {"hello", "world", "", ""},
  13378. };
  13379. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13381. ASSERT_EQ(StatusCode::OK_200, res->status);
  13382. }
  13383. }
  13384. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13385. std::string data(1024 * 1024 * 2, '&');
  13386. std::stringstream buffer;
  13387. buffer << data;
  13388. Client cli("https://localhost:8080");
  13389. cli.enable_server_certificate_verification(false);
  13390. UploadFormDataItems items{
  13391. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13392. {"hello", "world", "", ""},
  13393. };
  13394. for (const char &c : " \t\r\n") {
  13395. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13396. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13397. ASSERT_FALSE(res);
  13398. }
  13399. }
  13400. TEST(MultipartFormDataTest, AlternateFilename) {
  13401. auto handled = false;
  13402. Server svr;
  13403. svr.Post("/test", [&](const Request &req, Response &res) {
  13404. ASSERT_EQ(2u, req.form.files.size());
  13405. ASSERT_EQ(1u, req.form.fields.size());
  13406. // Test files
  13407. const auto &file1 = req.form.get_file("file1");
  13408. ASSERT_EQ("file1", file1.name);
  13409. ASSERT_EQ("A.txt", file1.filename);
  13410. ASSERT_EQ("text/plain", file1.content_type);
  13411. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13412. const auto &file2 = req.form.get_file("file2");
  13413. ASSERT_EQ("file2", file2.name);
  13414. ASSERT_EQ("a.html", file2.filename);
  13415. ASSERT_EQ("text/html", file2.content_type);
  13416. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13417. file2.content);
  13418. // Test text field
  13419. const auto &text = req.form.get_field("text");
  13420. ASSERT_EQ("text default", text);
  13421. res.set_content("ok", "text/plain");
  13422. handled = true;
  13423. });
  13424. thread t = thread([&] { svr.listen(HOST, PORT); });
  13425. auto se = detail::scope_exit([&] {
  13426. svr.stop();
  13427. t.join();
  13428. ASSERT_FALSE(svr.is_running());
  13429. ASSERT_TRUE(handled);
  13430. });
  13431. svr.wait_until_ready();
  13432. auto req = "POST /test HTTP/1.1\r\n"
  13433. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13434. "Content-Length: 399\r\n"
  13435. "\r\n"
  13436. "----------\r\n"
  13437. "Content-Disposition: form-data; name=\"text\"\r\n"
  13438. "\r\n"
  13439. "text default\r\n"
  13440. "----------\r\n"
  13441. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13442. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13443. "Content-Type: text/plain\r\n"
  13444. "\r\n"
  13445. "Content of a.txt.\r\n"
  13446. "\r\n"
  13447. "----------\r\n"
  13448. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13449. "\"a.html\"\r\n"
  13450. "Content-Type: text/html\r\n"
  13451. "\r\n"
  13452. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13453. "\r\n"
  13454. "------------\r\n";
  13455. ASSERT_TRUE(send_request(1, req));
  13456. }
  13457. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13458. auto handled = false;
  13459. Server svr;
  13460. svr.Post("/test", [&](const Request &req, Response &res) {
  13461. // Case-insensitive "utf-8''" prefix with a long value
  13462. const auto &file = req.form.get_file("file1");
  13463. ASSERT_EQ("file1", file.name);
  13464. // 8000 chars exercises both the Content-Disposition parser and the
  13465. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13466. // Prior to the fix, std::regex_match on this header would cause O(N)
  13467. // stack recursion in libstdc++, leading to SIGSEGV.
  13468. std::string expected_filename(8000, 'A');
  13469. ASSERT_EQ(expected_filename, file.filename);
  13470. res.set_content("ok", "text/plain");
  13471. handled = true;
  13472. });
  13473. thread t = thread([&] { svr.listen(HOST, PORT); });
  13474. auto se = detail::scope_exit([&] {
  13475. svr.stop();
  13476. t.join();
  13477. ASSERT_FALSE(svr.is_running());
  13478. ASSERT_TRUE(handled);
  13479. });
  13480. svr.wait_until_ready();
  13481. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13482. // Regression test for GHSA-qq6v-r583-3h69
  13483. std::string long_filename(8000, 'A');
  13484. std::string body = "----------\r\n"
  13485. "Content-Disposition: form-data; name=\"file1\"; "
  13486. "filename*=\"Utf-8''" +
  13487. long_filename +
  13488. "\"\r\n"
  13489. "\r\n"
  13490. "hello\r\n"
  13491. "------------\r\n";
  13492. auto req = "POST /test HTTP/1.1\r\n"
  13493. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13494. "Content-Length: " +
  13495. std::to_string(body.size()) + "\r\n\r\n" + body;
  13496. ASSERT_TRUE(send_request(1, req));
  13497. }
  13498. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13499. auto handled = false;
  13500. Server svr;
  13501. svr.Post("/test", [&](const Request &req, Response &) {
  13502. ASSERT_EQ(2u, req.form.fields.size());
  13503. const auto &text1 = req.form.get_field("text1");
  13504. ASSERT_EQ("text1", text1);
  13505. const auto &text2 = req.form.get_field("text2");
  13506. ASSERT_EQ("text2", text2);
  13507. handled = true;
  13508. });
  13509. thread t = thread([&] { svr.listen(HOST, PORT); });
  13510. auto se = detail::scope_exit([&] {
  13511. svr.stop();
  13512. t.join();
  13513. ASSERT_FALSE(svr.is_running());
  13514. ASSERT_TRUE(handled);
  13515. });
  13516. svr.wait_until_ready();
  13517. auto req = "POST /test HTTP/1.1\r\n"
  13518. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13519. "Content-Length: 146\r\n"
  13520. "\r\n----------\r\n"
  13521. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13522. "\r\n"
  13523. "text1"
  13524. "\r\n----------\r\n"
  13525. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13526. "\r\n"
  13527. "text2"
  13528. "\r\n------------";
  13529. std::string response;
  13530. ASSERT_TRUE(send_request(1, req, &response));
  13531. ASSERT_EQ("200", response.substr(9, 3));
  13532. }
  13533. TEST(MultipartFormDataTest, ContentLength) {
  13534. auto handled = false;
  13535. Server svr;
  13536. svr.Post("/test", [&](const Request &req, Response &) {
  13537. ASSERT_EQ(2u, req.form.fields.size());
  13538. const auto &text1 = req.form.get_field("text1");
  13539. ASSERT_EQ("text1", text1);
  13540. const auto &text2 = req.form.get_field("text2");
  13541. ASSERT_EQ("text2", text2);
  13542. handled = true;
  13543. });
  13544. thread t = thread([&] { svr.listen(HOST, PORT); });
  13545. auto se = detail::scope_exit([&] {
  13546. svr.stop();
  13547. t.join();
  13548. ASSERT_FALSE(svr.is_running());
  13549. ASSERT_TRUE(handled);
  13550. });
  13551. svr.wait_until_ready();
  13552. auto req = "POST /test HTTP/1.1\r\n"
  13553. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13554. "Content-Length: 167\r\n"
  13555. "\r\n----------\r\n"
  13556. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13557. "Content-Length: 5\r\n"
  13558. "\r\n"
  13559. "text1"
  13560. "\r\n----------\r\n"
  13561. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13562. "\r\n"
  13563. "text2"
  13564. "\r\n------------\r\n";
  13565. std::string response;
  13566. ASSERT_TRUE(send_request(1, req, &response));
  13567. ASSERT_EQ("200", response.substr(9, 3));
  13568. }
  13569. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13570. auto handled = false;
  13571. Server svr;
  13572. svr.Post("/test", [&](const Request &req, Response &) {
  13573. ASSERT_EQ(2u, req.form.fields.size());
  13574. const auto &text1 = req.form.get_field("text1");
  13575. ASSERT_EQ("text1", text1);
  13576. // TODO: Add header access for text fields if needed
  13577. const auto &text2 = req.form.get_field("text2");
  13578. ASSERT_EQ("text2", text2);
  13579. // TODO: Header access for text fields needs to be implemented
  13580. // auto &headers = it->second.headers;
  13581. // ASSERT_EQ(3U, headers.size());
  13582. // auto custom_header = headers.find("x-whatever");
  13583. // ASSERT_TRUE(custom_header != headers.end());
  13584. // ASSERT_NE("customvalue", custom_header->second);
  13585. // ASSERT_EQ("CustomValue", custom_header->second);
  13586. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13587. handled = true;
  13588. });
  13589. thread t = thread([&] { svr.listen(HOST, PORT); });
  13590. auto se = detail::scope_exit([&] {
  13591. svr.stop();
  13592. t.join();
  13593. ASSERT_FALSE(svr.is_running());
  13594. ASSERT_TRUE(handled);
  13595. });
  13596. svr.wait_until_ready();
  13597. auto req = "POST /test HTTP/1.1\r\n"
  13598. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13599. "Content-Length: 232\r\n"
  13600. "\r\n----------\r\n"
  13601. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13602. "Content-Length: 5\r\n"
  13603. "X-Test: 1\r\n"
  13604. "\r\n"
  13605. "text1"
  13606. "\r\n----------\r\n"
  13607. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13608. "Content-Type: text/plain\r\n"
  13609. "X-Whatever: CustomValue\r\n"
  13610. "\r\n"
  13611. "text2"
  13612. "\r\n------------\r\n"
  13613. "That should be disregarded. Not even read";
  13614. std::string response;
  13615. ASSERT_TRUE(send_request(1, req, &response));
  13616. ASSERT_EQ("200", response.substr(9, 3));
  13617. }
  13618. TEST(MultipartFormDataTest, LargeHeader) {
  13619. auto handled = false;
  13620. Server svr;
  13621. svr.Post("/test", [&](const Request &req, Response &) {
  13622. ASSERT_EQ(1u, req.form.fields.size());
  13623. const auto &text = req.form.get_field("name1");
  13624. ASSERT_EQ("text1", text);
  13625. handled = true;
  13626. });
  13627. thread t = thread([&] { svr.listen(HOST, PORT); });
  13628. auto se = detail::scope_exit([&] {
  13629. svr.stop();
  13630. t.join();
  13631. ASSERT_FALSE(svr.is_running());
  13632. ASSERT_TRUE(handled);
  13633. });
  13634. svr.wait_until_ready();
  13635. auto boundary = std::string("cpp-httplib-multipart-data");
  13636. std::string content = "--" + boundary +
  13637. "\r\n"
  13638. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13639. "\r\n"
  13640. "text1\r\n"
  13641. "--" +
  13642. boundary + "--\r\n";
  13643. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13644. "Content-Type: multipart/form-data;boundary=" +
  13645. boundary +
  13646. "\r\n"
  13647. "Content-Length: " +
  13648. std::to_string(content.size()) +
  13649. "\r\n"
  13650. "Dummy-Header: ";
  13651. std::string header_suffix = "\r\n"
  13652. "\r\n";
  13653. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13654. size_t header_dummy_size =
  13655. read_buff_size -
  13656. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13657. auto header_dummy = std::string(header_dummy_size, '@');
  13658. auto req = header_prefix + header_dummy + header_suffix + content;
  13659. std::string response;
  13660. ASSERT_TRUE(send_request(1, req, &response));
  13661. ASSERT_EQ("200", response.substr(9, 3));
  13662. }
  13663. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13664. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13665. // (not chunked Transfer-Encoding) after the streaming refactor.
  13666. auto handled = false;
  13667. Server svr;
  13668. svr.Post("/upload", [&](const Request &req, Response &res) {
  13669. auto cl_it = req.headers.find("Content-Length");
  13670. EXPECT_TRUE(cl_it != req.headers.end());
  13671. auto te_it = req.headers.find("Transfer-Encoding");
  13672. EXPECT_TRUE(te_it == req.headers.end());
  13673. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13674. res.set_content("ok", "text/plain");
  13675. handled = true;
  13676. });
  13677. auto port = svr.bind_to_any_port(HOST);
  13678. auto t = thread([&] { svr.listen_after_bind(); });
  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. UploadFormDataItems items = {
  13687. {"field1", "hello", "", "text/plain"},
  13688. {"file1", "world", "test.txt", "application/octet-stream"},
  13689. };
  13690. Client cli(HOST, port);
  13691. auto res = cli.Post("/upload", {}, items);
  13692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13693. EXPECT_EQ(StatusCode::OK_200, res->status);
  13694. }
  13695. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13696. // Verify that make_multipart_content_provider coalesces many small segments
  13697. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13698. constexpr size_t kItemCount = 1000;
  13699. UploadFormDataItems items;
  13700. items.reserve(kItemCount);
  13701. for (size_t i = 0; i < kItemCount; i++) {
  13702. items.push_back(
  13703. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13704. }
  13705. const std::string boundary = "----test-boundary";
  13706. auto content_length = detail::get_multipart_content_length(items, boundary);
  13707. auto provider = detail::make_multipart_content_provider(items, boundary);
  13708. // Drive the provider the same way write_content_with_progress does
  13709. size_t write_count = 0;
  13710. size_t total_bytes = 0;
  13711. DataSink sink;
  13712. size_t offset = 0;
  13713. sink.write = [&](const char *d, size_t l) -> bool {
  13714. (void)d;
  13715. write_count++;
  13716. total_bytes += l;
  13717. offset += l;
  13718. return true;
  13719. };
  13720. sink.is_writable = []() -> bool { return true; };
  13721. while (offset < content_length) {
  13722. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13723. }
  13724. EXPECT_EQ(content_length, total_bytes);
  13725. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13726. // With buffering into 64KB blocks, write_count should be much smaller.
  13727. auto segment_count = 3 * kItemCount + 1;
  13728. EXPECT_LT(write_count, segment_count / 10);
  13729. }
  13730. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13731. // Integration test: send many UploadFormDataItems and verify the server
  13732. // receives all of them correctly (#2410).
  13733. constexpr size_t kItemCount = 500;
  13734. auto handled = false;
  13735. Server svr;
  13736. svr.Post("/upload", [&](const Request &req, Response &res) {
  13737. EXPECT_EQ(kItemCount, req.form.fields.size());
  13738. for (size_t i = 0; i < kItemCount; i++) {
  13739. auto key = "field" + std::to_string(i);
  13740. auto val = "value" + std::to_string(i);
  13741. auto it = req.form.fields.find(key);
  13742. if (it != req.form.fields.end()) {
  13743. EXPECT_EQ(val, it->second.content);
  13744. } else {
  13745. ADD_FAILURE() << "Missing field: " << key;
  13746. }
  13747. }
  13748. res.set_content("ok", "text/plain");
  13749. handled = true;
  13750. });
  13751. auto port = svr.bind_to_any_port(HOST);
  13752. auto t = thread([&] { svr.listen_after_bind(); });
  13753. auto se = detail::scope_exit([&] {
  13754. svr.stop();
  13755. t.join();
  13756. ASSERT_FALSE(svr.is_running());
  13757. ASSERT_TRUE(handled);
  13758. });
  13759. svr.wait_until_ready();
  13760. UploadFormDataItems items;
  13761. items.reserve(kItemCount);
  13762. for (size_t i = 0; i < kItemCount; i++) {
  13763. items.push_back(
  13764. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13765. }
  13766. Client cli(HOST, port);
  13767. auto res = cli.Post("/upload", items);
  13768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13769. EXPECT_EQ(StatusCode::OK_200, res->status);
  13770. }
  13771. TEST(MultipartFormDataTest, MakeFileProvider) {
  13772. // Verify make_file_provider sends a file's contents correctly.
  13773. const std::string file_content(4096, 'Z');
  13774. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13775. {
  13776. std::ofstream ofs(tmp_path, std::ios::binary);
  13777. ofs.write(file_content.data(),
  13778. static_cast<std::streamsize>(file_content.size()));
  13779. }
  13780. auto handled = false;
  13781. Server svr;
  13782. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13783. const ContentReader &content_reader) {
  13784. ASSERT_TRUE(req.is_multipart_form_data());
  13785. std::vector<FormData> items;
  13786. content_reader(
  13787. [&](const FormData &file) {
  13788. items.push_back(file);
  13789. return true;
  13790. },
  13791. [&](const char *data, size_t data_length) {
  13792. items.back().content.append(data, data_length);
  13793. return true;
  13794. });
  13795. ASSERT_EQ(1u, items.size());
  13796. EXPECT_EQ("myfile", items[0].name);
  13797. EXPECT_EQ("data.bin", items[0].filename);
  13798. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13799. EXPECT_EQ(file_content, items[0].content);
  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. std::remove(tmp_path.c_str());
  13810. });
  13811. svr.wait_until_ready();
  13812. FormDataProviderItems providers;
  13813. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13814. "application/octet-stream"));
  13815. Client cli(HOST, port);
  13816. auto res = cli.Post("/upload", {}, {}, providers);
  13817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13818. EXPECT_EQ(StatusCode::OK_200, res->status);
  13819. }
  13820. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  13821. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  13822. // (100) headers is rejected with a 400 Bad Request response.
  13823. Server svr;
  13824. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13825. res.set_content("ok", "text/plain");
  13826. });
  13827. thread t = thread([&] { svr.listen(HOST, PORT); });
  13828. auto se = detail::scope_exit([&] {
  13829. svr.stop();
  13830. t.join();
  13831. ASSERT_FALSE(svr.is_running());
  13832. });
  13833. svr.wait_until_ready();
  13834. // Build a multipart part with 101 custom headers (exceeding
  13835. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  13836. std::stringstream body;
  13837. body << "--simpleboundary\r\n"
  13838. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  13839. for (int i = 0; i < 101; i++) {
  13840. body << "X-Custom-Header-" << i << ": value\r\n";
  13841. }
  13842. body << "\r\n"
  13843. << "value1\r\n"
  13844. << "--simpleboundary--\r\n";
  13845. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  13846. Client cli(HOST, PORT);
  13847. auto res = cli.Post("/post", body.str(), content_type.c_str());
  13848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13849. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13850. }
  13851. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  13852. // A body that never contains the declared boundary must not be accumulated
  13853. // while the parser waits for it. Buffering it would also make every read
  13854. // rescan everything seen so far, which is quadratic in the body size.
  13855. Server svr;
  13856. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13857. res.set_content("ok", "text/plain");
  13858. });
  13859. auto port = svr.bind_to_any_port(HOST);
  13860. thread t = thread([&] { svr.listen_after_bind(); });
  13861. auto se = detail::scope_exit([&] {
  13862. svr.stop();
  13863. t.join();
  13864. ASSERT_FALSE(svr.is_running());
  13865. });
  13866. svr.wait_until_ready();
  13867. Client cli(HOST, port);
  13868. cli.set_read_timeout(60, 0);
  13869. cli.set_write_timeout(60, 0);
  13870. // '-' is the worst case: it matches the first character of the boundary, so
  13871. // every position has to be checked against it.
  13872. auto post_dashes = [&](size_t size) {
  13873. const std::string body(size, '-');
  13874. auto start = std::chrono::steady_clock::now();
  13875. auto res =
  13876. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  13877. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  13878. std::chrono::steady_clock::now() - start)
  13879. .count();
  13880. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  13881. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  13882. return ms;
  13883. };
  13884. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  13885. // Windows.
  13886. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  13887. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  13888. // Comparing the two sizes rather than checking an absolute duration keeps
  13889. // this meaningful across build types and CI load, both of which move the
  13890. // absolute numbers by more than an order of magnitude. Four times the bytes
  13891. // costs about four times the time when parsing is linear, and about sixteen
  13892. // times when the body is buffered and rescanned.
  13893. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  13894. EXPECT_LT(ms_16mb, ms_4mb * 10)
  13895. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  13896. << "ms, which suggests the body is being buffered and rescanned";
  13897. }
  13898. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  13899. // A boundary can only be followed by CRLF or by "--", so anything else is
  13900. // malformed no matter what comes next. The parser must say so right away
  13901. // instead of buffering the rest of the declared body.
  13902. Server svr;
  13903. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  13904. res.set_content("ok", "text/plain");
  13905. });
  13906. auto port = svr.bind_to_any_port(HOST);
  13907. thread t = thread([&] { svr.listen_after_bind(); });
  13908. auto se = detail::scope_exit([&] {
  13909. svr.stop();
  13910. t.join();
  13911. ASSERT_FALSE(svr.is_running());
  13912. });
  13913. svr.wait_until_ready();
  13914. // Announce a 1 MB body but send only the malformed prefix. A parser that
  13915. // buffers instead of failing would still be waiting for the remaining bytes.
  13916. const std::string body = "--zzzz\r\n"
  13917. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13918. "\r\n"
  13919. "text1"
  13920. "\r\n--zzzzXX";
  13921. const std::string req = "POST /post HTTP/1.1\r\n"
  13922. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13923. "Content-Length: 1048576\r\n"
  13924. "\r\n" +
  13925. body;
  13926. std::string response;
  13927. ASSERT_TRUE(send_request(3, req, &response, port));
  13928. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  13929. EXPECT_EQ("400", response.substr(9, 3));
  13930. }
  13931. // Posts a multipart body split into two writes, so that the server sees the
  13932. // split at whatever offset the caller chose, and expects the single "text1"
  13933. // field to come through.
  13934. static void expect_split_multipart_ok(const std::string &body1,
  13935. const std::string &body2) {
  13936. auto handled = false;
  13937. Server svr;
  13938. svr.Post("/post", [&](const Request &req, Response &) {
  13939. EXPECT_EQ(1u, req.form.fields.size());
  13940. EXPECT_EQ("text1", req.form.get_field("text1"));
  13941. handled = true;
  13942. });
  13943. auto port = svr.bind_to_any_port(HOST);
  13944. thread t = thread([&] { svr.listen_after_bind(); });
  13945. auto se = detail::scope_exit([&] {
  13946. svr.stop();
  13947. t.join();
  13948. ASSERT_FALSE(svr.is_running());
  13949. ASSERT_TRUE(handled);
  13950. });
  13951. svr.wait_until_ready();
  13952. // "Connection: close" makes the server close once it has answered, so the
  13953. // response drain ends immediately instead of idling until the read timeout.
  13954. const std::string head =
  13955. "POST /post HTTP/1.1\r\n"
  13956. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  13957. "Connection: close\r\n"
  13958. "Content-Length: " +
  13959. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  13960. std::string response;
  13961. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  13962. ASSERT_GE(response.size(), 12u) << "no response";
  13963. EXPECT_EQ("200", response.substr(9, 3));
  13964. }
  13965. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  13966. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  13967. // ignored, including when it does not arrive in the same read as the
  13968. // close-delimiter itself.
  13969. expect_split_multipart_ok("--zzzz\r\n"
  13970. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13971. "\r\n"
  13972. "text1"
  13973. "\r\n--zzzz--",
  13974. "\r\nthis epilogue must be ignored\r\n");
  13975. }
  13976. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  13977. // The initial boundary may be preceded by a preamble of any length and may
  13978. // straddle a read boundary. Discarding data while waiting for it must not
  13979. // throw away a partial boundary sitting at the end of the buffer.
  13980. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  13981. "zz\r\n"
  13982. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13983. "\r\n"
  13984. "text1"
  13985. "\r\n--zzzz--\r\n");
  13986. }
  13987. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  13988. // The received boundary was only checked for being non-empty, so it could be
  13989. // as long as a header is allowed to be. The parser scans the body for
  13990. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  13991. // costs a nearly full comparison at nearly every position, making the
  13992. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  13993. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  13994. Server svr;
  13995. svr.Post("/post", [](const Request &req, Response &res) {
  13996. EXPECT_EQ(1u, req.form.fields.size());
  13997. EXPECT_EQ("text1", req.form.get_field("text1"));
  13998. res.set_content("ok", "text/plain");
  13999. });
  14000. auto port = svr.bind_to_any_port(HOST);
  14001. thread t = thread([&] { svr.listen_after_bind(); });
  14002. auto se = detail::scope_exit([&] {
  14003. svr.stop();
  14004. t.join();
  14005. ASSERT_FALSE(svr.is_running());
  14006. });
  14007. svr.wait_until_ready();
  14008. Client cli(HOST, port);
  14009. auto post_with_boundary_of_length = [&](size_t len) {
  14010. const std::string boundary(len, 'a');
  14011. const std::string body =
  14012. "--" + boundary +
  14013. "\r\n"
  14014. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14015. "\r\n"
  14016. "text1"
  14017. "\r\n--" +
  14018. boundary + "--\r\n";
  14019. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14020. };
  14021. auto res = post_with_boundary_of_length(70);
  14022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14023. EXPECT_EQ(StatusCode::OK_200, res->status);
  14024. res = post_with_boundary_of_length(71);
  14025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14026. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14027. }
  14028. TEST(MakeFileBodyTest, Basic) {
  14029. const std::string file_content(4096, 'Z');
  14030. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14031. {
  14032. std::ofstream ofs(tmp_path, std::ios::binary);
  14033. ofs.write(file_content.data(),
  14034. static_cast<std::streamsize>(file_content.size()));
  14035. }
  14036. auto handled = false;
  14037. Server svr;
  14038. svr.Post("/upload", [&](const Request &req, Response &res) {
  14039. EXPECT_EQ(file_content, req.body);
  14040. handled = true;
  14041. res.status = StatusCode::OK_200;
  14042. });
  14043. auto port = svr.bind_to_any_port(HOST);
  14044. auto t = thread([&] { svr.listen_after_bind(); });
  14045. auto se = detail::scope_exit([&] {
  14046. svr.stop();
  14047. t.join();
  14048. ASSERT_FALSE(svr.is_running());
  14049. ASSERT_TRUE(handled);
  14050. std::remove(tmp_path.c_str());
  14051. });
  14052. svr.wait_until_ready();
  14053. auto fb = make_file_body(tmp_path);
  14054. ASSERT_GT(fb.first, 0u);
  14055. Client cli(HOST, port);
  14056. auto res =
  14057. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14059. EXPECT_EQ(StatusCode::OK_200, res->status);
  14060. }
  14061. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14062. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14063. {
  14064. std::ofstream ofs(path, std::ios::binary);
  14065. const std::string content(100, 'A');
  14066. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14067. }
  14068. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14069. auto body = make_file_body(path);
  14070. ASSERT_EQ(100u, body.first);
  14071. ASSERT_TRUE(static_cast<bool>(body.second));
  14072. // Rewritten shorter after its length was measured - and, on a server, after
  14073. // that length has already gone out as Content-Length.
  14074. {
  14075. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14076. const std::string content(10, 'A');
  14077. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14078. }
  14079. std::string written;
  14080. DataSink sink;
  14081. sink.write = [&](const char *d, size_t l) {
  14082. written.append(d, l);
  14083. return true;
  14084. };
  14085. // The provider has to report failure. write_content_with_progress() advances
  14086. // its offset only by what was written, so a provider that returns true
  14087. // without completing the length it promised is called again straight away,
  14088. // and again.
  14089. EXPECT_FALSE(body.second(0, body.first, sink));
  14090. EXPECT_EQ(std::string(10, 'A'), written);
  14091. }
  14092. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14093. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14094. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14095. {
  14096. std::ofstream ofs(path, std::ios::binary);
  14097. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14098. }
  14099. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14100. auto body = make_file_body(path);
  14101. ASSERT_EQ(content.size(), body.first);
  14102. ASSERT_TRUE(static_cast<bool>(body.second));
  14103. std::string written;
  14104. DataSink sink;
  14105. sink.write = [&](const char *d, size_t l) {
  14106. written.append(d, l);
  14107. return true;
  14108. };
  14109. EXPECT_TRUE(body.second(0, body.first, sink));
  14110. EXPECT_EQ(content, written);
  14111. }
  14112. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14113. static constexpr unsigned int number_of_tasks{1000000};
  14114. std::atomic_uint count{0};
  14115. std::unique_ptr<TaskQueue> task_queue{
  14116. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14117. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14118. auto queued = task_queue->enqueue(
  14119. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14120. EXPECT_TRUE(queued);
  14121. }
  14122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14123. task_queue->shutdown();
  14124. #else
  14125. EXPECT_NO_THROW(task_queue->shutdown());
  14126. #endif
  14127. EXPECT_EQ(number_of_tasks, count.load());
  14128. }
  14129. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14130. static constexpr unsigned int number_of_tasks{1000000};
  14131. static constexpr unsigned int qlimit{2};
  14132. unsigned int queued_count{0};
  14133. std::atomic_uint count{0};
  14134. std::unique_ptr<TaskQueue> task_queue{
  14135. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14136. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14137. if (task_queue->enqueue(
  14138. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14139. queued_count++;
  14140. }
  14141. }
  14142. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14143. task_queue->shutdown();
  14144. #else
  14145. EXPECT_NO_THROW(task_queue->shutdown());
  14146. #endif
  14147. EXPECT_EQ(queued_count, count.load());
  14148. EXPECT_TRUE(queued_count <= number_of_tasks);
  14149. EXPECT_TRUE(queued_count >= qlimit);
  14150. }
  14151. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14152. // Use a short idle timeout so a dynamic thread spawns, times out and
  14153. // exits during the test, and the pool keeps working afterwards.
  14154. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14155. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14156. /*idle_timeout_sec=*/1}};
  14157. std::atomic_uint count{0};
  14158. std::condition_variable cv;
  14159. std::mutex mtx;
  14160. bool release = false;
  14161. // Block the base thread so the second task spawns a dynamic thread.
  14162. EXPECT_TRUE(task_queue->enqueue([&] {
  14163. std::unique_lock<std::mutex> lock(mtx);
  14164. while (!release) {
  14165. cv.wait(lock);
  14166. }
  14167. count++;
  14168. }));
  14169. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14170. // Let the dynamic thread finish its task and exceed the idle timeout.
  14171. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14172. {
  14173. std::unique_lock<std::mutex> lock(mtx);
  14174. release = true;
  14175. }
  14176. cv.notify_all();
  14177. // The pool must still accept and run tasks after the dynamic thread exited.
  14178. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14179. task_queue->shutdown();
  14180. EXPECT_EQ(3u, count.load());
  14181. }
  14182. TEST(TaskQueueTest, MaxQueuedRequests) {
  14183. static constexpr unsigned int qlimit{3};
  14184. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14185. std::condition_variable sem_cv;
  14186. std::mutex sem_mtx;
  14187. int credits = 0;
  14188. bool queued;
  14189. /* Fill up the queue with tasks that will block until we give them credits to
  14190. * complete. */
  14191. for (unsigned int n = 0; n <= qlimit;) {
  14192. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14193. std::unique_lock<std::mutex> lock(sem_mtx);
  14194. while (credits <= 0) {
  14195. sem_cv.wait(lock);
  14196. }
  14197. /* Consume the credit and signal the test code if they are all gone. */
  14198. if (--credits == 0) { sem_cv.notify_one(); }
  14199. });
  14200. if (n < qlimit) {
  14201. /* The first qlimit enqueues must succeed. */
  14202. EXPECT_TRUE(queued);
  14203. } else {
  14204. /* The last one will succeed only when the worker thread
  14205. * starts and dequeues the first blocking task. Although
  14206. * not necessary for the correctness of this test, we sleep for
  14207. * a short while to avoid busy waiting. */
  14208. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14209. }
  14210. if (queued) { n++; }
  14211. }
  14212. /* Further enqueues must fail since the queue is full. */
  14213. for (auto i = 0; i < 4; i++) {
  14214. queued = task_queue->enqueue([] {});
  14215. EXPECT_FALSE(queued);
  14216. }
  14217. /* Give the credits to allow the previous tasks to complete. */
  14218. {
  14219. std::unique_lock<std::mutex> lock(sem_mtx);
  14220. credits += qlimit + 1;
  14221. }
  14222. sem_cv.notify_all();
  14223. /* Wait for all the credits to be consumed. */
  14224. {
  14225. std::unique_lock<std::mutex> lock(sem_mtx);
  14226. while (credits > 0) {
  14227. sem_cv.wait(lock);
  14228. }
  14229. }
  14230. /* Check that we are able again to enqueue at least qlimit tasks. */
  14231. for (unsigned int i = 0; i < qlimit; i++) {
  14232. queued = task_queue->enqueue([] {});
  14233. EXPECT_TRUE(queued);
  14234. }
  14235. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14236. task_queue->shutdown();
  14237. #else
  14238. EXPECT_NO_THROW(task_queue->shutdown());
  14239. #endif
  14240. }
  14241. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14242. Server svr;
  14243. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14244. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14245. });
  14246. svr.Get("/hello", [](const Request &req, Response &res) {
  14247. res.set_content(req.get_param_value("key"), "text/plain");
  14248. });
  14249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14250. auto se = detail::scope_exit([&] {
  14251. svr.stop();
  14252. thread.join();
  14253. ASSERT_FALSE(svr.is_running());
  14254. });
  14255. svr.wait_until_ready();
  14256. {
  14257. Client cli(HOST, PORT);
  14258. cli.set_follow_location(true);
  14259. auto res = cli.Get("/");
  14260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14261. EXPECT_EQ(StatusCode::OK_200, res->status);
  14262. EXPECT_EQ("val&key2=val2", res->body);
  14263. }
  14264. }
  14265. #endif
  14266. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14267. Server svr;
  14268. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14269. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14270. });
  14271. svr.Get("/hello", [](const Request &req, Response &res) {
  14272. res.set_content(req.get_param_value("key"), "text/plain");
  14273. });
  14274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14275. auto se = detail::scope_exit([&] {
  14276. svr.stop();
  14277. thread.join();
  14278. ASSERT_FALSE(svr.is_running());
  14279. });
  14280. svr.wait_until_ready();
  14281. {
  14282. Client cli(HOST, PORT);
  14283. cli.set_follow_location(true);
  14284. auto res = cli.Get("/");
  14285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14286. EXPECT_EQ(StatusCode::OK_200, res->status);
  14287. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14288. }
  14289. }
  14290. TEST(RedirectTest, RedirectWithPlusInPath) {
  14291. Server svr;
  14292. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14293. res.set_redirect("/a+b");
  14294. });
  14295. // Route pattern uses regex; escape + as \\+
  14296. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14297. res.set_content(req.path, "text/plain");
  14298. });
  14299. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14300. auto se = detail::scope_exit([&] {
  14301. svr.stop();
  14302. thread.join();
  14303. ASSERT_FALSE(svr.is_running());
  14304. });
  14305. svr.wait_until_ready();
  14306. {
  14307. Client cli(HOST, PORT);
  14308. cli.set_follow_location(true);
  14309. auto res = cli.Get("/");
  14310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14311. EXPECT_EQ(StatusCode::OK_200, res->status);
  14312. EXPECT_EQ("/a+b", res->body);
  14313. }
  14314. }
  14315. #ifdef CPPHTTPLIB_SSL_ENABLED
  14316. TEST(RedirectTest, Issue2185_Online) {
  14317. SSLClient client("github.com");
  14318. client.set_follow_location(true);
  14319. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14320. "Coollab-Windows.zip");
  14321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14322. EXPECT_EQ(StatusCode::OK_200, res->status);
  14323. EXPECT_EQ(9920427U, res->body.size());
  14324. }
  14325. #endif
  14326. TEST(VulnerabilityTest, CRLFInjection) {
  14327. Server svr;
  14328. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14329. res.set_content("Hello 1", "text/plain");
  14330. });
  14331. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14332. res.set_content("Hello 2", "text/plain");
  14333. });
  14334. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14335. res.set_content("Hello 3", "text/plain");
  14336. });
  14337. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14338. res.set_content("Hello 4", "text/plain");
  14339. });
  14340. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14341. for (const auto &x : req.headers) {
  14342. auto key = x.first;
  14343. EXPECT_STRNE("evil", key.c_str());
  14344. }
  14345. });
  14346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14347. auto se = detail::scope_exit([&] {
  14348. svr.stop();
  14349. thread.join();
  14350. ASSERT_FALSE(svr.is_running());
  14351. });
  14352. svr.wait_until_ready();
  14353. {
  14354. Client cli(HOST, PORT);
  14355. cli.Post("/test1", "A=B",
  14356. "application/x-www-form-urlencoded\r\nevil: hello1");
  14357. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14358. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14359. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14360. }
  14361. }
  14362. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14363. auto server_thread = std::thread([] {
  14364. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14365. default_socket_options(srv);
  14366. sockaddr_in addr{};
  14367. addr.sin_family = AF_INET;
  14368. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14369. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14370. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14371. ::listen(srv, 1);
  14372. sockaddr_in cli_addr{};
  14373. socklen_t cli_len = sizeof(cli_addr);
  14374. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14375. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14376. std::string buf_all;
  14377. char buf[2048];
  14378. ssize_t n;
  14379. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14380. buf_all.append(buf, static_cast<size_t>(n));
  14381. size_t pos;
  14382. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14383. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14384. auto e = request_block.find("\r\n");
  14385. if (e != std::string::npos) {
  14386. auto request_line = request_block.substr(0, e);
  14387. std::string msg =
  14388. "CRLF injection detected in request line: '" + request_line + "'";
  14389. EXPECT_FALSE(true) << msg;
  14390. }
  14391. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14392. ::send(cli,
  14393. #ifdef _WIN32
  14394. static_cast<const char *>(resp.c_str()),
  14395. static_cast<int>(resp.size()),
  14396. #else
  14397. resp.c_str(), resp.size(),
  14398. #endif
  14399. 0);
  14400. buf_all.erase(0, pos + 4);
  14401. }
  14402. }
  14403. detail::close_socket(cli);
  14404. detail::close_socket(srv);
  14405. });
  14406. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14407. auto cli = Client("127.0.0.1", PORT + 1);
  14408. auto headers = Headers{
  14409. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14410. {"Connection", "keep-alive"}};
  14411. auto res = cli.Get("/hi", headers);
  14412. EXPECT_FALSE(res);
  14413. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14414. server_thread.join();
  14415. }
  14416. TEST(PathParamsTest, StaticMatch) {
  14417. const auto pattern = "/users/all";
  14418. detail::PathParamsMatcher matcher(pattern);
  14419. Request request;
  14420. request.path = "/users/all";
  14421. ASSERT_TRUE(matcher.match(request));
  14422. std::unordered_map<std::string, std::string> expected_params = {};
  14423. EXPECT_EQ(request.path_params, expected_params);
  14424. }
  14425. TEST(PathParamsTest, StaticMismatch) {
  14426. const auto pattern = "/users/all";
  14427. detail::PathParamsMatcher matcher(pattern);
  14428. Request request;
  14429. request.path = "/users/1";
  14430. ASSERT_FALSE(matcher.match(request));
  14431. }
  14432. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14433. const auto pattern = "/users/:id/subscriptions";
  14434. detail::PathParamsMatcher matcher(pattern);
  14435. Request request;
  14436. request.path = "/users/42/subscriptions";
  14437. ASSERT_TRUE(matcher.match(request));
  14438. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14439. EXPECT_EQ(request.path_params, expected_params);
  14440. }
  14441. TEST(PathParamsTest, SingleParamInTheEnd) {
  14442. const auto pattern = "/users/:id";
  14443. detail::PathParamsMatcher matcher(pattern);
  14444. Request request;
  14445. request.path = "/users/24";
  14446. ASSERT_TRUE(matcher.match(request));
  14447. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14448. EXPECT_EQ(request.path_params, expected_params);
  14449. }
  14450. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14451. const auto pattern = "/users/:id/";
  14452. detail::PathParamsMatcher matcher(pattern);
  14453. Request request;
  14454. request.path = "/users/42/";
  14455. ASSERT_TRUE(matcher.match(request));
  14456. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14457. EXPECT_EQ(request.path_params, expected_params);
  14458. }
  14459. TEST(PathParamsTest, EmptyParam) {
  14460. const auto pattern = "/users/:id/";
  14461. detail::PathParamsMatcher matcher(pattern);
  14462. Request request;
  14463. request.path = "/users//";
  14464. ASSERT_TRUE(matcher.match(request));
  14465. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14466. EXPECT_EQ(request.path_params, expected_params);
  14467. }
  14468. TEST(PathParamsTest, FragmentMismatch) {
  14469. const auto pattern = "/users/:id/";
  14470. detail::PathParamsMatcher matcher(pattern);
  14471. Request request;
  14472. request.path = "/admins/24/";
  14473. ASSERT_FALSE(matcher.match(request));
  14474. }
  14475. TEST(PathParamsTest, ExtraFragments) {
  14476. const auto pattern = "/users/:id";
  14477. detail::PathParamsMatcher matcher(pattern);
  14478. Request request;
  14479. request.path = "/users/42/subscriptions";
  14480. ASSERT_FALSE(matcher.match(request));
  14481. }
  14482. TEST(PathParamsTest, MissingTrailingParam) {
  14483. const auto pattern = "/users/:id";
  14484. detail::PathParamsMatcher matcher(pattern);
  14485. Request request;
  14486. request.path = "/users";
  14487. ASSERT_FALSE(matcher.match(request));
  14488. }
  14489. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14490. const auto pattern = "/users/:id/subscriptions";
  14491. detail::PathParamsMatcher matcher(pattern);
  14492. Request request;
  14493. request.path = "/users/subscriptions";
  14494. ASSERT_FALSE(matcher.match(request));
  14495. }
  14496. TEST(PathParamsTest, MultipleParams) {
  14497. const auto pattern = "/users/:userid/subscriptions/:subid";
  14498. detail::PathParamsMatcher matcher(pattern);
  14499. Request request;
  14500. request.path = "/users/42/subscriptions/2";
  14501. ASSERT_TRUE(matcher.match(request));
  14502. std::unordered_map<std::string, std::string> expected_params = {
  14503. {"userid", "42"}, {"subid", "2"}};
  14504. EXPECT_EQ(request.path_params, expected_params);
  14505. }
  14506. TEST(PathParamsTest, SequenceOfParams) {
  14507. const auto pattern = "/values/:x/:y/:z";
  14508. detail::PathParamsMatcher matcher(pattern);
  14509. Request request;
  14510. request.path = "/values/1/2/3";
  14511. ASSERT_TRUE(matcher.match(request));
  14512. std::unordered_map<std::string, std::string> expected_params = {
  14513. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14514. EXPECT_EQ(request.path_params, expected_params);
  14515. }
  14516. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14517. const auto pattern = "/prefix:suffix";
  14518. detail::PathParamsMatcher matcher(pattern);
  14519. Request request;
  14520. request.path = "/prefix:suffix";
  14521. ASSERT_TRUE(matcher.match(request));
  14522. const std::unordered_map<std::string, std::string> expected_params = {};
  14523. EXPECT_EQ(request.path_params, expected_params);
  14524. }
  14525. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14526. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14527. // calling thread's stack on a long enough path for a quantified pattern;
  14528. // RegexMatcher must refuse to run regex matching on paths beyond
  14529. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14530. detail::RegexMatcher matcher("/files/(.*)");
  14531. Request within_limit;
  14532. within_limit.path = "/files/" + std::string(10, 'A');
  14533. EXPECT_TRUE(matcher.match(within_limit));
  14534. Request over_limit;
  14535. over_limit.path =
  14536. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14537. EXPECT_FALSE(matcher.match(over_limit));
  14538. }
  14539. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14540. Server svr;
  14541. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14542. res.set_content("ok", "text/plain");
  14543. });
  14544. auto port = svr.bind_to_any_port(HOST);
  14545. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14546. auto se = detail::scope_exit([&] {
  14547. svr.stop();
  14548. thread.join();
  14549. ASSERT_FALSE(svr.is_running());
  14550. });
  14551. svr.wait_until_ready();
  14552. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14553. // request URI limit; this used to be able to crash the process.
  14554. std::string path =
  14555. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14556. std::string req = "GET " + path +
  14557. " HTTP/1.1\r\n"
  14558. "Host: " +
  14559. std::string(HOST) + ":" + std::to_string(port) +
  14560. "\r\n"
  14561. "Connection: close\r\n"
  14562. "\r\n";
  14563. std::string response;
  14564. ASSERT_TRUE(send_request(5, req, &response, port));
  14565. EXPECT_NE(std::string::npos, response.find("404"));
  14566. }
  14567. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14568. Server svr;
  14569. auto handler = [](const Request & /*req*/, Response &res) {
  14570. res.set_content("hit", "text/plain");
  14571. };
  14572. // No regex metacharacter, so this one is compared literally
  14573. svr.Get("/literal/route", handler);
  14574. // '.' is a regex metacharacter, so this one must keep regex semantics
  14575. svr.Get("/a.c", handler);
  14576. auto port = svr.bind_to_any_port(HOST);
  14577. std::thread t([&]() { svr.listen_after_bind(); });
  14578. auto se = detail::scope_exit([&] {
  14579. svr.stop();
  14580. t.join();
  14581. ASSERT_FALSE(svr.is_running());
  14582. });
  14583. svr.wait_until_ready();
  14584. Client cli(HOST, port);
  14585. struct {
  14586. const char *path;
  14587. int status;
  14588. } cases[] = {
  14589. {"/literal/route", StatusCode::OK_200},
  14590. {"/literal/routes", StatusCode::NotFound_404},
  14591. {"/literal/rout", StatusCode::NotFound_404},
  14592. {"/abc", StatusCode::OK_200},
  14593. {"/a.c", StatusCode::OK_200},
  14594. };
  14595. for (const auto &x : cases) {
  14596. auto res = cli.Get(x.path);
  14597. ASSERT_TRUE(res) << x.path;
  14598. EXPECT_EQ(x.status, res->status) << x.path;
  14599. }
  14600. }
  14601. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14602. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14603. // from exhausting the stack, so it must only constrain routes that actually
  14604. // run a regular expression. A literal route is matched by comparison and
  14605. // stays usable at any length.
  14606. Server svr;
  14607. const std::string pattern =
  14608. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14609. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14610. res.set_content("hit", "text/plain");
  14611. });
  14612. auto port = svr.bind_to_any_port(HOST);
  14613. std::thread t([&]() { svr.listen_after_bind(); });
  14614. auto se = detail::scope_exit([&] {
  14615. svr.stop();
  14616. t.join();
  14617. ASSERT_FALSE(svr.is_running());
  14618. });
  14619. svr.wait_until_ready();
  14620. Client cli(HOST, port);
  14621. auto res = cli.Get(pattern);
  14622. ASSERT_TRUE(res);
  14623. EXPECT_EQ(StatusCode::OK_200, res->status);
  14624. }
  14625. TEST(ParseUrlTest, VariousPatterns) {
  14626. {
  14627. detail::UrlComponents uc;
  14628. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14629. EXPECT_EQ("http", uc.scheme);
  14630. EXPECT_EQ("example.com", uc.host);
  14631. EXPECT_EQ("8080", uc.port);
  14632. EXPECT_EQ("/path", uc.path);
  14633. EXPECT_EQ("?q=1", uc.query);
  14634. }
  14635. {
  14636. detail::UrlComponents uc;
  14637. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14638. EXPECT_EQ("https", uc.scheme);
  14639. EXPECT_EQ("example.com", uc.host);
  14640. EXPECT_TRUE(uc.port.empty());
  14641. EXPECT_EQ("/path", uc.path);
  14642. }
  14643. {
  14644. detail::UrlComponents uc;
  14645. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14646. EXPECT_EQ("::1", uc.host);
  14647. EXPECT_EQ("8080", uc.port);
  14648. EXPECT_EQ("/path", uc.path);
  14649. }
  14650. {
  14651. detail::UrlComponents uc;
  14652. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14653. }
  14654. {
  14655. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14656. // the path while the connection still targets the bracketed host.
  14657. detail::UrlComponents uc;
  14658. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14659. }
  14660. {
  14661. detail::UrlComponents uc;
  14662. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14663. }
  14664. {
  14665. detail::UrlComponents uc;
  14666. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  14667. EXPECT_EQ("::1", uc.host);
  14668. EXPECT_TRUE(uc.port.empty());
  14669. EXPECT_EQ("/path", uc.path);
  14670. }
  14671. {
  14672. detail::UrlComponents uc;
  14673. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  14674. EXPECT_TRUE(uc.scheme.empty());
  14675. EXPECT_EQ("example.com", uc.host);
  14676. EXPECT_EQ("/path", uc.path);
  14677. EXPECT_EQ("?q=1", uc.query);
  14678. }
  14679. {
  14680. detail::UrlComponents uc;
  14681. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  14682. EXPECT_TRUE(uc.host.empty());
  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("example.com:8080", uc));
  14689. EXPECT_EQ("example.com", uc.host);
  14690. EXPECT_EQ("8080", uc.port);
  14691. }
  14692. {
  14693. // Unix socket path — must not be parsed as host
  14694. detail::UrlComponents uc;
  14695. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  14696. EXPECT_TRUE(uc.host.empty());
  14697. }
  14698. {
  14699. detail::UrlComponents uc;
  14700. ASSERT_TRUE(detail::parse_url("", uc));
  14701. EXPECT_TRUE(uc.host.empty());
  14702. EXPECT_TRUE(uc.path.empty());
  14703. }
  14704. {
  14705. detail::UrlComponents uc;
  14706. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  14707. }
  14708. {
  14709. detail::UrlComponents uc;
  14710. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  14711. }
  14712. {
  14713. // Accepted by parse_url; callers restrict to http/https
  14714. detail::UrlComponents uc;
  14715. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  14716. EXPECT_EQ("ftp", uc.scheme);
  14717. }
  14718. {
  14719. detail::UrlComponents uc;
  14720. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  14721. }
  14722. {
  14723. detail::UrlComponents uc;
  14724. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  14725. }
  14726. }
  14727. TEST(ParseUrlTest, FragmentHandling) {
  14728. {
  14729. detail::UrlComponents uc;
  14730. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  14731. EXPECT_EQ("/path", uc.path);
  14732. EXPECT_TRUE(uc.query.empty());
  14733. }
  14734. {
  14735. detail::UrlComponents uc;
  14736. ASSERT_TRUE(detail::parse_url("#frag", uc));
  14737. EXPECT_TRUE(uc.path.empty());
  14738. EXPECT_TRUE(uc.query.empty());
  14739. }
  14740. }
  14741. TEST(ParseUrlTest, UserinfoHandling) {
  14742. // Userinfo with @ but no colon — host includes @
  14743. detail::UrlComponents uc;
  14744. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  14745. EXPECT_EQ("user@host.com", uc.host);
  14746. EXPECT_EQ("/path", uc.path);
  14747. }
  14748. TEST(ParseUrlTest, IPv6EdgeCases) {
  14749. {
  14750. detail::UrlComponents uc;
  14751. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  14752. EXPECT_TRUE(uc.scheme.empty());
  14753. EXPECT_EQ("::1", uc.host);
  14754. EXPECT_EQ("8080", uc.port);
  14755. }
  14756. {
  14757. // Zone ID '%25' is not in [a-fA-F0-9:]
  14758. detail::UrlComponents uc;
  14759. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  14760. }
  14761. }
  14762. TEST(ParseUrlTest, SchemeEdgeCases) {
  14763. {
  14764. detail::UrlComponents uc;
  14765. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  14766. }
  14767. {
  14768. detail::UrlComponents uc;
  14769. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  14770. }
  14771. {
  14772. detail::UrlComponents uc;
  14773. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  14774. }
  14775. }
  14776. TEST(ParseUrlTest, PortEdgeCases) {
  14777. {
  14778. detail::UrlComponents uc;
  14779. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  14780. EXPECT_TRUE(uc.port.empty());
  14781. EXPECT_EQ("/path", uc.path);
  14782. }
  14783. {
  14784. // parse_url accepts any port string; validation is done by parse_port
  14785. detail::UrlComponents uc;
  14786. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  14787. EXPECT_EQ("abc", uc.port);
  14788. }
  14789. }
  14790. TEST(ParseUrlTest, WebSocketPatterns) {
  14791. {
  14792. detail::UrlComponents uc;
  14793. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  14794. EXPECT_EQ("ws", uc.scheme);
  14795. EXPECT_EQ("echo.example.com", uc.host);
  14796. EXPECT_EQ("8080", uc.port);
  14797. EXPECT_EQ("/ws", uc.path);
  14798. }
  14799. {
  14800. detail::UrlComponents uc;
  14801. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  14802. EXPECT_EQ("wss", uc.scheme);
  14803. EXPECT_EQ("echo.example.com", uc.host);
  14804. EXPECT_TRUE(uc.port.empty());
  14805. EXPECT_EQ("/ws", uc.path);
  14806. }
  14807. }
  14808. TEST(ParseUrlTest, QueryOnly) {
  14809. detail::UrlComponents uc;
  14810. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  14811. EXPECT_TRUE(uc.host.empty());
  14812. EXPECT_TRUE(uc.path.empty());
  14813. EXPECT_EQ("?q=1&r=2", uc.query);
  14814. }
  14815. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  14816. detail::UrlComponents uc;
  14817. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  14818. EXPECT_TRUE(uc.scheme.empty());
  14819. EXPECT_EQ("example.com", uc.host);
  14820. EXPECT_EQ("443", uc.port);
  14821. EXPECT_EQ("/path", uc.path);
  14822. }
  14823. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  14824. // If ipv6 regex working, regex match codepath is taken.
  14825. // else port will default to 80 in Client impl
  14826. int clientImplMagicPort = 80;
  14827. int port = 4321;
  14828. // above ports must be different to avoid false negative
  14829. EXPECT_NE(clientImplMagicPort, port);
  14830. std::string ipV6TestURL = "http://[ff06::c3]";
  14831. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  14832. CLIENT_PRIVATE_KEY_FILE);
  14833. EXPECT_EQ(cli.port(), port);
  14834. }
  14835. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  14836. auto file_path = "./www/dir/index.html";
  14837. auto dir_path = "./www/dir";
  14838. detail::FileStat stat_file(file_path);
  14839. EXPECT_TRUE(stat_file.is_file());
  14840. EXPECT_FALSE(stat_file.is_dir());
  14841. detail::FileStat stat_dir(dir_path);
  14842. EXPECT_FALSE(stat_dir.is_file());
  14843. EXPECT_TRUE(stat_dir.is_dir());
  14844. }
  14845. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  14846. // IPv4 with default HTTP port (80)
  14847. EXPECT_EQ("example.com",
  14848. detail::make_host_and_port_string("example.com", 80, false));
  14849. // IPv4 with default HTTPS port (443)
  14850. EXPECT_EQ("example.com",
  14851. detail::make_host_and_port_string("example.com", 443, true));
  14852. // IPv4 with non-default HTTP port
  14853. EXPECT_EQ("example.com:8080",
  14854. detail::make_host_and_port_string("example.com", 8080, false));
  14855. // IPv4 with non-default HTTPS port
  14856. EXPECT_EQ("example.com:8443",
  14857. detail::make_host_and_port_string("example.com", 8443, true));
  14858. // IPv6 with default HTTP port (80)
  14859. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  14860. // IPv6 with default HTTPS port (443)
  14861. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  14862. // IPv6 with non-default HTTP port
  14863. EXPECT_EQ("[::1]:8080",
  14864. detail::make_host_and_port_string("::1", 8080, false));
  14865. // IPv6 with non-default HTTPS port
  14866. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  14867. // IPv6 full address with default port
  14868. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  14869. detail::make_host_and_port_string(
  14870. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  14871. // IPv6 full address with non-default port
  14872. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  14873. detail::make_host_and_port_string(
  14874. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  14875. // IPv6 localhost with non-default port
  14876. EXPECT_EQ("[::1]:3000",
  14877. detail::make_host_and_port_string("::1", 3000, false));
  14878. // IPv6 with zone ID (link-local address) with default port
  14879. EXPECT_EQ("[fe80::1%eth0]",
  14880. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  14881. // IPv6 with zone ID (link-local address) with non-default port
  14882. EXPECT_EQ("[fe80::1%eth0]:8080",
  14883. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  14884. // Edge case: Port 443 with is_ssl=false (should add port)
  14885. EXPECT_EQ("example.com:443",
  14886. detail::make_host_and_port_string("example.com", 443, false));
  14887. // Edge case: Port 80 with is_ssl=true (should add port)
  14888. EXPECT_EQ("example.com:80",
  14889. detail::make_host_and_port_string("example.com", 80, true));
  14890. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  14891. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  14892. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  14893. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  14894. // Security fix: Already bracketed IPv6 should not get double brackets
  14895. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  14896. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  14897. EXPECT_EQ("[::1]:8080",
  14898. detail::make_host_and_port_string("[::1]", 8080, false));
  14899. EXPECT_EQ("[2001:db8::1]:8080",
  14900. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  14901. EXPECT_EQ("[fe80::1%eth0]",
  14902. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  14903. EXPECT_EQ("[fe80::1%eth0]:8080",
  14904. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  14905. // Edge case: Empty host (should return as-is)
  14906. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  14907. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  14908. // This is a known limitation but shouldn't crash
  14909. EXPECT_EQ("[host:name]",
  14910. detail::make_host_and_port_string("host:name", 80, false));
  14911. // Port number edge cases (no validation, but should not crash)
  14912. EXPECT_EQ("example.com:0",
  14913. detail::make_host_and_port_string("example.com", 0, false));
  14914. EXPECT_EQ("example.com:-1",
  14915. detail::make_host_and_port_string("example.com", -1, false));
  14916. EXPECT_EQ("example.com:65535",
  14917. detail::make_host_and_port_string("example.com", 65535, false));
  14918. EXPECT_EQ("example.com:65536",
  14919. detail::make_host_and_port_string("example.com", 65536, false));
  14920. }
  14921. #ifdef CPPHTTPLIB_SSL_ENABLED
  14922. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  14923. httplib::SSLClient cli("roblox.com", 443);
  14924. cli.set_follow_location(true);
  14925. auto res = cli.Get("/");
  14926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14927. EXPECT_EQ(StatusCode::OK_200, res->status);
  14928. }
  14929. #endif
  14930. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  14931. Server svr;
  14932. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14933. EXPECT_EQ(res.status, 400);
  14934. });
  14935. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14936. auto se = detail::scope_exit([&] {
  14937. svr.stop();
  14938. thread.join();
  14939. ASSERT_FALSE(svr.is_running());
  14940. });
  14941. svr.wait_until_ready();
  14942. Client cli(HOST, PORT);
  14943. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  14944. }
  14945. TEST(InvalidHeaderCharsTest, is_field_name) {
  14946. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  14947. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  14948. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  14949. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  14950. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  14951. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  14952. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  14953. EXPECT_FALSE(detail::fields::is_field_name(""));
  14954. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  14955. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  14956. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  14957. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  14958. }
  14959. TEST(InvalidHeaderCharsTest, is_field_value) {
  14960. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  14961. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  14962. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  14963. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  14964. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  14965. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  14966. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  14967. EXPECT_TRUE(detail::fields::is_field_value(""));
  14968. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  14969. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  14970. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  14971. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  14972. EXPECT_TRUE(detail::fields::is_field_value("0"));
  14973. }
  14974. TEST(InvalidHeaderCharsTest, OnServer) {
  14975. Server svr;
  14976. svr.Get("/test_name", [&](const Request &req, Response &res) {
  14977. std::string header = "Not Set";
  14978. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14979. res.set_header(header, "value");
  14980. res.set_content("Page Content Page Content", "text/plain");
  14981. });
  14982. svr.Get("/test_value", [&](const Request &req, Response &res) {
  14983. std::string header = "Not Set";
  14984. if (req.has_param("header")) { header = req.get_param_value("header"); }
  14985. res.set_header("X-Test", header);
  14986. res.set_content("Page Content Page Content", "text/plain");
  14987. });
  14988. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14989. auto se = detail::scope_exit([&] {
  14990. svr.stop();
  14991. thread.join();
  14992. ASSERT_FALSE(svr.is_running());
  14993. });
  14994. svr.wait_until_ready();
  14995. Client cli(HOST, PORT);
  14996. {
  14997. auto res = cli.Get(
  14998. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  14999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15000. EXPECT_EQ("Page Content Page Content", res->body);
  15001. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15002. }
  15003. {
  15004. auto res = cli.Get(
  15005. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15007. EXPECT_EQ("Page Content Page Content", res->body);
  15008. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15009. }
  15010. }
  15011. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15012. auto handled = false;
  15013. Server svr;
  15014. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15015. thread t = thread([&] { svr.listen(HOST, PORT); });
  15016. auto se = detail::scope_exit([&] {
  15017. svr.stop();
  15018. t.join();
  15019. ASSERT_FALSE(svr.is_running());
  15020. ASSERT_FALSE(handled);
  15021. });
  15022. svr.wait_until_ready();
  15023. auto req = "POST /test HTTP/1.1\r\n"
  15024. "Content-Length: x\r\n"
  15025. "\r\n";
  15026. std::string response;
  15027. ASSERT_TRUE(send_request(1, req, &response));
  15028. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15029. response.substr(0, response.find("\r\n")));
  15030. }
  15031. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15032. // case-insensitive, and a server that receives a 100-continue expectation in
  15033. // an HTTP/1.0 request MUST ignore it.
  15034. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15035. std::string response;
  15036. ASSERT_TRUE(send_request(1, req, &response, port));
  15037. *got_100 = response.find("100 Continue") != std::string::npos;
  15038. }
  15039. class ExpectTokenTest : public ::testing::Test {
  15040. protected:
  15041. void SetUp() override {
  15042. svr_.Post("/p", [](const Request &, Response &res) {
  15043. res.set_content("ok", "text/plain");
  15044. });
  15045. port_ = svr_.bind_to_any_port(HOST);
  15046. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15047. svr_.wait_until_ready();
  15048. }
  15049. void TearDown() override {
  15050. svr_.stop();
  15051. if (thread_.joinable()) { thread_.join(); }
  15052. }
  15053. std::string request(const char *version, const char *expect_value) const {
  15054. return std::string("POST /p ") + version +
  15055. "\r\n"
  15056. "Host: localhost\r\n"
  15057. "Content-Length: 2\r\n"
  15058. "Connection: close\r\n"
  15059. "Expect: " +
  15060. expect_value +
  15061. "\r\n"
  15062. "\r\n"
  15063. "hi";
  15064. }
  15065. Server svr_;
  15066. int port_ = 0;
  15067. thread thread_;
  15068. };
  15069. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15070. bool got_100 = false;
  15071. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15072. EXPECT_TRUE(got_100);
  15073. }
  15074. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15075. bool got_100 = true;
  15076. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15077. EXPECT_FALSE(got_100);
  15078. }
  15079. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15080. bool got_100 = false;
  15081. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15082. EXPECT_TRUE(got_100);
  15083. }
  15084. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15085. bool got_100 = false;
  15086. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15087. EXPECT_TRUE(got_100);
  15088. }
  15089. #ifndef _WIN32
  15090. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15091. static constexpr char reject[] = "Unauthorized";
  15092. static constexpr char accept[] = "Upload accepted";
  15093. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15094. Server svr;
  15095. svr.set_expect_100_continue_handler(
  15096. [](const Request & /*req*/, Response &res) {
  15097. res.status = StatusCode::Unauthorized_401;
  15098. res.set_content(reject, "text/plain");
  15099. return res.status;
  15100. });
  15101. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15102. res.set_content(accept, "text/plain");
  15103. });
  15104. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15105. auto se = detail::scope_exit([&] {
  15106. svr.stop();
  15107. thread.join();
  15108. ASSERT_FALSE(svr.is_running());
  15109. });
  15110. svr.wait_until_ready();
  15111. {
  15112. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15113. curl_easy_init(), &curl_easy_cleanup};
  15114. ASSERT_NE(curl, nullptr);
  15115. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15116. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15117. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15118. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15119. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15120. &curl_slist_free_all};
  15121. ASSERT_NE(list, nullptr);
  15122. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15123. struct read_data {
  15124. size_t read_size;
  15125. size_t total_size;
  15126. } data = {0, total_size};
  15127. using read_callback_t =
  15128. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15129. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15130. void *userdata) -> size_t {
  15131. read_data *d = (read_data *)userdata;
  15132. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15133. std::fill_n(ptr, size * nmemb, 'A');
  15134. d->read_size += size * nmemb;
  15135. return size * nmemb;
  15136. };
  15137. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15138. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15139. std::vector<char> buffer;
  15140. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15141. using write_callback_t =
  15142. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15143. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15144. void *userdata) -> size_t {
  15145. std::vector<char> *buf = (std::vector<char> *)userdata;
  15146. buf->reserve(buf->size() + size * nmemb + 1);
  15147. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15148. return size * nmemb;
  15149. };
  15150. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15151. {
  15152. const auto res = curl_easy_perform(curl.get());
  15153. ASSERT_EQ(res, CURLE_OK);
  15154. }
  15155. {
  15156. auto response_code = long{};
  15157. const auto res =
  15158. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15159. ASSERT_EQ(res, CURLE_OK);
  15160. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15161. }
  15162. {
  15163. auto dl = curl_off_t{};
  15164. const auto res =
  15165. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15166. ASSERT_EQ(res, CURLE_OK);
  15167. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15168. }
  15169. {
  15170. buffer.push_back('\0');
  15171. ASSERT_STRCASEEQ(buffer.data(), reject);
  15172. }
  15173. }
  15174. }
  15175. #endif
  15176. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15177. // Regression test for #2458.
  15178. //
  15179. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15180. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15181. // ticket can make the client socket spuriously readable during the
  15182. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15183. // the client withholds the body and then blocks reading a response that never
  15184. // comes, failing with `Failed to read connection`.
  15185. //
  15186. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15187. // within the timeout. This raw OpenSSL server deliberately never sends
  15188. // `100 Continue`; the client must still deliver the body and receive 200.
  15189. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15190. signal(SIGPIPE, SIG_IGN);
  15191. const auto port = PORT + 4;
  15192. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15193. ASSERT_NE(srv, INVALID_SOCKET);
  15194. int opt = 1;
  15195. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15196. sockaddr_in addr{};
  15197. addr.sin_family = AF_INET;
  15198. addr.sin_port = htons(static_cast<uint16_t>(port));
  15199. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15200. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15201. ASSERT_EQ(0, ::listen(srv, 1));
  15202. std::atomic<size_t> server_body_bytes{0};
  15203. auto server_thread = std::thread([&] {
  15204. sockaddr_in cli_addr{};
  15205. socklen_t cli_len = sizeof(cli_addr);
  15206. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15207. if (cli == INVALID_SOCKET) { return; }
  15208. // Bound the lifetime of the server side so a buggy client (which never
  15209. // sends the body) cannot make this thread block forever on join.
  15210. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15211. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15212. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15213. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15214. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15215. SSL *ssl = SSL_new(ctx);
  15216. SSL_set_fd(ssl, static_cast<int>(cli));
  15217. if (SSL_accept(ssl) > 0) {
  15218. // Read the request headers. Reading here also flushes the TLS 1.3
  15219. // session tickets to the client. Deliberately do NOT send
  15220. // `100 Continue`.
  15221. std::string buf;
  15222. char tmp[1024];
  15223. while (buf.find("\r\n\r\n") == std::string::npos) {
  15224. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15225. if (n <= 0) { break; }
  15226. buf.append(tmp, static_cast<size_t>(n));
  15227. }
  15228. // A correct client sends the body now; count what arrives.
  15229. auto pos = buf.find("\r\n\r\n");
  15230. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15231. while (body < 4096) {
  15232. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15233. if (n <= 0) { break; }
  15234. body += static_cast<size_t>(n);
  15235. }
  15236. server_body_bytes = body;
  15237. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15238. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15239. SSL_shutdown(ssl);
  15240. }
  15241. SSL_free(ssl);
  15242. detail::close_socket(cli);
  15243. SSL_CTX_free(ctx);
  15244. });
  15245. auto se = detail::scope_exit([&] {
  15246. server_thread.join();
  15247. detail::close_socket(srv);
  15248. });
  15249. SSLClient cli("127.0.0.1", port);
  15250. cli.enable_server_certificate_verification(false);
  15251. cli.set_connection_timeout(5, 0);
  15252. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15253. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15254. std::string body(4096, 'A');
  15255. auto res = cli.Put("/api/test", body, "application/json");
  15256. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15257. EXPECT_EQ(StatusCode::OK_200, res->status);
  15258. EXPECT_EQ(body.size(), server_body_bytes.load());
  15259. }
  15260. #endif
  15261. template <typename S, typename C>
  15262. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15263. svr.Get("/stream", [&](const Request &, Response &res) {
  15264. auto data = new std::string("01234567890123456789");
  15265. res.set_content_provider(
  15266. data->size(), "text/plain",
  15267. [&, data](size_t offset, size_t length, DataSink &sink) {
  15268. const size_t DATA_CHUNK_SIZE = 4;
  15269. const auto &d = *data;
  15270. std::this_thread::sleep_for(std::chrono::seconds(1));
  15271. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15272. return true;
  15273. },
  15274. [data](bool success) {
  15275. EXPECT_FALSE(success);
  15276. delete data;
  15277. });
  15278. });
  15279. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15280. auto i = new size_t(0);
  15281. res.set_content_provider(
  15282. "text/plain",
  15283. [i](size_t, DataSink &sink) {
  15284. if (*i < 5) {
  15285. std::this_thread::sleep_for(std::chrono::seconds(1));
  15286. sink.write("abcd", 4);
  15287. (*i)++;
  15288. } else {
  15289. sink.done();
  15290. }
  15291. return true;
  15292. },
  15293. [i](bool success) {
  15294. EXPECT_FALSE(success);
  15295. delete i;
  15296. });
  15297. });
  15298. svr.Get("/chunked", [&](const Request &, Response &res) {
  15299. auto i = new size_t(0);
  15300. res.set_chunked_content_provider(
  15301. "text/plain",
  15302. [i](size_t, DataSink &sink) {
  15303. if (*i < 5) {
  15304. std::this_thread::sleep_for(std::chrono::seconds(1));
  15305. sink.os << "abcd";
  15306. (*i)++;
  15307. } else {
  15308. sink.done();
  15309. }
  15310. return true;
  15311. },
  15312. [i](bool success) {
  15313. EXPECT_FALSE(success);
  15314. delete i;
  15315. });
  15316. });
  15317. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15318. auto se = detail::scope_exit([&] {
  15319. svr.stop();
  15320. listen_thread.join();
  15321. ASSERT_FALSE(svr.is_running());
  15322. });
  15323. svr.wait_until_ready();
  15324. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15325. {
  15326. auto start = std::chrono::steady_clock::now();
  15327. auto res = cli.Get("/stream");
  15328. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15329. std::chrono::steady_clock::now() - start)
  15330. .count();
  15331. ASSERT_FALSE(res);
  15332. EXPECT_EQ(Error::Read, res.error());
  15333. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15334. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15335. }
  15336. {
  15337. auto start = std::chrono::steady_clock::now();
  15338. auto res = cli.Get("/stream_without_length");
  15339. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15340. std::chrono::steady_clock::now() - start)
  15341. .count();
  15342. ASSERT_FALSE(res);
  15343. EXPECT_EQ(Error::Read, res.error());
  15344. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15345. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15346. }
  15347. {
  15348. auto start = std::chrono::steady_clock::now();
  15349. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15350. EXPECT_EQ("abcd", string(data, data_length));
  15351. return true;
  15352. });
  15353. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15354. std::chrono::steady_clock::now() - start)
  15355. .count();
  15356. ASSERT_FALSE(res);
  15357. EXPECT_EQ(Error::Read, res.error());
  15358. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15359. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15360. }
  15361. }
  15362. TEST(MaxTimeoutTest, ContentStream) {
  15363. time_t timeout = 2000;
  15364. time_t threshold = 200;
  15365. Server svr;
  15366. Client cli("localhost", PORT);
  15367. max_timeout_test(svr, cli, timeout, threshold);
  15368. }
  15369. #ifdef CPPHTTPLIB_SSL_ENABLED
  15370. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15371. time_t timeout = 2000;
  15372. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15374. SSLClient cli("localhost", PORT);
  15375. cli.enable_server_certificate_verification(false);
  15376. max_timeout_test(svr, cli, timeout, threshold);
  15377. }
  15378. #endif
  15379. class EventDispatcher {
  15380. public:
  15381. EventDispatcher() {}
  15382. bool wait_event(DataSink *sink) {
  15383. unique_lock<mutex> lk(m_);
  15384. int id = id_;
  15385. // Wait with timeout to prevent hanging if client disconnects
  15386. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15387. [&] { return cid_ == id; })) {
  15388. return false; // Timeout occurred
  15389. }
  15390. sink->write(message_.data(), message_.size());
  15391. return true;
  15392. }
  15393. void send_event(const string &message) {
  15394. lock_guard<mutex> lk(m_);
  15395. cid_ = id_++;
  15396. message_ = message;
  15397. cv_.notify_all();
  15398. }
  15399. private:
  15400. mutex m_;
  15401. condition_variable cv_;
  15402. atomic_int id_{0};
  15403. atomic_int cid_{-1};
  15404. string message_;
  15405. };
  15406. TEST(ClientInThreadTest, Issue2068) {
  15407. EventDispatcher ed;
  15408. Server svr;
  15409. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15410. res.set_chunked_content_provider("text/event-stream",
  15411. [&](size_t /*offset*/, DataSink &sink) {
  15412. return ed.wait_event(&sink);
  15413. });
  15414. });
  15415. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15416. svr.wait_until_ready();
  15417. thread event_thread([&] {
  15418. int id = 0;
  15419. while (svr.is_running()) {
  15420. this_thread::sleep_for(chrono::milliseconds(500));
  15421. std::stringstream ss;
  15422. ss << "data: " << id << "\n\n";
  15423. ed.send_event(ss.str());
  15424. id++;
  15425. }
  15426. });
  15427. auto se = detail::scope_exit([&] {
  15428. svr.stop();
  15429. listen_thread.join();
  15430. event_thread.join();
  15431. ASSERT_FALSE(svr.is_running());
  15432. });
  15433. {
  15434. auto client = detail::make_unique<Client>(HOST, PORT);
  15435. client->set_read_timeout(std::chrono::minutes(10));
  15436. std::atomic<bool> stop{false};
  15437. std::thread t([&] {
  15438. client->Get("/event1",
  15439. [&](const char *, size_t) -> bool { return !stop; });
  15440. });
  15441. std::this_thread::sleep_for(std::chrono::seconds(2));
  15442. stop = true;
  15443. client->stop();
  15444. t.join();
  15445. // Reset client after thread has finished
  15446. client.reset();
  15447. }
  15448. }
  15449. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15450. auto handled = false;
  15451. Server svr;
  15452. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15453. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15454. auto se = detail::scope_exit([&] {
  15455. svr.stop();
  15456. t.join();
  15457. ASSERT_FALSE(svr.is_running());
  15458. ASSERT_FALSE(handled);
  15459. });
  15460. svr.wait_until_ready();
  15461. // Two Content-Length headers with different values — must be rejected
  15462. auto req = "POST /test HTTP/1.1\r\n"
  15463. "Content-Length: 5\r\n"
  15464. "Content-Length: 10\r\n"
  15465. "\r\n"
  15466. "hello";
  15467. std::string response;
  15468. ASSERT_TRUE(send_request(1, req, &response));
  15469. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15470. response.substr(0, response.find("\r\n")));
  15471. }
  15472. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15473. auto handled = false;
  15474. Server svr;
  15475. svr.Post("/test", [&](const Request &, Response &res) {
  15476. handled = true;
  15477. res.set_content("ok", "text/plain");
  15478. });
  15479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15480. auto se = detail::scope_exit([&] {
  15481. svr.stop();
  15482. t.join();
  15483. ASSERT_FALSE(svr.is_running());
  15484. ASSERT_TRUE(handled);
  15485. });
  15486. svr.wait_until_ready();
  15487. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15488. auto req = "POST /test HTTP/1.1\r\n"
  15489. "Content-Length: 5\r\n"
  15490. "Content-Length: 5\r\n"
  15491. "\r\n"
  15492. "hello";
  15493. std::string response;
  15494. ASSERT_TRUE(send_request(1, req, &response));
  15495. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15496. }
  15497. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15498. Server svr;
  15499. svr.Get("/", [](const Request &req, Response &res) {
  15500. EXPECT_EQ(2U, req.trailers.size());
  15501. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15502. // Denied
  15503. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15504. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15505. // Accepted
  15506. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15507. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15508. EXPECT_TRUE(req.has_trailer("X-World"));
  15509. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15510. res.set_content("ok", "text/plain");
  15511. });
  15512. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15513. auto se = detail::scope_exit([&] {
  15514. svr.stop();
  15515. t.join();
  15516. ASSERT_FALSE(svr.is_running());
  15517. });
  15518. svr.wait_until_ready();
  15519. const std::string req = "GET / HTTP/1.1\r\n"
  15520. "Transfer-Encoding: chunked\r\n"
  15521. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15522. "\r\n"
  15523. "0\r\n"
  15524. "Content-Length: 10\r\n"
  15525. "Host: internal.local\r\n"
  15526. "Content-Type: malicious/content\r\n"
  15527. "Cookie: any\r\n"
  15528. "Set-Cookie: any\r\n"
  15529. "X-Forwarded-For: attacker.com\r\n"
  15530. "X-Real-Ip: 1.1.1.1\r\n"
  15531. "X-Hello: hello\r\n"
  15532. "X-World: world\r\n"
  15533. "\r\n";
  15534. std::string res;
  15535. ASSERT_TRUE(send_request(1, req, &res));
  15536. }
  15537. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  15538. // several field lines, and the combined value is what has to be parsed. A
  15539. // Trailer field split across lines therefore declares every name it lists;
  15540. // reading only the first line silently drops the trailers the later lines
  15541. // declare. The prohibited-trailer filter still applies to every line.
  15542. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  15543. Server svr;
  15544. size_t observed_trailer_count = 0;
  15545. std::string observed_hello;
  15546. std::string observed_world;
  15547. bool observed_content_length = true;
  15548. svr.Get("/", [&](const Request &req, Response &res) {
  15549. observed_trailer_count = req.trailers.size();
  15550. observed_hello = req.get_trailer_value("X-Hello");
  15551. observed_world = req.get_trailer_value("X-World");
  15552. observed_content_length = req.has_trailer("Content-Length");
  15553. res.set_content("ok", "text/plain");
  15554. });
  15555. auto port = svr.bind_to_any_port(HOST);
  15556. thread t = thread([&]() { svr.listen_after_bind(); });
  15557. auto se = detail::scope_exit([&] {
  15558. svr.stop();
  15559. t.join();
  15560. ASSERT_FALSE(svr.is_running());
  15561. });
  15562. svr.wait_until_ready();
  15563. const std::string req = "GET / HTTP/1.1\r\n"
  15564. "Transfer-Encoding: chunked\r\n"
  15565. "Trailer: X-Hello\r\n"
  15566. "Trailer: X-World, Content-Length\r\n"
  15567. "\r\n"
  15568. "0\r\n"
  15569. "X-Hello: hello\r\n"
  15570. "X-World: world\r\n"
  15571. "Content-Length: 10\r\n"
  15572. "\r\n";
  15573. std::string res;
  15574. ASSERT_TRUE(send_request(1, req, &res, port));
  15575. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  15576. // Accepted: both field lines contribute to the declared set
  15577. EXPECT_EQ(2U, observed_trailer_count);
  15578. EXPECT_EQ(observed_hello, "hello");
  15579. EXPECT_EQ(observed_world, "world");
  15580. // Denied: a prohibited name stays prohibited on a later field line
  15581. EXPECT_FALSE(observed_content_length);
  15582. }
  15583. // A direct client that is not listed in trusted_proxies must not be able to
  15584. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  15585. // the peer address on the actual TCP connection determines whether the
  15586. // header is honored.
  15587. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  15588. Server svr;
  15589. // Deliberately does NOT include the loopback address the test client
  15590. // actually connects from, so the direct connection is not a trusted proxy.
  15591. svr.set_trusted_proxies({"203.0.113.66"});
  15592. std::string observed_remote_addr;
  15593. svr.Get("/ip", [&](const Request &req, Response &res) {
  15594. observed_remote_addr = req.remote_addr;
  15595. res.set_content("ok", "text/plain");
  15596. });
  15597. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. t.join();
  15601. ASSERT_FALSE(svr.is_running());
  15602. });
  15603. svr.wait_until_ready();
  15604. Client cli(HOST, PORT);
  15605. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  15606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15607. EXPECT_EQ(StatusCode::OK_200, res->status);
  15608. // The connecting peer is not a trusted proxy, so the spoofed header must be
  15609. // ignored entirely and the real connection-level address retained.
  15610. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15611. observed_remote_addr == "127.0.0.1");
  15612. }
  15613. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  15614. Server svr;
  15615. std::string observed_remote_addr;
  15616. std::string observed_xff;
  15617. svr.Get("/ip", [&](const Request &req, Response &res) {
  15618. observed_remote_addr = req.remote_addr;
  15619. observed_xff = req.get_header_value("X-Forwarded-For");
  15620. res.set_content("ok", "text/plain");
  15621. });
  15622. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15623. auto se = detail::scope_exit([&] {
  15624. svr.stop();
  15625. t.join();
  15626. ASSERT_FALSE(svr.is_running());
  15627. });
  15628. svr.wait_until_ready();
  15629. Client cli(HOST, PORT);
  15630. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  15631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15632. EXPECT_EQ(StatusCode::OK_200, res->status);
  15633. EXPECT_EQ(observed_xff, "203.0.113.66");
  15634. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15635. observed_remote_addr == "127.0.0.1");
  15636. }
  15637. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  15638. Server svr;
  15639. svr.set_trusted_proxies({"203.0.113.66"});
  15640. std::string observed_remote_addr;
  15641. std::string observed_xff;
  15642. svr.Get("/ip", [&](const Request &req, Response &res) {
  15643. observed_remote_addr = req.remote_addr;
  15644. observed_xff = req.get_header_value("X-Forwarded-For");
  15645. res.set_content("ok", "text/plain");
  15646. });
  15647. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15648. auto se = detail::scope_exit([&] {
  15649. svr.stop();
  15650. t.join();
  15651. ASSERT_FALSE(svr.is_running());
  15652. });
  15653. svr.wait_until_ready();
  15654. Client cli(HOST, PORT);
  15655. auto res = cli.Get("/ip");
  15656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15657. EXPECT_EQ(StatusCode::OK_200, res->status);
  15658. EXPECT_EQ(observed_xff, "");
  15659. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15660. observed_remote_addr == "127.0.0.1");
  15661. }
  15662. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  15663. Server svr;
  15664. // Include the loopback address the test client actually connects from, so
  15665. // the direct connection itself is recognized as the trusted proxy hop.
  15666. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  15667. std::string observed_remote_addr;
  15668. std::string observed_xff;
  15669. svr.Get("/ip", [&](const Request &req, Response &res) {
  15670. observed_remote_addr = req.remote_addr;
  15671. observed_xff = req.get_header_value("X-Forwarded-For");
  15672. res.set_content("ok", "text/plain");
  15673. });
  15674. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15675. auto se = detail::scope_exit([&] {
  15676. svr.stop();
  15677. t.join();
  15678. ASSERT_FALSE(svr.is_running());
  15679. });
  15680. svr.wait_until_ready();
  15681. Client cli(HOST, PORT);
  15682. auto res = cli.Get(
  15683. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  15684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15685. EXPECT_EQ(StatusCode::OK_200, res->status);
  15686. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  15687. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15688. }
  15689. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  15690. Server svr;
  15691. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  15692. std::string observed_remote_addr;
  15693. std::string observed_xff;
  15694. svr.Get("/ip", [&](const Request &req, Response &res) {
  15695. observed_remote_addr = req.remote_addr;
  15696. observed_xff = req.get_header_value("X-Forwarded-For");
  15697. res.set_content("ok", "text/plain");
  15698. });
  15699. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15700. auto se = detail::scope_exit([&] {
  15701. svr.stop();
  15702. t.join();
  15703. ASSERT_FALSE(svr.is_running());
  15704. });
  15705. svr.wait_until_ready();
  15706. Client cli(HOST, PORT);
  15707. auto res = cli.Get(
  15708. "/ip",
  15709. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15711. EXPECT_EQ(StatusCode::OK_200, res->status);
  15712. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15713. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15714. }
  15715. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  15716. Server svr;
  15717. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15718. std::string observed_remote_addr;
  15719. std::string observed_xff;
  15720. svr.Get("/ip", [&](const Request &req, Response &res) {
  15721. observed_remote_addr = req.remote_addr;
  15722. observed_xff = req.get_header_value("X-Forwarded-For");
  15723. res.set_content("ok", "text/plain");
  15724. });
  15725. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15726. auto se = detail::scope_exit([&] {
  15727. svr.stop();
  15728. t.join();
  15729. ASSERT_FALSE(svr.is_running());
  15730. });
  15731. svr.wait_until_ready();
  15732. Client cli(HOST, PORT);
  15733. auto res = cli.Get(
  15734. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  15735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15736. EXPECT_EQ(StatusCode::OK_200, res->status);
  15737. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  15738. // by the closest hop) is used. The leftmost entry is fully client-controlled
  15739. // and must not be selected.
  15740. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  15741. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  15742. }
  15743. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  15744. Server svr;
  15745. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  15746. std::string observed_remote_addr;
  15747. svr.Get("/ip", [&](const Request &req, Response &res) {
  15748. observed_remote_addr = req.remote_addr;
  15749. res.set_content("ok", "text/plain");
  15750. });
  15751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15752. auto se = detail::scope_exit([&] {
  15753. svr.stop();
  15754. t.join();
  15755. ASSERT_FALSE(svr.is_running());
  15756. });
  15757. svr.wait_until_ready();
  15758. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  15759. // a forged address and the trusted proxy's own address; the forged value must
  15760. // not win over the address the trusted proxy actually recorded.
  15761. Client cli(HOST, PORT);
  15762. auto res = cli.Get(
  15763. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  15764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15765. EXPECT_EQ(StatusCode::OK_200, res->status);
  15766. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  15767. }
  15768. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  15769. Server svr;
  15770. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15771. std::string observed_remote_addr;
  15772. std::string observed_xff;
  15773. svr.Get("/ip", [&](const Request &req, Response &res) {
  15774. observed_remote_addr = req.remote_addr;
  15775. observed_xff = req.get_header_value("X-Forwarded-For");
  15776. res.set_content("ok", "text/plain");
  15777. });
  15778. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15779. auto se = detail::scope_exit([&] {
  15780. svr.stop();
  15781. t.join();
  15782. ASSERT_FALSE(svr.is_running());
  15783. });
  15784. svr.wait_until_ready();
  15785. Client cli(HOST, PORT);
  15786. auto res = cli.Get(
  15787. "/ip",
  15788. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  15789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15790. EXPECT_EQ(StatusCode::OK_200, res->status);
  15791. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  15792. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15793. }
  15794. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  15795. Server svr;
  15796. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15797. std::string observed_remote_addr;
  15798. std::string observed_xff;
  15799. svr.Get("/ip", [&](const Request &req, Response &res) {
  15800. observed_remote_addr = req.remote_addr;
  15801. observed_xff = req.get_header_value("X-Forwarded-For");
  15802. res.set_content("ok", "text/plain");
  15803. });
  15804. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15805. auto se = detail::scope_exit([&] {
  15806. svr.stop();
  15807. t.join();
  15808. ASSERT_FALSE(svr.is_running());
  15809. });
  15810. svr.wait_until_ready();
  15811. std::string raw_req =
  15812. "GET /ip HTTP/1.1\r\n"
  15813. "Host: localhost\r\n"
  15814. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  15815. "Connection: close\r\n"
  15816. "\r\n";
  15817. std::string out;
  15818. ASSERT_TRUE(send_request(5, raw_req, &out));
  15819. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15820. // Header parser trims surrounding whitespace of the header value
  15821. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  15822. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  15823. }
  15824. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  15825. // one comma-joined value, in the order received. Proxies such as HAProxy append
  15826. // their own X-Forwarded-For as a separate field line rather than extending the
  15827. // one the client sent, so every occurrence has to be taken into account.
  15828. // Reading only the first one hands back the address the client chose.
  15829. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  15830. Server svr;
  15831. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  15832. std::string observed_remote_addr;
  15833. size_t observed_xff_count = 0;
  15834. svr.Get("/ip", [&](const Request &req, Response &res) {
  15835. observed_remote_addr = req.remote_addr;
  15836. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  15837. res.set_content("ok", "text/plain");
  15838. });
  15839. auto port = svr.bind_to_any_port(HOST);
  15840. thread t = thread([&]() { svr.listen_after_bind(); });
  15841. auto se = detail::scope_exit([&] {
  15842. svr.stop();
  15843. t.join();
  15844. ASSERT_FALSE(svr.is_running());
  15845. });
  15846. svr.wait_until_ready();
  15847. // The client supplies the first field line; the trusted proxy appends the
  15848. // address it observed as a second one.
  15849. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  15850. "Host: localhost\r\n"
  15851. "X-Forwarded-For: 1.2.3.4\r\n"
  15852. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  15853. "Connection: close\r\n"
  15854. "\r\n";
  15855. std::string out;
  15856. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  15857. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15858. EXPECT_EQ(observed_xff_count, 2U);
  15859. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15860. // The same chain spread over one field line per hop derives the same client
  15861. // address, i.e. the split and the comma-joined representations agree.
  15862. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  15863. "Host: localhost\r\n"
  15864. "X-Forwarded-For: 1.2.3.4\r\n"
  15865. "X-Forwarded-For: 198.51.100.23\r\n"
  15866. "X-Forwarded-For: 192.0.2.45\r\n"
  15867. "Connection: close\r\n"
  15868. "\r\n";
  15869. out.clear();
  15870. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  15871. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15872. EXPECT_EQ(observed_xff_count, 3U);
  15873. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  15874. }
  15875. // An X-Forwarded-For header whose value parses to zero IP segments must not
  15876. // crash the server (it used to call front() on an empty vector inside
  15877. // get_client_ip). The connection-level remote address must be retained instead.
  15878. static void run_malformed_xff_test(const std::string &xff_value) {
  15879. Server svr;
  15880. svr.set_trusted_proxies({"192.0.2.45"});
  15881. std::string observed_remote_addr;
  15882. svr.Get("/ip", [&](const Request &req, Response &res) {
  15883. observed_remote_addr = req.remote_addr;
  15884. res.set_content("ok", "text/plain");
  15885. });
  15886. int port = 0;
  15887. thread t = thread([&]() {
  15888. port = svr.bind_to_any_port(HOST);
  15889. svr.listen_after_bind();
  15890. });
  15891. auto se = detail::scope_exit([&] {
  15892. svr.stop();
  15893. t.join();
  15894. ASSERT_FALSE(svr.is_running());
  15895. });
  15896. svr.wait_until_ready();
  15897. Client cli(HOST, port);
  15898. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  15899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15900. EXPECT_EQ(StatusCode::OK_200, res->status);
  15901. EXPECT_TRUE(observed_remote_addr == "::1" ||
  15902. observed_remote_addr == "127.0.0.1");
  15903. }
  15904. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  15905. run_malformed_xff_test("");
  15906. }
  15907. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  15908. run_malformed_xff_test(",");
  15909. }
  15910. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  15911. run_malformed_xff_test(", , ,");
  15912. }
  15913. // The same rule applies to Accept: a request whose acceptable types are spread
  15914. // over several field lines must be negotiated against all of them.
  15915. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  15916. // case-insensitive connection options. Comparing the whole field value against
  15917. // one option misses a client that sends several of them, and misses every
  15918. // casing but the one written in the comparison.
  15919. //
  15920. // Sends req, reads the response, then reuses the same socket for a second
  15921. // request to find out whether the server kept the connection.
  15922. static void probe_connection_reuse(int port, const std::string &req,
  15923. bool *announced_close, bool *reusable) {
  15924. auto error = Error::Success;
  15925. auto sock = detail::create_client_socket(
  15926. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15927. /*connection_timeout_sec=*/5, 0,
  15928. /*read_timeout_sec=*/1, 0,
  15929. /*write_timeout_sec=*/5, 0, std::string(), error);
  15930. ASSERT_NE(sock, INVALID_SOCKET);
  15931. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  15932. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  15933. "Host: localhost\r\n"
  15934. "Connection: close\r\n"
  15935. "\r\n";
  15936. std::string first_response;
  15937. std::string second_response;
  15938. detail::process_client_socket(
  15939. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  15940. [&](Stream &strm) {
  15941. if (strm.write(req.data(), req.size()) !=
  15942. static_cast<ssize_t>(req.size())) {
  15943. return false;
  15944. }
  15945. char buf[512];
  15946. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  15947. // Headers plus the two-byte body of the handler below
  15948. while (reader.getline()) {
  15949. first_response += reader.ptr();
  15950. if (first_response.find("ok") != std::string::npos) { break; }
  15951. }
  15952. if (strm.write(second.data(), second.size()) !=
  15953. static_cast<ssize_t>(second.size())) {
  15954. return true;
  15955. }
  15956. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  15957. while (reader2.getline()) {
  15958. second_response += reader2.ptr();
  15959. if (second_response.find("ok") != std::string::npos) { break; }
  15960. }
  15961. return true;
  15962. });
  15963. *announced_close =
  15964. first_response.find("Connection: close") != std::string::npos;
  15965. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  15966. }
  15967. class ConnectionTokenTest : public ::testing::Test {
  15968. protected:
  15969. void SetUp() override {
  15970. svr_.Get("/keepalive", [](const Request &, Response &res) {
  15971. res.set_content("ok", "text/plain");
  15972. });
  15973. port_ = svr_.bind_to_any_port(HOST);
  15974. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15975. svr_.wait_until_ready();
  15976. }
  15977. void TearDown() override {
  15978. svr_.stop();
  15979. if (thread_.joinable()) { thread_.join(); }
  15980. }
  15981. Server svr_;
  15982. int port_ = 0;
  15983. thread thread_;
  15984. };
  15985. // "close" alongside another option still closes the connection, and the
  15986. // response says so rather than leaving the peer to discover it.
  15987. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  15988. bool announced_close = false;
  15989. bool reusable = true;
  15990. probe_connection_reuse(port_,
  15991. "GET /keepalive HTTP/1.1\r\n"
  15992. "Host: localhost\r\n"
  15993. "Connection: keep-alive, close\r\n"
  15994. "\r\n",
  15995. &announced_close, &reusable);
  15996. EXPECT_TRUE(announced_close);
  15997. EXPECT_FALSE(reusable);
  15998. }
  15999. // "close" split over two field lines is the same list, so it is honored too.
  16000. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16001. bool announced_close = false;
  16002. bool reusable = true;
  16003. probe_connection_reuse(port_,
  16004. "GET /keepalive HTTP/1.1\r\n"
  16005. "Host: localhost\r\n"
  16006. "Connection: keep-alive\r\n"
  16007. "Connection: close\r\n"
  16008. "\r\n",
  16009. &announced_close, &reusable);
  16010. EXPECT_TRUE(announced_close);
  16011. EXPECT_FALSE(reusable);
  16012. }
  16013. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16014. // keep-alive in the spelling everyone actually sends keeps its connection.
  16015. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16016. bool announced_close = false;
  16017. bool reusable = false;
  16018. probe_connection_reuse(port_,
  16019. "GET /keepalive HTTP/1.0\r\n"
  16020. "Host: localhost\r\n"
  16021. "Connection: keep-alive\r\n"
  16022. "\r\n",
  16023. &announced_close, &reusable);
  16024. EXPECT_FALSE(announced_close);
  16025. EXPECT_TRUE(reusable);
  16026. }
  16027. // A token the value merely contains is not the token itself.
  16028. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16029. bool announced_close = false;
  16030. bool reusable = false;
  16031. probe_connection_reuse(port_,
  16032. "GET /keepalive HTTP/1.1\r\n"
  16033. "Host: localhost\r\n"
  16034. "Connection: notclose\r\n"
  16035. "\r\n",
  16036. &announced_close, &reusable);
  16037. EXPECT_FALSE(announced_close);
  16038. EXPECT_TRUE(reusable);
  16039. }
  16040. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16041. Server svr;
  16042. std::vector<std::string> observed_types;
  16043. svr.Get("/", [&](const Request &req, Response &res) {
  16044. observed_types = req.accept_content_types;
  16045. res.set_content("ok", "text/plain");
  16046. });
  16047. auto port = svr.bind_to_any_port(HOST);
  16048. thread t = thread([&]() { svr.listen_after_bind(); });
  16049. auto se = detail::scope_exit([&] {
  16050. svr.stop();
  16051. t.join();
  16052. ASSERT_FALSE(svr.is_running());
  16053. });
  16054. svr.wait_until_ready();
  16055. Client cli(HOST, port);
  16056. Headers headers;
  16057. headers.emplace("Accept", "text/plain;q=0.5");
  16058. headers.emplace("Accept", "application/json");
  16059. auto res = cli.Get("/", headers);
  16060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16061. EXPECT_EQ(StatusCode::OK_200, res->status);
  16062. // Sorted by q-value, so the second field line's type comes first
  16063. ASSERT_EQ(2U, observed_types.size());
  16064. EXPECT_EQ("application/json", observed_types[0]);
  16065. EXPECT_EQ("text/plain", observed_types[1]);
  16066. }
  16067. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16068. // empty field line must not contribute a bare comma to the combined value.
  16069. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16070. Server svr;
  16071. std::vector<std::string> observed_types;
  16072. svr.Get("/", [&](const Request &req, Response &res) {
  16073. observed_types = req.accept_content_types;
  16074. res.set_content("ok", "text/plain");
  16075. });
  16076. auto port = svr.bind_to_any_port(HOST);
  16077. thread t = thread([&]() { svr.listen_after_bind(); });
  16078. auto se = detail::scope_exit([&] {
  16079. svr.stop();
  16080. t.join();
  16081. ASSERT_FALSE(svr.is_running());
  16082. });
  16083. svr.wait_until_ready();
  16084. // Empty first field line, then a real one
  16085. std::string raw_req = "GET / HTTP/1.1\r\n"
  16086. "Host: localhost\r\n"
  16087. "Accept:\r\n"
  16088. "Accept: application/json\r\n"
  16089. "Connection: close\r\n"
  16090. "\r\n";
  16091. std::string out;
  16092. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16093. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16094. ASSERT_EQ(1U, observed_types.size());
  16095. EXPECT_EQ("application/json", observed_types[0]);
  16096. }
  16097. // The skip in get_combined_header_value() is what keeps an empty field line
  16098. // from contributing a bare comma. Only a trailing empty field line exercises
  16099. // it: a leading one is already covered by the "combined is still empty" check,
  16100. // and parse_accept_header() now ignores the empty element either way, so the
  16101. // request-level test above can no longer tell the two apart.
  16102. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16103. Headers headers;
  16104. headers.emplace("Accept", "text/html");
  16105. headers.emplace("Accept", "");
  16106. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16107. headers.clear();
  16108. headers.emplace("Accept", "");
  16109. headers.emplace("Accept", "application/json");
  16110. EXPECT_EQ("application/json",
  16111. detail::get_combined_header_value(headers, "Accept"));
  16112. }
  16113. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16114. // An encoding offered on a later Accept-Encoding field line is still offered.
  16115. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16116. Server svr;
  16117. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16118. res.set_content(std::string(1024, 'x'), "text/plain");
  16119. });
  16120. auto port = svr.bind_to_any_port(HOST);
  16121. thread t = thread([&]() { svr.listen_after_bind(); });
  16122. auto se = detail::scope_exit([&] {
  16123. svr.stop();
  16124. t.join();
  16125. ASSERT_FALSE(svr.is_running());
  16126. });
  16127. svr.wait_until_ready();
  16128. Client cli(HOST, port);
  16129. cli.set_decompress(false);
  16130. Headers headers;
  16131. headers.emplace("Accept-Encoding", "identity");
  16132. headers.emplace("Accept-Encoding", "gzip");
  16133. auto res = cli.Get("/", headers);
  16134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16135. EXPECT_EQ(StatusCode::OK_200, res->status);
  16136. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16137. }
  16138. #endif
  16139. #ifndef _WIN32
  16140. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16141. Server svr;
  16142. svr.Post("/post", [&](const Request &req, Response &res) {
  16143. res.set_content(req.body, "text/plain");
  16144. });
  16145. svr.Put("/put", [&](const Request &req, Response &res) {
  16146. res.set_content(req.body, "text/plain");
  16147. });
  16148. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16149. res.set_content(req.body, "text/plain");
  16150. });
  16151. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16152. res.set_content(req.body, "text/plain");
  16153. });
  16154. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16155. auto se = detail::scope_exit([&] {
  16156. svr.stop();
  16157. t.join();
  16158. ASSERT_FALSE(svr.is_running());
  16159. });
  16160. svr.wait_until_ready();
  16161. std::string resp;
  16162. // POST without Content-Length
  16163. ASSERT_TRUE(send_request(5,
  16164. "POST /post HTTP/1.1\r\n"
  16165. "Host: localhost\r\n"
  16166. "Connection: close\r\n"
  16167. "\r\n",
  16168. &resp));
  16169. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16170. // PUT without Content-Length
  16171. resp.clear();
  16172. ASSERT_TRUE(send_request(5,
  16173. "PUT /put HTTP/1.1\r\n"
  16174. "Host: localhost\r\n"
  16175. "Connection: close\r\n"
  16176. "\r\n",
  16177. &resp));
  16178. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16179. // PATCH without Content-Length
  16180. resp.clear();
  16181. ASSERT_TRUE(send_request(5,
  16182. "PATCH /patch HTTP/1.1\r\n"
  16183. "Host: localhost\r\n"
  16184. "Connection: close\r\n"
  16185. "\r\n",
  16186. &resp));
  16187. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16188. // DELETE without Content-Length
  16189. resp.clear();
  16190. ASSERT_TRUE(send_request(5,
  16191. "DELETE /delete HTTP/1.1\r\n"
  16192. "Host: localhost\r\n"
  16193. "Connection: close\r\n"
  16194. "\r\n",
  16195. &resp));
  16196. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16197. }
  16198. #endif
  16199. //==============================================================================
  16200. // open_stream() Tests
  16201. //==============================================================================
  16202. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16203. std::string result;
  16204. char buf[8192];
  16205. ssize_t n;
  16206. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16207. result.append(buf, static_cast<size_t>(n));
  16208. }
  16209. return result;
  16210. }
  16211. // Mock stream for unit tests
  16212. class MockStream : public Stream {
  16213. public:
  16214. std::string data;
  16215. size_t pos = 0;
  16216. ssize_t error_after = -1; // -1 = no error
  16217. explicit MockStream(const std::string &d, ssize_t err = -1)
  16218. : data(d), error_after(err) {}
  16219. bool is_readable() const override { return true; }
  16220. bool wait_readable() const override { return true; }
  16221. bool wait_writable() const override { return true; }
  16222. ssize_t read(char *ptr, size_t size) override {
  16223. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16224. if (pos >= data.size()) return 0;
  16225. size_t limit =
  16226. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16227. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16228. std::memcpy(ptr, data.data() + pos, to_read);
  16229. pos += to_read;
  16230. return static_cast<ssize_t>(to_read);
  16231. }
  16232. ssize_t write(const char *, size_t) override { return -1; }
  16233. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16234. ip = "127.0.0.1";
  16235. port = 0;
  16236. }
  16237. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16238. ip = "127.0.0.1";
  16239. port = 0;
  16240. }
  16241. socket_t socket() const override { return INVALID_SOCKET; }
  16242. time_t duration() const override { return 0; }
  16243. };
  16244. TEST(StreamHandleTest, Basic) {
  16245. ClientImpl::StreamHandle handle;
  16246. EXPECT_FALSE(handle.is_valid());
  16247. handle.response = detail::make_unique<Response>();
  16248. handle.error = Error::Connection;
  16249. EXPECT_FALSE(handle.is_valid());
  16250. handle.error = Error::Success;
  16251. EXPECT_TRUE(handle.is_valid());
  16252. }
  16253. TEST(BodyReaderTest, Basic) {
  16254. MockStream stream("Hello, World!");
  16255. detail::BodyReader reader;
  16256. reader.stream = &stream;
  16257. reader.content_length = 13;
  16258. char buf[32];
  16259. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16260. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16261. EXPECT_TRUE(reader.eof);
  16262. }
  16263. TEST(BodyReaderTest, NoStream) {
  16264. detail::BodyReader reader;
  16265. char buf[32];
  16266. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16267. EXPECT_EQ(Error::Connection, reader.last_error);
  16268. }
  16269. TEST(BodyReaderTest, Error) {
  16270. MockStream stream("Hello, World!", 5);
  16271. detail::BodyReader reader;
  16272. reader.stream = &stream;
  16273. reader.content_length = 13;
  16274. char buf[32];
  16275. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16276. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16277. EXPECT_EQ(Error::Read, reader.last_error);
  16278. }
  16279. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16280. // Mock-based StreamHandle tests relying on private internals are removed.
  16281. class OpenStreamTest : public ::testing::Test {
  16282. protected:
  16283. void SetUp() override {
  16284. svr_.Get("/hello", [](const Request &, Response &res) {
  16285. res.set_content("Hello World!", "text/plain");
  16286. });
  16287. svr_.Get("/large", [](const Request &, Response &res) {
  16288. res.set_content(std::string(10000, 'X'), "text/plain");
  16289. });
  16290. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16291. res.set_content("Hello World!", "image/jpeg");
  16292. res.set_header("Content-Encoding", "UTF-8");
  16293. });
  16294. svr_.Get("/chunked", [](const Request &, Response &res) {
  16295. res.set_chunked_content_provider("text/plain",
  16296. [](size_t offset, DataSink &sink) {
  16297. if (offset < 15) {
  16298. sink.write("chunk", 5);
  16299. return true;
  16300. }
  16301. sink.done();
  16302. return true;
  16303. });
  16304. });
  16305. svr_.Get("/compressible", [](const Request &, Response &res) {
  16306. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16307. DataSink &sink) {
  16308. if (offset < 100 * 1024) {
  16309. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16310. sink.write(chunk.data(), chunk.size());
  16311. return true;
  16312. }
  16313. sink.done();
  16314. return true;
  16315. });
  16316. });
  16317. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16318. [](const Request & /*req*/, Response &res) {
  16319. auto i = new int(0);
  16320. res.set_header("Trailer", "Content-Length, X-Allowed");
  16321. res.set_chunked_content_provider(
  16322. "text/plain",
  16323. [i](size_t /*offset*/, DataSink &sink) {
  16324. switch (*i) {
  16325. case 0: sink.os << "123"; break;
  16326. case 1: sink.os << "456"; break;
  16327. case 2: sink.os << "789"; break;
  16328. case 3: {
  16329. sink.done_with_trailer(
  16330. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16331. } break;
  16332. }
  16333. (*i)++;
  16334. return true;
  16335. },
  16336. [i](bool success) {
  16337. EXPECT_TRUE(success);
  16338. delete i;
  16339. });
  16340. });
  16341. // Echo headers endpoint for header-related tests
  16342. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16343. std::string body;
  16344. for (const auto &h : req.headers) {
  16345. body.append(h.first);
  16346. body.push_back(':');
  16347. body.append(h.second);
  16348. body.push_back('\n');
  16349. }
  16350. res.set_content(body, "text/plain");
  16351. });
  16352. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16353. std::string body;
  16354. for (const auto &h : req.headers) {
  16355. body.append(h.first);
  16356. body.push_back(':');
  16357. body.append(h.second);
  16358. body.push_back('\n');
  16359. }
  16360. res.set_content(body, "text/plain");
  16361. });
  16362. port_ = svr_.bind_to_any_port("127.0.0.1");
  16363. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16364. svr_.wait_until_ready();
  16365. }
  16366. void TearDown() override {
  16367. svr_.stop();
  16368. if (thread_.joinable()) thread_.join();
  16369. }
  16370. Server svr_;
  16371. std::thread thread_;
  16372. int port_ = 0;
  16373. };
  16374. TEST_F(OpenStreamTest, Basic) {
  16375. Client cli("127.0.0.1", port_);
  16376. auto handle = cli.open_stream("GET", "/hello");
  16377. EXPECT_TRUE(handle.is_valid());
  16378. EXPECT_EQ("Hello World!", read_all(handle));
  16379. }
  16380. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16381. Client cli("127.0.0.1", port_);
  16382. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16383. ASSERT_TRUE(handle.is_valid());
  16384. EXPECT_EQ("Hello World!", read_all(handle));
  16385. }
  16386. TEST_F(OpenStreamTest, SmallBuffer) {
  16387. Client cli("127.0.0.1", port_);
  16388. auto handle = cli.open_stream("GET", "/hello");
  16389. std::string result;
  16390. char buf[4];
  16391. ssize_t n;
  16392. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16393. result.append(buf, static_cast<size_t>(n));
  16394. EXPECT_EQ("Hello World!", result);
  16395. }
  16396. TEST_F(OpenStreamTest, DefaultHeaders) {
  16397. Client cli("127.0.0.1", port_);
  16398. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16399. {
  16400. auto handle = cli.open_stream("GET", "/echo-headers");
  16401. ASSERT_TRUE(handle.is_valid());
  16402. auto body = read_all(handle);
  16403. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16404. std::string::npos);
  16405. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16406. std::string::npos);
  16407. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16408. }
  16409. // open_stream POST with body and no explicit content_type should NOT add
  16410. // text/plain Content-Type (behavior differs from non-streaming path), but
  16411. // should include Content-Length
  16412. {
  16413. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16414. ASSERT_TRUE(handle.is_valid());
  16415. auto body = read_all(handle);
  16416. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16417. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16418. }
  16419. // open_stream POST with explicit Content-Type should preserve it
  16420. {
  16421. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16422. {{"Content-Type", "application/custom"}},
  16423. "{}", "application/custom");
  16424. ASSERT_TRUE(handle.is_valid());
  16425. auto body = read_all(handle);
  16426. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16427. }
  16428. // User-specified User-Agent must not be overwritten for stream API
  16429. {
  16430. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16431. {{"User-Agent", "MyAgent/1.2"}});
  16432. ASSERT_TRUE(handle.is_valid());
  16433. auto body = read_all(handle);
  16434. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16435. }
  16436. }
  16437. TEST_F(OpenStreamTest, Large) {
  16438. Client cli("127.0.0.1", port_);
  16439. auto handle = cli.open_stream("GET", "/large");
  16440. EXPECT_EQ(10000u, read_all(handle).size());
  16441. }
  16442. TEST_F(OpenStreamTest, ConnectionError) {
  16443. Client cli("127.0.0.1", 9999);
  16444. auto handle = cli.open_stream("GET", "/hello");
  16445. EXPECT_FALSE(handle.is_valid());
  16446. }
  16447. TEST_F(OpenStreamTest, Chunked) {
  16448. Client cli("127.0.0.1", port_);
  16449. auto handle = cli.open_stream("GET", "/chunked");
  16450. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16451. "Transfer-Encoding") == "chunked");
  16452. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  16453. }
  16454. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  16455. Client cli("127.0.0.1", port_);
  16456. auto handle =
  16457. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  16458. ASSERT_TRUE(handle.is_valid());
  16459. // Consume body to allow trailers to be received/parsed
  16460. auto body = read_all(handle);
  16461. // Explicitly parse trailers (ensure trailers are available for assertion)
  16462. handle.parse_trailers_if_needed();
  16463. EXPECT_EQ(std::string("123456789"), body);
  16464. // The response should include a Trailer header declaring both names
  16465. ASSERT_TRUE(handle.response);
  16466. EXPECT_TRUE(handle.response->has_header("Trailer"));
  16467. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  16468. handle.response->get_header_value("Trailer"));
  16469. // Prohibited trailer must not be present
  16470. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  16471. // Allowed trailer should be present
  16472. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  16473. EXPECT_EQ(std::string("yes"),
  16474. handle.response->get_trailer_value("X-Allowed"));
  16475. // Verify trailers are NOT present as regular headers
  16476. EXPECT_EQ(std::string(""),
  16477. handle.response->get_header_value("Content-Length"));
  16478. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  16479. }
  16480. static std::thread serve_single_response(std::promise<int> &port_promise,
  16481. const std::string &response) {
  16482. return std::thread([&port_promise, response] {
  16483. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16484. default_socket_options(srv);
  16485. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16486. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  16487. sockaddr_in addr{};
  16488. addr.sin_family = AF_INET;
  16489. addr.sin_port = htons(0); // Let OS assign a free port
  16490. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16491. int opt = 1;
  16492. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  16493. #ifdef _WIN32
  16494. reinterpret_cast<const char *>(&opt),
  16495. #else
  16496. &opt,
  16497. #endif
  16498. sizeof(opt));
  16499. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  16500. ::listen(srv, 1) != 0) {
  16501. port_promise.set_value(-1);
  16502. detail::close_socket(srv);
  16503. return;
  16504. }
  16505. socklen_t addr_len = sizeof(addr);
  16506. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  16507. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  16508. sockaddr_in cli_addr{};
  16509. socklen_t cli_len = sizeof(cli_addr);
  16510. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16511. if (cli != INVALID_SOCKET) {
  16512. // Read the complete HTTP request (until the blank line that terminates
  16513. // headers) before sending the response. If the server closes the socket
  16514. // while the client's request data is still unread in the kernel receive
  16515. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  16516. // connection on both sides: it discards the client's receive buffer
  16517. // (which already holds our response) and causes any in-progress write on
  16518. // the client to fail with ECONNRESET. Reading all request data first
  16519. // ensures close() emits a graceful FIN.
  16520. {
  16521. char rbuf[256];
  16522. std::string req;
  16523. while (req.find("\r\n\r\n") == std::string::npos) {
  16524. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  16525. if (n <= 0) { break; }
  16526. req.append(rbuf, static_cast<size_t>(n));
  16527. }
  16528. }
  16529. ::send(cli,
  16530. #ifdef _WIN32
  16531. static_cast<const char *>(response.c_str()),
  16532. static_cast<int>(response.size()),
  16533. #else
  16534. response.c_str(), response.size(),
  16535. #endif
  16536. 0);
  16537. detail::close_socket(cli);
  16538. }
  16539. detail::close_socket(srv);
  16540. });
  16541. }
  16542. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  16543. #ifndef _WIN32
  16544. signal(SIGPIPE, SIG_IGN);
  16545. #endif
  16546. std::promise<int> port_promise;
  16547. auto port_future = port_promise.get_future();
  16548. auto server_thread =
  16549. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  16550. "Content-Type: text/plain\r\n"
  16551. "Content-Length: not-a-number\r\n"
  16552. "Connection: close\r\n"
  16553. "\r\n"
  16554. "hello");
  16555. auto port = port_future.get();
  16556. ASSERT_GT(port, 0);
  16557. Client cli("127.0.0.1", port);
  16558. auto handle = cli.open_stream("GET", "/");
  16559. EXPECT_FALSE(handle.is_valid());
  16560. server_thread.join();
  16561. }
  16562. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  16563. #ifndef _WIN32
  16564. signal(SIGPIPE, SIG_IGN);
  16565. #endif
  16566. std::promise<int> port_promise;
  16567. auto port_future = port_promise.get_future();
  16568. auto server_thread = serve_single_response(
  16569. port_promise, "HTTP/1.1 200 OK\r\n"
  16570. "Content-Type: text/plain\r\n"
  16571. "Content-Length: 99999999999999999999999999\r\n"
  16572. "Connection: close\r\n"
  16573. "\r\n"
  16574. "hello");
  16575. auto port = port_future.get();
  16576. ASSERT_GT(port, 0);
  16577. // Historically std::stoull would throw std::out_of_range here and crash
  16578. // the process, then parsing silently clamped to a bogus framing length and
  16579. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  16580. // so the stream fails to open, matching the not-a-number case above. The
  16581. // process still must NOT terminate.
  16582. Client cli("127.0.0.1", port);
  16583. auto handle = cli.open_stream("GET", "/");
  16584. EXPECT_FALSE(handle.is_valid());
  16585. server_thread.join();
  16586. }
  16587. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16588. TEST_F(OpenStreamTest, Gzip) {
  16589. Client cli("127.0.0.1", port_);
  16590. auto handle = cli.open_stream("GET", "/compressible", {},
  16591. {{"Accept-Encoding", "gzip"}});
  16592. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  16593. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16594. }
  16595. #endif
  16596. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16597. TEST_F(OpenStreamTest, Brotli) {
  16598. Client cli("127.0.0.1", port_);
  16599. auto handle =
  16600. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  16601. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  16602. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16603. }
  16604. #endif
  16605. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16606. TEST_F(OpenStreamTest, Zstd) {
  16607. Client cli("127.0.0.1", port_);
  16608. auto handle = cli.open_stream("GET", "/compressible", {},
  16609. {{"Accept-Encoding", "zstd"}});
  16610. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  16611. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  16612. }
  16613. #endif
  16614. #ifdef CPPHTTPLIB_SSL_ENABLED
  16615. class SSLOpenStreamTest : public ::testing::Test {
  16616. protected:
  16617. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  16618. void SetUp() override {
  16619. svr_.Get("/hello", [](const Request &, Response &res) {
  16620. res.set_content("Hello SSL World!", "text/plain");
  16621. });
  16622. svr_.Get("/chunked", [](const Request &, Response &res) {
  16623. res.set_chunked_content_provider("text/plain",
  16624. [](size_t offset, DataSink &sink) {
  16625. if (offset < 15) {
  16626. sink.write("chunk", 5);
  16627. return true;
  16628. }
  16629. sink.done();
  16630. return true;
  16631. });
  16632. });
  16633. svr_.Post("/echo", [](const Request &req, Response &res) {
  16634. res.set_content(req.body, req.get_header_value("Content-Type"));
  16635. });
  16636. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  16637. std::string body = req.body;
  16638. res.set_chunked_content_provider(
  16639. "text/plain", [body](size_t offset, DataSink &sink) {
  16640. if (offset < body.size()) {
  16641. sink.write(body.data() + offset, body.size() - offset);
  16642. }
  16643. sink.done();
  16644. return true;
  16645. });
  16646. });
  16647. port_ = svr_.bind_to_any_port("127.0.0.1");
  16648. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16649. svr_.wait_until_ready();
  16650. }
  16651. void TearDown() override {
  16652. svr_.stop();
  16653. if (thread_.joinable()) thread_.join();
  16654. }
  16655. SSLServer svr_;
  16656. std::thread thread_;
  16657. int port_ = 0;
  16658. };
  16659. TEST_F(SSLOpenStreamTest, Basic) {
  16660. SSLClient cli("127.0.0.1", port_);
  16661. cli.enable_server_certificate_verification(false);
  16662. auto handle = cli.open_stream("GET", "/hello");
  16663. ASSERT_TRUE(handle.is_valid());
  16664. EXPECT_EQ("Hello SSL World!", read_all(handle));
  16665. }
  16666. TEST_F(SSLOpenStreamTest, Chunked) {
  16667. SSLClient cli("127.0.0.1", port_);
  16668. cli.enable_server_certificate_verification(false);
  16669. auto handle = cli.open_stream("GET", "/chunked");
  16670. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16671. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  16672. "Transfer-Encoding") == "chunked");
  16673. auto body = read_all(handle);
  16674. EXPECT_EQ("chunkchunkchunk", body);
  16675. }
  16676. TEST_F(SSLOpenStreamTest, Post) {
  16677. SSLClient cli("127.0.0.1", port_);
  16678. cli.enable_server_certificate_verification(false);
  16679. auto handle =
  16680. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  16681. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  16682. EXPECT_EQ(200, handle.response->status);
  16683. auto body = read_all(handle);
  16684. EXPECT_EQ("Hello SSL POST", body);
  16685. }
  16686. TEST_F(SSLOpenStreamTest, PostChunked) {
  16687. SSLClient cli("127.0.0.1", port_);
  16688. cli.enable_server_certificate_verification(false);
  16689. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  16690. "Chunked SSL Data", "text/plain");
  16691. ASSERT_TRUE(handle.is_valid());
  16692. EXPECT_EQ(200, handle.response->status);
  16693. auto body = read_all(handle);
  16694. EXPECT_EQ("Chunked SSL Data", body);
  16695. }
  16696. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  16697. // Content-Length is terminated by the server closing the connection. When the
  16698. // SSL peer sends a close_notify after the body, the client must treat it as a
  16699. // clean EOF and return a successful response rather than an error.
  16700. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  16701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16702. ASSERT_TRUE(svr.is_valid());
  16703. svr.set_keep_alive_max_count(1);
  16704. const std::string expected_body = "Hello from connection-close response!";
  16705. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  16706. res.set_content_provider("text/plain",
  16707. [&](size_t offset, DataSink &sink) -> bool {
  16708. if (offset < expected_body.size()) {
  16709. sink.write(expected_body.data() + offset,
  16710. expected_body.size() - offset);
  16711. }
  16712. sink.done();
  16713. return true;
  16714. });
  16715. });
  16716. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  16717. auto se = detail::scope_exit([&] {
  16718. svr.stop();
  16719. listen_thread.join();
  16720. ASSERT_FALSE(svr.is_running());
  16721. });
  16722. svr.wait_until_ready();
  16723. SSLClient cli(HOST, PORT);
  16724. cli.enable_server_certificate_verification(false);
  16725. auto res = cli.Get("/no-content-length");
  16726. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  16727. EXPECT_EQ(StatusCode::OK_200, res->status);
  16728. EXPECT_EQ(expected_body, res->body);
  16729. }
  16730. #endif // CPPHTTPLIB_SSL_ENABLED
  16731. //==============================================================================
  16732. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  16733. // results for various scenarios.
  16734. //==============================================================================
  16735. TEST(ParityTest, GetVsOpenStream) {
  16736. Server svr;
  16737. const std::string path = "/parity";
  16738. const std::string content = "Parity test content: hello world";
  16739. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16740. res.set_content(content, "text/plain");
  16741. });
  16742. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  16743. auto se = detail::scope_exit([&] {
  16744. svr.stop();
  16745. t.join();
  16746. ASSERT_FALSE(svr.is_running());
  16747. });
  16748. svr.wait_until_ready();
  16749. Client cli(HOST, PORT);
  16750. // Non-stream path
  16751. auto r1 = cli.Get(path);
  16752. ASSERT_TRUE(r1);
  16753. EXPECT_EQ(StatusCode::OK_200, r1->status);
  16754. // Stream path
  16755. auto h = cli.open_stream("GET", path);
  16756. ASSERT_TRUE(h.is_valid());
  16757. EXPECT_EQ(r1->body, read_all(h));
  16758. }
  16759. // Helper to compress data with provided compressor type T
  16760. template <typename Compressor>
  16761. static std::string compress_payload_for_parity(const std::string &in) {
  16762. std::string out;
  16763. Compressor compressor;
  16764. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  16765. [&](const char *data, size_t n) {
  16766. out.append(data, n);
  16767. return true;
  16768. });
  16769. EXPECT_TRUE(ok);
  16770. return out;
  16771. }
  16772. // Helper function for compression parity tests
  16773. template <typename Compressor>
  16774. static void test_compression_parity(const std::string &original,
  16775. const std::string &path,
  16776. const std::string &encoding) {
  16777. const std::string compressed =
  16778. compress_payload_for_parity<Compressor>(original);
  16779. Server svr;
  16780. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  16781. res.set_content(compressed, "application/octet-stream");
  16782. res.set_header("Content-Encoding", encoding);
  16783. });
  16784. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  16785. auto se = detail::scope_exit([&] {
  16786. svr.stop();
  16787. t.join();
  16788. ASSERT_FALSE(svr.is_running());
  16789. });
  16790. svr.wait_until_ready();
  16791. Client cli(HOST, PORT);
  16792. // Non-streaming
  16793. {
  16794. auto res = cli.Get(path);
  16795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16796. EXPECT_EQ(StatusCode::OK_200, res->status);
  16797. EXPECT_EQ(original, res->body);
  16798. }
  16799. // Streaming
  16800. {
  16801. auto h = cli.open_stream("GET", path);
  16802. ASSERT_TRUE(h.is_valid());
  16803. EXPECT_EQ(original, read_all(h));
  16804. }
  16805. }
  16806. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16807. TEST(ParityTest, Gzip) {
  16808. test_compression_parity<detail::gzip_compressor>(
  16809. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  16810. }
  16811. #endif
  16812. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16813. TEST(ParityTest, Brotli) {
  16814. test_compression_parity<detail::brotli_compressor>(
  16815. "Hello, brotli parity test payload", "/parity-br", "br");
  16816. }
  16817. #endif
  16818. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  16819. TEST(ParityTest, Zstd) {
  16820. test_compression_parity<detail::zstd_compressor>(
  16821. "Zstandard parity test payload", "/parity-zstd", "zstd");
  16822. }
  16823. #endif
  16824. //==============================================================================
  16825. // New Stream API Tests
  16826. //==============================================================================
  16827. inline std::string read_body(httplib::stream::Result &result) {
  16828. std::string body;
  16829. while (result.next()) {
  16830. body.append(result.data(), result.size());
  16831. }
  16832. return body;
  16833. }
  16834. TEST(ClientConnectionTest, Basic) {
  16835. httplib::ClientConnection conn;
  16836. EXPECT_FALSE(conn.is_open());
  16837. conn.sock = 1;
  16838. EXPECT_TRUE(conn.is_open());
  16839. httplib::ClientConnection conn2(std::move(conn));
  16840. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  16841. conn2.sock = INVALID_SOCKET;
  16842. }
  16843. // Unified test server for all stream::* tests
  16844. class StreamApiTest : public ::testing::Test {
  16845. protected:
  16846. void SetUp() override {
  16847. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16848. res.set_content("Hello World!", "text/plain");
  16849. });
  16850. svr_.Get("/echo-params",
  16851. [](const httplib::Request &req, httplib::Response &res) {
  16852. std::string r;
  16853. for (const auto &p : req.params) {
  16854. if (!r.empty()) r += "&";
  16855. r += p.first + "=" + p.second;
  16856. }
  16857. res.set_content(r, "text/plain");
  16858. });
  16859. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16860. res.set_content(req.body, req.get_header_value("Content-Type"));
  16861. });
  16862. svr_.Post("/echo-headers",
  16863. [](const httplib::Request &req, httplib::Response &res) {
  16864. std::string r;
  16865. for (const auto &h : req.headers)
  16866. r += h.first + ": " + h.second + "\n";
  16867. res.set_content(r, "text/plain");
  16868. });
  16869. svr_.Post("/echo-params",
  16870. [](const httplib::Request &req, httplib::Response &res) {
  16871. std::string r = "params:";
  16872. for (const auto &p : req.params)
  16873. r += p.first + "=" + p.second + ";";
  16874. res.set_content(r + " body:" + req.body, "text/plain");
  16875. });
  16876. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  16877. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  16878. });
  16879. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  16880. res.set_content("PUT:" + req.body, "text/plain");
  16881. });
  16882. svr_.Patch("/echo",
  16883. [](const httplib::Request &req, httplib::Response &res) {
  16884. res.set_content("PATCH:" + req.body, "text/plain");
  16885. });
  16886. svr_.Delete(
  16887. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  16888. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  16889. "text/plain");
  16890. });
  16891. svr_.Get("/head-test",
  16892. [](const httplib::Request &, httplib::Response &res) {
  16893. res.set_content("body for HEAD", "text/plain");
  16894. });
  16895. svr_.Options("/options",
  16896. [](const httplib::Request &, httplib::Response &res) {
  16897. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  16898. });
  16899. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  16900. svr_.wait_until_ready();
  16901. }
  16902. void TearDown() override {
  16903. svr_.stop();
  16904. if (thread_.joinable()) thread_.join();
  16905. }
  16906. httplib::Server svr_;
  16907. std::thread thread_;
  16908. };
  16909. // stream::Get tests
  16910. TEST_F(StreamApiTest, GetBasic) {
  16911. httplib::Client cli(HOST, PORT);
  16912. auto result = httplib::stream::Get(cli, "/hello");
  16913. ASSERT_TRUE(result.is_valid());
  16914. EXPECT_EQ(200, result.status());
  16915. EXPECT_EQ("Hello World!", read_body(result));
  16916. }
  16917. TEST_F(StreamApiTest, GetWithParams) {
  16918. httplib::Client cli(HOST, PORT);
  16919. httplib::Params params{{"foo", "bar"}};
  16920. auto result = httplib::stream::Get(cli, "/echo-params", params);
  16921. ASSERT_TRUE(result.is_valid());
  16922. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  16923. }
  16924. TEST_F(StreamApiTest, GetConnectionError) {
  16925. httplib::Client cli(HOST, 9999);
  16926. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  16927. }
  16928. TEST_F(StreamApiTest, Get404) {
  16929. httplib::Client cli(HOST, PORT);
  16930. auto result = httplib::stream::Get(cli, "/nonexistent");
  16931. EXPECT_TRUE(result.is_valid());
  16932. EXPECT_EQ(404, result.status());
  16933. }
  16934. // stream::Post tests
  16935. TEST_F(StreamApiTest, PostBasic) {
  16936. httplib::Client cli(HOST, PORT);
  16937. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  16938. "application/json");
  16939. ASSERT_TRUE(result.is_valid());
  16940. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  16941. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  16942. }
  16943. TEST_F(StreamApiTest, PostWithHeaders) {
  16944. httplib::Client cli(HOST, PORT);
  16945. httplib::Headers headers{{"X-Custom", "value"}};
  16946. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  16947. "text/plain");
  16948. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  16949. }
  16950. TEST_F(StreamApiTest, PostWithParams) {
  16951. httplib::Client cli(HOST, PORT);
  16952. httplib::Params params{{"k", "v"}};
  16953. auto result =
  16954. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  16955. auto body = read_body(result);
  16956. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  16957. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  16958. }
  16959. TEST_F(StreamApiTest, PostLarge) {
  16960. httplib::Client cli(HOST, PORT);
  16961. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  16962. size_t total = 0;
  16963. while (result.next()) {
  16964. total += result.size();
  16965. }
  16966. EXPECT_EQ(100u * 1024u, total);
  16967. }
  16968. // stream::Put/Patch tests
  16969. TEST_F(StreamApiTest, PutAndPatch) {
  16970. httplib::Client cli(HOST, PORT);
  16971. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  16972. EXPECT_EQ("PUT:test", read_body(put));
  16973. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  16974. EXPECT_EQ("PATCH:test", read_body(patch));
  16975. }
  16976. // stream::Delete tests
  16977. TEST_F(StreamApiTest, Delete) {
  16978. httplib::Client cli(HOST, PORT);
  16979. auto del1 = httplib::stream::Delete(cli, "/resource");
  16980. EXPECT_EQ("Deleted", read_body(del1));
  16981. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  16982. EXPECT_EQ("Deleted:data", read_body(del2));
  16983. }
  16984. // stream::Head/Options tests
  16985. TEST_F(StreamApiTest, HeadAndOptions) {
  16986. httplib::Client cli(HOST, PORT);
  16987. auto head = httplib::stream::Head(cli, "/head-test");
  16988. EXPECT_TRUE(head.is_valid());
  16989. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  16990. auto opts = httplib::stream::Options(cli, "/options");
  16991. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  16992. }
  16993. // SSL stream::* tests
  16994. #ifdef CPPHTTPLIB_SSL_ENABLED
  16995. class SSLStreamApiTest : public ::testing::Test {
  16996. protected:
  16997. void SetUp() override {
  16998. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  16999. res.set_content("Hello SSL!", "text/plain");
  17000. });
  17001. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17002. res.set_content(req.body, "text/plain");
  17003. });
  17004. port_ = svr_.bind_to_any_port("127.0.0.1");
  17005. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17006. svr_.wait_until_ready();
  17007. }
  17008. void TearDown() override {
  17009. svr_.stop();
  17010. if (thread_.joinable()) thread_.join();
  17011. }
  17012. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17013. std::thread thread_;
  17014. int port_ = 0;
  17015. };
  17016. TEST_F(SSLStreamApiTest, GetAndPost) {
  17017. httplib::SSLClient cli("127.0.0.1", port_);
  17018. cli.enable_server_certificate_verification(false);
  17019. auto get = httplib::stream::Get(cli, "/hello");
  17020. EXPECT_EQ("Hello SSL!", read_body(get));
  17021. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17022. EXPECT_EQ("test", read_body(post));
  17023. }
  17024. #endif
  17025. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17026. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17027. // BodyReader
  17028. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17029. // Test that read timeout during streaming is detected
  17030. // Use a large content-length response where server delays mid-stream
  17031. Server svr;
  17032. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17033. // Send a large response with delay in the middle
  17034. res.set_content_provider(
  17035. 1000, // content_length
  17036. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17037. if (offset < 100) {
  17038. // Send first 100 bytes immediately
  17039. std::string data(100, 'A');
  17040. sink.write(data.c_str(), data.size());
  17041. return true;
  17042. }
  17043. // Then delay longer than client timeout
  17044. std::this_thread::sleep_for(std::chrono::seconds(3));
  17045. std::string data(900, 'B');
  17046. sink.write(data.c_str(), data.size());
  17047. return true;
  17048. });
  17049. });
  17050. auto port = 8091;
  17051. std::thread t([&]() { svr.listen("localhost", port); });
  17052. svr.wait_until_ready();
  17053. Client cli("localhost", port);
  17054. cli.set_read_timeout(1, 0); // 1 second timeout
  17055. auto handle = cli.open_stream("GET", "/slow-stream");
  17056. ASSERT_TRUE(handle.is_valid());
  17057. char buf[256];
  17058. ssize_t total = 0;
  17059. ssize_t n;
  17060. bool got_error = false;
  17061. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17062. total += n;
  17063. }
  17064. if (n < 0) {
  17065. got_error = true;
  17066. // Should be timeout or read error
  17067. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17068. handle.get_read_error() == Error::Read)
  17069. << "Actual error: " << to_string(handle.get_read_error());
  17070. }
  17071. // Either we got an error, or we got less data than expected
  17072. EXPECT_TRUE(got_error || total < 1000)
  17073. << "Expected timeout but got all " << total << " bytes";
  17074. svr.stop();
  17075. t.join();
  17076. }
  17077. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17078. // Test connection closed detection via BodyReader
  17079. Server svr;
  17080. std::atomic<bool> close_now{false};
  17081. svr.Get("/will-close", [&](const Request &, Response &res) {
  17082. res.set_content_provider(
  17083. 10000, // Large content_length that we won't fully send
  17084. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17085. if (offset < 100) {
  17086. std::string data(100, 'X');
  17087. sink.write(data.c_str(), data.size());
  17088. return true;
  17089. }
  17090. // Wait for signal then abort
  17091. while (!close_now) {
  17092. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17093. }
  17094. return false; // Abort - server will close connection
  17095. });
  17096. });
  17097. auto port = 8092;
  17098. std::thread t([&]() { svr.listen("localhost", port); });
  17099. svr.wait_until_ready();
  17100. Client cli("localhost", port);
  17101. auto handle = cli.open_stream("GET", "/will-close");
  17102. ASSERT_TRUE(handle.is_valid());
  17103. char buf[256];
  17104. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17105. EXPECT_GT(n, 0) << "First read should succeed";
  17106. // Signal server to close
  17107. close_now = true;
  17108. // Keep reading until error or EOF
  17109. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17110. // Keep reading
  17111. }
  17112. // Should get an error since content_length wasn't satisfied
  17113. if (n < 0) {
  17114. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17115. handle.get_read_error() == Error::Read)
  17116. << "Actual error: " << to_string(handle.get_read_error());
  17117. }
  17118. svr.stop();
  17119. t.join();
  17120. }
  17121. #ifdef CPPHTTPLIB_SSL_ENABLED
  17122. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17123. // Test that read timeout during SSL streaming is detected
  17124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17125. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17126. res.set_content_provider(
  17127. 1000, "text/plain",
  17128. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17129. if (offset < 100) {
  17130. std::string data(100, 'A');
  17131. sink.write(data.c_str(), data.size());
  17132. return true;
  17133. }
  17134. std::this_thread::sleep_for(std::chrono::seconds(3));
  17135. std::string data(900, 'B');
  17136. sink.write(data.c_str(), data.size());
  17137. return true;
  17138. });
  17139. });
  17140. auto port = 8093;
  17141. std::thread t([&]() { svr.listen("localhost", port); });
  17142. svr.wait_until_ready();
  17143. SSLClient cli("localhost", port);
  17144. cli.enable_server_certificate_verification(false);
  17145. cli.set_read_timeout(1, 0); // 1 second timeout
  17146. auto handle = cli.open_stream("GET", "/slow-stream");
  17147. ASSERT_TRUE(handle.is_valid());
  17148. char buf[256];
  17149. ssize_t total = 0;
  17150. ssize_t n;
  17151. bool got_error = false;
  17152. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17153. total += n;
  17154. }
  17155. if (n < 0) {
  17156. got_error = true;
  17157. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17158. handle.get_read_error() == Error::Read)
  17159. << "Actual error: " << to_string(handle.get_read_error());
  17160. }
  17161. EXPECT_TRUE(got_error || total < 1000)
  17162. << "Expected timeout but got all " << total << " bytes";
  17163. svr.stop();
  17164. t.join();
  17165. }
  17166. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17167. // Test SSL connection closed detection
  17168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17169. std::atomic<bool> close_now{false};
  17170. svr.Get("/will-close", [&](const Request &, Response &res) {
  17171. res.set_content_provider(
  17172. 10000, "text/plain",
  17173. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17174. if (offset < 100) {
  17175. std::string data(100, 'X');
  17176. sink.write(data.c_str(), data.size());
  17177. return true;
  17178. }
  17179. while (!close_now) {
  17180. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17181. }
  17182. return false;
  17183. });
  17184. });
  17185. auto port = 8094;
  17186. std::thread t([&]() { svr.listen("localhost", port); });
  17187. svr.wait_until_ready();
  17188. SSLClient cli("localhost", port);
  17189. cli.enable_server_certificate_verification(false);
  17190. auto handle = cli.open_stream("GET", "/will-close");
  17191. ASSERT_TRUE(handle.is_valid());
  17192. char buf[256];
  17193. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17194. EXPECT_GT(n, 0);
  17195. // Signal server to close
  17196. close_now = true;
  17197. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17198. // Keep reading
  17199. }
  17200. if (n < 0) {
  17201. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17202. handle.get_read_error() == Error::Read)
  17203. << "Actual error: " << to_string(handle.get_read_error());
  17204. }
  17205. svr.stop();
  17206. t.join();
  17207. }
  17208. #endif
  17209. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17210. using namespace httplib;
  17211. // Create a test file
  17212. const char *fname = "etag_testfile.txt";
  17213. const char *content = "etag-content";
  17214. {
  17215. std::ofstream ofs(fname);
  17216. ofs << content;
  17217. ASSERT_TRUE(ofs.good());
  17218. }
  17219. Server svr;
  17220. svr.set_mount_point("/static", ".");
  17221. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17222. svr.wait_until_ready();
  17223. Client cli(HOST, PORT);
  17224. // First request: should get 200 with ETag header
  17225. auto res1 = cli.Get("/static/etag_testfile.txt");
  17226. ASSERT_TRUE(res1);
  17227. ASSERT_EQ(200, res1->status);
  17228. ASSERT_TRUE(res1->has_header("ETag"));
  17229. std::string etag = res1->get_header_value("ETag");
  17230. EXPECT_FALSE(etag.empty());
  17231. // Verify ETag format: W/"hex-hex"
  17232. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17233. EXPECT_EQ('W', etag[0]);
  17234. EXPECT_EQ('/', etag[1]);
  17235. EXPECT_EQ('"', etag[2]);
  17236. EXPECT_EQ('"', etag.back());
  17237. // Exact match: expect 304 Not Modified
  17238. Headers h2 = {{"If-None-Match", etag}};
  17239. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17240. ASSERT_TRUE(res2);
  17241. EXPECT_EQ(304, res2->status);
  17242. // Wildcard match: expect 304 Not Modified
  17243. Headers h3 = {{"If-None-Match", "*"}};
  17244. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17245. ASSERT_TRUE(res3);
  17246. EXPECT_EQ(304, res3->status);
  17247. // Non-matching ETag: expect 200
  17248. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17249. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17250. ASSERT_TRUE(res4);
  17251. EXPECT_EQ(200, res4->status);
  17252. // Multiple ETags with one matching: expect 304
  17253. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17254. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17255. ASSERT_TRUE(res5);
  17256. EXPECT_EQ(304, res5->status);
  17257. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17258. // that equivalent to the single comma-separated list above, so the match on
  17259. // the second line must still be found.
  17260. Headers h6;
  17261. h6.emplace("If-None-Match", "W/\"other\"");
  17262. h6.emplace("If-None-Match", etag);
  17263. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17264. ASSERT_TRUE(res6);
  17265. EXPECT_EQ(304, res6->status);
  17266. svr.stop();
  17267. t.join();
  17268. std::remove(fname);
  17269. }
  17270. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17271. using namespace httplib;
  17272. Server svr;
  17273. svr.set_mount_point("/static", ".");
  17274. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17275. svr.wait_until_ready();
  17276. Client cli(HOST, PORT);
  17277. // Send If-None-Match: * to a non-existent file
  17278. Headers h = {{"If-None-Match", "*"}};
  17279. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17281. EXPECT_EQ(404, res->status);
  17282. svr.stop();
  17283. t.join();
  17284. }
  17285. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17286. using namespace httplib;
  17287. // Create a test file
  17288. const char *fname = "etag_boundary_testfile.txt";
  17289. const char *content = "boundary-test";
  17290. {
  17291. std::ofstream ofs(fname);
  17292. ofs << content;
  17293. ASSERT_TRUE(ofs.good());
  17294. }
  17295. Server svr;
  17296. svr.set_mount_point("/static", ".");
  17297. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17298. svr.wait_until_ready();
  17299. Client cli(HOST, PORT);
  17300. // Get the actual ETag
  17301. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17302. ASSERT_TRUE(res1);
  17303. ASSERT_EQ(200, res1->status);
  17304. ASSERT_TRUE(res1->has_header("ETag"));
  17305. std::string etag = res1->get_header_value("ETag");
  17306. // Test 1: Very long ETag value (longer than actual ETag)
  17307. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17308. Headers h1 = {{"If-None-Match", "W/"
  17309. "\"very-long-etag-value-that-is-much-longer-"
  17310. "than-the-actual-etag-value\""}};
  17311. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17312. ASSERT_TRUE(res2);
  17313. EXPECT_EQ(200, res2->status); // Should not match
  17314. // Test 2: Long string followed by wildcard
  17315. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17316. // string)
  17317. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17318. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17319. ASSERT_TRUE(res3);
  17320. EXPECT_EQ(304, res3->status); // Should match on "*"
  17321. // Test 3: Wildcard followed by long string
  17322. // Should match on "*" immediately and return 304
  17323. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17324. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17325. ASSERT_TRUE(res4);
  17326. EXPECT_EQ(304, res4->status); // Should match on "*"
  17327. // Test 4: Multiple long non-matching values
  17328. // Should NOT match and return 200 (test that all comparisons are safe)
  17329. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17330. "W/\"second-long-non-matching-value\", "
  17331. "W/\"third-long-non-matching-value\""}};
  17332. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17333. ASSERT_TRUE(res5);
  17334. EXPECT_EQ(200, res5->status); // Should not match
  17335. // Test 5: Single character that is not "*" (edge case)
  17336. Headers h5 = {{"If-None-Match", "X"}};
  17337. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17338. ASSERT_TRUE(res6);
  17339. EXPECT_EQ(200, res6->status); // Should not match
  17340. svr.stop();
  17341. t.join();
  17342. std::remove(fname);
  17343. }
  17344. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17345. using namespace httplib;
  17346. // Create a test file
  17347. const char *fname = "ims_testfile.txt";
  17348. const char *content = "if-modified-since-test";
  17349. {
  17350. std::ofstream ofs(fname);
  17351. ofs << content;
  17352. ASSERT_TRUE(ofs.good());
  17353. }
  17354. Server svr;
  17355. svr.set_mount_point("/static", ".");
  17356. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17357. svr.wait_until_ready();
  17358. Client cli(HOST, PORT);
  17359. // First request: should get 200 with Last-Modified header
  17360. auto res1 = cli.Get("/static/ims_testfile.txt");
  17361. ASSERT_TRUE(res1);
  17362. ASSERT_EQ(200, res1->status);
  17363. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17364. std::string last_modified = res1->get_header_value("Last-Modified");
  17365. EXPECT_FALSE(last_modified.empty());
  17366. // If-Modified-Since with same time: expect 304
  17367. Headers h2 = {{"If-Modified-Since", last_modified}};
  17368. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  17369. ASSERT_TRUE(res2);
  17370. EXPECT_EQ(304, res2->status);
  17371. // If-Modified-Since with future time: expect 304
  17372. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17373. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  17374. ASSERT_TRUE(res3);
  17375. EXPECT_EQ(304, res3->status);
  17376. // If-Modified-Since with past time: expect 200
  17377. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17378. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  17379. ASSERT_TRUE(res4);
  17380. EXPECT_EQ(200, res4->status);
  17381. // If-None-Match takes precedence over If-Modified-Since
  17382. // (send matching ETag with old If-Modified-Since -> should still be 304)
  17383. ASSERT_TRUE(res1->has_header("ETag"));
  17384. std::string etag = res1->get_header_value("ETag");
  17385. Headers h5 = {{"If-None-Match", etag},
  17386. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17387. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  17388. ASSERT_TRUE(res5);
  17389. EXPECT_EQ(304, res5->status);
  17390. svr.stop();
  17391. t.join();
  17392. std::remove(fname);
  17393. }
  17394. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  17395. using namespace httplib;
  17396. Server svr;
  17397. // Endpoint that returns compressible content
  17398. svr.Get("/compressible", [](const Request &, Response &res) {
  17399. // Return a large enough body to trigger compression
  17400. std::string body(1000, 'a');
  17401. res.set_content(body, "text/plain");
  17402. });
  17403. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17404. svr.wait_until_ready();
  17405. Client cli(HOST, PORT);
  17406. // Request with gzip support: should get Vary header when compressed
  17407. cli.set_compress(true);
  17408. auto res1 = cli.Get("/compressible");
  17409. ASSERT_TRUE(res1);
  17410. EXPECT_EQ(200, res1->status);
  17411. // If Content-Encoding is set, Vary should also be set
  17412. if (res1->has_header("Content-Encoding")) {
  17413. EXPECT_TRUE(res1->has_header("Vary"));
  17414. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  17415. }
  17416. // Request without Accept-Encoding header: should not have compression
  17417. Headers h_no_compress;
  17418. auto res2 = cli.Get("/compressible", h_no_compress);
  17419. ASSERT_TRUE(res2);
  17420. EXPECT_EQ(200, res2->status);
  17421. // Verify Vary header is present when compression is applied
  17422. // (the exact behavior depends on server configuration)
  17423. svr.stop();
  17424. t.join();
  17425. }
  17426. TEST(ETagTest, IfRangeWithETag) {
  17427. using namespace httplib;
  17428. // Create a test file with known content
  17429. const char *fname = "if_range_testfile.txt";
  17430. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  17431. {
  17432. std::ofstream ofs(fname);
  17433. ofs << content;
  17434. ASSERT_TRUE(ofs.good());
  17435. }
  17436. Server svr;
  17437. svr.set_mount_point("/static", ".");
  17438. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17439. svr.wait_until_ready();
  17440. Client cli(HOST, PORT);
  17441. // First request: get ETag
  17442. auto res1 = cli.Get("/static/if_range_testfile.txt");
  17443. ASSERT_TRUE(res1);
  17444. ASSERT_EQ(200, res1->status);
  17445. ASSERT_TRUE(res1->has_header("ETag"));
  17446. std::string etag = res1->get_header_value("ETag");
  17447. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  17448. // Since our server generates weak ETags (W/"..."), If-Range with our
  17449. // ETag should NOT result in partial content - it should return full content.
  17450. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  17451. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  17452. ASSERT_TRUE(res2);
  17453. // Weak ETag in If-Range -> full content (200), not partial (206)
  17454. EXPECT_EQ(200, res2->status);
  17455. EXPECT_EQ(content, res2->body);
  17456. EXPECT_FALSE(res2->has_header("Content-Range"));
  17457. // Range request with non-matching If-Range (ETag): should get 200 (full
  17458. // content)
  17459. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  17460. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  17461. ASSERT_TRUE(res3);
  17462. EXPECT_EQ(200, res3->status);
  17463. EXPECT_EQ(content, res3->body);
  17464. EXPECT_FALSE(res3->has_header("Content-Range"));
  17465. // Range request with strong ETag (hypothetical - our server doesn't generate
  17466. // strong ETags, but if client sends a strong ETag that doesn't match, it
  17467. // should return full content)
  17468. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  17469. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  17470. ASSERT_TRUE(res4);
  17471. EXPECT_EQ(200, res4->status);
  17472. EXPECT_EQ(content, res4->body);
  17473. EXPECT_FALSE(res4->has_header("Content-Range"));
  17474. svr.stop();
  17475. t.join();
  17476. std::remove(fname);
  17477. }
  17478. TEST(ETagTest, IfRangeWithDate) {
  17479. using namespace httplib;
  17480. // Create a test file
  17481. const char *fname = "if_range_date_testfile.txt";
  17482. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  17483. {
  17484. std::ofstream ofs(fname);
  17485. ofs << content;
  17486. ASSERT_TRUE(ofs.good());
  17487. }
  17488. Server svr;
  17489. svr.set_mount_point("/static", ".");
  17490. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17491. svr.wait_until_ready();
  17492. Client cli(HOST, PORT);
  17493. // First request: get Last-Modified
  17494. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  17495. ASSERT_TRUE(res1);
  17496. ASSERT_EQ(200, res1->status);
  17497. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17498. std::string last_modified = res1->get_header_value("Last-Modified");
  17499. // Range request with matching If-Range (date): should get 206
  17500. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  17501. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  17502. ASSERT_TRUE(res2);
  17503. EXPECT_EQ(206, res2->status);
  17504. EXPECT_EQ("FGHIJ", res2->body);
  17505. // Range request with old If-Range date: should get 200 (full content)
  17506. Headers h3 = {{"Range", "bytes=5-9"},
  17507. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  17508. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  17509. ASSERT_TRUE(res3);
  17510. EXPECT_EQ(200, res3->status);
  17511. EXPECT_EQ(content, res3->body);
  17512. // Range request with future If-Range date: should get 206
  17513. Headers h4 = {{"Range", "bytes=0-4"},
  17514. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  17515. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  17516. ASSERT_TRUE(res4);
  17517. EXPECT_EQ(206, res4->status);
  17518. EXPECT_EQ("ABCDE", res4->body);
  17519. svr.stop();
  17520. t.join();
  17521. std::remove(fname);
  17522. }
  17523. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  17524. using namespace httplib;
  17525. const char *fname = "etag_malformed.txt";
  17526. const char *content = "malformed-etag";
  17527. {
  17528. std::ofstream ofs(fname);
  17529. ofs << content;
  17530. ASSERT_TRUE(ofs.good());
  17531. }
  17532. Server svr;
  17533. svr.set_mount_point("/static", ".");
  17534. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17535. svr.wait_until_ready();
  17536. Client cli(HOST, PORT);
  17537. // baseline: should get 200 and an ETag
  17538. auto res1 = cli.Get("/static/etag_malformed.txt");
  17539. ASSERT_TRUE(res1);
  17540. ASSERT_EQ(200, res1->status);
  17541. ASSERT_TRUE(res1->has_header("ETag"));
  17542. // Malformed ETag value (missing quotes) should be treated as non-matching
  17543. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  17544. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  17545. ASSERT_TRUE(res_bad);
  17546. EXPECT_EQ(200, res_bad->status);
  17547. // Whitespace-only header value should be considered invalid / non-matching
  17548. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  17549. "Host: localhost\r\n"
  17550. "If-None-Match: \r\n"
  17551. "Connection: close\r\n"
  17552. "\r\n";
  17553. std::string out;
  17554. ASSERT_TRUE(send_request(5, raw_req, &out));
  17555. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17556. svr.stop();
  17557. t.join();
  17558. std::remove(fname);
  17559. }
  17560. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  17561. using namespace httplib;
  17562. const char *fname = "ims_invalid_format.txt";
  17563. const char *content = "ims-bad-format";
  17564. {
  17565. std::ofstream ofs(fname);
  17566. ofs << content;
  17567. ASSERT_TRUE(ofs.good());
  17568. }
  17569. Server svr;
  17570. svr.set_mount_point("/static", ".");
  17571. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17572. svr.wait_until_ready();
  17573. Client cli(HOST, PORT);
  17574. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  17575. ASSERT_TRUE(res1);
  17576. ASSERT_EQ(200, res1->status);
  17577. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17578. // If-Modified-Since with invalid format should not result in 304
  17579. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  17580. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  17581. ASSERT_TRUE(res_bad);
  17582. EXPECT_EQ(200, res_bad->status);
  17583. // If-Range with invalid date format should be treated as mismatch -> full
  17584. // content (200)
  17585. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  17586. {"If-Range", "invalid-date"}};
  17587. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  17588. ASSERT_TRUE(res_ifrange);
  17589. EXPECT_EQ(200, res_ifrange->status);
  17590. svr.stop();
  17591. t.join();
  17592. std::remove(fname);
  17593. }
  17594. TEST(ETagTest, IfRangeWithMalformedETag) {
  17595. using namespace httplib;
  17596. const char *fname = "ifrange_malformed.txt";
  17597. const std::string content = "0123456789";
  17598. {
  17599. std::ofstream ofs(fname);
  17600. ofs << content;
  17601. ASSERT_TRUE(ofs.good());
  17602. }
  17603. Server svr;
  17604. svr.set_mount_point("/static", ".");
  17605. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17606. svr.wait_until_ready();
  17607. Client cli(HOST, PORT);
  17608. // First request: get ETag
  17609. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  17610. ASSERT_TRUE(res1);
  17611. ASSERT_EQ(200, res1->status);
  17612. ASSERT_TRUE(res1->has_header("ETag"));
  17613. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  17614. // full content (200)
  17615. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  17616. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  17617. ASSERT_TRUE(res2);
  17618. EXPECT_EQ(200, res2->status);
  17619. EXPECT_EQ(content, res2->body);
  17620. svr.stop();
  17621. t.join();
  17622. std::remove(fname);
  17623. }
  17624. TEST(ETagTest, ExtremeLargeDateValues) {
  17625. using namespace httplib;
  17626. const char *fname = "ims_extreme_date.txt";
  17627. const char *content = "ims-extreme-date";
  17628. {
  17629. std::ofstream ofs(fname);
  17630. ofs << content;
  17631. ASSERT_TRUE(ofs.good());
  17632. }
  17633. Server svr;
  17634. svr.set_mount_point("/static", ".");
  17635. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17636. svr.wait_until_ready();
  17637. Client cli(HOST, PORT);
  17638. auto res1 = cli.Get(std::string("/static/") + fname);
  17639. ASSERT_TRUE(res1);
  17640. ASSERT_EQ(200, res1->status);
  17641. ASSERT_TRUE(res1->has_header("Last-Modified"));
  17642. // Extremely large year that may overflow date parsing routines.
  17643. Headers h_large_date = {
  17644. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17645. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  17646. ASSERT_TRUE(res_bad);
  17647. // Expect server to treat this as invalid/mismatch and return full content
  17648. EXPECT_EQ(200, res_bad->status);
  17649. // If-Range with extremely large date should be treated as mismatch -> full
  17650. // content (200)
  17651. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  17652. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17653. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  17654. ASSERT_TRUE(res_ifrange);
  17655. EXPECT_EQ(200, res_ifrange->status);
  17656. svr.stop();
  17657. t.join();
  17658. std::remove(fname);
  17659. }
  17660. TEST(ETagTest, NegativeFileModificationTime) {
  17661. using namespace httplib;
  17662. const char *fname = "ims_negative_mtime.txt";
  17663. const std::string content = "negative-mtime";
  17664. {
  17665. std::ofstream ofs(fname);
  17666. ofs << content;
  17667. ASSERT_TRUE(ofs.good());
  17668. }
  17669. // Try to set file mtime to a negative value. This may fail on some
  17670. // platforms/filesystems; if it fails, the test will still verify server
  17671. // behaves safely by performing a regular conditional request.
  17672. #if defined(__APPLE__) || defined(__linux__)
  17673. bool set_negative = false;
  17674. do {
  17675. struct timeval times[2];
  17676. // access time: now
  17677. times[0].tv_sec = time(nullptr);
  17678. times[0].tv_usec = 0;
  17679. // modification time: negative (e.g., -1)
  17680. times[1].tv_sec = -1;
  17681. times[1].tv_usec = 0;
  17682. if (utimes(fname, times) == 0) { set_negative = true; }
  17683. } while (0);
  17684. #else
  17685. bool set_negative = false;
  17686. #endif
  17687. Server svr;
  17688. svr.set_mount_point("/static", ".");
  17689. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17690. svr.wait_until_ready();
  17691. Client cli(HOST, PORT);
  17692. auto res1 = cli.Get(std::string("/static/") + fname);
  17693. ASSERT_TRUE(res1);
  17694. ASSERT_EQ(200, res1->status);
  17695. bool has_last_modified = res1->has_header("Last-Modified");
  17696. std::string last_modified;
  17697. if (has_last_modified) {
  17698. last_modified = res1->get_header_value("Last-Modified");
  17699. }
  17700. if (set_negative) {
  17701. // If we successfully set a negative mtime, ensure server returns a
  17702. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  17703. // with an old date and ensure server handles it without crash.
  17704. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  17705. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  17706. ASSERT_TRUE(res2);
  17707. // Behavior may vary; at minimum ensure server responds (200 or 304).
  17708. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  17709. } else {
  17710. // Could not set negative mtime on this platform; fall back to verifying
  17711. // that normal invalid/malformed dates are treated safely (non-304).
  17712. Headers h_bad_date = {
  17713. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  17714. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  17715. ASSERT_TRUE(res_bad);
  17716. EXPECT_EQ(200, res_bad->status);
  17717. }
  17718. svr.stop();
  17719. t.join();
  17720. std::remove(fname);
  17721. }
  17722. //==============================================================================
  17723. // SSE Parsing Tests
  17724. //==============================================================================
  17725. class SSEParsingTest : public ::testing::Test {
  17726. protected:
  17727. // Test helper that mimics SSE parsing behavior
  17728. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  17729. int &retry_ms) {
  17730. // Blank line signals end of event
  17731. if (line.empty() || line == "\r") { return true; }
  17732. // Lines starting with ':' are comments (ignored)
  17733. if (!line.empty() && line[0] == ':') { return false; }
  17734. // Find the colon separator
  17735. auto colon_pos = line.find(':');
  17736. if (colon_pos == std::string::npos) {
  17737. // Line with no colon is treated as field name with empty value
  17738. return false;
  17739. }
  17740. std::string field = line.substr(0, colon_pos);
  17741. std::string value;
  17742. // Value starts after colon, skip optional single space
  17743. if (colon_pos + 1 < line.size()) {
  17744. size_t value_start = colon_pos + 1;
  17745. if (line[value_start] == ' ') { value_start++; }
  17746. value = line.substr(value_start);
  17747. // Remove trailing \r if present
  17748. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  17749. }
  17750. // Handle known fields
  17751. if (field == "event") {
  17752. msg.event = value;
  17753. } else if (field == "data") {
  17754. // Multiple data lines are concatenated with newlines
  17755. if (!msg.data.empty()) { msg.data += "\n"; }
  17756. msg.data += value;
  17757. } else if (field == "id") {
  17758. // Empty id is valid (clears the last event ID)
  17759. msg.id = value;
  17760. } else if (field == "retry") {
  17761. // Parse retry interval in milliseconds
  17762. {
  17763. int v = 0;
  17764. auto res =
  17765. detail::from_chars(value.data(), value.data() + value.size(), v);
  17766. if (res.ec == std::errc{}) { retry_ms = v; }
  17767. }
  17768. }
  17769. // Unknown fields are ignored per SSE spec
  17770. return false;
  17771. }
  17772. };
  17773. // Test: Single-line data
  17774. TEST_F(SSEParsingTest, SingleLineData) {
  17775. sse::SSEMessage msg;
  17776. int retry_ms = 3000;
  17777. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  17778. EXPECT_EQ(msg.data, "hello");
  17779. EXPECT_EQ(msg.event, "message");
  17780. // Blank line ends event
  17781. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17782. }
  17783. // Test: Multi-line data
  17784. TEST_F(SSEParsingTest, MultiLineData) {
  17785. sse::SSEMessage msg;
  17786. int retry_ms = 3000;
  17787. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  17788. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  17789. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  17790. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  17791. }
  17792. // Test: Custom event types
  17793. TEST_F(SSEParsingTest, CustomEventType) {
  17794. sse::SSEMessage msg;
  17795. int retry_ms = 3000;
  17796. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  17797. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  17798. EXPECT_EQ(msg.event, "update");
  17799. EXPECT_EQ(msg.data, "payload");
  17800. }
  17801. // Test: Event ID handling
  17802. TEST_F(SSEParsingTest, EventIdHandling) {
  17803. sse::SSEMessage msg;
  17804. int retry_ms = 3000;
  17805. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  17806. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  17807. EXPECT_EQ(msg.id, "12345");
  17808. }
  17809. // Test: Empty event ID (clears last event ID)
  17810. TEST_F(SSEParsingTest, EmptyEventId) {
  17811. sse::SSEMessage msg;
  17812. msg.id = "previous";
  17813. int retry_ms = 3000;
  17814. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  17815. EXPECT_EQ(msg.id, "");
  17816. }
  17817. // Test: Retry field parsing
  17818. TEST_F(SSEParsingTest, RetryFieldParsing) {
  17819. sse::SSEMessage msg;
  17820. int retry_ms = 3000;
  17821. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  17822. EXPECT_EQ(retry_ms, 5000);
  17823. }
  17824. // Test: Invalid retry value
  17825. TEST_F(SSEParsingTest, InvalidRetryValue) {
  17826. sse::SSEMessage msg;
  17827. int retry_ms = 3000;
  17828. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  17829. EXPECT_EQ(retry_ms, 3000); // Unchanged
  17830. }
  17831. // Test: Comments (lines starting with :)
  17832. TEST_F(SSEParsingTest, CommentsIgnored) {
  17833. sse::SSEMessage msg;
  17834. int retry_ms = 3000;
  17835. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  17836. EXPECT_EQ(msg.data, "");
  17837. EXPECT_EQ(msg.event, "message");
  17838. }
  17839. // Test: Colon in value
  17840. TEST_F(SSEParsingTest, ColonInValue) {
  17841. sse::SSEMessage msg;
  17842. int retry_ms = 3000;
  17843. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  17844. EXPECT_EQ(msg.data, "hello:world:test");
  17845. }
  17846. // Test: Line with no colon (field name only)
  17847. TEST_F(SSEParsingTest, FieldNameOnly) {
  17848. sse::SSEMessage msg;
  17849. int retry_ms = 3000;
  17850. // According to SSE spec, this is treated as field name with empty value
  17851. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  17852. // Since we don't recognize "data" without colon, data should be empty
  17853. EXPECT_EQ(msg.data, "");
  17854. }
  17855. // Test: Trailing \r handling
  17856. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  17857. sse::SSEMessage msg;
  17858. int retry_ms = 3000;
  17859. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  17860. EXPECT_EQ(msg.data, "hello");
  17861. }
  17862. // Test: Unknown fields ignored
  17863. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  17864. sse::SSEMessage msg;
  17865. int retry_ms = 3000;
  17866. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  17867. EXPECT_EQ(msg.data, "");
  17868. EXPECT_EQ(msg.event, "message");
  17869. }
  17870. // Test: Space after colon is optional
  17871. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  17872. sse::SSEMessage msg1, msg2;
  17873. int retry_ms = 3000;
  17874. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  17875. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  17876. EXPECT_EQ(msg1.data, "hello");
  17877. EXPECT_EQ(msg2.data, "hello");
  17878. }
  17879. // Test: SSEMessage clear
  17880. TEST_F(SSEParsingTest, MessageClear) {
  17881. sse::SSEMessage msg;
  17882. msg.event = "custom";
  17883. msg.data = "some data";
  17884. msg.id = "123";
  17885. msg.clear();
  17886. EXPECT_EQ(msg.event, "message");
  17887. EXPECT_EQ(msg.data, "");
  17888. EXPECT_EQ(msg.id, "");
  17889. }
  17890. // Test: Complete event parsing
  17891. TEST_F(SSEParsingTest, CompleteEventParsing) {
  17892. sse::SSEMessage msg;
  17893. int retry_ms = 3000;
  17894. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  17895. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  17896. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  17897. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  17898. // Blank line ends event
  17899. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  17900. EXPECT_EQ(msg.event, "notification");
  17901. EXPECT_EQ(msg.id, "evt-42");
  17902. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  17903. EXPECT_EQ(retry_ms, 1000);
  17904. }
  17905. //==============================================================================
  17906. // Integration Tests with Server
  17907. //==============================================================================
  17908. class SSEIntegrationTest : public ::testing::Test {
  17909. protected:
  17910. void SetUp() override {
  17911. stop_server_.store(false);
  17912. events_.clear();
  17913. server_ = httplib::detail::make_unique<Server>();
  17914. setup_server();
  17915. start_server();
  17916. }
  17917. void TearDown() override {
  17918. stop_server_.store(true);
  17919. event_cv_.notify_all();
  17920. server_->stop();
  17921. if (server_thread_.joinable()) { server_thread_.join(); }
  17922. }
  17923. void setup_server() {
  17924. // Simple SSE endpoint
  17925. server_->Get("/events", [this](const Request &req, Response &res) {
  17926. auto last_id = req.get_header_value("Last-Event-ID");
  17927. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  17928. res.set_chunked_content_provider(
  17929. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  17930. std::unique_lock<std::mutex> lock(event_mutex_);
  17931. if (event_cv_.wait_for(
  17932. lock, std::chrono::milliseconds(200), [this] {
  17933. return !events_.empty() || stop_server_.load();
  17934. })) {
  17935. if (stop_server_.load()) { return false; }
  17936. if (!events_.empty()) {
  17937. std::string event = events_.front();
  17938. events_.erase(events_.begin());
  17939. sink.write(event.data(), event.size());
  17940. return true;
  17941. }
  17942. }
  17943. return !stop_server_.load();
  17944. });
  17945. });
  17946. // Endpoint that returns error
  17947. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  17948. res.status = 500;
  17949. res.set_content("Internal Server Error", "text/plain");
  17950. });
  17951. // Endpoint for custom event types
  17952. server_->Get("/custom-events", [](const Request &, Response &res) {
  17953. res.set_chunked_content_provider(
  17954. "text/event-stream", [](size_t offset, DataSink &sink) {
  17955. if (offset == 0) {
  17956. std::string event = "event: update\ndata: updated\n\n"
  17957. "event: delete\ndata: deleted\n\n";
  17958. sink.write(event.data(), event.size());
  17959. }
  17960. return false; // End stream after sending
  17961. });
  17962. });
  17963. }
  17964. void start_server() {
  17965. port_ = server_->bind_to_any_port(HOST);
  17966. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17967. // Wait for server to start
  17968. while (!server_->is_running()) {
  17969. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17970. }
  17971. }
  17972. int get_port() const { return port_; }
  17973. void send_event(const std::string &event) {
  17974. std::lock_guard<std::mutex> lock(event_mutex_);
  17975. events_.push_back(event);
  17976. event_cv_.notify_all();
  17977. }
  17978. std::unique_ptr<Server> server_;
  17979. std::thread server_thread_;
  17980. std::mutex event_mutex_;
  17981. std::condition_variable event_cv_;
  17982. std::vector<std::string> events_;
  17983. std::atomic<bool> stop_server_{false};
  17984. std::string last_received_event_id_;
  17985. int port_ = 0;
  17986. };
  17987. // Test: Successful connection and on_open callback
  17988. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  17989. // Add a simple endpoint that sends one event and closes
  17990. server_->Get("/simple-event", [](const Request &, Response &res) {
  17991. res.set_chunked_content_provider(
  17992. "text/event-stream", [](size_t offset, DataSink &sink) {
  17993. if (offset == 0) {
  17994. std::string event = "data: hello\n\n";
  17995. sink.write(event.data(), event.size());
  17996. }
  17997. return false; // Close stream after sending
  17998. });
  17999. });
  18000. Client client("localhost", get_port());
  18001. sse::SSEClient sse(client, "/simple-event");
  18002. std::atomic<bool> open_called{false};
  18003. std::atomic<bool> message_received{false};
  18004. sse.on_open([&open_called]() { open_called.store(true); });
  18005. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18006. if (msg.data == "hello") { message_received.store(true); }
  18007. });
  18008. sse.set_reconnect_interval(100);
  18009. sse.set_max_reconnect_attempts(1);
  18010. // Start async
  18011. sse.start_async();
  18012. // Wait for message to be processed
  18013. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18014. sse.stop();
  18015. EXPECT_TRUE(open_called.load());
  18016. EXPECT_TRUE(message_received.load());
  18017. }
  18018. // Test: on_message callback
  18019. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18020. // Endpoint that sends multiple events then closes
  18021. server_->Get("/multi-event", [](const Request &, Response &res) {
  18022. res.set_chunked_content_provider(
  18023. "text/event-stream", [](size_t offset, DataSink &sink) {
  18024. if (offset == 0) {
  18025. std::string events = "data: message1\n\ndata: message2\n\n";
  18026. sink.write(events.data(), events.size());
  18027. }
  18028. return false;
  18029. });
  18030. });
  18031. Client client("localhost", get_port());
  18032. sse::SSEClient sse(client, "/multi-event");
  18033. std::vector<std::string> received_messages;
  18034. std::mutex messages_mutex;
  18035. sse.on_message([&](const sse::SSEMessage &msg) {
  18036. std::lock_guard<std::mutex> lock(messages_mutex);
  18037. received_messages.push_back(msg.data);
  18038. });
  18039. sse.set_reconnect_interval(100);
  18040. sse.set_max_reconnect_attempts(1);
  18041. sse.start_async();
  18042. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18043. sse.stop();
  18044. std::lock_guard<std::mutex> lock(messages_mutex);
  18045. EXPECT_GE(received_messages.size(), 2u);
  18046. if (received_messages.size() >= 2) {
  18047. EXPECT_EQ(received_messages[0], "message1");
  18048. EXPECT_EQ(received_messages[1], "message2");
  18049. }
  18050. }
  18051. // Test: on_event for specific types
  18052. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18053. Client client("localhost", get_port());
  18054. sse::SSEClient sse(client, "/custom-events");
  18055. std::atomic<bool> update_received{false};
  18056. std::atomic<bool> delete_received{false};
  18057. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18058. if (msg.data == "updated") { update_received.store(true); }
  18059. });
  18060. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18061. if (msg.data == "deleted") { delete_received.store(true); }
  18062. });
  18063. sse.set_max_reconnect_attempts(1);
  18064. sse.start_async();
  18065. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18066. sse.stop();
  18067. EXPECT_TRUE(update_received.load());
  18068. EXPECT_TRUE(delete_received.load());
  18069. }
  18070. // Test: on_error callback on connection failure
  18071. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18072. // Connect to a non-existent port
  18073. Client client("localhost", 59999);
  18074. sse::SSEClient sse(client, "/events");
  18075. std::atomic<bool> error_called{false};
  18076. Error received_error = Error::Success;
  18077. sse.on_error([&](Error err) {
  18078. error_called.store(true);
  18079. received_error = err;
  18080. });
  18081. sse.set_reconnect_interval(50);
  18082. sse.set_max_reconnect_attempts(1);
  18083. sse.start_async();
  18084. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18085. sse.stop();
  18086. EXPECT_TRUE(error_called.load());
  18087. EXPECT_NE(received_error, Error::Success);
  18088. }
  18089. // Test: Last-Event-ID header sent on reconnect
  18090. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18091. // Endpoint that sends event with ID
  18092. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18093. res.set_chunked_content_provider(
  18094. "text/event-stream", [](size_t offset, DataSink &sink) {
  18095. if (offset == 0) {
  18096. std::string event = "id: evt-123\ndata: test\n\n";
  18097. sink.write(event.data(), event.size());
  18098. }
  18099. return false;
  18100. });
  18101. });
  18102. Client client("localhost", get_port());
  18103. sse::SSEClient sse(client, "/event-with-id");
  18104. std::atomic<bool> id_received{false};
  18105. sse.on_message([&](const sse::SSEMessage &msg) {
  18106. if (!msg.id.empty()) { id_received.store(true); }
  18107. });
  18108. sse.set_reconnect_interval(100);
  18109. sse.set_max_reconnect_attempts(1);
  18110. sse.start_async();
  18111. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18112. sse.stop();
  18113. EXPECT_TRUE(id_received.load());
  18114. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18115. }
  18116. // Test: Manual stop
  18117. TEST_F(SSEIntegrationTest, ManualStop) {
  18118. // Endpoint that sends one event and stays open briefly
  18119. std::atomic<bool> handler_running{true};
  18120. server_->Get("/stay-open", [&handler_running](const Request &,
  18121. Response &res) {
  18122. res.set_chunked_content_provider(
  18123. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18124. if (offset == 0) {
  18125. std::string event = "data: connected\n\n";
  18126. sink.write(event.data(), event.size());
  18127. }
  18128. // Keep connection open while handler_running is true
  18129. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18130. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18131. }
  18132. return false;
  18133. });
  18134. });
  18135. Client client("localhost", get_port());
  18136. sse::SSEClient sse(client, "/stay-open");
  18137. std::atomic<bool> connected{false};
  18138. sse.on_open([&connected]() { connected.store(true); });
  18139. sse.set_reconnect_interval(100);
  18140. sse.set_max_reconnect_attempts(1);
  18141. sse.start_async();
  18142. // Wait for connection to establish
  18143. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18144. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18145. }
  18146. EXPECT_TRUE(connected.load());
  18147. EXPECT_TRUE(sse.is_connected());
  18148. // Signal handler to stop
  18149. handler_running.store(false);
  18150. // Stop SSE client
  18151. sse.stop();
  18152. EXPECT_FALSE(sse.is_connected());
  18153. }
  18154. // Test: SSEClient with custom headers
  18155. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18156. // Setup a server endpoint that checks for custom header
  18157. std::atomic<bool> header_received{false};
  18158. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18159. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18160. header_received.store(true);
  18161. }
  18162. res.set_chunked_content_provider("text/event-stream",
  18163. [](size_t, DataSink &) { return false; });
  18164. });
  18165. Client client("localhost", get_port());
  18166. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18167. sse::SSEClient sse(client, "/header-check", headers);
  18168. sse.set_max_reconnect_attempts(1);
  18169. sse.start_async();
  18170. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18171. sse.stop();
  18172. EXPECT_TRUE(header_received.load());
  18173. }
  18174. // Test: Reconnect interval configuration
  18175. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18176. Client client("localhost", get_port());
  18177. sse::SSEClient sse(client, "/events");
  18178. auto &result = sse.set_reconnect_interval(500);
  18179. // Builder pattern should return reference to self
  18180. EXPECT_EQ(&result, &sse);
  18181. }
  18182. // Test: Max reconnect attempts
  18183. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18184. // Connect to non-existent port to force reconnects
  18185. Client client("localhost", 59998);
  18186. sse::SSEClient sse(client, "/events");
  18187. std::atomic<int> error_count{0};
  18188. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18189. sse.set_reconnect_interval(50);
  18190. sse.set_max_reconnect_attempts(2);
  18191. auto start = std::chrono::steady_clock::now();
  18192. sse.start(); // Blocking call
  18193. auto end = std::chrono::steady_clock::now();
  18194. // Should have stopped after 2 failed attempts
  18195. EXPECT_GE(error_count.load(), 2);
  18196. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18197. auto duration =
  18198. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18199. #ifdef _WIN32
  18200. // Windows is much slower for socket connection failures
  18201. EXPECT_LT(duration.count(), 7000);
  18202. #else
  18203. EXPECT_LT(duration.count(), 1000);
  18204. #endif
  18205. }
  18206. // Test: Multi-line data in integration
  18207. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18208. // Endpoint with multi-line data
  18209. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18210. res.set_chunked_content_provider(
  18211. "text/event-stream", [](size_t offset, DataSink &sink) {
  18212. if (offset == 0) {
  18213. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18214. sink.write(event.data(), event.size());
  18215. }
  18216. return false;
  18217. });
  18218. });
  18219. Client client("localhost", get_port());
  18220. sse::SSEClient sse(client, "/multiline-data");
  18221. std::string received_data;
  18222. std::mutex data_mutex;
  18223. sse.on_message([&](const sse::SSEMessage &msg) {
  18224. std::lock_guard<std::mutex> lock(data_mutex);
  18225. received_data = msg.data;
  18226. });
  18227. sse.set_reconnect_interval(100);
  18228. sse.set_max_reconnect_attempts(1);
  18229. sse.start_async();
  18230. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18231. sse.stop();
  18232. std::lock_guard<std::mutex> lock(data_mutex);
  18233. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18234. }
  18235. // Test: Auto-reconnect after server disconnection
  18236. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18237. std::atomic<int> connection_count{0};
  18238. std::atomic<int> message_count{0};
  18239. // Endpoint that sends one event and closes, forcing reconnect
  18240. server_->Get("/reconnect-test",
  18241. [&connection_count](const Request &, Response &res) {
  18242. connection_count.fetch_add(1);
  18243. res.set_chunked_content_provider(
  18244. "text/event-stream", [](size_t offset, DataSink &sink) {
  18245. if (offset == 0) {
  18246. std::string event = "data: hello\n\n";
  18247. sink.write(event.data(), event.size());
  18248. }
  18249. return false; // Close connection after sending
  18250. });
  18251. });
  18252. Client client("localhost", get_port());
  18253. sse::SSEClient sse(client, "/reconnect-test");
  18254. sse.on_message([&message_count](const sse::SSEMessage &) {
  18255. message_count.fetch_add(1);
  18256. });
  18257. sse.set_reconnect_interval(100);
  18258. sse.set_max_reconnect_attempts(3);
  18259. sse.start_async();
  18260. // Wait long enough for multiple reconnects
  18261. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18262. sse.stop();
  18263. // Should have connected multiple times (initial + reconnects)
  18264. EXPECT_GE(connection_count.load(), 2);
  18265. // Should have received messages from multiple connections
  18266. EXPECT_GE(message_count.load(), 2);
  18267. }
  18268. // Test: Last-Event-ID sent on reconnect
  18269. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18270. std::atomic<int> connection_count{0};
  18271. std::vector<std::string> received_last_event_ids;
  18272. std::mutex id_mutex;
  18273. // Endpoint that checks Last-Event-ID header and sends event with ID
  18274. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18275. int conn = connection_count.fetch_add(1);
  18276. // Capture the Last-Event-ID header from each connection
  18277. {
  18278. std::lock_guard<std::mutex> lock(id_mutex);
  18279. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18280. }
  18281. res.set_chunked_content_provider(
  18282. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18283. if (offset == 0) {
  18284. std::string event =
  18285. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18286. sink.write(event.data(), event.size());
  18287. }
  18288. return false;
  18289. });
  18290. });
  18291. Client client("localhost", get_port());
  18292. sse::SSEClient sse(client, "/reconnect-with-id");
  18293. sse.set_reconnect_interval(100);
  18294. sse.set_max_reconnect_attempts(3);
  18295. sse.start_async();
  18296. // Wait for at least 2 connections
  18297. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18298. sse.stop();
  18299. // Verify behavior
  18300. std::lock_guard<std::mutex> lock(id_mutex);
  18301. EXPECT_GE(received_last_event_ids.size(), 2u);
  18302. // First connection should have no Last-Event-ID
  18303. if (!received_last_event_ids.empty()) {
  18304. EXPECT_EQ(received_last_event_ids[0], "");
  18305. }
  18306. // Second connection should have Last-Event-ID from first connection
  18307. if (received_last_event_ids.size() >= 2) {
  18308. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18309. }
  18310. }
  18311. // Test: set_headers updates headers used on reconnect
  18312. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18313. std::vector<std::string> received_tokens;
  18314. std::mutex token_mutex;
  18315. // Endpoint that captures Authorization header
  18316. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18317. {
  18318. std::lock_guard<std::mutex> lock(token_mutex);
  18319. received_tokens.push_back(req.get_header_value("Authorization"));
  18320. }
  18321. res.set_chunked_content_provider(
  18322. "text/event-stream", [](size_t offset, DataSink &sink) {
  18323. if (offset == 0) {
  18324. std::string event = "data: hello\n\n";
  18325. sink.write(event.data(), event.size());
  18326. }
  18327. return false; // Close connection to trigger reconnect
  18328. });
  18329. });
  18330. Client client("localhost", get_port());
  18331. Headers headers = {{"Authorization", "Bearer old-token"}};
  18332. sse::SSEClient sse(client, "/auth-check", headers);
  18333. // Update headers on each successful connection
  18334. sse.on_open(
  18335. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18336. sse.set_reconnect_interval(100);
  18337. sse.set_max_reconnect_attempts(3);
  18338. sse.start_async();
  18339. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18340. sse.stop();
  18341. std::lock_guard<std::mutex> lock(token_mutex);
  18342. ASSERT_GE(received_tokens.size(), 2u);
  18343. // First connection uses original header
  18344. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18345. // Second connection uses updated header from set_headers
  18346. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18347. }
  18348. // Test: 401 allows reconnection (so on_error can refresh headers)
  18349. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18350. std::atomic<int> connection_count{0};
  18351. // Endpoint: returns 401 on first attempt, 200 on second
  18352. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18353. int conn = connection_count.fetch_add(1);
  18354. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  18355. res.status = StatusCode::Unauthorized_401;
  18356. res.set_content("Unauthorized", "text/plain");
  18357. return;
  18358. }
  18359. res.set_chunked_content_provider(
  18360. "text/event-stream", [](size_t offset, DataSink &sink) {
  18361. if (offset == 0) {
  18362. std::string event = "data: authenticated\n\n";
  18363. sink.write(event.data(), event.size());
  18364. }
  18365. return false;
  18366. });
  18367. });
  18368. Client client("localhost", get_port());
  18369. Headers headers = {{"Authorization", "Bearer expired"}};
  18370. sse::SSEClient sse(client, "/auth-retry", headers);
  18371. std::atomic<bool> message_received{false};
  18372. // Refresh token on error
  18373. sse.on_error(
  18374. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  18375. sse.on_message([&](const sse::SSEMessage &msg) {
  18376. if (msg.data == "authenticated") { message_received.store(true); }
  18377. });
  18378. sse.set_reconnect_interval(100);
  18379. sse.set_max_reconnect_attempts(3);
  18380. sse.start_async();
  18381. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18382. sse.stop();
  18383. // Should have reconnected after 401 and succeeded with new token
  18384. EXPECT_GE(connection_count.load(), 2);
  18385. EXPECT_TRUE(message_received.load());
  18386. }
  18387. TEST(Issue2318Test, EmptyHostString) {
  18388. {
  18389. httplib::Client cli_empty("", PORT);
  18390. auto res = cli_empty.Get("/");
  18391. ASSERT_FALSE(res);
  18392. EXPECT_EQ(httplib::Error::Connection, res.error());
  18393. }
  18394. {
  18395. httplib::Client cli(" ", PORT);
  18396. auto res = cli.Get("/");
  18397. ASSERT_FALSE(res);
  18398. EXPECT_EQ(httplib::Error::Connection, res.error());
  18399. }
  18400. }
  18401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18402. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  18403. Server svr;
  18404. // Set a small payload limit (1KB)
  18405. svr.set_payload_max_length(1024);
  18406. svr.Post("/test", [&](const Request &req, Response &res) {
  18407. res.set_content("Body size: " + std::to_string(req.body.size()),
  18408. "text/plain");
  18409. });
  18410. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18411. auto se = detail::scope_exit([&] {
  18412. svr.stop();
  18413. listen_thread.join();
  18414. });
  18415. svr.wait_until_ready();
  18416. // Create data that compresses well but exceeds limit when decompressed
  18417. // 8KB of repeated null bytes compresses to a very small size
  18418. std::string original_data(8 * 1024, '\0');
  18419. // Compress the data using gzip
  18420. std::string compressed_data;
  18421. detail::gzip_compressor compressor;
  18422. compressor.compress(original_data.data(), original_data.size(), true,
  18423. [&](const char *data, size_t size) {
  18424. compressed_data.append(data, size);
  18425. return true;
  18426. });
  18427. // Verify compression worked (compressed should be much smaller)
  18428. ASSERT_LT(compressed_data.size(), original_data.size());
  18429. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  18430. // Send compressed data with Content-Encoding: gzip
  18431. Client cli(HOST, PORT);
  18432. Headers headers = {{"Content-Encoding", "gzip"}};
  18433. auto res =
  18434. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  18435. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  18436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18437. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  18438. }
  18439. #endif
  18440. // ============================================================================
  18441. // OpenSSL-Specific Tests
  18442. // ============================================================================
  18443. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  18444. X509 *readCertificate(const std::string &strFileName) {
  18445. std::ifstream inStream(strFileName);
  18446. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  18447. std::istreambuf_iterator<char>());
  18448. if (strCertPEM.empty()) return (nullptr);
  18449. BIO *pbCert = BIO_new(BIO_s_mem());
  18450. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  18451. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  18452. BIO_free(pbCert);
  18453. return (pCert);
  18454. }
  18455. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  18456. std::ifstream inStream(strFileName);
  18457. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  18458. std::istreambuf_iterator<char>());
  18459. if (strPrivateKeyPEM.empty()) return (nullptr);
  18460. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  18461. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  18462. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  18463. BIO_free(pbPrivKey);
  18464. return (pPrivateKey);
  18465. }
  18466. TEST(BindServerTest, UpdateCerts) {
  18467. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18468. int port = svr.bind_to_any_port("0.0.0.0");
  18469. ASSERT_TRUE(svr.is_valid());
  18470. ASSERT_TRUE(port > 0);
  18471. X509 *cert = readCertificate(SERVER_CERT_FILE);
  18472. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  18473. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  18474. ASSERT_TRUE(cert != nullptr);
  18475. ASSERT_TRUE(ca_cert != nullptr);
  18476. ASSERT_TRUE(key != nullptr);
  18477. X509_STORE *cert_store = X509_STORE_new();
  18478. X509_STORE_add_cert(cert_store, ca_cert);
  18479. // svr.update_certs(cert, key, cert_store); // deprecated
  18480. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  18481. CLIENT_CA_CERT_FILE);
  18482. ASSERT_TRUE(svr.is_valid());
  18483. svr.stop();
  18484. X509_STORE_free(cert_store);
  18485. X509_free(cert);
  18486. X509_free(ca_cert);
  18487. EVP_PKEY_free(key);
  18488. }
  18489. // Test that update_certs() updates client CA list correctly
  18490. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  18491. // Start with file-based constructor
  18492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18493. ASSERT_TRUE(svr.is_valid());
  18494. // Initially no client CA list should be set
  18495. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18496. ASSERT_TRUE(ssl_ctx != nullptr);
  18497. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  18498. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  18499. EXPECT_EQ(0, count_before);
  18500. // Now update with client CA (PEM string)
  18501. std::string cert_pem, key_pem, ca_pem;
  18502. read_file(SERVER_CERT_FILE, cert_pem);
  18503. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  18504. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  18505. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  18506. ASSERT_TRUE(svr.is_valid());
  18507. // Now client CA list should be set
  18508. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  18509. ASSERT_TRUE(ca_list_after != nullptr);
  18510. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  18511. }
  18512. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  18513. // Test that the file-path SSLServer constructor properly sets the client CA
  18514. // list that is sent to clients during the TLS handshake (CertificateRequest)
  18515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  18516. ASSERT_TRUE(svr.is_valid());
  18517. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  18518. ASSERT_TRUE(ssl_ctx != nullptr);
  18519. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  18520. ASSERT_TRUE(ca_list != nullptr);
  18521. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  18522. }
  18523. #endif
  18524. // ============================================================================
  18525. // MbedTLS-Specific Tests
  18526. // ============================================================================
  18527. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  18528. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  18529. using namespace httplib::tls;
  18530. // Track if callback was invoked
  18531. bool callback_invoked = false;
  18532. // The callback receives void* ctx which is actually MbedTlsContext*
  18533. // We can access the mbedtls_ssl_config via the context
  18534. auto setup_callback = [&callback_invoked](void *ctx) {
  18535. callback_invoked = true;
  18536. // Cast to MbedTlsContext* to access the ssl config
  18537. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  18538. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  18539. // Use static variables to hold certificate data (simplified for test)
  18540. static mbedtls_x509_crt own_cert;
  18541. static mbedtls_pk_context own_key;
  18542. static mbedtls_x509_crt ca_chain;
  18543. static bool initialized = false;
  18544. if (!initialized) {
  18545. mbedtls_x509_crt_init(&own_cert);
  18546. mbedtls_pk_init(&own_key);
  18547. mbedtls_x509_crt_init(&ca_chain);
  18548. // Load server certificate
  18549. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  18550. return false;
  18551. }
  18552. // Load server private key.
  18553. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  18554. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  18555. #if MBEDTLS_VERSION_MAJOR == 3
  18556. ,
  18557. mbedtls_ctr_drbg_random, nullptr
  18558. #endif
  18559. ) != 0) {
  18560. return false;
  18561. }
  18562. // Load CA chain for client verification
  18563. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  18564. return false;
  18565. }
  18566. initialized = true;
  18567. }
  18568. // Configure the SSL config
  18569. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  18570. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  18571. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  18572. // Set minimum TLS version using mbedTLS native API
  18573. #if MBEDTLS_VERSION_MAJOR >= 3
  18574. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  18575. #else
  18576. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  18577. MBEDTLS_SSL_MINOR_VERSION_3);
  18578. #endif
  18579. return true;
  18580. };
  18581. SSLServer svr(setup_callback);
  18582. ASSERT_TRUE(svr.is_valid());
  18583. ASSERT_TRUE(callback_invoked);
  18584. svr.Get("/test", [&](const Request &req, Response &res) {
  18585. res.set_content("test", "text/plain");
  18586. auto cert = req.peer_cert();
  18587. ASSERT_TRUE(static_cast<bool>(cert));
  18588. auto common_name = cert.subject_cn();
  18589. EXPECT_EQ("Common Name", common_name);
  18590. });
  18591. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18592. auto se = detail::scope_exit([&] {
  18593. svr.stop();
  18594. t.join();
  18595. ASSERT_FALSE(svr.is_running());
  18596. });
  18597. svr.wait_until_ready();
  18598. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  18599. cli.enable_server_certificate_verification(false);
  18600. cli.set_connection_timeout(30);
  18601. auto res = cli.Get("/test");
  18602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18603. ASSERT_EQ(StatusCode::OK_200, res->status);
  18604. }
  18605. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  18606. // context (owning mbedtls_ssl_config) before shutting down a still-open
  18607. // keep-alive SSL session, which reads through that config in
  18608. // mbedtls_ssl_close_notify.
  18609. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  18610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18611. ASSERT_TRUE(svr.is_valid());
  18612. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18613. res.set_content("test", "text/plain");
  18614. });
  18615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  18616. auto se = detail::scope_exit([&] {
  18617. svr.stop();
  18618. t.join();
  18619. ASSERT_FALSE(svr.is_running());
  18620. });
  18621. svr.wait_until_ready();
  18622. {
  18623. SSLClient cli(HOST, PORT);
  18624. cli.enable_server_certificate_verification(false);
  18625. cli.set_keep_alive(true);
  18626. auto res = cli.Get("/test");
  18627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18628. ASSERT_EQ(StatusCode::OK_200, res->status);
  18629. // cli is destructed here with the keep-alive SSL session still open.
  18630. }
  18631. }
  18632. #endif
  18633. // WebSocket Tests
  18634. TEST(WebSocketTest, RSVBitsMustBeZero) {
  18635. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  18636. // defining the meaning of these bits has been negotiated.
  18637. auto make_frame = [](uint8_t first_byte) {
  18638. std::string frame;
  18639. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  18640. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  18641. frame += "Hello";
  18642. return frame;
  18643. };
  18644. // RSV1 set (0x40)
  18645. {
  18646. detail::BufferStream strm;
  18647. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  18648. ws::Opcode opcode;
  18649. std::string payload;
  18650. bool fin;
  18651. EXPECT_EQ(
  18652. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18653. ws::impl::FrameRead::Fail);
  18654. }
  18655. // RSV2 set (0x20)
  18656. {
  18657. detail::BufferStream strm;
  18658. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  18659. ws::Opcode opcode;
  18660. std::string payload;
  18661. bool fin;
  18662. EXPECT_EQ(
  18663. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18664. ws::impl::FrameRead::Fail);
  18665. }
  18666. // RSV3 set (0x10)
  18667. {
  18668. detail::BufferStream strm;
  18669. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  18670. ws::Opcode opcode;
  18671. std::string payload;
  18672. bool fin;
  18673. EXPECT_EQ(
  18674. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18675. ws::impl::FrameRead::Fail);
  18676. }
  18677. // No RSV bits set - should succeed
  18678. {
  18679. detail::BufferStream strm;
  18680. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  18681. ws::Opcode opcode;
  18682. std::string payload;
  18683. bool fin;
  18684. EXPECT_EQ(
  18685. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18686. ws::impl::FrameRead::Ok);
  18687. EXPECT_EQ(ws::Opcode::Text, opcode);
  18688. EXPECT_EQ("Hello", payload);
  18689. EXPECT_TRUE(fin);
  18690. }
  18691. }
  18692. TEST(WebSocketTest, ControlFrameValidation) {
  18693. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  18694. // payload length <= 125.
  18695. // Ping with FIN=0 - must be rejected
  18696. {
  18697. detail::BufferStream strm;
  18698. std::string frame;
  18699. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  18700. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18701. strm.write(frame.data(), frame.size());
  18702. ws::Opcode opcode;
  18703. std::string payload;
  18704. bool fin;
  18705. EXPECT_EQ(
  18706. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18707. ws::impl::FrameRead::Fail);
  18708. }
  18709. // Close with FIN=0 - must be rejected
  18710. {
  18711. detail::BufferStream strm;
  18712. std::string frame;
  18713. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  18714. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  18715. strm.write(frame.data(), frame.size());
  18716. ws::Opcode opcode;
  18717. std::string payload;
  18718. bool fin;
  18719. EXPECT_EQ(
  18720. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18721. ws::impl::FrameRead::Fail);
  18722. }
  18723. // Ping with payload_len=126 (extended length) - must be rejected
  18724. {
  18725. detail::BufferStream strm;
  18726. std::string frame;
  18727. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18728. frame += static_cast<char>(126); // payload_len=126 (>125)
  18729. frame += static_cast<char>(0x00); // extended length high byte
  18730. frame += static_cast<char>(126); // extended length low byte
  18731. frame += std::string(126, 'x');
  18732. strm.write(frame.data(), frame.size());
  18733. ws::Opcode opcode;
  18734. std::string payload;
  18735. bool fin;
  18736. EXPECT_EQ(
  18737. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18738. ws::impl::FrameRead::Fail);
  18739. }
  18740. // Ping with FIN=1 and payload_len=125 - should succeed
  18741. {
  18742. detail::BufferStream strm;
  18743. std::string frame;
  18744. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  18745. frame += static_cast<char>(125); // payload_len=125
  18746. frame += std::string(125, 'x');
  18747. strm.write(frame.data(), frame.size());
  18748. ws::Opcode opcode;
  18749. std::string payload;
  18750. bool fin;
  18751. EXPECT_EQ(
  18752. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18753. ws::impl::FrameRead::Ok);
  18754. EXPECT_EQ(ws::Opcode::Ping, opcode);
  18755. EXPECT_EQ(125u, payload.size());
  18756. EXPECT_TRUE(fin);
  18757. }
  18758. }
  18759. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  18760. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  18761. // length MUST be 0.
  18762. // MSB set - must be rejected
  18763. {
  18764. detail::BufferStream strm;
  18765. std::string frame;
  18766. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18767. frame += static_cast<char>(127); // 64-bit extended length
  18768. frame += static_cast<char>(0x80); // MSB set (invalid)
  18769. frame += std::string(7, '\0'); // remaining 7 bytes of length
  18770. strm.write(frame.data(), frame.size());
  18771. ws::Opcode opcode;
  18772. std::string payload;
  18773. bool fin;
  18774. EXPECT_EQ(
  18775. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18776. ws::impl::FrameRead::Fail);
  18777. }
  18778. // MSB clear - should pass length parsing (will be rejected by max_len,
  18779. // but that's a different check; use a small length to verify)
  18780. {
  18781. detail::BufferStream strm;
  18782. std::string frame;
  18783. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  18784. frame += static_cast<char>(127); // 64-bit extended length
  18785. frame += std::string(7, '\0'); // high bytes = 0
  18786. frame += static_cast<char>(0x03); // length = 3
  18787. frame += "abc";
  18788. strm.write(frame.data(), frame.size());
  18789. ws::Opcode opcode;
  18790. std::string payload;
  18791. bool fin;
  18792. EXPECT_EQ(
  18793. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  18794. ws::impl::FrameRead::Ok);
  18795. EXPECT_EQ(ws::Opcode::Text, opcode);
  18796. EXPECT_EQ("abc", payload);
  18797. }
  18798. }
  18799. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  18800. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  18801. // Valid UTF-8
  18802. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  18803. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  18804. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  18805. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  18806. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  18807. // Invalid UTF-8
  18808. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  18809. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  18810. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  18811. EXPECT_FALSE(
  18812. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  18813. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  18814. }
  18815. TEST(WebSocketTest, ConnectAndDisconnect) {
  18816. Server svr;
  18817. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18818. std::string msg;
  18819. while (ws.read(msg)) {}
  18820. });
  18821. auto port = svr.bind_to_any_port(HOST);
  18822. std::thread t([&]() { svr.listen_after_bind(); });
  18823. svr.wait_until_ready();
  18824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18825. auto res = client.connect();
  18826. ASSERT_TRUE(res);
  18827. EXPECT_EQ(Error::Success, res.error());
  18828. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  18829. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  18830. EXPECT_TRUE(client.is_open());
  18831. client.close();
  18832. EXPECT_FALSE(client.is_open());
  18833. svr.stop();
  18834. t.join();
  18835. }
  18836. TEST(WebSocketTest, ValidURL) {
  18837. ws::WebSocketClient ws1("ws://localhost:8080/path");
  18838. EXPECT_TRUE(ws1.is_valid());
  18839. ws::WebSocketClient ws2("ws://example.com/path");
  18840. EXPECT_TRUE(ws2.is_valid());
  18841. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  18842. EXPECT_TRUE(ws3.is_valid());
  18843. #ifdef CPPHTTPLIB_SSL_ENABLED
  18844. ws::WebSocketClient wss1("wss://example.com/path");
  18845. EXPECT_TRUE(wss1.is_valid());
  18846. ws::WebSocketClient wss2("wss://example.com:443/path");
  18847. EXPECT_TRUE(wss2.is_valid());
  18848. #endif
  18849. }
  18850. TEST(WebSocketTest, InvalidURL) {
  18851. // No scheme
  18852. ws::WebSocketClient ws1("localhost:8080/path");
  18853. EXPECT_FALSE(ws1.is_valid());
  18854. // No path
  18855. ws::WebSocketClient ws2("ws://localhost:8080");
  18856. EXPECT_FALSE(ws2.is_valid());
  18857. // Empty string
  18858. ws::WebSocketClient ws3("");
  18859. EXPECT_FALSE(ws3.is_valid());
  18860. // Missing host
  18861. ws::WebSocketClient ws4("ws://:8080/path");
  18862. EXPECT_FALSE(ws4.is_valid());
  18863. // Port number overflow — should not crash
  18864. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  18865. EXPECT_FALSE(ws5.is_valid());
  18866. // Port out of range
  18867. ws::WebSocketClient ws6("ws://localhost:99999/path");
  18868. EXPECT_FALSE(ws6.is_valid());
  18869. }
  18870. TEST(WebSocketTest, UnsupportedScheme) {
  18871. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18872. ws::WebSocketClient ws1("http://localhost:8080/path");
  18873. EXPECT_FALSE(ws1.is_valid());
  18874. ws::WebSocketClient ws2("https://localhost:8080/path");
  18875. EXPECT_FALSE(ws2.is_valid());
  18876. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  18877. EXPECT_FALSE(ws3.is_valid());
  18878. #else
  18879. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  18880. std::invalid_argument);
  18881. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  18882. std::invalid_argument);
  18883. #endif
  18884. }
  18885. TEST(WebSocketTest, ConnectWhenInvalid) {
  18886. ws::WebSocketClient ws("not a valid url");
  18887. EXPECT_FALSE(ws.is_valid());
  18888. auto res = ws.connect();
  18889. EXPECT_FALSE(res);
  18890. EXPECT_EQ(Error::Connection, res.error());
  18891. EXPECT_EQ(-1, res.status());
  18892. }
  18893. TEST(WebSocketTest, ConnectRefusedReportsError) {
  18894. // Grab a port that is free, then close it again so nothing listens there
  18895. Server svr;
  18896. auto port = svr.bind_to_any_port(HOST);
  18897. svr.stop();
  18898. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18899. auto res = client.connect();
  18900. ASSERT_FALSE(res);
  18901. EXPECT_EQ(Error::Connection, res.error());
  18902. EXPECT_EQ(-1, res.status());
  18903. }
  18904. TEST(WebSocketTest, DefaultPort) {
  18905. ws::WebSocketClient ws1("ws://example.com/path");
  18906. EXPECT_TRUE(ws1.is_valid());
  18907. // ws:// defaults to port 80 (verified by successful parse)
  18908. #ifdef CPPHTTPLIB_SSL_ENABLED
  18909. ws::WebSocketClient ws2("wss://example.com/path");
  18910. EXPECT_TRUE(ws2.is_valid());
  18911. // wss:// defaults to port 443 (verified by successful parse)
  18912. #endif
  18913. }
  18914. TEST(WebSocketTest, IPv6LiteralAddress) {
  18915. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  18916. EXPECT_TRUE(ws1.is_valid());
  18917. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  18918. EXPECT_TRUE(ws2.is_valid());
  18919. }
  18920. TEST(WebSocketTest, ComplexPath) {
  18921. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  18922. EXPECT_TRUE(ws1.is_valid());
  18923. ws::WebSocketClient ws2("ws://localhost:8080/");
  18924. EXPECT_TRUE(ws2.is_valid());
  18925. }
  18926. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  18927. Server svr;
  18928. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18929. std::string msg;
  18930. while (ws.read(msg)) {}
  18931. });
  18932. auto port = svr.bind_to_any_port(HOST);
  18933. std::thread t([&]() { svr.listen_after_bind(); });
  18934. svr.wait_until_ready();
  18935. auto another_host = "example.com";
  18936. auto wrong_ip = "192.0.2.1";
  18937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18938. client.set_hostname_addr_map({{another_host, wrong_ip}});
  18939. ASSERT_TRUE(client.connect());
  18940. EXPECT_TRUE(client.is_open());
  18941. client.close();
  18942. svr.stop();
  18943. t.join();
  18944. }
  18945. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  18946. Server svr;
  18947. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  18948. std::string msg;
  18949. while (ws.read(msg)) {}
  18950. });
  18951. auto port = svr.bind_to_any_port(HOST);
  18952. std::thread t([&]() { svr.listen_after_bind(); });
  18953. svr.wait_until_ready();
  18954. auto wrong_ip = "192.0.2.1";
  18955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  18956. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  18957. client.set_connection_timeout(1);
  18958. client.set_read_timeout(1);
  18959. client.set_write_timeout(1);
  18960. EXPECT_FALSE(client.connect());
  18961. EXPECT_FALSE(client.is_open());
  18962. svr.stop();
  18963. t.join();
  18964. }
  18965. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  18966. // A mapped value that is not an IP literal must be resolved. HOST resolves
  18967. // from the hosts file, so this test needs no external DNS. "target.invalid"
  18968. // (RFC 6761) is only a map key and the Host header value.
  18969. auto host = "target.invalid";
  18970. Server svr;
  18971. std::string received_host;
  18972. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  18973. received_host = req.get_header_value("Host");
  18974. std::string msg;
  18975. while (ws.read(msg)) {}
  18976. });
  18977. auto port = svr.bind_to_any_port(HOST);
  18978. std::thread t([&]() { svr.listen_after_bind(); });
  18979. // ASSERT_* below returns from the test body, which would leave t joinable
  18980. // and make ~thread call std::terminate.
  18981. auto se = detail::scope_exit([&] {
  18982. svr.stop();
  18983. if (t.joinable()) { t.join(); }
  18984. });
  18985. svr.wait_until_ready();
  18986. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  18987. std::to_string(port) + "/ws");
  18988. client.set_hostname_addr_map({{host, HOST}});
  18989. ASSERT_TRUE(client.connect());
  18990. EXPECT_TRUE(client.is_open());
  18991. client.close();
  18992. svr.stop();
  18993. t.join();
  18994. // The mapping only redirects the connection; the identity stays host_.
  18995. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  18996. }
  18997. class WebSocketIntegrationTest : public ::testing::Test {
  18998. protected:
  18999. void SetUp() override {
  19000. server_ = httplib::detail::make_unique<Server>();
  19001. setup_server();
  19002. start_server();
  19003. }
  19004. void TearDown() override {
  19005. server_->stop();
  19006. if (server_thread_.joinable()) { server_thread_.join(); }
  19007. }
  19008. void setup_server() {
  19009. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19010. std::string msg;
  19011. ws::ReadResult ret;
  19012. while ((ret = ws.read(msg))) {
  19013. if (ret == ws::Binary) {
  19014. ws.send(msg.data(), msg.size());
  19015. } else {
  19016. ws.send(msg);
  19017. }
  19018. }
  19019. });
  19020. server_->WebSocket("/ws-echo-string",
  19021. [](const Request &, ws::WebSocket &ws) {
  19022. std::string msg;
  19023. while (ws.read(msg)) {
  19024. ws.send("echo: " + msg);
  19025. }
  19026. });
  19027. server_->WebSocket(
  19028. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19029. // Echo back request metadata
  19030. ws.send("path:" + req.path);
  19031. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19032. std::string msg;
  19033. while (ws.read(msg)) {}
  19034. });
  19035. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19036. std::string msg;
  19037. ws.read(msg); // wait for a message
  19038. ws.close();
  19039. });
  19040. server_->WebSocket("/ws-close-status",
  19041. [](const Request &, ws::WebSocket &ws) {
  19042. std::string msg;
  19043. ws.read(msg); // wait for a message
  19044. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19045. });
  19046. server_->WebSocket(
  19047. "/ws-subprotocol",
  19048. [](const Request &, ws::WebSocket &ws) {
  19049. std::string msg;
  19050. while (ws.read(msg)) {
  19051. ws.send(msg);
  19052. }
  19053. },
  19054. [](const std::vector<std::string> &protocols) -> std::string {
  19055. for (const auto &p : protocols) {
  19056. if (p == "graphql-ws") { return p; }
  19057. }
  19058. return "";
  19059. });
  19060. }
  19061. void start_server() {
  19062. port_ = server_->bind_to_any_port(HOST);
  19063. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19064. server_->wait_until_ready();
  19065. }
  19066. std::unique_ptr<Server> server_;
  19067. std::thread server_thread_;
  19068. int port_ = 0;
  19069. };
  19070. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19071. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19072. "/ws-echo");
  19073. ASSERT_TRUE(client.connect());
  19074. ASSERT_TRUE(client.is_open());
  19075. ASSERT_TRUE(client.send("Hello WebSocket"));
  19076. std::string msg;
  19077. EXPECT_EQ(ws::Text, client.read(msg));
  19078. EXPECT_EQ("Hello WebSocket", msg);
  19079. client.close();
  19080. }
  19081. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19083. "/ws-echo");
  19084. ASSERT_TRUE(client.connect());
  19085. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19086. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19087. std::string msg;
  19088. EXPECT_EQ(ws::Binary, client.read(msg));
  19089. EXPECT_EQ(binary_data, msg);
  19090. client.close();
  19091. }
  19092. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19094. "/ws-echo");
  19095. ASSERT_TRUE(client.connect());
  19096. for (int i = 0; i < 10; i++) {
  19097. auto text = "message " + std::to_string(i);
  19098. ASSERT_TRUE(client.send(text));
  19099. std::string msg;
  19100. ASSERT_TRUE(client.read(msg));
  19101. EXPECT_EQ(text, msg);
  19102. }
  19103. client.close();
  19104. }
  19105. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19106. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19107. "/ws-close");
  19108. ASSERT_TRUE(client.connect());
  19109. // Send a message to trigger the server to close
  19110. ASSERT_TRUE(client.send("trigger close"));
  19111. // The server will close, so read should return false
  19112. std::string msg;
  19113. EXPECT_FALSE(client.read(msg));
  19114. EXPECT_FALSE(client.is_open());
  19115. }
  19116. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19117. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19118. "/ws-echo");
  19119. ASSERT_TRUE(client.connect());
  19120. // 128KB message
  19121. std::string large_data(128 * 1024, 'X');
  19122. ASSERT_TRUE(client.send(large_data));
  19123. std::string msg;
  19124. ASSERT_TRUE(client.read(msg));
  19125. EXPECT_EQ(large_data, msg);
  19126. client.close();
  19127. }
  19128. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19130. "/ws-echo");
  19131. ASSERT_TRUE(client.connect());
  19132. const int num_threads = 4;
  19133. std::vector<std::thread> threads;
  19134. std::atomic<int> send_count{0};
  19135. for (int t = 0; t < num_threads; t++) {
  19136. threads.emplace_back([&client, &send_count, t]() {
  19137. for (int i = 0; i < 5; i++) {
  19138. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19139. if (client.send(text)) { send_count++; }
  19140. }
  19141. });
  19142. }
  19143. for (auto &th : threads) {
  19144. th.join();
  19145. }
  19146. int received = 0;
  19147. std::string msg;
  19148. while (received < send_count.load()) {
  19149. if (!client.read(msg)) { break; }
  19150. received++;
  19151. }
  19152. EXPECT_EQ(send_count.load(), received);
  19153. client.close();
  19154. }
  19155. TEST_F(WebSocketIntegrationTest, ReadString) {
  19156. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19157. "/ws-echo-string");
  19158. ASSERT_TRUE(client.connect());
  19159. ASSERT_TRUE(client.send("hello"));
  19160. std::string msg;
  19161. ASSERT_TRUE(client.read(msg));
  19162. EXPECT_EQ("echo: hello", msg);
  19163. ASSERT_TRUE(client.send("world"));
  19164. ASSERT_TRUE(client.read(msg));
  19165. EXPECT_EQ("echo: world", msg);
  19166. client.close();
  19167. }
  19168. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19169. Headers headers = {{"X-Test-Header", "test-value"}};
  19170. ws::WebSocketClient client(
  19171. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19172. ASSERT_TRUE(client.connect());
  19173. std::string msg;
  19174. ASSERT_TRUE(client.read(msg));
  19175. EXPECT_EQ("path:/ws-request-info", msg);
  19176. ASSERT_TRUE(client.read(msg));
  19177. EXPECT_EQ("header:test-value", msg);
  19178. client.close();
  19179. }
  19180. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19181. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19182. "/ws-echo");
  19183. client.set_read_timeout(1, 0); // 1 second
  19184. ASSERT_TRUE(client.connect());
  19185. // Don't send anything — server echo handler waits for a message, so read()
  19186. // should time out. The connection survives it: nothing was consumed.
  19187. std::string msg;
  19188. EXPECT_EQ(client.read(msg), ws::Timeout);
  19189. EXPECT_TRUE(client.is_open());
  19190. // And it is still usable afterwards.
  19191. EXPECT_TRUE(client.send("after timeout"));
  19192. EXPECT_EQ(client.read(msg), ws::Text);
  19193. EXPECT_EQ(msg, "after timeout");
  19194. }
  19195. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19196. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19197. "/ws-echo");
  19198. client.set_read_timeout(1, 0);
  19199. ASSERT_TRUE(client.connect());
  19200. ASSERT_TRUE(client.send("first"));
  19201. std::string msg;
  19202. ASSERT_EQ(client.read(msg), ws::Text);
  19203. ASSERT_EQ(msg, "first");
  19204. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19205. // not be used with a read timeout: it would reprocess the previous message.
  19206. EXPECT_EQ(client.read(msg), ws::Timeout);
  19207. EXPECT_EQ(msg, "first");
  19208. }
  19209. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19210. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19211. "/ws-echo");
  19212. ASSERT_TRUE(client.connect());
  19213. // Setting it once the connection is open reaches the live stream, not just
  19214. // the seed for the next connect().
  19215. client.set_read_timeout(1, 0);
  19216. std::string msg;
  19217. EXPECT_EQ(client.read(msg), ws::Timeout);
  19218. EXPECT_TRUE(client.is_open());
  19219. }
  19220. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19222. "/ws-echo");
  19223. client.set_read_timeout(5, 0);
  19224. ASSERT_TRUE(client.connect());
  19225. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19226. // The server should reject it and close the connection.
  19227. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19228. client.send(oversized);
  19229. // The server's read() should have failed due to payload limit,
  19230. // so our read() should return false (connection closed).
  19231. std::string msg;
  19232. EXPECT_FALSE(client.read(msg));
  19233. }
  19234. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19235. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19236. "/ws-echo");
  19237. client.set_read_timeout(10, 0);
  19238. ASSERT_TRUE(client.connect());
  19239. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19240. // This should succeed.
  19241. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19242. ASSERT_TRUE(client.send(at_limit));
  19243. std::string msg;
  19244. ASSERT_TRUE(client.read(msg));
  19245. EXPECT_EQ(at_limit.size(), msg.size());
  19246. client.close();
  19247. }
  19248. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19249. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19250. "/nonexistent");
  19251. auto res = client.connect();
  19252. EXPECT_FALSE(res);
  19253. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19254. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19255. EXPECT_FALSE(client.is_open());
  19256. }
  19257. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19259. "/ws-echo");
  19260. ASSERT_TRUE(client.connect());
  19261. ASSERT_TRUE(client.send(""));
  19262. std::string msg;
  19263. EXPECT_EQ(ws::Text, client.read(msg));
  19264. EXPECT_EQ("", msg);
  19265. client.close();
  19266. }
  19267. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19269. "/ws-echo");
  19270. // First connection
  19271. ASSERT_TRUE(client.connect());
  19272. ASSERT_TRUE(client.send("first"));
  19273. std::string msg;
  19274. ASSERT_TRUE(client.read(msg));
  19275. EXPECT_EQ("first", msg);
  19276. client.close();
  19277. EXPECT_FALSE(client.is_open());
  19278. // Reconnect using the same client object
  19279. ASSERT_TRUE(client.connect());
  19280. ASSERT_TRUE(client.is_open());
  19281. ASSERT_TRUE(client.send("second"));
  19282. ASSERT_TRUE(client.read(msg));
  19283. EXPECT_EQ("second", msg);
  19284. client.close();
  19285. }
  19286. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19287. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19288. "/ws-close-status");
  19289. ASSERT_TRUE(client.connect());
  19290. // Trigger the server to close with GoingAway status
  19291. ASSERT_TRUE(client.send("trigger"));
  19292. // read() should return false after receiving the close frame
  19293. std::string msg;
  19294. EXPECT_FALSE(client.read(msg));
  19295. EXPECT_FALSE(client.is_open());
  19296. }
  19297. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19298. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19299. "/ws-echo");
  19300. ASSERT_TRUE(client.connect());
  19301. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19302. EXPECT_FALSE(client.is_open());
  19303. }
  19304. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19305. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19306. ws::WebSocketClient client(
  19307. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19308. ASSERT_TRUE(client.connect());
  19309. // Server should have selected graphql-ws
  19310. EXPECT_EQ("graphql-ws", client.subprotocol());
  19311. client.close();
  19312. }
  19313. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19314. Headers headers;
  19315. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19316. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19317. ws::WebSocketClient client(
  19318. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19319. ASSERT_TRUE(client.connect());
  19320. // The offer on the second field line counts too, so graphql-ws is selected
  19321. EXPECT_EQ("graphql-ws", client.subprotocol());
  19322. client.close();
  19323. }
  19324. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19325. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19326. ws::WebSocketClient client(
  19327. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19328. ASSERT_TRUE(client.connect());
  19329. // Server should not have selected any subprotocol
  19330. EXPECT_TRUE(client.subprotocol().empty());
  19331. client.close();
  19332. }
  19333. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19334. // Connect without requesting any subprotocol
  19335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19336. "/ws-subprotocol");
  19337. ASSERT_TRUE(client.connect());
  19338. EXPECT_TRUE(client.subprotocol().empty());
  19339. client.close();
  19340. }
  19341. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19342. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19343. "/ws-echo");
  19344. client.set_tcp_nodelay(true);
  19345. client.set_connection_timeout(3, 0);
  19346. bool socket_options_called = false;
  19347. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19348. ASSERT_TRUE(client.connect());
  19349. ASSERT_TRUE(client.is_open());
  19350. EXPECT_TRUE(socket_options_called);
  19351. ASSERT_TRUE(client.send("hello"));
  19352. std::string msg;
  19353. auto result = client.read(msg);
  19354. EXPECT_EQ(result, ws::ReadResult::Text);
  19355. EXPECT_EQ(msg, "hello");
  19356. client.close();
  19357. }
  19358. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  19359. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19360. "/ws-echo");
  19361. client.set_connection_timeout(std::chrono::seconds(3));
  19362. client.set_write_timeout(std::chrono::seconds(3));
  19363. // A sub-second remainder exercises the seconds/microseconds split.
  19364. client.set_read_timeout(std::chrono::milliseconds(1500));
  19365. ASSERT_TRUE(client.connect());
  19366. auto start = std::chrono::steady_clock::now();
  19367. std::string msg;
  19368. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  19369. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19370. std::chrono::steady_clock::now() - start)
  19371. .count();
  19372. // Above 1s so that dropping the microseconds half of the split fails here.
  19373. // Ignoring the setter altogether would not reach this line at all: a client
  19374. // waits forever by default.
  19375. EXPECT_GE(elapsed, 1400);
  19376. EXPECT_LT(elapsed, 30000);
  19377. }
  19378. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  19379. Server svr;
  19380. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  19381. if (!req.has_header("Authorization")) {
  19382. res.status = StatusCode::Unauthorized_401;
  19383. res.set_content("Unauthorized", "text/plain");
  19384. return Server::HandlerResponse::Handled;
  19385. }
  19386. return Server::HandlerResponse::Unhandled;
  19387. });
  19388. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19389. std::string msg;
  19390. while (ws.read(msg)) {
  19391. ws.send(msg);
  19392. }
  19393. });
  19394. auto port = svr.bind_to_any_port("localhost");
  19395. std::thread t([&]() { svr.listen_after_bind(); });
  19396. svr.wait_until_ready();
  19397. // Without Authorization header - should be rejected before upgrade
  19398. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  19399. EXPECT_FALSE(client1.connect());
  19400. // With Authorization header - should succeed
  19401. Headers headers = {{"Authorization", "Bearer token123"}};
  19402. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  19403. headers);
  19404. ASSERT_TRUE(client2.connect());
  19405. ASSERT_TRUE(client2.send("hello"));
  19406. std::string msg;
  19407. ASSERT_TRUE(client2.read(msg));
  19408. EXPECT_EQ("hello", msg);
  19409. client2.close();
  19410. svr.stop();
  19411. t.join();
  19412. }
  19413. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  19414. Server svr;
  19415. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19416. // A read timeout is how a handler gets control back. Without it, a handler
  19417. // parked in read() can never write on the connection it is reading.
  19418. ws.set_read_timeout(std::chrono::milliseconds(100));
  19419. std::string msg;
  19420. while (ws.is_open()) {
  19421. auto r = ws.read(msg);
  19422. if (r == httplib::ws::Timeout) {
  19423. ws.send("tick");
  19424. continue;
  19425. }
  19426. if (r == httplib::ws::Fail) { break; }
  19427. ws.send(msg);
  19428. }
  19429. });
  19430. auto port = svr.bind_to_any_port("localhost");
  19431. std::thread t([&]() { svr.listen_after_bind(); });
  19432. svr.wait_until_ready();
  19433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19434. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  19435. ASSERT_TRUE(client.connect());
  19436. // The client sends nothing, so anything it receives came out of the
  19437. // handler's timeout path.
  19438. std::string msg;
  19439. ASSERT_EQ(client.read(msg), ws::Text);
  19440. EXPECT_EQ("tick", msg);
  19441. client.close();
  19442. svr.stop();
  19443. t.join();
  19444. }
  19445. // Stream::read may return fewer bytes than asked for. This is that contract at
  19446. // its worst -- one byte per call -- which is what a frame header straddling a
  19447. // read buffer's boundary looks like to the frame parser.
  19448. class WsByteAtATimeStream : public Stream {
  19449. public:
  19450. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  19451. bool is_readable() const override { return true; }
  19452. bool wait_readable() const override { return true; }
  19453. bool wait_writable() const override { return true; }
  19454. ssize_t read(char *ptr, size_t size) override {
  19455. if (size == 0 || pos_ >= data_.size()) { return 0; }
  19456. *ptr = data_[pos_++];
  19457. return 1;
  19458. }
  19459. ssize_t write(const char *, size_t size) override {
  19460. return static_cast<ssize_t>(size);
  19461. }
  19462. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19463. ip = "127.0.0.1";
  19464. port = 0;
  19465. }
  19466. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19467. ip = "127.0.0.1";
  19468. port = 0;
  19469. }
  19470. socket_t socket() const override { return INVALID_SOCKET; }
  19471. time_t duration() const override { return 0; }
  19472. private:
  19473. std::string data_;
  19474. size_t pos_ = 0;
  19475. };
  19476. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  19477. // A 200-byte payload uses the 16-bit extended length, so the header, the
  19478. // length and the mask key are all multi-byte fields here. Each used to be
  19479. // read with a single read() call, which fails as soon as one is split.
  19480. std::string body(200, 'x');
  19481. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  19482. std::string frame;
  19483. frame += static_cast<char>(0x81); // FIN + Text
  19484. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  19485. frame += static_cast<char>(body.size() >> 8);
  19486. frame += static_cast<char>(body.size() & 0xff);
  19487. for (size_t i = 0; i < 4; i++) {
  19488. frame += static_cast<char>(mask[i]);
  19489. }
  19490. for (size_t i = 0; i < body.size(); i++) {
  19491. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  19492. }
  19493. WsByteAtATimeStream strm(frame);
  19494. ws::Opcode opcode;
  19495. std::string payload;
  19496. bool fin = false;
  19497. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  19498. /*expect_masked=*/true, 1024),
  19499. ws::impl::FrameRead::Ok);
  19500. EXPECT_TRUE(fin);
  19501. EXPECT_EQ(opcode, ws::Opcode::Text);
  19502. EXPECT_EQ(payload, body);
  19503. }
  19504. TEST(WebSocketTest, QueryStringInHandshake) {
  19505. Server svr;
  19506. std::mutex mtx;
  19507. std::string received_target;
  19508. std::string received_token;
  19509. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19510. {
  19511. std::lock_guard<std::mutex> lock(mtx);
  19512. received_target = req.target;
  19513. if (req.has_param("token")) {
  19514. received_token = req.get_param_value("token");
  19515. }
  19516. }
  19517. std::string msg;
  19518. while (ws.read(msg)) {
  19519. ws.send(msg);
  19520. }
  19521. });
  19522. auto port = svr.bind_to_any_port("localhost");
  19523. std::thread t([&]() { svr.listen_after_bind(); });
  19524. svr.wait_until_ready();
  19525. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  19526. "/ws?token=ABC&session=123");
  19527. ASSERT_TRUE(client.connect());
  19528. // Round-trip ensures the handler has run and captured the request.
  19529. ASSERT_TRUE(client.send("hello"));
  19530. std::string msg;
  19531. ASSERT_TRUE(client.read(msg));
  19532. EXPECT_EQ("hello", msg);
  19533. client.close();
  19534. {
  19535. std::lock_guard<std::mutex> lock(mtx);
  19536. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  19537. EXPECT_EQ("ABC", received_token);
  19538. }
  19539. svr.stop();
  19540. t.join();
  19541. }
  19542. // Run a handshake against a throwaway server and hand the request the server
  19543. // received back to the caller, so tests can assert on the headers the client
  19544. // actually put on the wire.
  19545. static void capture_websocket_handshake_request(
  19546. const Headers &client_headers,
  19547. std::function<void(const Request &, int port)> verify) {
  19548. Server svr;
  19549. std::mutex mtx;
  19550. Request received;
  19551. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19552. {
  19553. std::lock_guard<std::mutex> lock(mtx);
  19554. received = req;
  19555. }
  19556. std::string msg;
  19557. while (ws.read(msg)) {
  19558. ws.send(msg);
  19559. }
  19560. });
  19561. auto port = svr.bind_to_any_port("localhost");
  19562. std::thread t([&]() { svr.listen_after_bind(); });
  19563. auto se = detail::scope_exit([&] {
  19564. svr.stop();
  19565. t.join();
  19566. });
  19567. svr.wait_until_ready();
  19568. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  19569. client_headers);
  19570. ASSERT_TRUE(client.connect());
  19571. ASSERT_TRUE(client.send("hello"));
  19572. std::string msg;
  19573. ASSERT_TRUE(client.read(msg));
  19574. client.close();
  19575. {
  19576. std::lock_guard<std::mutex> lock(mtx);
  19577. verify(received, port);
  19578. }
  19579. }
  19580. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  19581. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  19582. // Non-default port must be present in the Host header. Default ports
  19583. // (80/443) are omitted; that logic is covered by
  19584. // MakeHostAndPortStringTest.
  19585. EXPECT_EQ("localhost:" + std::to_string(port),
  19586. req.get_header_value("Host"));
  19587. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  19588. req.get_header_value("User-Agent"));
  19589. EXPECT_FALSE(req.has_header("Accept"));
  19590. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  19591. EXPECT_FALSE(req.has_header("Content-Length"));
  19592. });
  19593. }
  19594. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  19595. capture_websocket_handshake_request(
  19596. {{"Host", "example.com"},
  19597. {"User-Agent", "custom-agent"},
  19598. {"X-Custom", "value"}},
  19599. [](const Request &req, int) {
  19600. EXPECT_EQ("example.com", req.get_header_value("Host"));
  19601. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  19602. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  19603. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  19604. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  19605. });
  19606. }
  19607. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  19608. capture_websocket_handshake_request(
  19609. {{"Upgrade", "bogus"},
  19610. {"Connection", "close"},
  19611. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  19612. {"Sec-WebSocket-Version", "8"}},
  19613. [](const Request &req, int) {
  19614. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  19615. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  19616. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  19617. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  19618. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  19619. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  19620. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  19621. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  19622. req.get_header_value("Sec-WebSocket-Key"));
  19623. });
  19624. }
  19625. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  19626. // A header the client refuses to send must abort the handshake before any
  19627. // part of it reaches the wire; a lone request line would otherwise sit in
  19628. // the peer's buffer as a truncated request.
  19629. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19630. ASSERT_NE(INVALID_SOCKET, srv);
  19631. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  19632. sockaddr_in addr{};
  19633. addr.sin_family = AF_INET;
  19634. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  19635. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19636. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19637. ASSERT_EQ(0, ::listen(srv, 1));
  19638. sockaddr_in bound{};
  19639. socklen_t bound_len = sizeof(bound);
  19640. ASSERT_EQ(
  19641. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  19642. auto port = ntohs(bound.sin_port);
  19643. ssize_t received = -1;
  19644. std::thread t([&] {
  19645. // Bound every blocking call so a regression fails the test with a bad
  19646. // value instead of hanging the suite.
  19647. fd_set rfds;
  19648. FD_ZERO(&rfds);
  19649. FD_SET(srv, &rfds);
  19650. timeval tv{5, 0};
  19651. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  19652. 0) {
  19653. return;
  19654. }
  19655. sockaddr_in cli_addr{};
  19656. socklen_t cli_len = sizeof(cli_addr);
  19657. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19658. if (cli == INVALID_SOCKET) { return; }
  19659. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  19660. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19661. char buf[4096];
  19662. received = ::recv(cli, buf, sizeof(buf), 0);
  19663. });
  19664. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  19665. // connect() has already shut the socket down by the time it returns false,
  19666. // so the peer sees EOF without waiting for the client to be destroyed.
  19667. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  19668. {{"X-Bad", "a\r\nInjected: 1"}});
  19669. EXPECT_FALSE(client.connect());
  19670. t.join();
  19671. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  19672. EXPECT_EQ(0, received);
  19673. }
  19674. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  19675. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  19676. // contains "upgrade" as a substring is a different token and must not
  19677. // start a WebSocket handshake.
  19678. auto make_request = [](const std::vector<std::string> &connection_values) {
  19679. Request req;
  19680. req.method = "GET";
  19681. req.headers.emplace("Upgrade", "websocket");
  19682. for (const auto &value : connection_values) {
  19683. req.headers.emplace("Connection", value);
  19684. }
  19685. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19686. req.headers.emplace("Sec-WebSocket-Version", "13");
  19687. return req;
  19688. };
  19689. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  19690. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  19691. EXPECT_TRUE(
  19692. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  19693. EXPECT_TRUE(
  19694. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  19695. EXPECT_TRUE(
  19696. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  19697. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  19698. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  19699. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  19700. EXPECT_FALSE(
  19701. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  19702. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  19703. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19704. }
  19705. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  19706. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  19707. // asks recipients to match each protocol-name case-insensitively, and RFC
  19708. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  19709. // client naming websocket alongside another protocol, or on a second field
  19710. // line, is offering websocket; a value that merely contains "websocket" as a
  19711. // substring is a different protocol name and is not.
  19712. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  19713. Request req;
  19714. req.method = "GET";
  19715. for (const auto &value : upgrade_values) {
  19716. req.headers.emplace("Upgrade", value);
  19717. }
  19718. req.headers.emplace("Connection", "Upgrade");
  19719. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  19720. req.headers.emplace("Sec-WebSocket-Version", "13");
  19721. return req;
  19722. };
  19723. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  19724. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  19725. EXPECT_TRUE(
  19726. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  19727. EXPECT_TRUE(
  19728. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  19729. EXPECT_TRUE(
  19730. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  19731. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  19732. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  19733. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  19734. EXPECT_FALSE(
  19735. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  19736. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  19737. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  19738. }
  19739. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  19740. Server svr;
  19741. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  19742. auto port = svr.bind_to_any_port("localhost");
  19743. std::thread t([&]() { svr.listen_after_bind(); });
  19744. auto se = detail::scope_exit([&] {
  19745. svr.stop();
  19746. t.join();
  19747. });
  19748. svr.wait_until_ready();
  19749. Headers headers = {{"Upgrade", "websocket"},
  19750. {"Connection", "notupgrade"},
  19751. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  19752. {"Sec-WebSocket-Version", "13"}};
  19753. Client cli("localhost", port);
  19754. auto res = cli.Get("/ws", headers);
  19755. // The route exists only as a WebSocket route, so a request that fails the
  19756. // handshake check falls through to ordinary routing.
  19757. ASSERT_TRUE(res);
  19758. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  19759. }
  19760. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  19761. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  19762. // Connection value is the only thing left for the client to reject.
  19763. Server svr;
  19764. svr.Get("/ws", [](const Request &req, Response &res) {
  19765. res.status = StatusCode::SwitchingProtocol_101;
  19766. res.set_header("Upgrade", "websocket");
  19767. res.set_header("Connection", "notupgrade");
  19768. res.set_header("Sec-WebSocket-Accept",
  19769. detail::websocket_accept_key(
  19770. req.get_header_value("Sec-WebSocket-Key")));
  19771. });
  19772. auto port = svr.bind_to_any_port("localhost");
  19773. std::thread t([&]() { svr.listen_after_bind(); });
  19774. auto se = detail::scope_exit([&] {
  19775. svr.stop();
  19776. t.join();
  19777. });
  19778. svr.wait_until_ready();
  19779. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19780. auto res = client.connect();
  19781. EXPECT_FALSE(res);
  19782. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19783. EXPECT_FALSE(client.is_open());
  19784. }
  19785. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  19786. // The socket path doubles as the URL host, so it must not contain '/'.
  19787. const char *shard = getenv("GTEST_SHARD_INDEX");
  19788. const std::string sock_path =
  19789. shard ? std::string("httplib-ws-") + shard + ".sock"
  19790. : std::string("httplib-ws.sock");
  19791. std::remove(sock_path.c_str());
  19792. Server svr;
  19793. std::mutex mtx;
  19794. std::string received_host;
  19795. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19796. {
  19797. std::lock_guard<std::mutex> lock(mtx);
  19798. received_host = req.get_header_value("Host");
  19799. }
  19800. std::string msg;
  19801. while (ws.read(msg)) {
  19802. ws.send(msg);
  19803. }
  19804. });
  19805. svr.set_address_family(AF_UNIX);
  19806. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  19807. auto se = detail::scope_exit([&] {
  19808. svr.stop();
  19809. t.join();
  19810. std::remove(sock_path.c_str());
  19811. });
  19812. svr.wait_until_ready();
  19813. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  19814. client.set_address_family(AF_UNIX);
  19815. ASSERT_TRUE(client.connect());
  19816. ASSERT_TRUE(client.send("hello"));
  19817. std::string msg;
  19818. ASSERT_TRUE(client.read(msg));
  19819. client.close();
  19820. {
  19821. std::lock_guard<std::mutex> lock(mtx);
  19822. // There is no host:port for a Unix socket, so the same "localhost"
  19823. // placeholder the HTTP client uses is expected.
  19824. EXPECT_EQ("localhost", received_host);
  19825. }
  19826. }
  19827. // Two threads must never parse WebSocket frames from the same stream.
  19828. // close() used to read the peer's Close reply with its own frame read, so it
  19829. // raced a reader thread that was in the middle of a payload: the payload loop
  19830. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  19831. // so bytes taken by close() were replaced with bytes from further along the
  19832. // stream. The message kept its length and silently changed content.
  19833. //
  19834. // The raw peer below sends a frame header plus part of the payload, waits for
  19835. // the handler to call close(), and only then sends the rest. Whichever thread
  19836. // would win the race for those bytes, the message must arrive intact, because
  19837. // close() must not touch the stream while read() owns it.
  19838. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  19839. #ifndef _WIN32
  19840. signal(SIGPIPE, SIG_IGN);
  19841. #endif
  19842. const size_t payload_len = 120; // fits the 7-bit length field
  19843. const size_t prefix_len = 8;
  19844. const int attempts = 8;
  19845. std::string expected(payload_len, '\0');
  19846. for (size_t i = 0; i < payload_len; i++) {
  19847. expected[i] = static_cast<char>('a' + i % 26);
  19848. }
  19849. std::atomic<bool> peer_stalled{false};
  19850. std::atomic<bool> handler_done{false};
  19851. std::mutex received_mutex;
  19852. std::vector<std::string> received;
  19853. // Bound every wait, so a regression fails the test instead of hanging the
  19854. // suite.
  19855. auto wait_for = [](const std::atomic<bool> &flag) {
  19856. for (int i = 0; i < 500 && !flag; i++) {
  19857. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19858. }
  19859. };
  19860. Server svr;
  19861. svr.set_websocket_ping_interval(0);
  19862. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  19863. std::thread reader([&]() {
  19864. std::string msg;
  19865. while (ws.read(msg)) {
  19866. std::lock_guard<std::mutex> guard(received_mutex);
  19867. received.push_back(msg);
  19868. }
  19869. });
  19870. // Wait until the peer stalls mid-payload, so the reader thread is parked
  19871. // inside read_websocket_frame() when close() runs.
  19872. wait_for(peer_stalled);
  19873. ws.close();
  19874. reader.join();
  19875. handler_done = true;
  19876. });
  19877. auto port = svr.bind_to_any_port("127.0.0.1");
  19878. std::thread t([&]() { svr.listen_after_bind(); });
  19879. auto se = detail::scope_exit([&] {
  19880. svr.stop();
  19881. t.join();
  19882. });
  19883. svr.wait_until_ready();
  19884. auto send_bytes = [](socket_t s, const std::string &data) {
  19885. #ifdef _WIN32
  19886. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  19887. #else
  19888. auto n = ::send(s, data.data(), data.size(), 0);
  19889. #endif
  19890. return n == static_cast<decltype(n)>(data.size());
  19891. };
  19892. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  19893. // Every length used here fits the 7-bit length field.
  19894. auto masked_header = [](uint8_t first_byte, size_t len) {
  19895. std::string h;
  19896. h += static_cast<char>(first_byte);
  19897. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  19898. h.append(4, '\0'); // mask key
  19899. return h;
  19900. };
  19901. for (int attempt = 0; attempt < attempts; attempt++) {
  19902. peer_stalled = false;
  19903. handler_done = false;
  19904. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  19905. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  19906. auto se_sock = detail::scope_exit([&] {
  19907. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  19908. });
  19909. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19910. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19911. sockaddr_in addr{};
  19912. addr.sin_family = AF_INET;
  19913. addr.sin_port = htons(static_cast<uint16_t>(port));
  19914. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19915. ASSERT_EQ(
  19916. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  19917. << "attempt " << attempt;
  19918. ASSERT_TRUE(send_bytes(sock,
  19919. "GET /ws HTTP/1.1\r\n"
  19920. "Host: 127.0.0.1\r\n"
  19921. "Upgrade: websocket\r\n"
  19922. "Connection: Upgrade\r\n"
  19923. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  19924. "Sec-WebSocket-Version: 13\r\n"
  19925. "\r\n"))
  19926. << "attempt " << attempt;
  19927. std::string response;
  19928. while (response.find("\r\n\r\n") == std::string::npos) {
  19929. char buf[512];
  19930. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  19931. if (n <= 0) { break; }
  19932. response.append(buf, static_cast<size_t>(n));
  19933. }
  19934. ASSERT_NE(std::string::npos, response.find(" 101 "))
  19935. << "attempt " << attempt;
  19936. // Send the header of a Binary message but only the first prefix_len bytes
  19937. // of its payload, leaving the reader thread stalled inside the payload.
  19938. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  19939. expected.substr(0, prefix_len)))
  19940. << "attempt " << attempt;
  19941. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19942. peer_stalled = true;
  19943. // Let close() send its Close frame and park in its own read before the
  19944. // rest of the payload arrives, so both threads are waiting for it.
  19945. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19946. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  19947. close_frame += static_cast<char>(0x03); // status 1000
  19948. close_frame += static_cast<char>(0xE8);
  19949. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  19950. << "attempt " << attempt;
  19951. // Closing the peer releases the reader thread even on the buggy path,
  19952. // where it waits for bytes another thread already consumed.
  19953. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19954. detail::close_socket(sock);
  19955. sock = INVALID_SOCKET;
  19956. wait_for(handler_done);
  19957. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  19958. }
  19959. std::lock_guard<std::mutex> guard(received_mutex);
  19960. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  19961. << "a message in flight when close() ran was dropped";
  19962. for (size_t i = 0; i < received.size(); i++) {
  19963. EXPECT_EQ(expected, received[i]) << "message " << i;
  19964. }
  19965. }
  19966. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19967. class WebSocketSSLIntegrationTest : public ::testing::Test {
  19968. protected:
  19969. void SetUp() override {
  19970. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  19971. SERVER_PRIVATE_KEY_FILE);
  19972. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19973. std::string msg;
  19974. ws::ReadResult ret;
  19975. while ((ret = ws.read(msg))) {
  19976. if (ret == ws::Binary) {
  19977. ws.send(msg.data(), msg.size());
  19978. } else {
  19979. ws.send(msg);
  19980. }
  19981. }
  19982. });
  19983. port_ = server_->bind_to_any_port(HOST);
  19984. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19985. server_->wait_until_ready();
  19986. }
  19987. void TearDown() override {
  19988. server_->stop();
  19989. if (server_thread_.joinable()) { server_thread_.join(); }
  19990. }
  19991. std::unique_ptr<SSLServer> server_;
  19992. std::thread server_thread_;
  19993. int port_ = 0;
  19994. };
  19995. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  19996. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  19997. "/ws-echo");
  19998. client.enable_server_certificate_verification(false);
  19999. ASSERT_TRUE(client.connect());
  20000. ASSERT_TRUE(client.is_open());
  20001. ASSERT_TRUE(client.send("Hello WSS"));
  20002. std::string msg;
  20003. EXPECT_EQ(ws::Text, client.read(msg));
  20004. EXPECT_EQ("Hello WSS", msg);
  20005. client.close();
  20006. }
  20007. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20008. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20009. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20010. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20011. // client (without calling close() first) is the only path that runs
  20012. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20013. // bug exactly.
  20014. //
  20015. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20016. // when linked against an instrumented libssl; run under Valgrind to catch it
  20017. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20018. // suite (the freed session otherwise stalls on the close handshake) — this test
  20019. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20020. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20021. {
  20022. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20023. "/ws-echo");
  20024. client.enable_server_certificate_verification(false);
  20025. client.set_read_timeout(2, 0);
  20026. client.set_write_timeout(2, 0);
  20027. ASSERT_TRUE(client.connect());
  20028. ASSERT_TRUE(client.is_open());
  20029. ASSERT_TRUE(client.send("still open"));
  20030. // Intentionally do NOT call client.close(): leaving scope runs
  20031. // shutdown_and_close() with the WebSocket still open, which must send the
  20032. // close frame while the TLS session is still alive.
  20033. }
  20034. }
  20035. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20036. // shutdown_and_close() at the start of connect(), reproducing the same
  20037. // use-after-free within the test body rather than at scope exit. The second
  20038. // connect must succeed and echo, proving the close handshake ran over a live
  20039. // session. See the note above about memory-tool requirements.
  20040. TEST_F(WebSocketSSLIntegrationTest,
  20041. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20042. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20043. "/ws-echo");
  20044. client.enable_server_certificate_verification(false);
  20045. client.set_read_timeout(2, 0);
  20046. client.set_write_timeout(2, 0);
  20047. ASSERT_TRUE(client.connect());
  20048. ASSERT_TRUE(client.is_open());
  20049. ASSERT_TRUE(client.send("still open"));
  20050. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20051. // the still-open connection, which must not touch a freed TLS session.
  20052. ASSERT_TRUE(client.connect());
  20053. ASSERT_TRUE(client.is_open());
  20054. ASSERT_TRUE(client.send("after reconnect"));
  20055. std::string msg;
  20056. EXPECT_EQ(ws::Text, client.read(msg));
  20057. EXPECT_EQ("after reconnect", msg);
  20058. client.close();
  20059. }
  20060. #endif
  20061. #ifdef CPPHTTPLIB_SSL_ENABLED
  20062. class WebSocketSSLCATest : public ::testing::Test {
  20063. protected:
  20064. void SetUp() override {
  20065. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20066. SERVER_PRIVATE_KEY_FILE);
  20067. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20068. std::string msg;
  20069. while (ws.read(msg)) {
  20070. ws.send(msg);
  20071. }
  20072. });
  20073. port_ = server_->bind_to_any_port("127.0.0.1");
  20074. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20075. server_->wait_until_ready();
  20076. }
  20077. void TearDown() override {
  20078. server_->stop();
  20079. if (server_thread_.joinable()) { server_thread_.join(); }
  20080. }
  20081. std::string url() const {
  20082. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20083. }
  20084. std::unique_ptr<SSLServer> server_;
  20085. std::thread server_thread_;
  20086. int port_ = 0;
  20087. };
  20088. // A custom CA loaded as PEM verifies the server with full certificate
  20089. // verification enabled
  20090. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20091. ws::WebSocketClient client(url());
  20092. std::string cert;
  20093. read_file(SERVER_CERT2_FILE, cert);
  20094. client.load_ca_cert_store(cert.c_str(), cert.size());
  20095. ASSERT_TRUE(client.connect());
  20096. ASSERT_TRUE(client.send("hello"));
  20097. std::string msg;
  20098. EXPECT_EQ(ws::Text, client.read(msg));
  20099. EXPECT_EQ("hello", msg);
  20100. client.close();
  20101. }
  20102. // A custom CA that does not cover the server must fail verification (the
  20103. // custom CA is exclusive; system certs are not loaded alongside it)
  20104. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20105. ws::WebSocketClient client(url());
  20106. std::string cert;
  20107. read_file(CLIENT_CA_CERT_FILE, cert);
  20108. client.load_ca_cert_store(cert.c_str(), cert.size());
  20109. auto res = client.connect();
  20110. ASSERT_FALSE(res);
  20111. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20112. EXPECT_EQ(-1, res.status());
  20113. EXPECT_NE(0u, res.ssl_backend_error());
  20114. }
  20115. // The same CA as a file path rather than PEM in memory
  20116. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20117. ws::WebSocketClient client(url());
  20118. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20119. ASSERT_TRUE(client.connect());
  20120. ASSERT_TRUE(client.send("hello"));
  20121. std::string msg;
  20122. EXPECT_EQ(ws::Text, client.read(msg));
  20123. EXPECT_EQ("hello", msg);
  20124. client.close();
  20125. }
  20126. // ...and a CA file that does not cover the server still fails, so it is the
  20127. // path above that decides the outcome
  20128. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20129. ws::WebSocketClient client(url());
  20130. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20131. ASSERT_FALSE(client.connect());
  20132. }
  20133. // Regression test: reconnecting with a native custom CA store used to reuse
  20134. // a store handle the previous TLS context had already freed (use-after-free
  20135. // under the OpenSSL backend). The context now lives as long as the client.
  20136. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20137. ws::WebSocketClient client(url());
  20138. std::string cert;
  20139. read_file(SERVER_CERT2_FILE, cert);
  20140. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20141. ASSERT_TRUE(client.connect());
  20142. client.close();
  20143. ASSERT_TRUE(client.connect());
  20144. ASSERT_TRUE(client.send("again"));
  20145. std::string msg;
  20146. EXPECT_EQ(ws::Text, client.read(msg));
  20147. EXPECT_EQ("again", msg);
  20148. client.close();
  20149. }
  20150. // Regression test: a certificate with a trusted chain but no identity match
  20151. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20152. // verification entirely for IP hosts, so this connection succeeded there.
  20153. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20154. // chain verification while the identity check must still fail.
  20155. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20157. ASSERT_TRUE(svr.is_valid());
  20158. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20159. std::string msg;
  20160. while (ws.read(msg)) {
  20161. ws.send(msg);
  20162. }
  20163. });
  20164. auto port = svr.bind_to_any_port("127.0.0.1");
  20165. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20166. auto se = detail::scope_exit([&] {
  20167. svr.stop();
  20168. t.join();
  20169. });
  20170. svr.wait_until_ready();
  20171. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20172. "/echo");
  20173. std::string cert;
  20174. read_file(SERVER_CERT_FILE, cert);
  20175. client.load_ca_cert_store(cert.c_str(), cert.size());
  20176. ASSERT_FALSE(client.connect());
  20177. }
  20178. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20179. // SNI, so nothing binds the host name to the TLS session. These bind the
  20180. // server to "localhost" instead, the only shape that exercises the SNI and
  20181. // hostname-verification path with certificate verification left enabled.
  20182. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20183. protected:
  20184. void Start(const char *cert_file) {
  20185. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20186. SERVER_PRIVATE_KEY_FILE);
  20187. ASSERT_TRUE(server_->is_valid());
  20188. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20189. std::string msg;
  20190. while (ws.read(msg)) {
  20191. ws.send(msg);
  20192. }
  20193. });
  20194. port_ = server_->bind_to_any_port("localhost");
  20195. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20196. server_->wait_until_ready();
  20197. }
  20198. void TearDown() override {
  20199. if (server_) { server_->stop(); }
  20200. if (server_thread_.joinable()) { server_thread_.join(); }
  20201. }
  20202. std::string url() const {
  20203. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20204. }
  20205. std::unique_ptr<SSLServer> server_;
  20206. std::thread server_thread_;
  20207. int port_ = 0;
  20208. };
  20209. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  20210. // out and the connection is usable
  20211. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  20212. Start(SERVER_CERT2_FILE);
  20213. ws::WebSocketClient client(url());
  20214. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20215. ASSERT_TRUE(client.connect());
  20216. ASSERT_TRUE(client.send("hello"));
  20217. std::string msg;
  20218. EXPECT_EQ(ws::Text, client.read(msg));
  20219. EXPECT_EQ("hello", msg);
  20220. client.close();
  20221. }
  20222. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  20223. // while the identity check must still reject "localhost"
  20224. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  20225. Start(SERVER_CERT_FILE);
  20226. ws::WebSocketClient client(url());
  20227. client.set_ca_cert_path(SERVER_CERT_FILE);
  20228. auto res = client.connect();
  20229. ASSERT_FALSE(res);
  20230. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  20231. EXPECT_EQ(-1, res.status());
  20232. }
  20233. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  20234. // disabled: the chain is still checked, only the identity check is skipped
  20235. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  20236. Start(SERVER_CERT_FILE);
  20237. ws::WebSocketClient client(url());
  20238. client.set_ca_cert_path(SERVER_CERT_FILE);
  20239. client.enable_server_hostname_verification(false);
  20240. ASSERT_TRUE(client.connect());
  20241. ASSERT_TRUE(client.send("hello"));
  20242. std::string msg;
  20243. EXPECT_EQ(ws::Text, client.read(msg));
  20244. EXPECT_EQ("hello", msg);
  20245. client.close();
  20246. }
  20247. // A CA that did not sign the server certificate fails the chain, even though
  20248. // the name would match
  20249. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  20250. Start(SERVER_CERT2_FILE);
  20251. ws::WebSocketClient client(url());
  20252. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20253. ASSERT_FALSE(client.connect());
  20254. }
  20255. // With verification disabled, neither the chain nor the name is checked
  20256. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  20257. Start(SERVER_CERT_FILE);
  20258. ws::WebSocketClient client(url());
  20259. client.enable_server_certificate_verification(false);
  20260. ASSERT_TRUE(client.connect());
  20261. ASSERT_TRUE(client.send("hello"));
  20262. std::string msg;
  20263. EXPECT_EQ(ws::Text, client.read(msg));
  20264. EXPECT_EQ("hello", msg);
  20265. client.close();
  20266. }
  20267. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  20268. protected:
  20269. void SetUp() override {
  20270. server_ = httplib::detail::make_unique<SSLServer>(
  20271. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20272. ASSERT_TRUE(server_->is_valid());
  20273. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20274. std::string msg;
  20275. while (ws.read(msg)) {
  20276. ws.send(msg);
  20277. }
  20278. });
  20279. port_ = server_->bind_to_any_port("localhost");
  20280. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20281. server_->wait_until_ready();
  20282. }
  20283. void TearDown() override {
  20284. server_->stop();
  20285. if (server_thread_.joinable()) { server_thread_.join(); }
  20286. }
  20287. std::string url() const {
  20288. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  20289. }
  20290. void ConnectWithClientCert(const std::string &client_cert_file,
  20291. const std::string &client_private_key_file,
  20292. const char *private_key_password) {
  20293. std::string cert_pem, key_pem;
  20294. read_file(client_cert_file, cert_pem);
  20295. read_file(client_private_key_file, key_pem);
  20296. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  20297. key_pem.c_str(), key_pem.size(),
  20298. private_key_password};
  20299. ws::WebSocketClient client(url(), pem);
  20300. ASSERT_TRUE(client.is_valid());
  20301. client.enable_server_certificate_verification(false);
  20302. ASSERT_TRUE(client.connect());
  20303. ASSERT_TRUE(client.send("hello"));
  20304. std::string msg;
  20305. EXPECT_EQ(ws::Text, client.read(msg));
  20306. EXPECT_EQ("hello", msg);
  20307. client.close();
  20308. }
  20309. std::unique_ptr<SSLServer> server_;
  20310. std::thread server_thread_;
  20311. int port_ = 0;
  20312. };
  20313. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  20314. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  20315. }
  20316. // Control for the tests above: the fixture's server really does require a
  20317. // client certificate, so it is the PEM the constructor installed that decides
  20318. // the outcome.
  20319. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  20320. ws::WebSocketClient client(url());
  20321. ASSERT_TRUE(client.is_valid());
  20322. client.enable_server_certificate_verification(false);
  20323. EXPECT_FALSE(client.connect());
  20324. }
  20325. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  20326. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  20327. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  20328. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  20329. }
  20330. #endif
  20331. #if !defined(_WIN32)
  20332. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  20333. auto secret_dir = std::string("./symlink_test_secret");
  20334. auto served_dir = std::string("./symlink_test_served");
  20335. auto secret_file = secret_dir + "/secret.txt";
  20336. auto symlink_path = served_dir + "/escape";
  20337. // Setup: create directories and files
  20338. mkdir(secret_dir.c_str(), 0755);
  20339. mkdir(served_dir.c_str(), 0755);
  20340. {
  20341. std::ofstream ofs(secret_file);
  20342. ofs << "SECRET_DATA";
  20343. }
  20344. // Create symlink using absolute path so it resolves correctly
  20345. #ifdef PATH_MAX
  20346. char abs_secret[PATH_MAX];
  20347. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  20348. #else
  20349. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  20350. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  20351. ASSERT_NE(nullptr, abs_secret);
  20352. #endif
  20353. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  20354. auto se = detail::scope_exit([&] {
  20355. unlink(symlink_path.c_str());
  20356. unlink(secret_file.c_str());
  20357. rmdir(served_dir.c_str());
  20358. rmdir(secret_dir.c_str());
  20359. });
  20360. Server svr;
  20361. svr.set_mount_point("/", served_dir);
  20362. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  20363. auto se2 = detail::scope_exit([&] {
  20364. svr.stop();
  20365. listen_thread.join();
  20366. });
  20367. svr.wait_until_ready();
  20368. Client cli("localhost", PORT);
  20369. // Symlink pointing outside base dir should be blocked
  20370. auto res = cli.Get("/escape/secret.txt");
  20371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20372. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  20373. }
  20374. #endif
  20375. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  20376. // A GET request with Content-Length to a static file handler must have its
  20377. // body drained before the keep-alive connection is reused. Otherwise the
  20378. // unread body bytes are interpreted as the next HTTP request.
  20379. //
  20380. // The body is sent AFTER receiving the first response (as in the original
  20381. // PoC) so that the stream_line_reader cannot buffer it together with the
  20382. // headers of the first request.
  20383. Server svr;
  20384. svr.set_mount_point("/", "./www");
  20385. std::atomic<int> smuggled_count(0);
  20386. svr.Get("/smuggled", [&](const Request &, Response &res) {
  20387. smuggled_count++;
  20388. res.set_content("oops", "text/plain");
  20389. });
  20390. auto port = svr.bind_to_any_port("localhost");
  20391. thread t = thread([&] { svr.listen_after_bind(); });
  20392. auto se = detail::scope_exit([&] {
  20393. svr.stop();
  20394. t.join();
  20395. });
  20396. svr.wait_until_ready();
  20397. auto error = Error::Success;
  20398. auto sock = detail::create_client_socket(
  20399. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  20400. /*connection_timeout_sec=*/2, 0,
  20401. /*read_timeout_sec=*/2, 0,
  20402. /*write_timeout_sec=*/2, 0, std::string(), error);
  20403. ASSERT_NE(INVALID_SOCKET, sock);
  20404. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20405. // The "smuggled" request will be sent as the body of the outer GET
  20406. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  20407. "Host: localhost\r\n"
  20408. "Connection: close\r\n"
  20409. "\r\n";
  20410. // Step 1: Send only the outer request headers (no body yet)
  20411. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  20412. "Host: localhost\r\n"
  20413. "Content-Length: " +
  20414. std::to_string(smuggled.size()) +
  20415. "\r\n"
  20416. "\r\n";
  20417. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  20418. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  20419. // Step 2: Read the first response (server serves file without reading body)
  20420. std::string first_response;
  20421. char buf[4096];
  20422. for (;;) {
  20423. auto n = recv(sock, buf, sizeof(buf), 0);
  20424. if (n <= 0) break;
  20425. first_response.append(buf, static_cast<size_t>(n));
  20426. // Stop once we have a complete response (headers + body)
  20427. auto hdr_end = first_response.find("\r\n\r\n");
  20428. if (hdr_end != std::string::npos) {
  20429. // Check for Content-Length to know when the body is complete
  20430. auto cl_pos = first_response.find("Content-Length:");
  20431. if (cl_pos != std::string::npos) {
  20432. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  20433. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  20434. auto cl = std::stoul(
  20435. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  20436. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  20437. } else {
  20438. break; // No Content-Length, assume headers-only response
  20439. }
  20440. }
  20441. }
  20442. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  20443. // Step 3: Now send the body, which looks like a new HTTP request.
  20444. // On a vulnerable server the keep-alive loop reads this as a second request.
  20445. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  20446. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  20447. // Step 4: Try to read a second response (should NOT exist after fix)
  20448. std::string second_response;
  20449. for (;;) {
  20450. auto n = recv(sock, buf, sizeof(buf), 0);
  20451. if (n <= 0) break;
  20452. second_response.append(buf, static_cast<size_t>(n));
  20453. }
  20454. // The smuggled request must NOT have been processed
  20455. EXPECT_EQ(0, smuggled_count.load());
  20456. }
  20457. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20458. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  20459. // must be rejected with 400 Bad Request.
  20460. Server svr;
  20461. svr.Post("/test", [&](const Request &, Response &res) {
  20462. res.set_content("ok", "text/plain");
  20463. });
  20464. thread t = thread([&] { svr.listen(HOST, PORT); });
  20465. auto se = detail::scope_exit([&] {
  20466. svr.stop();
  20467. t.join();
  20468. ASSERT_FALSE(svr.is_running());
  20469. });
  20470. svr.wait_until_ready();
  20471. // Exact "chunked"
  20472. {
  20473. auto req = "POST /test HTTP/1.1\r\n"
  20474. "Host: localhost\r\n"
  20475. "Content-Length: 5\r\n"
  20476. "Transfer-Encoding: chunked\r\n"
  20477. "Connection: close\r\n"
  20478. "\r\n"
  20479. "hello";
  20480. std::string response;
  20481. ASSERT_TRUE(send_request(1, req, &response));
  20482. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20483. response.substr(0, response.find("\r\n")));
  20484. }
  20485. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  20486. {
  20487. auto req = "POST /test HTTP/1.1\r\n"
  20488. "Host: localhost\r\n"
  20489. "Content-Length: 5\r\n"
  20490. "Transfer-Encoding: gzip, chunked\r\n"
  20491. "Connection: close\r\n"
  20492. "\r\n"
  20493. "hello";
  20494. std::string response;
  20495. ASSERT_TRUE(send_request(1, req, &response));
  20496. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20497. response.substr(0, response.find("\r\n")));
  20498. }
  20499. }
  20500. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  20501. Server svr;
  20502. svr.Post("/test", [&](const Request &, Response &res) {
  20503. res.set_content("ok", "text/plain");
  20504. });
  20505. thread t = thread([&] { svr.listen(HOST, PORT); });
  20506. auto se = detail::scope_exit([&] {
  20507. svr.stop();
  20508. t.join();
  20509. ASSERT_FALSE(svr.is_running());
  20510. });
  20511. svr.wait_until_ready();
  20512. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  20513. // length cannot be determined, so the server must answer 400 and close
  20514. // rather than treat the request as bodyless and leave the body in the
  20515. // socket for the next request to pick up.
  20516. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  20517. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  20518. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  20519. std::string response;
  20520. ASSERT_TRUE(send_request(1, req, &response));
  20521. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20522. response.substr(0, response.find("\r\n")))
  20523. << transfer_encoding;
  20524. }
  20525. // RFC 9110 5.3: the codings may also be split across several
  20526. // Transfer-Encoding lines, which combine in the order they were received.
  20527. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  20528. // just like the single-line "chunked, gzip" above.
  20529. {
  20530. auto req = "POST /test HTTP/1.1\r\n"
  20531. "Host: localhost\r\n"
  20532. "Transfer-Encoding: chunked\r\n"
  20533. "Transfer-Encoding: gzip\r\n"
  20534. "\r\n"
  20535. "0\r\n\r\n";
  20536. std::string response;
  20537. ASSERT_TRUE(send_request(1, req, &response));
  20538. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  20539. response.substr(0, response.find("\r\n")));
  20540. }
  20541. // A sequence ending in chunked stays valid.
  20542. auto req = "POST /test HTTP/1.1\r\n"
  20543. "Host: localhost\r\n"
  20544. "Transfer-Encoding: gzip, chunked\r\n"
  20545. "Connection: close\r\n"
  20546. "\r\n"
  20547. "0\r\n\r\n";
  20548. std::string response;
  20549. ASSERT_TRUE(send_request(1, req, &response));
  20550. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  20551. // ...including when it is spread over several lines.
  20552. auto split_req = "POST /test HTTP/1.1\r\n"
  20553. "Host: localhost\r\n"
  20554. "Transfer-Encoding: gzip\r\n"
  20555. "Transfer-Encoding: chunked\r\n"
  20556. "Connection: close\r\n"
  20557. "\r\n"
  20558. "0\r\n\r\n";
  20559. std::string split_response;
  20560. ASSERT_TRUE(send_request(1, split_req, &split_response));
  20561. EXPECT_EQ("HTTP/1.1 200 OK",
  20562. split_response.substr(0, split_response.find("\r\n")));
  20563. }
  20564. // Regression for issue #2450: a DELETE without Content-Length on a
  20565. // keep-alive connection must not let the post-response drain consume the
  20566. // next request's bytes.
  20567. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  20568. Server svr;
  20569. std::atomic<int> delete_count(0);
  20570. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  20571. delete_count++;
  20572. res.status = StatusCode::NoContent_204;
  20573. });
  20574. auto port = svr.bind_to_any_port(HOST);
  20575. thread t = thread([&] { svr.listen_after_bind(); });
  20576. auto se = detail::scope_exit([&] {
  20577. svr.stop();
  20578. t.join();
  20579. });
  20580. svr.wait_until_ready();
  20581. auto error = Error::Success;
  20582. auto sock = detail::create_client_socket(
  20583. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20584. /*connection_timeout_sec=*/2, 0,
  20585. /*read_timeout_sec=*/2, 0,
  20586. /*write_timeout_sec=*/2, 0, std::string(), error);
  20587. ASSERT_NE(INVALID_SOCKET, sock);
  20588. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20589. auto send_request_and_read_response = [&](const std::string &req,
  20590. std::string &out) -> bool {
  20591. auto sent = send(sock, req.data(), req.size(), 0);
  20592. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  20593. char buf[4096];
  20594. for (;;) {
  20595. auto n = recv(sock, buf, sizeof(buf), 0);
  20596. if (n <= 0) { return !out.empty(); }
  20597. out.append(buf, static_cast<size_t>(n));
  20598. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  20599. }
  20600. };
  20601. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  20602. "Host: localhost\r\n"
  20603. "\r\n";
  20604. std::string resp1;
  20605. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  20606. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  20607. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  20608. "Host: localhost\r\n"
  20609. "Connection: close\r\n"
  20610. "\r\n";
  20611. std::string resp2;
  20612. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  20613. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  20614. EXPECT_EQ(2, delete_count.load());
  20615. }
  20616. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  20617. Server svr;
  20618. svr.Post("/ingest", [&](const Request &, Response &res,
  20619. const ContentReader &content_reader) {
  20620. auto consumed = content_reader([](const char *, size_t) { return false; });
  20621. EXPECT_FALSE(consumed);
  20622. res.status = StatusCode::Conflict_409;
  20623. res.set_header("Connection", "close");
  20624. });
  20625. auto port = svr.bind_to_any_port(HOST);
  20626. thread t = thread([&] { svr.listen_after_bind(); });
  20627. auto se = detail::scope_exit([&] {
  20628. svr.stop();
  20629. t.join();
  20630. });
  20631. svr.wait_until_ready();
  20632. auto error = Error::Success;
  20633. auto sock = detail::create_client_socket(
  20634. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20635. /*connection_timeout_sec=*/2, 0,
  20636. /*read_timeout_sec=*/1, 0,
  20637. /*write_timeout_sec=*/2, 0, std::string(), error);
  20638. ASSERT_NE(INVALID_SOCKET, sock);
  20639. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  20640. std::string request = "POST /ingest HTTP/1.1\r\n"
  20641. "Host: localhost\r\n"
  20642. "Transfer-Encoding: chunked\r\n"
  20643. "\r\n"
  20644. "4\r\n"
  20645. "data\r\n";
  20646. auto sent = send(sock, request.data(), request.size(), 0);
  20647. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  20648. std::string response;
  20649. ssize_t received = 0;
  20650. do {
  20651. char buf[4096];
  20652. received = recv(sock, buf, sizeof(buf), 0);
  20653. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  20654. } while (received > 0);
  20655. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  20656. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  20657. EXPECT_EQ(0, received);
  20658. }
  20659. namespace no_proxy_test {
  20660. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  20661. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  20662. // calling listen().
  20663. class ScopedServer {
  20664. public:
  20665. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  20666. ~ScopedServer() {
  20667. svr_.stop();
  20668. if (th_.joinable()) { th_.join(); }
  20669. }
  20670. Server &svr() { return svr_; }
  20671. int port() const { return port_; }
  20672. void listen() {
  20673. th_ = std::thread([this] { svr_.listen_after_bind(); });
  20674. svr_.wait_until_ready();
  20675. }
  20676. private:
  20677. Server svr_;
  20678. std::thread th_;
  20679. int port_ = 0;
  20680. };
  20681. class ProxyAndTargetServers {
  20682. public:
  20683. ProxyAndTargetServers() {
  20684. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  20685. proxy_hits_++;
  20686. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20687. res.set_content("via-proxy", "text/plain");
  20688. });
  20689. target_.Get(".*", [this](const Request &req, Response &res) {
  20690. target_hits_++;
  20691. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  20692. res.set_content("direct", "text/plain");
  20693. });
  20694. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  20695. target_port_ = target_.bind_to_any_port("127.0.0.1");
  20696. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  20697. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  20698. proxy_mock_.wait_until_ready();
  20699. target_.wait_until_ready();
  20700. }
  20701. ~ProxyAndTargetServers() {
  20702. proxy_mock_.stop();
  20703. target_.stop();
  20704. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  20705. if (target_thread_.joinable()) { target_thread_.join(); }
  20706. }
  20707. Server &proxy_mock() { return proxy_mock_; }
  20708. Server &target() { return target_; }
  20709. int proxy_port() const { return proxy_port_; }
  20710. int target_port() const { return target_port_; }
  20711. int proxy_hits() const { return proxy_hits_.load(); }
  20712. int target_hits() const { return target_hits_.load(); }
  20713. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  20714. void reset_counters() {
  20715. proxy_hits_ = 0;
  20716. target_hits_ = 0;
  20717. last_had_proxy_authz_ = false;
  20718. }
  20719. private:
  20720. Server proxy_mock_;
  20721. Server target_;
  20722. std::thread proxy_thread_;
  20723. std::thread target_thread_;
  20724. int proxy_port_ = 0;
  20725. int target_port_ = 0;
  20726. std::atomic<int> proxy_hits_{0};
  20727. std::atomic<int> target_hits_{0};
  20728. std::atomic<bool> last_had_proxy_authz_{false};
  20729. };
  20730. inline std::unique_ptr<Client> make_client(const std::string &host,
  20731. ProxyAndTargetServers &s) {
  20732. auto cli = detail::make_unique<Client>(host, s.target_port());
  20733. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  20734. cli->set_proxy("127.0.0.1", s.proxy_port());
  20735. return cli;
  20736. }
  20737. } // namespace no_proxy_test
  20738. using no_proxy_test::make_client;
  20739. using no_proxy_test::ProxyAndTargetServers;
  20740. TEST(NoProxyTest, ExactHostnameBypasses) {
  20741. ProxyAndTargetServers s;
  20742. auto cli = make_client("example.com", s);
  20743. cli->set_no_proxy({"example.com"});
  20744. auto res = cli->Get("/");
  20745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20746. EXPECT_EQ(0, s.proxy_hits());
  20747. EXPECT_EQ(1, s.target_hits());
  20748. }
  20749. TEST(NoProxyTest, SubdomainBypasses) {
  20750. ProxyAndTargetServers s;
  20751. auto cli = make_client("foo.example.com", s);
  20752. cli->set_no_proxy({"example.com"});
  20753. auto res = cli->Get("/");
  20754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20755. EXPECT_EQ(0, s.proxy_hits());
  20756. EXPECT_EQ(1, s.target_hits());
  20757. }
  20758. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  20759. // Regression guard: "evilexample.com" must not be considered a subdomain
  20760. // of "example.com". Without the dot-boundary rule, a naive endsWith
  20761. // check would let traffic bypass the proxy and leak credentials direct
  20762. // to the attacker host.
  20763. ProxyAndTargetServers s;
  20764. auto cli = make_client("evilexample.com", s);
  20765. cli->set_no_proxy({"example.com"});
  20766. auto res = cli->Get("/");
  20767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20768. EXPECT_GE(s.proxy_hits(), 1);
  20769. EXPECT_EQ(0, s.target_hits());
  20770. }
  20771. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  20772. ProxyAndTargetServers s;
  20773. auto cli = make_client("example.com.evil.com", s);
  20774. cli->set_no_proxy({"example.com"});
  20775. auto res = cli->Get("/");
  20776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20777. EXPECT_GE(s.proxy_hits(), 1);
  20778. EXPECT_EQ(0, s.target_hits());
  20779. }
  20780. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  20781. ProxyAndTargetServers s;
  20782. auto cli = make_client("example.com", s);
  20783. cli->set_no_proxy({".example.com"});
  20784. auto res = cli->Get("/");
  20785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20786. EXPECT_EQ(0, s.proxy_hits());
  20787. EXPECT_EQ(1, s.target_hits());
  20788. }
  20789. TEST(NoProxyTest, CaseInsensitiveHostname) {
  20790. ProxyAndTargetServers s;
  20791. auto cli = make_client("Example.COM", s);
  20792. cli->set_no_proxy({"EXAMPLE.com"});
  20793. auto res = cli->Get("/");
  20794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20795. EXPECT_EQ(0, s.proxy_hits());
  20796. EXPECT_EQ(1, s.target_hits());
  20797. }
  20798. TEST(NoProxyTest, TrailingDotIsNormalized) {
  20799. ProxyAndTargetServers s;
  20800. auto cli = make_client("example.com.", s);
  20801. cli->set_no_proxy({"example.com"});
  20802. auto res = cli->Get("/");
  20803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20804. EXPECT_EQ(0, s.proxy_hits());
  20805. EXPECT_EQ(1, s.target_hits());
  20806. }
  20807. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  20808. // Trailing dots must be normalized on BOTH sides — host and entry.
  20809. // An implementation that only strips the host-side trailing dot would
  20810. // fail to match host "example.com" against entry "example.com." because
  20811. // a literal substring search would compare 11 chars against 12.
  20812. ProxyAndTargetServers s;
  20813. auto cli = make_client("example.com", s);
  20814. cli->set_no_proxy({"example.com."});
  20815. auto res = cli->Get("/");
  20816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20817. EXPECT_EQ(0, s.proxy_hits());
  20818. EXPECT_EQ(1, s.target_hits());
  20819. }
  20820. TEST(NoProxyTest, WildcardBypassesEverything) {
  20821. ProxyAndTargetServers s;
  20822. auto cli = make_client("anything.invalid.test", s);
  20823. cli->set_no_proxy({"*"});
  20824. auto res = cli->Get("/");
  20825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20826. EXPECT_EQ(0, s.proxy_hits());
  20827. EXPECT_EQ(1, s.target_hits());
  20828. }
  20829. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  20830. ProxyAndTargetServers s;
  20831. Client cli("127.0.0.1", s.target_port());
  20832. cli.set_proxy("127.0.0.1", s.proxy_port());
  20833. cli.set_no_proxy({"127.0.0.1"});
  20834. auto res = cli.Get("/");
  20835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20836. EXPECT_EQ(0, s.proxy_hits());
  20837. EXPECT_EQ(1, s.target_hits());
  20838. }
  20839. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  20840. ProxyAndTargetServers s;
  20841. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  20842. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  20843. cli.set_proxy("127.0.0.1", s.proxy_port());
  20844. cli.set_no_proxy({"::1"});
  20845. auto res = cli.Get("/");
  20846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20847. EXPECT_EQ(0, s.proxy_hits());
  20848. EXPECT_EQ(1, s.target_hits());
  20849. }
  20850. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  20851. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  20852. // must still be recognized as IPv6 for CIDR matching. Implementations
  20853. // that detect IPv6 only when the host begins with '[' would parse the
  20854. // host as a hostname and miss the match.
  20855. ProxyAndTargetServers s;
  20856. Client cli("fe80::1", s.target_port());
  20857. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20858. cli.set_proxy("127.0.0.1", s.proxy_port());
  20859. cli.set_no_proxy({"fe80::/10"});
  20860. auto res = cli.Get("/");
  20861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20862. EXPECT_EQ(0, s.proxy_hits());
  20863. EXPECT_EQ(1, s.target_hits());
  20864. }
  20865. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  20866. ProxyAndTargetServers s;
  20867. Client cli("::1", s.target_port());
  20868. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  20869. cli.set_proxy("127.0.0.1", s.proxy_port());
  20870. cli.set_no_proxy({"[::1]"});
  20871. auto res = cli.Get("/");
  20872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20873. EXPECT_EQ(0, s.proxy_hits());
  20874. EXPECT_EQ(1, s.target_hits());
  20875. }
  20876. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  20877. ProxyAndTargetServers s;
  20878. Client cli("fe80::1", s.target_port());
  20879. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  20880. cli.set_proxy("127.0.0.1", s.proxy_port());
  20881. cli.set_no_proxy({"[fe80::]/10"});
  20882. auto res = cli.Get("/");
  20883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20884. EXPECT_EQ(0, s.proxy_hits());
  20885. EXPECT_EQ(1, s.target_hits());
  20886. }
  20887. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  20888. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  20889. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  20890. // tricks via address-family conversion.
  20891. ProxyAndTargetServers s;
  20892. Client cli("::ffff:127.0.0.1", s.target_port());
  20893. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  20894. cli.set_proxy("127.0.0.1", s.proxy_port());
  20895. cli.set_no_proxy({"127.0.0.1"});
  20896. auto res = cli.Get("/");
  20897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20898. EXPECT_GE(s.proxy_hits(), 1);
  20899. EXPECT_EQ(0, s.target_hits());
  20900. }
  20901. TEST(NoProxyTest, IPv4CidrMatch) {
  20902. ProxyAndTargetServers s;
  20903. Client cli("127.0.0.1", s.target_port());
  20904. cli.set_proxy("127.0.0.1", s.proxy_port());
  20905. cli.set_no_proxy({"127.0.0.0/8"});
  20906. auto res = cli.Get("/");
  20907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20908. EXPECT_EQ(0, s.proxy_hits());
  20909. EXPECT_EQ(1, s.target_hits());
  20910. }
  20911. TEST(NoProxyTest, IPv4CidrNonMatch) {
  20912. ProxyAndTargetServers s;
  20913. Client cli("127.0.0.1", s.target_port());
  20914. cli.set_proxy("127.0.0.1", s.proxy_port());
  20915. cli.set_no_proxy({"10.0.0.0/8"});
  20916. auto res = cli.Get("/");
  20917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20918. EXPECT_GE(s.proxy_hits(), 1);
  20919. EXPECT_EQ(0, s.target_hits());
  20920. }
  20921. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  20922. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  20923. // IPv4 target matches.
  20924. ProxyAndTargetServers s;
  20925. Client cli("127.0.0.1", s.target_port());
  20926. cli.set_proxy("127.0.0.1", s.proxy_port());
  20927. cli.set_no_proxy({"0.0.0.0/0"});
  20928. auto res = cli.Get("/");
  20929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20930. EXPECT_EQ(0, s.proxy_hits());
  20931. EXPECT_EQ(1, s.target_hits());
  20932. }
  20933. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  20934. ProxyAndTargetServers s;
  20935. Client cli("127.0.0.1", s.target_port());
  20936. cli.set_proxy("127.0.0.1", s.proxy_port());
  20937. cli.set_no_proxy({"127.0.0.1"});
  20938. auto res = cli.Get("/");
  20939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20940. EXPECT_EQ(0, s.proxy_hits());
  20941. EXPECT_EQ(1, s.target_hits());
  20942. }
  20943. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  20944. ProxyAndTargetServers s;
  20945. Client cli("127.0.0.1", s.target_port());
  20946. cli.set_proxy("127.0.0.1", s.proxy_port());
  20947. cli.set_no_proxy({"127.0.0.0/33"});
  20948. auto res = cli.Get("/");
  20949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20950. EXPECT_GE(s.proxy_hits(), 1);
  20951. EXPECT_EQ(0, s.target_hits());
  20952. }
  20953. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  20954. // Empty prefix after the slash must be rejected, not silently treated as /32.
  20955. ProxyAndTargetServers s;
  20956. Client cli("127.0.0.1", s.target_port());
  20957. cli.set_proxy("127.0.0.1", s.proxy_port());
  20958. cli.set_no_proxy({"127.0.0.1/"});
  20959. auto res = cli.Get("/");
  20960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20961. EXPECT_GE(s.proxy_hits(), 1);
  20962. EXPECT_EQ(0, s.target_hits());
  20963. }
  20964. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  20965. ProxyAndTargetServers s;
  20966. auto cli = make_client("internal.corp", s);
  20967. cli->set_proxy_basic_auth("u", "p");
  20968. cli->set_no_proxy({"internal.corp"});
  20969. auto res = cli->Get("/");
  20970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20971. EXPECT_EQ(1, s.target_hits());
  20972. EXPECT_EQ(0, s.proxy_hits());
  20973. EXPECT_FALSE(s.last_had_proxy_authz())
  20974. << "Proxy-Authorization must not be sent direct to the target";
  20975. }
  20976. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  20977. ProxyAndTargetServers s;
  20978. auto cli = make_client("public.example", s);
  20979. cli->set_proxy_basic_auth("u", "p");
  20980. cli->set_no_proxy({"internal.corp"}); // does not match
  20981. auto res = cli->Get("/");
  20982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20983. EXPECT_GE(s.proxy_hits(), 1);
  20984. EXPECT_TRUE(s.last_had_proxy_authz());
  20985. }
  20986. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  20987. ProxyAndTargetServers s;
  20988. auto cli = make_client("anything.test", s);
  20989. auto res = cli->Get("/");
  20990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20991. EXPECT_GE(s.proxy_hits(), 1);
  20992. EXPECT_EQ(0, s.target_hits());
  20993. }
  20994. TEST(NoProxyTest, PortSpecificEntryRejected) {
  20995. ProxyAndTargetServers s;
  20996. auto cli = make_client("example.com", s);
  20997. cli->set_no_proxy({"example.com:8080"});
  20998. auto res = cli->Get("/");
  20999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21000. EXPECT_GE(s.proxy_hits(), 1);
  21001. EXPECT_EQ(0, s.target_hits());
  21002. }
  21003. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21004. ProxyAndTargetServers s;
  21005. auto cli = make_client("anything.test", s);
  21006. cli->set_no_proxy({"", " ", "\t"});
  21007. auto res = cli->Get("/");
  21008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21009. EXPECT_GE(s.proxy_hits(), 1);
  21010. EXPECT_EQ(0, s.target_hits());
  21011. }
  21012. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21013. // An entry with leading/trailing whitespace must still match — env-style
  21014. // values are commonly pasted with stray spaces and an implementation
  21015. // that feeds the raw token directly to inet_pton would fail to match
  21016. // valid CIDRs because of the spaces.
  21017. ProxyAndTargetServers s;
  21018. Client cli("127.0.0.1", s.target_port());
  21019. cli.set_proxy("127.0.0.1", s.proxy_port());
  21020. cli.set_no_proxy({" 127.0.0.0/8 "});
  21021. auto res = cli.Get("/");
  21022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21023. EXPECT_EQ(0, s.proxy_hits());
  21024. EXPECT_EQ(1, s.target_hits());
  21025. }
  21026. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21027. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21028. // go direct and must NOT carry Proxy-Authorization.
  21029. std::atomic<int> proxy_hits{0};
  21030. std::atomic<int> target_hits{0};
  21031. std::atomic<bool> target_saw_authz{false};
  21032. no_proxy_test::ScopedServer proxy_mock, target;
  21033. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21034. proxy_hits++;
  21035. res.status = 302;
  21036. res.set_header("Location", "http://127.0.0.1:" +
  21037. std::to_string(target.port()) + "/landed");
  21038. });
  21039. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21040. target_hits++;
  21041. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21042. res.set_content("direct", "text/plain");
  21043. });
  21044. proxy_mock.listen();
  21045. target.listen();
  21046. Client cli("public.example", target.port());
  21047. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21048. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21049. cli.set_proxy_basic_auth("u", "p");
  21050. cli.set_no_proxy({"127.0.0.1"});
  21051. cli.set_follow_location(true);
  21052. auto res = cli.Get("/redir");
  21053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21054. EXPECT_GE(proxy_hits.load(), 1);
  21055. EXPECT_GE(target_hits.load(), 1);
  21056. EXPECT_FALSE(target_saw_authz.load());
  21057. }
  21058. #ifdef CPPHTTPLIB_SSL_ENABLED
  21059. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21060. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21061. // proxy creds would be sent to the (possibly hostile) origin.
  21062. std::atomic<int> target_hits{0};
  21063. std::atomic<bool> target_saw_proxy_authz{false};
  21064. no_proxy_test::ScopedServer target;
  21065. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21066. target_hits++;
  21067. if (req.has_header("Proxy-Authorization")) {
  21068. target_saw_proxy_authz = true;
  21069. }
  21070. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21071. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21072. "nonce=\"abc\", algorithm=MD5");
  21073. });
  21074. target.listen();
  21075. // The proxy address is set to the target's port: the bypass MUST kick in;
  21076. // if it doesn't, the test still routes "via proxy" to the same server and
  21077. // the Proxy-Authorization assertion below catches the leak.
  21078. Client cli("evil.example", target.port());
  21079. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21080. cli.set_proxy("127.0.0.1", target.port());
  21081. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21082. cli.set_no_proxy({"evil.example"});
  21083. auto res = cli.Get("/x");
  21084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21085. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21086. EXPECT_EQ(1, target_hits.load());
  21087. EXPECT_FALSE(target_saw_proxy_authz.load());
  21088. }
  21089. #endif
  21090. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21091. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21092. std::atomic<int> proxy_hits{0};
  21093. std::atomic<int> bypass_hits{0};
  21094. std::atomic<bool> proxy_saw_c_url{false};
  21095. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21096. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21097. proxy_hits++;
  21098. if (req.path.find("/start") != std::string::npos) {
  21099. res.status = 302;
  21100. res.set_header("Location", "http://127.0.0.1:" +
  21101. std::to_string(bypass_server.port()) +
  21102. "/middle");
  21103. return;
  21104. }
  21105. if (req.path.find("/end") != std::string::npos) {
  21106. proxy_saw_c_url = true;
  21107. res.set_content("c-via-proxy", "text/plain");
  21108. return;
  21109. }
  21110. res.set_content("unexpected", "text/plain");
  21111. });
  21112. // public.example's "advertised" port is arbitrary (the request never lands
  21113. // there — it goes through the proxy), but use a dynamic value to stay
  21114. // friendly with sharded parallel runs.
  21115. int public_port = bypass_server.port();
  21116. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21117. bypass_hits++;
  21118. res.status = 302;
  21119. res.set_header("Location", "http://public.example:" +
  21120. std::to_string(public_port) + "/end");
  21121. });
  21122. proxy_mock.listen();
  21123. bypass_server.listen();
  21124. Client cli("public.example", public_port);
  21125. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21126. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21127. cli.set_no_proxy({"127.0.0.1"});
  21128. cli.set_follow_location(true);
  21129. auto res = cli.Get("/start");
  21130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21131. EXPECT_EQ(StatusCode::OK_200, res->status);
  21132. EXPECT_EQ("c-via-proxy", res->body);
  21133. EXPECT_GE(proxy_hits.load(), 2);
  21134. EXPECT_GE(bypass_hits.load(), 1);
  21135. EXPECT_TRUE(proxy_saw_c_url.load());
  21136. }
  21137. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21138. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21139. // request reconnects to the correct endpoint.
  21140. std::atomic<int> proxy_hits{0};
  21141. std::atomic<int> target_hits{0};
  21142. no_proxy_test::ScopedServer proxy_mock, target;
  21143. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21144. proxy_hits++;
  21145. res.set_content("via-proxy", "text/plain");
  21146. });
  21147. target.svr().Get(".*", [&](const Request &, Response &res) {
  21148. target_hits++;
  21149. res.set_content("direct", "text/plain");
  21150. });
  21151. proxy_mock.listen();
  21152. target.listen();
  21153. Client cli("public.example", target.port());
  21154. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21155. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21156. cli.set_keep_alive(true);
  21157. auto res1 = cli.Get("/a");
  21158. ASSERT_TRUE(res1);
  21159. EXPECT_EQ("via-proxy", res1->body);
  21160. EXPECT_EQ(1, proxy_hits.load());
  21161. EXPECT_EQ(0, target_hits.load());
  21162. cli.set_no_proxy({"public.example"});
  21163. auto res2 = cli.Get("/b");
  21164. ASSERT_TRUE(res2);
  21165. EXPECT_EQ("direct", res2->body);
  21166. EXPECT_EQ(1, proxy_hits.load());
  21167. EXPECT_EQ(1, target_hits.load());
  21168. }
  21169. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21170. namespace proxy_tunnel_test {
  21171. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21172. class ScopedSSLServer {
  21173. public:
  21174. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21175. port_ = svr_.bind_to_any_port("127.0.0.1");
  21176. }
  21177. ~ScopedSSLServer() {
  21178. svr_.stop();
  21179. if (th_.joinable()) { th_.join(); }
  21180. }
  21181. SSLServer &svr() { return svr_; }
  21182. int port() const { return port_; }
  21183. void listen() {
  21184. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21185. svr_.wait_until_ready();
  21186. }
  21187. private:
  21188. SSLServer svr_;
  21189. std::thread th_;
  21190. int port_ = 0;
  21191. };
  21192. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21193. class ScopedConnectProxy {
  21194. public:
  21195. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21196. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21197. if (listen_fd_ < 0) { return; }
  21198. int yes = 1;
  21199. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21200. sockaddr_in a{};
  21201. a.sin_family = AF_INET;
  21202. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21203. a.sin_port = 0;
  21204. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21205. return;
  21206. }
  21207. socklen_t alen = sizeof(a);
  21208. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  21209. 0) {
  21210. return;
  21211. }
  21212. port_ = ntohs(a.sin_port);
  21213. if (::listen(listen_fd_, 1) != 0) { return; }
  21214. th_ = std::thread([this] { run(); });
  21215. }
  21216. ~ScopedConnectProxy() {
  21217. stop_ = true;
  21218. if (listen_fd_ >= 0) {
  21219. ::shutdown(listen_fd_, SHUT_RDWR);
  21220. ::close(listen_fd_);
  21221. }
  21222. if (th_.joinable()) { th_.join(); }
  21223. }
  21224. int port() const { return port_; }
  21225. int connect_hits() const { return connect_hits_.load(); }
  21226. private:
  21227. void run() {
  21228. while (!stop_.load()) {
  21229. fd_set rfds;
  21230. FD_ZERO(&rfds);
  21231. FD_SET(listen_fd_, &rfds);
  21232. timeval tv{0, 100 * 1000};
  21233. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  21234. if (sel <= 0) { continue; }
  21235. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  21236. if (client_fd < 0) { continue; }
  21237. std::string req;
  21238. char buf[2048];
  21239. while (req.find("\r\n\r\n") == std::string::npos) {
  21240. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  21241. if (n <= 0) { break; }
  21242. req.append(buf, static_cast<size_t>(n));
  21243. }
  21244. if (req.compare(0, 7, "CONNECT") != 0) {
  21245. ::close(client_fd);
  21246. continue;
  21247. }
  21248. connect_hits_++;
  21249. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  21250. ::send(client_fd, ok, std::strlen(ok), 0);
  21251. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  21252. sockaddr_in o{};
  21253. o.sin_family = AF_INET;
  21254. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21255. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  21256. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  21257. 0) {
  21258. ::close(client_fd);
  21259. ::close(origin_fd);
  21260. continue;
  21261. }
  21262. auto forward = [](int from, int to) {
  21263. char b[8192];
  21264. for (;;) {
  21265. ssize_t n = ::recv(from, b, sizeof(b), 0);
  21266. if (n <= 0) { break; }
  21267. ssize_t off = 0;
  21268. while (off < n) {
  21269. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  21270. if (s <= 0) {
  21271. off = n;
  21272. break;
  21273. }
  21274. off += s;
  21275. }
  21276. }
  21277. ::shutdown(to, SHUT_WR);
  21278. };
  21279. std::thread t1([&] { forward(client_fd, origin_fd); });
  21280. std::thread t2([&] { forward(origin_fd, client_fd); });
  21281. t1.join();
  21282. t2.join();
  21283. ::close(client_fd);
  21284. ::close(origin_fd);
  21285. }
  21286. }
  21287. int forward_port_ = -1;
  21288. int listen_fd_ = -1;
  21289. int port_ = 0;
  21290. std::thread th_;
  21291. std::atomic<bool> stop_{false};
  21292. std::atomic<int> connect_hits_{0};
  21293. };
  21294. } // namespace proxy_tunnel_test
  21295. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  21296. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  21297. // retry; otherwise proxy creds would be sent to the origin.
  21298. std::atomic<int> origin_hits{0};
  21299. std::atomic<bool> origin_saw_proxy_authz{false};
  21300. proxy_tunnel_test::ScopedSSLServer origin;
  21301. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  21302. origin_hits++;
  21303. if (req.has_header("Proxy-Authorization")) {
  21304. origin_saw_proxy_authz = true;
  21305. }
  21306. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21307. res.set_header("Proxy-Authenticate",
  21308. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  21309. "algorithm=MD5");
  21310. });
  21311. origin.listen();
  21312. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  21313. ASSERT_NE(0, proxy.port());
  21314. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  21315. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  21316. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  21317. // and answer with its own status, making this test flaky.
  21318. SSLClient cli("127.0.0.1", origin.port());
  21319. cli.enable_server_certificate_verification(false);
  21320. cli.set_proxy("127.0.0.1", proxy.port());
  21321. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21322. auto res = cli.Get("/x");
  21323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21324. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21325. EXPECT_EQ(1, origin_hits.load());
  21326. EXPECT_FALSE(origin_saw_proxy_authz.load());
  21327. EXPECT_EQ(1, proxy.connect_hits());
  21328. }
  21329. #endif