test.cc 713 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351
  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(ClientTest, MoveConstructible) {
  305. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  306. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  307. }
  308. TEST(ClientTest, MoveAssignable) {
  309. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  310. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  311. }
  312. #ifdef _WIN32
  313. TEST(StartupTest, WSAStartup) {
  314. WSADATA wsaData;
  315. int ret = WSAStartup(0x0002, &wsaData);
  316. ASSERT_EQ(0, ret);
  317. }
  318. #endif
  319. TEST(DecodePathTest, PercentCharacter) {
  320. EXPECT_EQ(
  321. decode_path_component(
  322. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  323. U8("descrip=Gastos áéíóúñÑ 6"));
  324. }
  325. TEST(DecodePathTest, PercentCharacterNUL) {
  326. string expected;
  327. expected.push_back('x');
  328. expected.push_back('\0');
  329. expected.push_back('x');
  330. EXPECT_EQ(decode_path_component("x%00x"), expected);
  331. }
  332. TEST(DecodePathTest, UnicodeEncoding) {
  333. // %u0041 = 'A' (1-byte UTF-8)
  334. EXPECT_EQ("A", decode_path_component("%u0041"));
  335. // %u00E9 = 'é' (2-byte UTF-8)
  336. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  337. // %u3042 = 'あ' (3-byte UTF-8)
  338. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  339. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  340. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  341. // %uD800 = surrogate (invalid, silently dropped)
  342. EXPECT_EQ("", decode_path_component("%uD800"));
  343. }
  344. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  345. // A sign or whitespace inside the two-character escape window must not be
  346. // accepted as a valid percent-encoding; the sequence is passed through
  347. // literally, matching decode_uri_component / decode_path_component.
  348. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  349. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  350. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  351. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  352. // Well-formed escapes still decode.
  353. EXPECT_EQ("-", decode_query_component("%2D", false));
  354. EXPECT_EQ("A", decode_query_component("%41", false));
  355. }
  356. TEST(SanitizeFilenameTest, VariousPatterns) {
  357. // Path traversal
  358. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  359. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  360. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  361. // Normal and edge cases
  362. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  363. EXPECT_EQ("filename.txt",
  364. httplib::sanitize_filename("/path/to/filename.txt"));
  365. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  366. EXPECT_EQ("", httplib::sanitize_filename(".."));
  367. EXPECT_EQ("", httplib::sanitize_filename(""));
  368. // Null bytes stripped
  369. EXPECT_EQ("safe.txt",
  370. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  371. // Whitespace-only rejected
  372. EXPECT_EQ("", httplib::sanitize_filename(" "));
  373. }
  374. // Forward declaration (see the base64_encode note below): split builds move the
  375. // definition into httplib.cc, so re-declaring it here lets the test link.
  376. namespace httplib {
  377. namespace detail {
  378. bool is_chunked_transfer_encoding(const Headers &headers);
  379. } // namespace detail
  380. } // namespace httplib
  381. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  382. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  383. auto make = [](std::initializer_list<const char *> lines) {
  384. Headers h;
  385. for (auto te : lines) {
  386. if (te) { h.emplace("Transfer-Encoding", te); }
  387. }
  388. return h;
  389. };
  390. // Sole coding, matched case-insensitively.
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  394. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  395. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  396. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  397. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  398. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  399. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  401. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  403. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  404. // were received, into one list. Headers preserves that order, so the answer
  405. // is decided by the last coding of the last line and the order the lines
  406. // arrived in is significant.
  407. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  408. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  409. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  410. // The split can fall anywhere in the list.
  411. EXPECT_TRUE(
  412. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  413. EXPECT_FALSE(
  414. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  415. // A trailing line naming no coding leaves the list ending in nothing, so it
  416. // must not inherit the chunked from the line before it.
  417. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  418. }
  419. // Forward declaration: in split builds split.py strips `inline` and moves the
  420. // definition into httplib.cc, so detail::base64_encode is not visible from the
  421. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  422. // in both header-only and split builds.
  423. namespace httplib {
  424. namespace detail {
  425. std::string base64_encode(const std::string &in);
  426. } // namespace detail
  427. } // namespace httplib
  428. TEST(Base64EncodeTest, KnownAnswers) {
  429. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  430. // where the accumulator's top bit is already set before the next shift.
  431. EXPECT_EQ("", detail::base64_encode(""));
  432. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  433. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  434. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  435. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  436. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  437. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  438. // High bytes keep the top bit set across several rounds.
  439. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  440. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  441. }
  442. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  447. string reservedCharacters = ";,/?:@&=+$";
  448. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  449. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  450. }
  451. TEST(ClientQueryOrder, PreserveOrder) {
  452. // This test reproduces Issue #2259: client may reorder query parameters
  453. // when sending a GET request. The expected behavior is that the client
  454. // preserves the original query string order when the caller supplied it
  455. // as part of the path.
  456. Server svr;
  457. svr.Get("/", [&](const Request &req, Response &res) {
  458. // Echo back the raw target so the test can assert ordering
  459. res.set_content(req.target, "text/plain");
  460. });
  461. std::thread t{[&] { svr.listen(HOST, PORT); }};
  462. auto se = detail::scope_exit([&] {
  463. svr.stop();
  464. t.join();
  465. ASSERT_FALSE(svr.is_running());
  466. });
  467. svr.wait_until_ready();
  468. Client cli(HOST, PORT);
  469. ASSERT_TRUE(cli.is_valid());
  470. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  471. auto res = cli.Get(original);
  472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  473. // Expect the echoed target to exactly match the original path (order
  474. // preserved)
  475. EXPECT_EQ(res->body, original);
  476. }
  477. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  478. string chineseCharacters = U8("中国語");
  479. string russianCharacters = U8("дом");
  480. string brazilianCharacters = U8("óculos");
  481. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  482. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  483. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  484. "%D0%B4%D0%BE%D0%BC");
  485. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  486. }
  487. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  488. string unescapedCharacters = "-_.!~*'()";
  489. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  490. }
  491. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  492. string reservedCharacters = ";,/?:@&=+$";
  493. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  494. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  495. }
  496. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  497. string chineseCharacters = U8("中国語");
  498. string russianCharacters = U8("дом");
  499. string brazilianCharacters = U8("óculos");
  500. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  501. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  502. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  503. "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  507. // Issue #2082 use case: encoding path component with ampersand
  508. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  509. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  510. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  511. }
  512. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  513. string unescapedCharacters = "-_.!~*'()";
  514. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  515. }
  516. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  517. string reservedCharacters = ";,/?:@&=+$#";
  518. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  519. }
  520. TEST(EncodeUriTest, TestUTF8Characters) {
  521. string chineseCharacters = U8("中国語");
  522. string russianCharacters = U8("дом");
  523. string brazilianCharacters = U8("óculos");
  524. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  525. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  526. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  527. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  528. }
  529. TEST(EncodeUriTest, TestCompleteUri) {
  530. string uri =
  531. "https://example.com/path/to/resource?query=value&param=test#fragment";
  532. EXPECT_EQ(
  533. httplib::encode_uri(uri),
  534. "https://example.com/path/to/resource?query=value&param=test#fragment");
  535. }
  536. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  537. string uri =
  538. "https://example.com/path with spaces/file name.html?q=hello world";
  539. EXPECT_EQ(httplib::encode_uri(uri),
  540. "https://example.com/path%20with%20spaces/"
  541. "file%20name.html?q=hello%20world");
  542. }
  543. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  544. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  545. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  546. }
  547. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  548. string unescapedCharacters = "-_.!~*'()";
  549. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  550. }
  551. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  552. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  553. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  554. string encodedBrazilian = "%C3%B3culos";
  555. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  556. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  557. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  558. }
  559. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  560. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  561. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  562. "Piri Tommy Villiers - on & on");
  563. }
  564. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  565. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  566. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  567. }
  568. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  569. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  570. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  571. }
  572. TEST(DecodeUriTest, TestUTF8Characters) {
  573. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  574. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  575. string encodedBrazilian = "%C3%B3culos";
  576. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  577. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  578. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  579. }
  580. TEST(DecodeUriTest, TestCompleteUri) {
  581. string encodedUri = "https://example.com/path%20with%20spaces/"
  582. "file%20name.html?q=hello%20world";
  583. EXPECT_EQ(
  584. httplib::decode_uri(encodedUri),
  585. "https://example.com/path with spaces/file name.html?q=hello world");
  586. }
  587. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  588. string original =
  589. "https://example.com/path with spaces/file name.html?q=hello world";
  590. string encoded = httplib::encode_uri(original);
  591. string decoded = httplib::decode_uri(encoded);
  592. EXPECT_EQ(decoded, original);
  593. }
  594. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  595. string original = "Piri Tommy Villiers - on & on";
  596. string encoded = httplib::encode_uri_component(original);
  597. string decoded = httplib::decode_uri_component(encoded);
  598. EXPECT_EQ(decoded, original);
  599. }
  600. TEST(TrimTests, TrimStringTests) {
  601. EXPECT_EQ("abc", detail::trim_copy("abc"));
  602. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  603. EXPECT_TRUE(detail::trim_copy("").empty());
  604. }
  605. TEST(AsciiTest, LocaleIndependentClassification) {
  606. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  607. // which consult the global C locale: std::isalnum(0xC5) can return true
  608. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  609. // helpers must classify every byte by the ASCII grammar alone.
  610. for (int i = 0; i < 256; i++) {
  611. auto c = static_cast<char>(i);
  612. auto is_digit = i >= '0' && i <= '9';
  613. auto is_upper = i >= 'A' && i <= 'Z';
  614. auto is_lower = i >= 'a' && i <= 'z';
  615. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  616. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  617. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  618. << "byte " << i;
  619. }
  620. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  621. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  622. // Non-ASCII bytes must be percent-encoded, never passed through as
  623. // alphanumeric.
  624. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  625. }
  626. TEST(FromCharsTest, Double) {
  627. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  628. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  629. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  630. auto parse = [](const std::string &s, double &v) {
  631. return detail::from_chars(s.data(), s.data() + s.size(), v);
  632. };
  633. double v = -1.0;
  634. // Representative quality values.
  635. EXPECT_EQ(parse("0", v).ec, std::errc{});
  636. EXPECT_DOUBLE_EQ(v, 0.0);
  637. EXPECT_EQ(parse("1", v).ec, std::errc{});
  638. EXPECT_DOUBLE_EQ(v, 1.0);
  639. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  640. EXPECT_DOUBLE_EQ(v, 0.8);
  641. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  642. EXPECT_DOUBLE_EQ(v, 0.001);
  643. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  644. EXPECT_DOUBLE_EQ(v, 1.0);
  645. // A missing integer or fractional part is tolerated.
  646. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  647. EXPECT_DOUBLE_EQ(v, 0.5);
  648. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  649. EXPECT_DOUBLE_EQ(v, 5.0);
  650. // Values outside [0, 1] still parse; the caller range-checks them.
  651. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  652. EXPECT_DOUBLE_EQ(v, 123.456);
  653. // Stops at the first byte that is not part of the number and reports where.
  654. std::string trailing = "0.9, text/html";
  655. auto r = parse(trailing, v);
  656. EXPECT_EQ(r.ec, std::errc{});
  657. EXPECT_DOUBLE_EQ(v, 0.9);
  658. EXPECT_EQ(*r.ptr, ',');
  659. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  660. // outright, and an 'e'/'E' simply ends the number.
  661. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  662. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  663. std::string exp_input = "1.5e3";
  664. r = parse(exp_input, v);
  665. EXPECT_EQ(r.ec, std::errc{});
  666. EXPECT_DOUBLE_EQ(v, 1.5);
  667. EXPECT_EQ(*r.ptr, 'e');
  668. // Invalid inputs.
  669. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  670. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  671. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  672. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  673. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  674. // Pathological but well-formed inputs must stay bounded (no overflow, no
  675. // out-of-bounds table access) and stay within [0, 1] for the caller.
  676. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  677. std::errc{});
  678. EXPECT_DOUBLE_EQ(v, 0.0);
  679. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  680. std::errc{});
  681. EXPECT_GE(v, 0.0);
  682. EXPECT_LE(v, 1.0);
  683. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  684. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  685. }
  686. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  687. // Simple case without quality values
  688. std::vector<std::string> result1;
  689. EXPECT_TRUE(detail::parse_accept_header(
  690. "text/html,application/json,text/plain", result1));
  691. EXPECT_EQ(result1.size(), 3U);
  692. EXPECT_EQ(result1[0], "text/html");
  693. EXPECT_EQ(result1[1], "application/json");
  694. EXPECT_EQ(result1[2], "text/plain");
  695. // With quality values
  696. std::vector<std::string> result2;
  697. EXPECT_TRUE(detail::parse_accept_header(
  698. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  699. EXPECT_EQ(result2.size(), 3U);
  700. EXPECT_EQ(result2[0], "application/json"); // highest q value
  701. EXPECT_EQ(result2[1], "text/html");
  702. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  703. }
  704. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  705. // Mixed with and without quality values
  706. std::vector<std::string> result;
  707. EXPECT_TRUE(detail::parse_accept_header(
  708. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  709. EXPECT_EQ(result.size(), 3U);
  710. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  711. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  712. EXPECT_EQ(result[2], "application/json"); // q=0.5
  713. }
  714. TEST(ParseAcceptHeaderTest, EdgeCases) {
  715. // Empty header
  716. std::vector<std::string> empty_result;
  717. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  718. EXPECT_TRUE(empty_result.empty());
  719. // Single type
  720. std::vector<std::string> single_result;
  721. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  722. EXPECT_EQ(single_result.size(), 1U);
  723. EXPECT_EQ(single_result[0], "application/json");
  724. // Wildcard types
  725. std::vector<std::string> wildcard_result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  728. EXPECT_EQ(wildcard_result.size(), 3U);
  729. EXPECT_EQ(wildcard_result[0], "application/json");
  730. EXPECT_EQ(wildcard_result[1], "text/*");
  731. EXPECT_EQ(wildcard_result[2], "*/*");
  732. }
  733. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  734. // Common browser Accept header
  735. std::vector<std::string> browser_result;
  736. EXPECT_TRUE(
  737. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  738. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  739. browser_result));
  740. EXPECT_EQ(browser_result.size(), 6U);
  741. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  742. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  743. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  744. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  745. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  746. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  747. // API client header
  748. std::vector<std::string> api_result;
  749. EXPECT_TRUE(detail::parse_accept_header(
  750. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  751. api_result));
  752. EXPECT_EQ(api_result.size(), 3U);
  753. EXPECT_EQ(api_result[0], "application/json");
  754. EXPECT_EQ(api_result[1], "application/xml");
  755. EXPECT_EQ(api_result[2], "text/plain");
  756. }
  757. TEST(ParseAcceptHeaderTest, SpecialCases) {
  758. // Quality value with 3 decimal places
  759. std::vector<std::string> decimal_result;
  760. EXPECT_TRUE(detail::parse_accept_header(
  761. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  762. EXPECT_EQ(decimal_result.size(), 2U);
  763. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  764. EXPECT_EQ(decimal_result[1], "text/html");
  765. // Zero quality (should still be included but with lowest priority)
  766. std::vector<std::string> zero_q_result;
  767. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  768. zero_q_result));
  769. EXPECT_EQ(zero_q_result.size(), 2U);
  770. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  771. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  772. // No spaces around commas
  773. std::vector<std::string> no_space_result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  776. no_space_result));
  777. EXPECT_EQ(no_space_result.size(), 3U);
  778. EXPECT_EQ(no_space_result[0], "text/html");
  779. EXPECT_EQ(no_space_result[1], "application/json");
  780. EXPECT_EQ(no_space_result[2], "text/plain");
  781. }
  782. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  783. // Quality values always use '.' as the decimal separator, so parsing must
  784. // not depend on the process locale. An embedding application may have
  785. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  786. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  787. std::string saved = cur ? cur : "C";
  788. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  789. "fr_FR.UTF-8"};
  790. bool switched = false;
  791. for (const auto loc : comma_locales) {
  792. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  793. std::localeconv()->decimal_point[0] == ',') {
  794. switched = true;
  795. break;
  796. }
  797. }
  798. if (!switched) {
  799. std::setlocale(LC_NUMERIC, saved.c_str());
  800. GTEST_SKIP() << "no comma-decimal locale available on this host";
  801. }
  802. // The higher-weighted type appears later in the list, so a correct parse
  803. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  804. // sensitive parse reads both weights as 0 and leaves the original order.
  805. std::vector<std::string> result;
  806. EXPECT_TRUE(detail::parse_accept_header(
  807. "application/json;q=0.1,text/html;q=0.9", result));
  808. ASSERT_EQ(result.size(), 2U);
  809. EXPECT_EQ(result[0], "text/html");
  810. EXPECT_EQ(result[1], "application/json");
  811. std::setlocale(LC_NUMERIC, saved.c_str());
  812. }
  813. TEST(ParseAcceptHeaderTest, InvalidCases) {
  814. std::vector<std::string> result;
  815. // Invalid quality value (> 1.0)
  816. EXPECT_FALSE(
  817. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  818. // Invalid quality value (< 0.0)
  819. EXPECT_FALSE(
  820. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  821. // Invalid quality value (not a number)
  822. EXPECT_FALSE(detail::parse_accept_header(
  823. "text/html;q=invalid,application/json", result));
  824. // Empty quality value
  825. EXPECT_FALSE(
  826. detail::parse_accept_header("text/html;q=,application/json", result));
  827. // Invalid media type format (no slash and not wildcard)
  828. EXPECT_FALSE(
  829. detail::parse_accept_header("invalidtype,application/json", result));
  830. // Empty media type
  831. result.clear();
  832. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  833. // Only commas
  834. result.clear();
  835. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  836. // Valid cases should still work
  837. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  838. EXPECT_EQ(result.size(), 1U);
  839. EXPECT_EQ(result[0], "*/*");
  840. EXPECT_TRUE(detail::parse_accept_header("*", result));
  841. EXPECT_EQ(result.size(), 1U);
  842. EXPECT_EQ(result[0], "*");
  843. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  844. EXPECT_EQ(result.size(), 1U);
  845. EXPECT_EQ(result[0], "text/*");
  846. }
  847. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  848. Server svr;
  849. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  850. EXPECT_EQ(req.accept_content_types.size(), 3U);
  851. EXPECT_EQ(req.accept_content_types[0], "application/json");
  852. EXPECT_EQ(req.accept_content_types[1], "text/html");
  853. EXPECT_EQ(req.accept_content_types[2], "*/*");
  854. res.set_content("ok", "text/plain");
  855. });
  856. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  857. EXPECT_TRUE(false);
  858. res.set_content("bad request", "text/plain");
  859. });
  860. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  861. auto se = detail::scope_exit([&] {
  862. svr.stop();
  863. listen_thread.join();
  864. ASSERT_FALSE(svr.is_running());
  865. });
  866. svr.wait_until_ready();
  867. Client cli("localhost", PORT);
  868. {
  869. auto res = cli.Get(
  870. "/accept_ok",
  871. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  873. EXPECT_EQ(StatusCode::OK_200, res->status);
  874. }
  875. {
  876. auto res = cli.Get("/accept_bad_request",
  877. Headers{{"Accept", "text/html;q=abc,application/json"}});
  878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  879. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  880. }
  881. }
  882. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  883. Server svr;
  884. svr.Get("/", [](const Request & /*req*/, Response &res) {
  885. res.set_content("ok", "text/plain");
  886. });
  887. std::atomic<int> start_count{0};
  888. std::atomic<bool> running_when_called{false};
  889. svr.set_start_handler([&]() {
  890. running_when_called = svr.is_running();
  891. start_count++;
  892. });
  893. auto port = svr.bind_to_any_port(HOST);
  894. std::thread t([&]() { svr.listen_after_bind(); });
  895. auto se = detail::scope_exit([&] {
  896. svr.stop();
  897. t.join();
  898. ASSERT_FALSE(svr.is_running());
  899. });
  900. svr.wait_until_ready();
  901. // A successful request proves the accept loop is running, which the start
  902. // handler precedes; so by now the handler must have run exactly once.
  903. Client cli(HOST, port);
  904. cli.set_connection_timeout(std::chrono::seconds(5));
  905. auto res = cli.Get("/");
  906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  907. EXPECT_EQ(StatusCode::OK_200, res->status);
  908. EXPECT_EQ(1, start_count.load());
  909. EXPECT_TRUE(running_when_called.load());
  910. }
  911. TEST(DivideTest, DivideStringTests) {
  912. auto divide = [](const std::string &str, char d) {
  913. std::string lhs;
  914. std::string rhs;
  915. detail::divide(str, d,
  916. [&](const char *lhs_data, std::size_t lhs_size,
  917. const char *rhs_data, std::size_t rhs_size) {
  918. lhs.assign(lhs_data, lhs_size);
  919. rhs.assign(rhs_data, rhs_size);
  920. });
  921. return std::make_pair(std::move(lhs), std::move(rhs));
  922. };
  923. {
  924. const auto res = divide("", '=');
  925. EXPECT_EQ(res.first, "");
  926. EXPECT_EQ(res.second, "");
  927. }
  928. {
  929. const auto res = divide("=", '=');
  930. EXPECT_EQ(res.first, "");
  931. EXPECT_EQ(res.second, "");
  932. }
  933. {
  934. const auto res = divide(" ", '=');
  935. EXPECT_EQ(res.first, " ");
  936. EXPECT_EQ(res.second, "");
  937. }
  938. {
  939. const auto res = divide("a", '=');
  940. EXPECT_EQ(res.first, "a");
  941. EXPECT_EQ(res.second, "");
  942. }
  943. {
  944. const auto res = divide("a=", '=');
  945. EXPECT_EQ(res.first, "a");
  946. EXPECT_EQ(res.second, "");
  947. }
  948. {
  949. const auto res = divide("=b", '=');
  950. EXPECT_EQ(res.first, "");
  951. EXPECT_EQ(res.second, "b");
  952. }
  953. {
  954. const auto res = divide("a=b", '=');
  955. EXPECT_EQ(res.first, "a");
  956. EXPECT_EQ(res.second, "b");
  957. }
  958. {
  959. const auto res = divide("a=b=", '=');
  960. EXPECT_EQ(res.first, "a");
  961. EXPECT_EQ(res.second, "b=");
  962. }
  963. {
  964. const auto res = divide("a=b=c", '=');
  965. EXPECT_EQ(res.first, "a");
  966. EXPECT_EQ(res.second, "b=c");
  967. }
  968. }
  969. TEST(SplitTest, ParseQueryString) {
  970. string s = "key1=val1&key2=val2&key3=val3";
  971. Params dic;
  972. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  973. [&](const char *b, const char *e) {
  974. string key, val;
  975. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  976. if (key.empty()) {
  977. key.assign(b2, e2);
  978. } else {
  979. val.assign(b2, e2);
  980. }
  981. });
  982. dic.emplace(key, val);
  983. });
  984. EXPECT_EQ("val1", dic.find("key1")->second);
  985. EXPECT_EQ("val2", dic.find("key2")->second);
  986. EXPECT_EQ("val3", dic.find("key3")->second);
  987. }
  988. TEST(SplitTest, ParseInvalidQueryTests) {
  989. {
  990. string s = " ";
  991. Params dict;
  992. detail::parse_query_text(s, dict);
  993. EXPECT_TRUE(dict.empty());
  994. }
  995. {
  996. string s = " = =";
  997. Params dict;
  998. detail::parse_query_text(s, dict);
  999. EXPECT_TRUE(dict.empty());
  1000. }
  1001. }
  1002. TEST(ParseQueryTest, ParseQueryString) {
  1003. {
  1004. std::string s = "key1=val1&key2=val2&key3=val3";
  1005. Params dic;
  1006. detail::parse_query_text(s, dic);
  1007. EXPECT_EQ("val1", dic.find("key1")->second);
  1008. EXPECT_EQ("val2", dic.find("key2")->second);
  1009. EXPECT_EQ("val3", dic.find("key3")->second);
  1010. }
  1011. {
  1012. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1013. Params dic;
  1014. detail::parse_query_text(s, dic);
  1015. EXPECT_EQ("", dic.find("key1")->second);
  1016. EXPECT_EQ("val1", dic.find("key2")->second);
  1017. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1018. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1019. }
  1020. }
  1021. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1022. Params dic;
  1023. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1024. dic.emplace("key1", "val1");
  1025. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1026. dic.emplace("key2", "val2");
  1027. dic.emplace("key3", "val3");
  1028. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1029. }
  1030. // Joins every entry of a Headers or Params into "key=value " so a whole
  1031. // traversal can be compared in one assertion. Both are instantiations of the
  1032. // same insertion-ordered container, so one helper serves both.
  1033. template <typename Map> static std::string entries_to_string(const Map &m) {
  1034. std::string s;
  1035. for (const auto &entry : m) {
  1036. s += entry.first + "=" + entry.second + " ";
  1037. }
  1038. return s;
  1039. }
  1040. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1041. // Params used to be a std::multimap, which sorted by name and handed the
  1042. // caller's query back alphabetised. A client signing its query string could
  1043. // not reproduce the order it asked for.
  1044. Params dic;
  1045. dic.emplace("zulu", "1");
  1046. dic.emplace("alpha", "2");
  1047. dic.emplace("mike", "3");
  1048. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1049. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1050. }
  1051. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1052. Params dic;
  1053. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1054. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1055. }
  1056. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1057. Request req;
  1058. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1059. req.params);
  1060. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1061. EXPECT_EQ("first", req.get_param_value("tag"));
  1062. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1063. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1064. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1065. EXPECT_EQ("", req.get_param_value("tag", 3));
  1066. }
  1067. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1068. // Params shares its container with Headers, which matches field names
  1069. // case-insensitively. Parameter names must not pick that up.
  1070. Params dic;
  1071. dic.emplace("Key", "upper");
  1072. dic.emplace("key", "lower");
  1073. EXPECT_EQ(2U, dic.size());
  1074. EXPECT_EQ(1U, dic.count("Key"));
  1075. EXPECT_EQ(1U, dic.count("key"));
  1076. EXPECT_EQ("upper", dic.find("Key")->second);
  1077. EXPECT_EQ("lower", dic.find("key")->second);
  1078. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1079. }
  1080. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1081. Server svr;
  1082. std::string order;
  1083. svr.Get("/order", [&](const Request &req, Response &res) {
  1084. order = entries_to_string(req.params);
  1085. res.set_content("ok", "text/plain");
  1086. });
  1087. auto port = svr.bind_to_any_port(HOST);
  1088. thread t = thread([&] { svr.listen_after_bind(); });
  1089. auto se = detail::scope_exit([&] {
  1090. svr.stop();
  1091. t.join();
  1092. ASSERT_FALSE(svr.is_running());
  1093. });
  1094. svr.wait_until_ready();
  1095. Client cli(HOST, port);
  1096. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1097. ASSERT_TRUE(res);
  1098. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1099. }
  1100. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1101. Server svr;
  1102. std::string field_order, file_order;
  1103. svr.Post("/order", [&](const Request &req, Response &res) {
  1104. for (const auto &field : req.form.fields) {
  1105. field_order += field.first + "=" + field.second.content + " ";
  1106. }
  1107. for (const auto &file : req.form.files) {
  1108. file_order += file.first + "=" + file.second.filename + " ";
  1109. }
  1110. res.set_content("ok", "text/plain");
  1111. });
  1112. auto port = svr.bind_to_any_port(HOST);
  1113. thread t = thread([&] { svr.listen_after_bind(); });
  1114. auto se = detail::scope_exit([&] {
  1115. svr.stop();
  1116. t.join();
  1117. ASSERT_FALSE(svr.is_running());
  1118. });
  1119. svr.wait_until_ready();
  1120. UploadFormDataItems items = {
  1121. {"zulu", "1", "", ""},
  1122. {"alpha", "2", "", ""},
  1123. {"mike", "3", "", ""},
  1124. {"zebra", "z", "z.txt", "text/plain"},
  1125. {"apple", "a", "a.txt", "text/plain"},
  1126. };
  1127. Client cli(HOST, port);
  1128. auto res = cli.Post("/order", items);
  1129. ASSERT_TRUE(res);
  1130. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1131. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1132. }
  1133. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1134. Server svr;
  1135. std::vector<std::string> values;
  1136. std::string first, second, out_of_range, order;
  1137. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1138. values = req.form.get_fields("tag");
  1139. first = req.form.get_field("tag", 0);
  1140. second = req.form.get_field("tag", 1);
  1141. out_of_range = req.form.get_field("tag", 2);
  1142. for (const auto &field : req.form.fields) {
  1143. order += field.first + "=" + field.second.content + " ";
  1144. }
  1145. res.set_content("ok", "text/plain");
  1146. });
  1147. auto port = svr.bind_to_any_port(HOST);
  1148. thread t = thread([&] { svr.listen_after_bind(); });
  1149. auto se = detail::scope_exit([&] {
  1150. svr.stop();
  1151. t.join();
  1152. ASSERT_FALSE(svr.is_running());
  1153. });
  1154. svr.wait_until_ready();
  1155. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1156. // not adjacent in the container.
  1157. UploadFormDataItems items = {
  1158. {"tag", "first", "", ""},
  1159. {"other", "x", "", ""},
  1160. {"tag", "second", "", ""},
  1161. };
  1162. Client cli(HOST, port);
  1163. auto res = cli.Post("/repeated", items);
  1164. ASSERT_TRUE(res);
  1165. ASSERT_EQ(2U, values.size());
  1166. EXPECT_EQ("first", values[0]);
  1167. EXPECT_EQ("second", values[1]);
  1168. EXPECT_EQ("first", first);
  1169. EXPECT_EQ("second", second);
  1170. // std::multimap already kept entries sharing a name in insertion order, so
  1171. // everything above passes without this change too. The whole traversal is
  1172. // what tells the two apart: sorting by name would hoist "other" to the front
  1173. // and the two "tag" parts would end up adjacent.
  1174. EXPECT_EQ("tag=first other=x tag=second ", order);
  1175. // Advancing past the last entry of a name used to run off the container;
  1176. // the container's saturating increment makes it return the default instead.
  1177. EXPECT_EQ("", out_of_range);
  1178. }
  1179. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1180. // Server::read_content() keeps a FormFields::iterator alive across the
  1181. // content callbacks that fill the part it points at. The container is
  1182. // vector-backed, so a later emplace can reallocate and invalidate an older
  1183. // iterator; 64 parts grow the vector through seven reallocations, which
  1184. // checks that every part's content still lands in its own entry.
  1185. const size_t part_count = 64;
  1186. // One formula for both the parts sent and the values expected back, so the
  1187. // two cannot drift apart.
  1188. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1189. auto content_of = [](size_t i) {
  1190. return std::string(64, static_cast<char>('a' + (i % 26)));
  1191. };
  1192. Server svr;
  1193. std::vector<std::pair<std::string, std::string>> received;
  1194. svr.Post("/many", [&](const Request &req, Response &res) {
  1195. for (const auto &field : req.form.fields) {
  1196. received.emplace_back(field.first, field.second.content);
  1197. }
  1198. res.set_content("ok", "text/plain");
  1199. });
  1200. auto port = svr.bind_to_any_port(HOST);
  1201. thread t = thread([&] { svr.listen_after_bind(); });
  1202. auto se = detail::scope_exit([&] {
  1203. svr.stop();
  1204. t.join();
  1205. ASSERT_FALSE(svr.is_running());
  1206. });
  1207. svr.wait_until_ready();
  1208. UploadFormDataItems items;
  1209. for (size_t i = 0; i < part_count; i++) {
  1210. items.push_back({name_of(i), content_of(i), "", ""});
  1211. }
  1212. Client cli(HOST, port);
  1213. auto res = cli.Post("/many", items);
  1214. ASSERT_TRUE(res);
  1215. ASSERT_EQ(part_count, received.size());
  1216. for (size_t i = 0; i < part_count; i++) {
  1217. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1218. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1219. }
  1220. }
  1221. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1222. string content_type = "multipart/form-data; boundary=something";
  1223. string boundary;
  1224. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1225. EXPECT_TRUE(ret);
  1226. EXPECT_EQ(boundary, "something");
  1227. }
  1228. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1229. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1230. string boundary;
  1231. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1232. EXPECT_TRUE(ret);
  1233. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1234. }
  1235. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1236. string content_type =
  1237. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1238. string boundary;
  1239. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1240. EXPECT_TRUE(ret);
  1241. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1242. }
  1243. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1244. string content_type =
  1245. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1246. string boundary;
  1247. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1248. EXPECT_TRUE(ret);
  1249. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1250. }
  1251. TEST(GetHeaderValueTest, DefaultValue) {
  1252. Headers headers = {{"Dummy", "Dummy"}};
  1253. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1254. EXPECT_STREQ("text/plain", val);
  1255. }
  1256. TEST(GetHeaderValueTest, DefaultValueInt) {
  1257. Headers headers = {{"Dummy", "Dummy"}};
  1258. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1259. EXPECT_EQ(100ull, val);
  1260. }
  1261. TEST(GetHeaderValueTest, RegularValue) {
  1262. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1263. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1264. EXPECT_STREQ("text/html", val);
  1265. }
  1266. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1267. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1268. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1269. EXPECT_STREQ("text/html", val);
  1270. }
  1271. TEST(GetHeaderValueTest, SetContent) {
  1272. Response res;
  1273. res.set_content("html", "text/html");
  1274. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1275. res.set_content("text", "text/plain");
  1276. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1277. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1278. }
  1279. TEST(GetHeaderValueTest, RegularValueInt) {
  1280. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1281. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1282. EXPECT_EQ(100ull, val);
  1283. }
  1284. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1285. Headers headers = {{"Content-Length", "x"}};
  1286. auto is_invalid_value = false;
  1287. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1288. is_invalid_value);
  1289. EXPECT_EQ(0ull, val);
  1290. EXPECT_TRUE(is_invalid_value);
  1291. }
  1292. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1293. // An all-digit value that overflows size_t must be reported as invalid, not
  1294. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1295. // a large length to a small one on 32-bit builds, leaving the framing length
  1296. // wrong while is_invalid_value stayed false.
  1297. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1298. auto is_invalid_value = false;
  1299. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1300. is_invalid_value);
  1301. EXPECT_TRUE(is_invalid_value);
  1302. // A well-formed length is unaffected.
  1303. Headers ok = {{"Content-Length", "1234"}};
  1304. is_invalid_value = false;
  1305. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1306. is_invalid_value);
  1307. EXPECT_EQ(1234ull, val);
  1308. EXPECT_FALSE(is_invalid_value);
  1309. }
  1310. TEST(GetHeaderValueTest, Range) {
  1311. {
  1312. Headers headers = {make_range_header({{1, -1}})};
  1313. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1314. EXPECT_STREQ("bytes=1-", val);
  1315. }
  1316. {
  1317. Headers headers = {make_range_header({{-1, 1}})};
  1318. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1319. EXPECT_STREQ("bytes=-1", val);
  1320. }
  1321. {
  1322. Headers headers = {make_range_header({{1, 10}})};
  1323. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1324. EXPECT_STREQ("bytes=1-10", val);
  1325. }
  1326. {
  1327. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1328. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1329. EXPECT_STREQ("bytes=1-10, 100-", val);
  1330. }
  1331. {
  1332. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1333. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1334. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1335. }
  1336. {
  1337. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1338. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1339. EXPECT_STREQ("bytes=0-0, -1", val);
  1340. }
  1341. }
  1342. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1343. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1344. // to depend on the standard library (libstdc++ handed back duplicates in
  1345. // reverse insertion order, libc++ in insertion order).
  1346. Request req;
  1347. req.set_header("Accept-Encoding", "gzip");
  1348. req.set_header("Accept-Encoding", "deflate");
  1349. req.set_header("Accept-Encoding", "br");
  1350. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1351. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1352. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1353. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1354. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1355. }
  1356. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1357. Request req;
  1358. req.set_header("X-Test", "only");
  1359. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1360. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1361. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1362. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1363. }
  1364. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1365. Headers headers;
  1366. headers.emplace("Host", "example.com");
  1367. headers.emplace("Accept-Encoding", "gzip");
  1368. headers.emplace("User-Agent", "test");
  1369. headers.emplace("Accept-Encoding", "deflate");
  1370. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1371. "Accept-Encoding=deflate ",
  1372. entries_to_string(headers));
  1373. }
  1374. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1375. Headers headers = {{"Content-Type", "text/html"},
  1376. {"CONTENT-TYPE", "text/xml"}};
  1377. EXPECT_EQ(2U, headers.count("content-type"));
  1378. auto it = headers.find("content-type");
  1379. ASSERT_TRUE(it != headers.end());
  1380. EXPECT_EQ("text/html", it->second);
  1381. }
  1382. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1383. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1384. // drop only those fields and leave everything positioned between them.
  1385. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1386. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1387. auto rng = headers.equal_range("a");
  1388. headers.erase(rng.first, rng.second);
  1389. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1390. }
  1391. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1392. Headers headers = {
  1393. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1394. EXPECT_EQ(3U, headers.erase("A"));
  1395. EXPECT_EQ(0U, headers.count("A"));
  1396. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1397. }
  1398. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1399. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1400. headers.emplace_front("Host", "example.com");
  1401. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1402. entries_to_string(headers));
  1403. }
  1404. TEST(ParseHeaderValueTest, Range) {
  1405. {
  1406. Ranges ranges;
  1407. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1408. EXPECT_TRUE(ret);
  1409. EXPECT_EQ(1u, ranges.size());
  1410. EXPECT_EQ(1u, ranges[0].first);
  1411. EXPECT_EQ(-1, ranges[0].second);
  1412. }
  1413. {
  1414. Ranges ranges;
  1415. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1416. EXPECT_TRUE(ret);
  1417. EXPECT_EQ(1u, ranges.size());
  1418. EXPECT_EQ(-1, ranges[0].first);
  1419. EXPECT_EQ(1u, ranges[0].second);
  1420. }
  1421. {
  1422. Ranges ranges;
  1423. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1424. EXPECT_TRUE(ret);
  1425. EXPECT_EQ(1u, ranges.size());
  1426. EXPECT_EQ(1u, ranges[0].first);
  1427. EXPECT_EQ(10u, ranges[0].second);
  1428. }
  1429. {
  1430. Ranges ranges;
  1431. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1432. EXPECT_FALSE(ret);
  1433. }
  1434. {
  1435. Ranges ranges;
  1436. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1437. EXPECT_TRUE(ret);
  1438. EXPECT_EQ(2u, ranges.size());
  1439. EXPECT_EQ(1u, ranges[0].first);
  1440. EXPECT_EQ(10u, ranges[0].second);
  1441. EXPECT_EQ(100u, ranges[1].first);
  1442. EXPECT_EQ(-1, ranges[1].second);
  1443. }
  1444. {
  1445. Ranges ranges;
  1446. auto ret =
  1447. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1448. EXPECT_TRUE(ret);
  1449. EXPECT_EQ(3u, ranges.size());
  1450. EXPECT_EQ(1u, ranges[0].first);
  1451. EXPECT_EQ(10u, ranges[0].second);
  1452. EXPECT_EQ(100u, ranges[1].first);
  1453. EXPECT_EQ(200u, ranges[1].second);
  1454. EXPECT_EQ(300u, ranges[2].first);
  1455. EXPECT_EQ(400u, ranges[2].second);
  1456. }
  1457. {
  1458. Ranges ranges;
  1459. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1460. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1461. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1462. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1463. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1464. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1465. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1466. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1467. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1468. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1469. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1470. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1471. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1472. EXPECT_TRUE(ranges.empty());
  1473. }
  1474. }
  1475. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1476. Request req;
  1477. req.set_header("Accept-Encoding", "gzip");
  1478. Response res;
  1479. res.set_header("Content-Type", "text/plain");
  1480. auto ret = detail::encoding_type(req, res);
  1481. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1482. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1483. #else
  1484. EXPECT_TRUE(ret == detail::EncodingType::None);
  1485. #endif
  1486. }
  1487. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1488. Request req;
  1489. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1490. Response res;
  1491. res.set_header("Content-Type", "text/plain");
  1492. auto ret = detail::encoding_type(req, res);
  1493. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1494. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1495. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1496. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1497. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1498. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1499. #else
  1500. EXPECT_TRUE(ret == detail::EncodingType::None);
  1501. #endif
  1502. }
  1503. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1504. Request req;
  1505. req.set_header("Accept-Encoding",
  1506. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1507. Response res;
  1508. res.set_header("Content-Type", "text/plain");
  1509. auto ret = detail::encoding_type(req, res);
  1510. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1511. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1512. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1513. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1514. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1515. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1516. #else
  1517. EXPECT_TRUE(ret == detail::EncodingType::None);
  1518. #endif
  1519. }
  1520. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1521. // All supported encodings rejected with q=0 should return None
  1522. Request req;
  1523. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1524. Response res;
  1525. res.set_header("Content-Type", "text/plain");
  1526. auto ret = detail::encoding_type(req, res);
  1527. EXPECT_TRUE(ret == detail::EncodingType::None);
  1528. }
  1529. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1530. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1531. Request req;
  1532. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1533. Response res;
  1534. res.set_header("Content-Type", "text/plain");
  1535. auto ret = detail::encoding_type(req, res);
  1536. EXPECT_TRUE(ret == detail::EncodingType::None);
  1537. }
  1538. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1539. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1540. Request req;
  1541. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1542. Response res;
  1543. res.set_header("Content-Type", "text/plain");
  1544. auto ret = detail::encoding_type(req, res);
  1545. EXPECT_TRUE(ret == detail::EncodingType::None);
  1546. }
  1547. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1548. // RFC 7231: Accept-Encoding values are case-insensitive
  1549. Request req;
  1550. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1551. Response res;
  1552. res.set_header("Content-Type", "text/plain");
  1553. auto ret = detail::encoding_type(req, res);
  1554. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1555. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1556. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1557. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1558. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1559. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1560. #else
  1561. EXPECT_TRUE(ret == detail::EncodingType::None);
  1562. #endif
  1563. }
  1564. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1565. // q value should determine priority, not hardcoded order
  1566. Request req;
  1567. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1568. Response res;
  1569. res.set_header("Content-Type", "text/plain");
  1570. auto ret = detail::encoding_type(req, res);
  1571. // gzip has highest q=1.0, so it should be selected even though
  1572. // br and zstd are also supported
  1573. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1574. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1575. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1576. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1577. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1578. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1579. #else
  1580. EXPECT_TRUE(ret == detail::EncodingType::None);
  1581. #endif
  1582. }
  1583. TEST(BufferStreamTest, read) {
  1584. detail::BufferStream strm1;
  1585. Stream &strm = strm1;
  1586. EXPECT_EQ(5, strm.write("hello"));
  1587. char buf[512];
  1588. EXPECT_EQ(2, strm.read(buf, 2));
  1589. EXPECT_EQ('h', buf[0]);
  1590. EXPECT_EQ('e', buf[1]);
  1591. EXPECT_EQ(2, strm.read(buf, 2));
  1592. EXPECT_EQ('l', buf[0]);
  1593. EXPECT_EQ('l', buf[1]);
  1594. EXPECT_EQ(1, strm.read(buf, 1));
  1595. EXPECT_EQ('o', buf[0]);
  1596. EXPECT_EQ(0, strm.read(buf, 1));
  1597. }
  1598. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1599. auto host = "www.httpwatch.com";
  1600. auto ip = hosted_at(host);
  1601. EXPECT_EQ("23.96.13.243", ip);
  1602. std::vector<std::string> addrs;
  1603. hosted_at(host, addrs);
  1604. EXPECT_EQ(1u, addrs.size());
  1605. }
  1606. #if 0 // It depends on each test environment...
  1607. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1608. auto host = "www.youtube.com";
  1609. std::vector<std::string> addrs;
  1610. hosted_at(host, addrs);
  1611. EXPECT_EQ(20u, addrs.size());
  1612. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1613. EXPECT_TRUE(it != addrs.end());
  1614. }
  1615. #endif
  1616. class ChunkedEncodingTest : public ::testing::Test {
  1617. protected:
  1618. ChunkedEncodingTest()
  1619. : cli_(HOST, PORT)
  1620. #ifdef CPPHTTPLIB_SSL_ENABLED
  1621. ,
  1622. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1623. #endif
  1624. {
  1625. cli_.set_connection_timeout(2);
  1626. #ifdef CPPHTTPLIB_SSL_ENABLED
  1627. cli_.enable_server_certificate_verification(false);
  1628. #endif
  1629. }
  1630. virtual void SetUp() {
  1631. read_file("./image.jpg", image_data_);
  1632. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1633. res.set_content("Hello World!", "text/plain");
  1634. });
  1635. svr_.Get(
  1636. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1637. res.set_chunked_content_provider(
  1638. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1639. size_t remaining = image_data_.size() - offset;
  1640. if (remaining == 0) {
  1641. sink.done();
  1642. } else {
  1643. constexpr size_t CHUNK_SIZE = 1024;
  1644. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1645. sink.write(&image_data_[offset], send_size);
  1646. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1647. }
  1648. return true;
  1649. });
  1650. });
  1651. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1652. svr_.wait_until_ready();
  1653. }
  1654. virtual void TearDown() {
  1655. svr_.stop();
  1656. if (!request_threads_.empty()) {
  1657. std::this_thread::sleep_for(std::chrono::seconds(1));
  1658. for (auto &t : request_threads_) {
  1659. t.join();
  1660. }
  1661. }
  1662. t_.join();
  1663. }
  1664. #ifdef CPPHTTPLIB_SSL_ENABLED
  1665. SSLClient cli_;
  1666. SSLServer svr_;
  1667. #else
  1668. Client cli_;
  1669. Server svr_;
  1670. #endif
  1671. thread t_;
  1672. std::vector<thread> request_threads_;
  1673. std::string image_data_;
  1674. };
  1675. TEST_F(ChunkedEncodingTest, NormalGet) {
  1676. auto res = cli_.Get("/chunked");
  1677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1678. std::string out;
  1679. read_file("./image.jpg", out);
  1680. EXPECT_EQ(StatusCode::OK_200, res->status);
  1681. EXPECT_EQ(out, res->body);
  1682. }
  1683. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1684. std::string body;
  1685. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1686. body.append(data, data_length);
  1687. return true;
  1688. });
  1689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1690. std::string out;
  1691. read_file("./image.jpg", out);
  1692. EXPECT_EQ(StatusCode::OK_200, res->status);
  1693. EXPECT_EQ(out, body);
  1694. }
  1695. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1696. std::string body;
  1697. auto res = cli_.Get(
  1698. "/chunked",
  1699. [&](const Response &response) {
  1700. EXPECT_EQ(StatusCode::OK_200, response.status);
  1701. return true;
  1702. },
  1703. [&](const char *data, size_t data_length) {
  1704. body.append(data, data_length);
  1705. return true;
  1706. });
  1707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1708. std::string out;
  1709. read_file("./image.jpg", out);
  1710. EXPECT_EQ(StatusCode::OK_200, res->status);
  1711. EXPECT_EQ(out, body);
  1712. }
  1713. TEST(RangeTest, FromHTTPBin_Online) {
  1714. auto host = "httpbingo.org";
  1715. auto path = std::string{"/range/32"};
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. auto port = 443;
  1718. SSLClient cli(host, port);
  1719. #else
  1720. auto port = 80;
  1721. Client cli(host, port);
  1722. #endif
  1723. cli.set_connection_timeout(5);
  1724. {
  1725. auto res = cli.Get(path);
  1726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1727. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1728. EXPECT_EQ(StatusCode::OK_200, res->status);
  1729. }
  1730. {
  1731. Headers headers = {make_range_header({{1, -1}})};
  1732. auto res = cli.Get(path, headers);
  1733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1734. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1736. }
  1737. {
  1738. Headers headers = {make_range_header({{1, 10}})};
  1739. auto res = cli.Get(path, headers);
  1740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1741. EXPECT_EQ("bcdefghijk", res->body);
  1742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1743. }
  1744. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1745. // entire resource, while the original httpbin returned 200. Both are
  1746. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1747. {
  1748. Headers headers = {make_range_header({{0, 31}})};
  1749. auto res = cli.Get(path, headers);
  1750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1751. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1752. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1753. res->status == StatusCode::PartialContent_206);
  1754. }
  1755. {
  1756. Headers headers = {make_range_header({{0, -1}})};
  1757. auto res = cli.Get(path, headers);
  1758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1759. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1760. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1761. res->status == StatusCode::PartialContent_206);
  1762. }
  1763. // go-httpbin returns 206 with clamped range for over-range requests,
  1764. // while the original httpbin returned 416. Both behaviors are observed
  1765. // in real servers, so we only verify the request succeeds.
  1766. {
  1767. Headers headers = {make_range_header({{0, 32}})};
  1768. auto res = cli.Get(path, headers);
  1769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1770. }
  1771. }
  1772. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1773. auto host = "unresolvableaddress.local";
  1774. auto path = std::string{"/"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. cli.set_connection_timeout(1);
  1783. {
  1784. auto res = cli.Get(path);
  1785. ASSERT_FALSE(res);
  1786. }
  1787. std::this_thread::sleep_for(std::chrono::seconds(8));
  1788. }
  1789. #if defined(__linux__) && defined(__GLIBC__) && \
  1790. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1791. // Forward declaration: in split builds split.py strips `inline` and moves the
  1792. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1793. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1794. // against the symbol in both header-only and split builds.
  1795. namespace httplib {
  1796. namespace detail {
  1797. int getaddrinfo_with_timeout(const char *node, const char *service,
  1798. const struct addrinfo *hints,
  1799. struct addrinfo **res, time_t timeout_sec);
  1800. } // namespace detail
  1801. } // namespace httplib
  1802. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1803. //
  1804. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1805. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1806. // gai_suspend() call hits the connection timeout the function calls
  1807. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1808. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1809. // still alive and still references the now-destroyed stack frame.
  1810. //
  1811. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1812. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1813. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1814. // and runs them in a container.
  1815. namespace {
  1816. bool should_run_issue_2431_tests() {
  1817. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1818. return v && *v && std::string(v) != "0";
  1819. }
  1820. std::string unique_unresolvable_host(int n) {
  1821. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1822. // glibc still asks the configured nameserver — which is exactly the path
  1823. // we want to exercise. A unique label per call avoids the resolver cache.
  1824. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1825. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1826. std::to_string(n) + ".invalid";
  1827. }
  1828. } // namespace
  1829. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1830. if (!should_run_issue_2431_tests()) {
  1831. GTEST_SKIP()
  1832. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1833. }
  1834. for (int i = 0; i < 8; ++i) {
  1835. struct addrinfo hints;
  1836. memset(&hints, 0, sizeof(hints));
  1837. hints.ai_family = AF_UNSPEC;
  1838. hints.ai_socktype = SOCK_STREAM;
  1839. auto host = unique_unresolvable_host(i);
  1840. struct addrinfo *result = nullptr;
  1841. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1842. &result, /*timeout_sec=*/1);
  1843. if (rc == 0 && result) { freeaddrinfo(result); }
  1844. }
  1845. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1846. // stack region they still believe holds their gaicb.
  1847. std::this_thread::sleep_for(std::chrono::seconds(3));
  1848. }
  1849. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1850. if (!should_run_issue_2431_tests()) {
  1851. GTEST_SKIP()
  1852. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1853. }
  1854. std::atomic<bool> stop{false};
  1855. std::vector<std::thread> threads;
  1856. for (int t = 0; t < 8; ++t) {
  1857. threads.emplace_back([t, &stop] {
  1858. int i = 0;
  1859. while (!stop.load(std::memory_order_relaxed)) {
  1860. struct addrinfo hints;
  1861. memset(&hints, 0, sizeof(hints));
  1862. hints.ai_family = AF_UNSPEC;
  1863. hints.ai_socktype = SOCK_STREAM;
  1864. auto host = unique_unresolvable_host(t * 100000 + i++);
  1865. struct addrinfo *result = nullptr;
  1866. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1867. &result, /*timeout_sec=*/1);
  1868. if (rc == 0 && result) { freeaddrinfo(result); }
  1869. }
  1870. });
  1871. }
  1872. std::this_thread::sleep_for(std::chrono::seconds(8));
  1873. stop.store(true, std::memory_order_relaxed);
  1874. for (auto &th : threads) {
  1875. th.join();
  1876. }
  1877. std::this_thread::sleep_for(std::chrono::seconds(3));
  1878. }
  1879. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1880. if (!should_run_issue_2431_tests()) {
  1881. GTEST_SKIP()
  1882. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1883. }
  1884. std::atomic<bool> stop{false};
  1885. std::vector<std::thread> threads;
  1886. for (int t = 0; t < 8; ++t) {
  1887. threads.emplace_back([t, &stop] {
  1888. int i = 0;
  1889. while (!stop.load(std::memory_order_relaxed)) {
  1890. auto host = unique_unresolvable_host(t * 100000 + i++);
  1891. Client cli(host, 80);
  1892. cli.set_connection_timeout(1, 0);
  1893. cli.set_read_timeout(1, 0);
  1894. cli.set_write_timeout(1, 0);
  1895. (void)cli.Get("/");
  1896. }
  1897. });
  1898. }
  1899. std::this_thread::sleep_for(std::chrono::seconds(8));
  1900. stop.store(true, std::memory_order_relaxed);
  1901. for (auto &th : threads) {
  1902. th.join();
  1903. }
  1904. std::this_thread::sleep_for(std::chrono::seconds(3));
  1905. }
  1906. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1907. TEST(ConnectionErrorTest, InvalidHost) {
  1908. auto host = "-abcde.com";
  1909. #ifdef CPPHTTPLIB_SSL_ENABLED
  1910. auto port = 443;
  1911. SSLClient cli(host, port);
  1912. #else
  1913. auto port = 80;
  1914. Client cli(host, port);
  1915. #endif
  1916. cli.set_connection_timeout(std::chrono::seconds(2));
  1917. auto res = cli.Get("/");
  1918. ASSERT_TRUE(!res);
  1919. EXPECT_EQ(Error::Connection, res.error());
  1920. }
  1921. TEST(ConnectionErrorTest, InvalidHost2) {
  1922. auto host = "httpcan.org/";
  1923. #ifdef CPPHTTPLIB_SSL_ENABLED
  1924. SSLClient cli(host);
  1925. #else
  1926. Client cli(host);
  1927. #endif
  1928. cli.set_connection_timeout(std::chrono::seconds(2));
  1929. auto res = cli.Get("/");
  1930. ASSERT_TRUE(!res);
  1931. EXPECT_EQ(Error::Connection, res.error());
  1932. }
  1933. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1934. auto host = "httpcan.org/";
  1935. #ifdef CPPHTTPLIB_SSL_ENABLED
  1936. SSLClient cli(host);
  1937. #else
  1938. Client cli(host);
  1939. #endif
  1940. cli.set_connection_timeout(std::chrono::seconds(2));
  1941. auto res = cli.Get("/");
  1942. ASSERT_TRUE(!res);
  1943. stringstream s;
  1944. s << "error code: " << res.error();
  1945. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1946. }
  1947. TEST(ConnectionErrorTest, InvalidPort) {
  1948. auto host = "localhost";
  1949. auto port = 44380;
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host, port);
  1952. #else
  1953. Client cli(host, port);
  1954. #endif
  1955. cli.set_connection_timeout(std::chrono::seconds(2));
  1956. auto res = cli.Get("/");
  1957. ASSERT_TRUE(!res);
  1958. EXPECT_TRUE(Error::Connection == res.error() ||
  1959. Error::ConnectionTimeout == res.error());
  1960. }
  1961. TEST(ConnectionErrorTest, Timeout_Online) {
  1962. auto host = "google.com";
  1963. #ifdef CPPHTTPLIB_SSL_ENABLED
  1964. auto port = 44380;
  1965. SSLClient cli(host, port);
  1966. #else
  1967. auto port = 8080;
  1968. Client cli(host, port);
  1969. #endif
  1970. cli.set_connection_timeout(std::chrono::seconds(2));
  1971. // only probe one address type so that the error reason
  1972. // correlates to the timed-out IPv4, not the unsupported
  1973. // IPv6 connection attempt
  1974. cli.set_address_family(AF_INET);
  1975. auto res = cli.Get("/");
  1976. ASSERT_TRUE(!res);
  1977. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1978. }
  1979. TEST(CancelTest, NoCancel_Online) {
  1980. auto host = "httpbingo.org";
  1981. auto path = std::string{"/range/32"};
  1982. #ifdef CPPHTTPLIB_SSL_ENABLED
  1983. auto port = 443;
  1984. SSLClient cli(host, port);
  1985. #else
  1986. auto port = 80;
  1987. Client cli(host, port);
  1988. #endif
  1989. cli.set_connection_timeout(std::chrono::seconds(5));
  1990. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1992. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1993. EXPECT_EQ(StatusCode::OK_200, res->status);
  1994. }
  1995. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1996. // Use /bytes with a large payload so that the DownloadProgress callback
  1997. // (which only fires for Content-Length responses) is invoked before the
  1998. // entire body is received, giving cancellation a chance to fire.
  1999. auto host = "httpbingo.org";
  2000. auto path = std::string{"/bytes/524288"};
  2001. #ifdef CPPHTTPLIB_SSL_ENABLED
  2002. auto port = 443;
  2003. SSLClient cli(host, port);
  2004. #else
  2005. auto port = 80;
  2006. Client cli(host, port);
  2007. #endif
  2008. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2009. cli.set_connection_timeout(std::chrono::seconds(5));
  2010. ASSERT_TRUE(!res);
  2011. EXPECT_EQ(Error::Canceled, res.error());
  2012. }
  2013. TEST(CancelTest, WithCancelLargePayload_Online) {
  2014. auto host = "httpbingo.org";
  2015. auto path = std::string{"/bytes/524288"};
  2016. #ifdef CPPHTTPLIB_SSL_ENABLED
  2017. auto port = 443;
  2018. SSLClient cli(host, port);
  2019. #else
  2020. auto port = 80;
  2021. Client cli(host, port);
  2022. #endif
  2023. cli.set_connection_timeout(std::chrono::seconds(5));
  2024. uint32_t count = 0;
  2025. auto res =
  2026. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2027. ASSERT_TRUE(!res);
  2028. EXPECT_EQ(Error::Canceled, res.error());
  2029. }
  2030. TEST(CancelTest, NoCancelPost) {
  2031. Server svr;
  2032. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2033. res.set_content("Hello World!", "text/plain");
  2034. });
  2035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2036. auto se = detail::scope_exit([&] {
  2037. svr.stop();
  2038. thread.join();
  2039. ASSERT_FALSE(svr.is_running());
  2040. });
  2041. svr.wait_until_ready();
  2042. Client cli(HOST, PORT);
  2043. cli.set_connection_timeout(std::chrono::seconds(5));
  2044. auto res =
  2045. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2046. "application/json", [](uint64_t, uint64_t) { return true; });
  2047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2048. EXPECT_EQ("Hello World!", res->body);
  2049. EXPECT_EQ(StatusCode::OK_200, res->status);
  2050. }
  2051. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2052. Server svr;
  2053. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2054. res.set_content("Hello World!", "text/plain");
  2055. });
  2056. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2057. auto se = detail::scope_exit([&] {
  2058. svr.stop();
  2059. thread.join();
  2060. ASSERT_FALSE(svr.is_running());
  2061. });
  2062. svr.wait_until_ready();
  2063. Client cli(HOST, PORT);
  2064. cli.set_connection_timeout(std::chrono::seconds(5));
  2065. auto res =
  2066. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2067. "application/json", [](uint64_t, uint64_t) { return false; });
  2068. ASSERT_TRUE(!res);
  2069. EXPECT_EQ(Error::Canceled, res.error());
  2070. }
  2071. TEST(CancelTest, WithCancelLargePayloadPost) {
  2072. Server svr;
  2073. svr.set_payload_max_length(200 * 1024 * 1024);
  2074. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2075. res.set_content(LARGE_DATA, "text/plain");
  2076. });
  2077. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2078. auto se = detail::scope_exit([&] {
  2079. svr.stop();
  2080. thread.join();
  2081. ASSERT_FALSE(svr.is_running());
  2082. });
  2083. svr.wait_until_ready();
  2084. Client cli(HOST, PORT);
  2085. cli.set_payload_max_length(200 * 1024 * 1024);
  2086. cli.set_connection_timeout(std::chrono::seconds(5));
  2087. auto res =
  2088. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2089. "application/json", [](uint64_t, uint64_t) { return false; });
  2090. ASSERT_TRUE(!res);
  2091. EXPECT_EQ(Error::Canceled, res.error());
  2092. }
  2093. TEST(CancelTest, NoCancelPut) {
  2094. Server svr;
  2095. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2096. res.set_content("Hello World!", "text/plain");
  2097. });
  2098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2099. auto se = detail::scope_exit([&] {
  2100. svr.stop();
  2101. thread.join();
  2102. ASSERT_FALSE(svr.is_running());
  2103. });
  2104. svr.wait_until_ready();
  2105. Client cli(HOST, PORT);
  2106. cli.set_connection_timeout(std::chrono::seconds(5));
  2107. auto res =
  2108. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2109. "application/json", [](uint64_t, uint64_t) { return true; });
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. EXPECT_EQ("Hello World!", res->body);
  2112. EXPECT_EQ(StatusCode::OK_200, res->status);
  2113. }
  2114. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2115. Server svr;
  2116. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2117. res.set_content("Hello World!", "text/plain");
  2118. });
  2119. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2120. auto se = detail::scope_exit([&] {
  2121. svr.stop();
  2122. thread.join();
  2123. ASSERT_FALSE(svr.is_running());
  2124. });
  2125. svr.wait_until_ready();
  2126. Client cli(HOST, PORT);
  2127. cli.set_connection_timeout(std::chrono::seconds(5));
  2128. auto res =
  2129. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2130. "application/json", [](uint64_t, uint64_t) { return false; });
  2131. ASSERT_TRUE(!res);
  2132. EXPECT_EQ(Error::Canceled, res.error());
  2133. }
  2134. TEST(CancelTest, WithCancelLargePayloadPut) {
  2135. Server svr;
  2136. svr.set_payload_max_length(200 * 1024 * 1024);
  2137. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2138. res.set_content(LARGE_DATA, "text/plain");
  2139. });
  2140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2141. auto se = detail::scope_exit([&] {
  2142. svr.stop();
  2143. thread.join();
  2144. ASSERT_FALSE(svr.is_running());
  2145. });
  2146. svr.wait_until_ready();
  2147. Client cli(HOST, PORT);
  2148. cli.set_payload_max_length(200 * 1024 * 1024);
  2149. cli.set_connection_timeout(std::chrono::seconds(5));
  2150. auto res =
  2151. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2152. "application/json", [](uint64_t, uint64_t) { return false; });
  2153. ASSERT_TRUE(!res);
  2154. EXPECT_EQ(Error::Canceled, res.error());
  2155. }
  2156. TEST(CancelTest, NoCancelPatch) {
  2157. Server svr;
  2158. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2159. res.set_content("Hello World!", "text/plain");
  2160. });
  2161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2162. auto se = detail::scope_exit([&] {
  2163. svr.stop();
  2164. thread.join();
  2165. ASSERT_FALSE(svr.is_running());
  2166. });
  2167. svr.wait_until_ready();
  2168. Client cli(HOST, PORT);
  2169. cli.set_connection_timeout(std::chrono::seconds(5));
  2170. auto res =
  2171. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2172. "application/json", [](uint64_t, uint64_t) { return true; });
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ("Hello World!", res->body);
  2175. EXPECT_EQ(StatusCode::OK_200, res->status);
  2176. }
  2177. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2178. Server svr;
  2179. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2180. res.set_content("Hello World!", "text/plain");
  2181. });
  2182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2183. auto se = detail::scope_exit([&] {
  2184. svr.stop();
  2185. thread.join();
  2186. ASSERT_FALSE(svr.is_running());
  2187. });
  2188. svr.wait_until_ready();
  2189. Client cli(HOST, PORT);
  2190. cli.set_connection_timeout(std::chrono::seconds(5));
  2191. auto res =
  2192. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2193. "application/json", [](uint64_t, uint64_t) { return false; });
  2194. ASSERT_TRUE(!res);
  2195. EXPECT_EQ(Error::Canceled, res.error());
  2196. }
  2197. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2198. Server svr;
  2199. svr.set_payload_max_length(200 * 1024 * 1024);
  2200. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2201. res.set_content(LARGE_DATA, "text/plain");
  2202. });
  2203. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2204. auto se = detail::scope_exit([&] {
  2205. svr.stop();
  2206. thread.join();
  2207. ASSERT_FALSE(svr.is_running());
  2208. });
  2209. svr.wait_until_ready();
  2210. Client cli(HOST, PORT);
  2211. cli.set_payload_max_length(200 * 1024 * 1024);
  2212. cli.set_connection_timeout(std::chrono::seconds(5));
  2213. auto res =
  2214. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2215. "application/json", [](uint64_t, uint64_t) { return false; });
  2216. ASSERT_TRUE(!res);
  2217. EXPECT_EQ(Error::Canceled, res.error());
  2218. }
  2219. TEST(CancelTest, NoCancelDelete) {
  2220. Server svr;
  2221. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2222. res.set_content("Hello World!", "text/plain");
  2223. });
  2224. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2225. auto se = detail::scope_exit([&] {
  2226. svr.stop();
  2227. thread.join();
  2228. ASSERT_FALSE(svr.is_running());
  2229. });
  2230. svr.wait_until_ready();
  2231. Client cli(HOST, PORT);
  2232. cli.set_connection_timeout(std::chrono::seconds(5));
  2233. auto res =
  2234. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2235. "application/json", [](uint64_t, uint64_t) { return true; });
  2236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2237. EXPECT_EQ("Hello World!", res->body);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. }
  2240. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2241. Server svr;
  2242. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2243. res.set_content("Hello World!", "text/plain");
  2244. });
  2245. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2246. auto se = detail::scope_exit([&] {
  2247. svr.stop();
  2248. thread.join();
  2249. ASSERT_FALSE(svr.is_running());
  2250. });
  2251. svr.wait_until_ready();
  2252. Client cli(HOST, PORT);
  2253. cli.set_connection_timeout(std::chrono::seconds(5));
  2254. auto res =
  2255. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2256. "application/json", [](uint64_t, uint64_t) { return false; });
  2257. ASSERT_TRUE(!res);
  2258. EXPECT_EQ(Error::Canceled, res.error());
  2259. }
  2260. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2261. Server svr;
  2262. svr.set_payload_max_length(200 * 1024 * 1024);
  2263. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2264. res.set_content(LARGE_DATA, "text/plain");
  2265. });
  2266. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2267. auto se = detail::scope_exit([&] {
  2268. svr.stop();
  2269. thread.join();
  2270. ASSERT_FALSE(svr.is_running());
  2271. });
  2272. svr.wait_until_ready();
  2273. Client cli(HOST, PORT);
  2274. cli.set_payload_max_length(200 * 1024 * 1024);
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. auto res =
  2277. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2278. "application/json", [](uint64_t, uint64_t) { return false; });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. static std::string remove_whitespace(const std::string &input) {
  2283. std::string output;
  2284. output.reserve(input.size());
  2285. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2286. [](unsigned char c) { return !std::isspace(c); });
  2287. return output;
  2288. }
  2289. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2290. auto host = "httpbingo.org";
  2291. auto path = std::string{"/basic-auth/hello/world"};
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. auto port = 443;
  2294. SSLClient cli(host, port);
  2295. #else
  2296. auto port = 80;
  2297. Client cli(host, port);
  2298. #endif
  2299. {
  2300. auto res = cli.Get(path);
  2301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2302. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2303. }
  2304. {
  2305. auto res = cli.Get(
  2306. path, Headers{make_basic_authentication_header("hello", "world")});
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. auto body = remove_whitespace(res->body);
  2309. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2310. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2311. EXPECT_EQ(StatusCode::OK_200, res->status);
  2312. }
  2313. {
  2314. cli.set_basic_auth("hello", "world");
  2315. auto res = cli.Get(path);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. auto body = remove_whitespace(res->body);
  2318. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2319. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2320. EXPECT_EQ(StatusCode::OK_200, res->status);
  2321. }
  2322. {
  2323. cli.set_basic_auth("hello", "bad");
  2324. auto res = cli.Get(path);
  2325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2326. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2327. }
  2328. {
  2329. cli.set_basic_auth("bad", "world");
  2330. auto res = cli.Get(path);
  2331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2332. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2333. }
  2334. }
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2337. auto host = "httpbingo.org";
  2338. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2339. auto paths = std::vector<std::string>{
  2340. "/digest-auth/auth/hello/world/MD5",
  2341. "/digest-auth/auth/hello/world/SHA-256",
  2342. };
  2343. auto port = 443;
  2344. SSLClient cli(host, port);
  2345. {
  2346. auto res = cli.Get(unauth_path);
  2347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2348. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2349. }
  2350. {
  2351. cli.set_digest_auth("hello", "world");
  2352. for (const auto &path : paths) {
  2353. auto res = cli.Get(path.c_str());
  2354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2355. auto body = remove_whitespace(res->body);
  2356. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2357. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2358. EXPECT_EQ(StatusCode::OK_200, res->status);
  2359. }
  2360. cli.set_digest_auth("hello", "bad");
  2361. for (const auto &path : paths) {
  2362. auto res = cli.Get(path.c_str());
  2363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2364. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2365. }
  2366. }
  2367. }
  2368. #endif
  2369. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2370. auto host = "google.com";
  2371. auto another_host = "example.com";
  2372. auto wrong_ip = "0.0.0.0";
  2373. #ifdef CPPHTTPLIB_SSL_ENABLED
  2374. SSLClient cli(host);
  2375. #else
  2376. Client cli(host);
  2377. #endif
  2378. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2379. auto res = cli.Get("/");
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2382. }
  2383. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2384. auto host = "google.com";
  2385. auto wrong_ip = "0.0.0.0";
  2386. #ifdef CPPHTTPLIB_SSL_ENABLED
  2387. SSLClient cli(host);
  2388. #else
  2389. Client cli(host);
  2390. #endif
  2391. cli.set_hostname_addr_map({{host, wrong_ip}});
  2392. auto res = cli.Get("/");
  2393. ASSERT_TRUE(!res);
  2394. EXPECT_EQ(Error::Connection, res.error());
  2395. }
  2396. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2397. // A mapped value that is not an IP literal must be resolved. "localhost"
  2398. // resolves from the hosts file, so this test needs no external DNS.
  2399. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2400. auto host = "target.invalid";
  2401. Server svr;
  2402. std::string received_host;
  2403. svr.Get("/hi", [&](const Request &req, Response &res) {
  2404. received_host = req.get_header_value("Host");
  2405. res.set_content("Hello World!", "text/plain");
  2406. });
  2407. auto port = svr.bind_to_any_port(HOST);
  2408. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2409. auto se = detail::scope_exit([&] {
  2410. svr.stop();
  2411. thread.join();
  2412. ASSERT_FALSE(svr.is_running());
  2413. });
  2414. svr.wait_until_ready();
  2415. Client cli(host, port);
  2416. cli.set_hostname_addr_map({{host, HOST}});
  2417. auto res = cli.Get("/hi");
  2418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2419. EXPECT_EQ(StatusCode::OK_200, res->status);
  2420. // The mapping only redirects the connection; the identity stays host_.
  2421. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2422. }
  2423. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2424. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2425. auto host = "target.invalid";
  2426. Server svr;
  2427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2428. res.set_content("Hello World!", "text/plain");
  2429. });
  2430. auto port = svr.bind_to_any_port("127.0.0.1");
  2431. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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_hostname_addr_map({{host, "127.0.0.1"}});
  2440. auto res = cli.Get("/hi");
  2441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2442. EXPECT_EQ(StatusCode::OK_200, res->status);
  2443. }
  2444. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2445. // An empty mapped value must leave host_ as the connection target. Without
  2446. // that guard the empty value would become the host argument, getaddrinfo
  2447. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2448. // loopback - silently connecting somewhere the caller never asked for.
  2449. // The server listens on loopback, so such a fallback would succeed and is
  2450. // therefore observable as a failure of this test.
  2451. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2452. Server svr;
  2453. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2454. res.set_content("Hello World!", "text/plain");
  2455. });
  2456. auto port = svr.bind_to_any_port(HOST);
  2457. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2458. auto se = detail::scope_exit([&] {
  2459. svr.stop();
  2460. thread.join();
  2461. ASSERT_FALSE(svr.is_running());
  2462. });
  2463. svr.wait_until_ready();
  2464. Client cli(blackhole, port);
  2465. cli.set_hostname_addr_map({{blackhole, ""}});
  2466. cli.set_connection_timeout(1);
  2467. auto res = cli.Get("/hi");
  2468. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2469. }
  2470. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2471. auto host = "httpbingo.org";
  2472. auto path = std::string{"/absolute-redirect/3"};
  2473. #ifdef CPPHTTPLIB_SSL_ENABLED
  2474. SSLClient cli(host);
  2475. #else
  2476. Client cli(host);
  2477. #endif
  2478. cli.set_follow_location(true);
  2479. auto res = cli.Get(path);
  2480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2481. EXPECT_EQ(StatusCode::OK_200, res->status);
  2482. }
  2483. TEST(RedirectTest, Redirect_Online) {
  2484. auto host = "httpbingo.org";
  2485. auto path = std::string{"/redirect/3"};
  2486. #ifdef CPPHTTPLIB_SSL_ENABLED
  2487. SSLClient cli(host);
  2488. #else
  2489. Client cli(host);
  2490. #endif
  2491. cli.set_follow_location(true);
  2492. auto res = cli.Get(path);
  2493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2494. EXPECT_EQ(StatusCode::OK_200, res->status);
  2495. }
  2496. TEST(RelativeRedirectTest, Redirect_Online) {
  2497. auto host = "httpbingo.org";
  2498. auto path = std::string{"/relative-redirect/3"};
  2499. #ifdef CPPHTTPLIB_SSL_ENABLED
  2500. SSLClient cli(host);
  2501. #else
  2502. Client cli(host);
  2503. #endif
  2504. cli.set_follow_location(true);
  2505. auto res = cli.Get(path);
  2506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2507. EXPECT_EQ(StatusCode::OK_200, res->status);
  2508. }
  2509. TEST(TooManyRedirectTest, Redirect_Online) {
  2510. auto host = "httpbingo.org";
  2511. auto path = std::string{"/redirect/21"};
  2512. #ifdef CPPHTTPLIB_SSL_ENABLED
  2513. SSLClient cli(host);
  2514. #else
  2515. Client cli(host);
  2516. #endif
  2517. cli.set_follow_location(true);
  2518. auto res = cli.Get(path);
  2519. ASSERT_TRUE(!res);
  2520. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2521. }
  2522. #ifdef CPPHTTPLIB_SSL_ENABLED
  2523. TEST(YahooRedirectTest, Redirect_Online) {
  2524. Client cli("yahoo.com");
  2525. auto res = cli.Get("/");
  2526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2527. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2528. cli.set_follow_location(true);
  2529. res = cli.Get("/");
  2530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2531. EXPECT_EQ(StatusCode::OK_200, res->status);
  2532. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2533. }
  2534. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2535. #define REDIR_HOST "httpbingo.org"
  2536. #define REDIR_PATH "/redirect-to"
  2537. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2538. SSLClient cli(REDIR_HOST);
  2539. cli.set_follow_location(true);
  2540. auto res =
  2541. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. }
  2545. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2546. SSLClient cli(REDIR_HOST);
  2547. cli.set_follow_location(true);
  2548. Params params;
  2549. params.emplace("url", "http://example.com");
  2550. params.emplace("status_code", "302");
  2551. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2556. SSLClient cli(REDIR_HOST);
  2557. cli.set_follow_location(true);
  2558. Params params;
  2559. params.emplace("url", "http://example.com");
  2560. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2562. EXPECT_EQ(StatusCode::OK_200, res->status);
  2563. }
  2564. TEST(UrlWithSpace, Redirect_Online) {
  2565. SSLClient cli("edge.forgecdn.net");
  2566. cli.set_follow_location(true);
  2567. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. EXPECT_EQ(StatusCode::OK_200, res->status);
  2570. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2571. }
  2572. #endif
  2573. #if !defined(_WIN32) && !defined(_WIN64)
  2574. TEST(ReceiveSignals, Signal) {
  2575. auto setupSignalHandlers = []() {
  2576. struct sigaction act;
  2577. sigemptyset(&act.sa_mask);
  2578. act.sa_flags = SA_SIGINFO;
  2579. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2580. switch (sig) {
  2581. case SIGINT:
  2582. default: break;
  2583. }
  2584. };
  2585. ::sigaction(SIGINT, &act, nullptr);
  2586. };
  2587. Server svr;
  2588. int port = 0;
  2589. auto thread = std::thread([&]() {
  2590. setupSignalHandlers();
  2591. port = svr.bind_to_any_port(HOST);
  2592. svr.listen_after_bind();
  2593. });
  2594. auto se = detail::scope_exit([&] {
  2595. svr.stop();
  2596. thread.join();
  2597. ASSERT_FALSE(svr.is_running());
  2598. });
  2599. svr.wait_until_ready();
  2600. ASSERT_TRUE(svr.is_running());
  2601. pthread_kill(thread.native_handle(), SIGINT);
  2602. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2603. ASSERT_TRUE(svr.is_running());
  2604. }
  2605. #endif
  2606. TEST(RedirectToDifferentPort, Redirect) {
  2607. Server svr1;
  2608. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2609. res.set_content("Hello World!", "text/plain");
  2610. });
  2611. int svr1_port = 0;
  2612. auto thread1 = std::thread([&]() {
  2613. svr1_port = svr1.bind_to_any_port(HOST);
  2614. svr1.listen_after_bind();
  2615. });
  2616. Server svr2;
  2617. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2618. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2619. });
  2620. int svr2_port = 0;
  2621. auto thread2 = std::thread([&]() {
  2622. svr2_port = svr2.bind_to_any_port(HOST);
  2623. svr2.listen_after_bind();
  2624. });
  2625. auto se = detail::scope_exit([&] {
  2626. svr2.stop();
  2627. thread2.join();
  2628. svr1.stop();
  2629. thread1.join();
  2630. ASSERT_FALSE(svr2.is_running());
  2631. ASSERT_FALSE(svr1.is_running());
  2632. });
  2633. svr1.wait_until_ready();
  2634. svr2.wait_until_ready();
  2635. Client cli("localhost", svr2_port);
  2636. cli.set_follow_location(true);
  2637. auto res = cli.Get("/2");
  2638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2639. EXPECT_EQ(StatusCode::OK_200, res->status);
  2640. EXPECT_EQ("Hello World!", res->body);
  2641. }
  2642. static void
  2643. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2644. Server svr1;
  2645. std::string captured_authorization;
  2646. svr1.Get("/target", [&](const Request &req, Response &res) {
  2647. captured_authorization = req.get_header_value("Authorization");
  2648. res.set_content("OK", "text/plain");
  2649. });
  2650. int svr1_port = 0;
  2651. auto thread1 = std::thread([&]() {
  2652. svr1_port = svr1.bind_to_any_port(HOST);
  2653. svr1.listen_after_bind();
  2654. });
  2655. Server svr2;
  2656. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2657. res.set_redirect(
  2658. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2659. });
  2660. int svr2_port = 0;
  2661. auto thread2 = std::thread([&]() {
  2662. svr2_port = svr2.bind_to_any_port(HOST);
  2663. svr2.listen_after_bind();
  2664. });
  2665. auto se = detail::scope_exit([&] {
  2666. svr2.stop();
  2667. thread2.join();
  2668. svr1.stop();
  2669. thread1.join();
  2670. ASSERT_FALSE(svr2.is_running());
  2671. ASSERT_FALSE(svr1.is_running());
  2672. });
  2673. svr1.wait_until_ready();
  2674. svr2.wait_until_ready();
  2675. Client cli("localhost", svr2_port);
  2676. cli.set_follow_location(true);
  2677. set_auth(cli);
  2678. auto res = cli.Get("/redir");
  2679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2680. EXPECT_EQ(StatusCode::OK_200, res->status);
  2681. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2682. EXPECT_TRUE(captured_authorization.empty());
  2683. }
  2684. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2685. TestDoNotForwardCredentialsOnRedirect(
  2686. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2687. }
  2688. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2689. TestDoNotForwardCredentialsOnRedirect(
  2690. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2691. }
  2692. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2693. Server svr1;
  2694. std::string captured_cookie;
  2695. bool target_hit = false;
  2696. svr1.Get("/target", [&](const Request &req, Response &res) {
  2697. captured_cookie = req.get_header_value("Cookie");
  2698. target_hit = true;
  2699. res.set_content("OK", "text/plain");
  2700. });
  2701. int svr1_port = 0;
  2702. auto thread1 = std::thread([&]() {
  2703. svr1_port = svr1.bind_to_any_port(HOST);
  2704. svr1.listen_after_bind();
  2705. });
  2706. Server svr2;
  2707. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2708. res.set_redirect(
  2709. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2710. });
  2711. int svr2_port = 0;
  2712. auto thread2 = std::thread([&]() {
  2713. svr2_port = svr2.bind_to_any_port(HOST);
  2714. svr2.listen_after_bind();
  2715. });
  2716. auto se = detail::scope_exit([&] {
  2717. svr2.stop();
  2718. thread2.join();
  2719. svr1.stop();
  2720. thread1.join();
  2721. ASSERT_FALSE(svr2.is_running());
  2722. ASSERT_FALSE(svr1.is_running());
  2723. });
  2724. svr1.wait_until_ready();
  2725. svr2.wait_until_ready();
  2726. Client cli("localhost", svr2_port);
  2727. cli.set_follow_location(true);
  2728. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2729. auto res = cli.Get("/redir", headers);
  2730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2731. EXPECT_EQ(StatusCode::OK_200, res->status);
  2732. EXPECT_TRUE(target_hit);
  2733. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2734. EXPECT_TRUE(captured_cookie.empty());
  2735. }
  2736. TEST(RedirectToSamePort, ForwardCookie) {
  2737. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2738. // header so that ordinary session flows keep working.
  2739. Server svr;
  2740. std::string captured_cookie;
  2741. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2742. res.set_redirect("/target", 302);
  2743. });
  2744. svr.Get("/target", [&](const Request &req, Response &res) {
  2745. captured_cookie = req.get_header_value("Cookie");
  2746. res.set_content("OK", "text/plain");
  2747. });
  2748. auto port = svr.bind_to_any_port(HOST);
  2749. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli(HOST, port);
  2757. cli.set_follow_location(true);
  2758. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2759. auto res = cli.Get("/redir", headers);
  2760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2761. EXPECT_EQ(StatusCode::OK_200, res->status);
  2762. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2763. }
  2764. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2765. Server svr;
  2766. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2767. // Port number that overflows int — should not crash
  2768. res.set_redirect("http://localhost:99999999999999999999/target");
  2769. });
  2770. auto port = svr.bind_to_any_port(HOST);
  2771. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2772. auto se = detail::scope_exit([&] {
  2773. svr.stop();
  2774. thread.join();
  2775. ASSERT_FALSE(svr.is_running());
  2776. });
  2777. svr.wait_until_ready();
  2778. Client cli(HOST, port);
  2779. cli.set_follow_location(true);
  2780. auto res = cli.Get("/redir");
  2781. // Should fail gracefully, not crash (no valid response due to bad port)
  2782. EXPECT_FALSE(res);
  2783. }
  2784. TEST(RedirectFromPageWithContent, Redirect) {
  2785. Server svr;
  2786. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2787. res.set_content("___", "text/plain");
  2788. res.set_redirect("/2");
  2789. });
  2790. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2791. res.set_content("Hello World!", "text/plain");
  2792. });
  2793. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2794. auto se = detail::scope_exit([&] {
  2795. svr.stop();
  2796. th.join();
  2797. ASSERT_FALSE(svr.is_running());
  2798. });
  2799. svr.wait_until_ready();
  2800. {
  2801. Client cli("localhost", PORT);
  2802. cli.set_follow_location(true);
  2803. std::string body;
  2804. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2805. body.append(data, data_length);
  2806. return true;
  2807. });
  2808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2809. EXPECT_EQ(StatusCode::OK_200, res->status);
  2810. EXPECT_EQ("Hello World!", body);
  2811. }
  2812. {
  2813. Client cli("localhost", PORT);
  2814. std::string body;
  2815. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2816. body.append(data, data_length);
  2817. return true;
  2818. });
  2819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2820. EXPECT_EQ(StatusCode::Found_302, res->status);
  2821. EXPECT_EQ("___", body);
  2822. }
  2823. }
  2824. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2825. Server svr;
  2826. auto port_str = std::to_string(PORT);
  2827. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2828. auto expected_host = "[::1]:" + port_str;
  2829. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2830. res.set_content("___", "text/plain");
  2831. // res.set_redirect("/2");
  2832. res.set_redirect(redirect_url);
  2833. });
  2834. svr.Get("/2", [&](const Request &req, Response &res) {
  2835. auto host_header = req.headers.find("Host");
  2836. ASSERT_TRUE(host_header != req.headers.end());
  2837. EXPECT_EQ(expected_host, host_header->second);
  2838. res.set_content("Hello World!", "text/plain");
  2839. });
  2840. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2841. auto se = detail::scope_exit([&] {
  2842. svr.stop();
  2843. th.join();
  2844. ASSERT_FALSE(svr.is_running());
  2845. });
  2846. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2847. // actually starts anything, so the condition !svr.is_running() will
  2848. // always remain true, and the loop never stops.
  2849. // This basically counts how many milliseconds have passed since the
  2850. // call to svr.listen(), and if after 5 seconds nothing started yet
  2851. // aborts the test.
  2852. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2853. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2854. ASSERT_LT(milliseconds, 5000U);
  2855. }
  2856. {
  2857. Client cli("::1", PORT);
  2858. cli.set_follow_location(true);
  2859. std::string body;
  2860. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2861. body.append(data, data_length);
  2862. return true;
  2863. });
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. EXPECT_EQ("Hello World!", body);
  2867. }
  2868. {
  2869. Client cli("::1", PORT);
  2870. std::string body;
  2871. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2872. body.append(data, data_length);
  2873. return true;
  2874. });
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Found_302, res->status);
  2877. EXPECT_EQ("___", body);
  2878. }
  2879. }
  2880. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2881. Server svr;
  2882. svr.Get("/foo", [](const Request &req, Response &res) {
  2883. auto a = req.params.find("a");
  2884. if (a != req.params.end()) {
  2885. res.set_content((*a).second, "text/plain");
  2886. res.status = StatusCode::OK_200;
  2887. } else {
  2888. res.status = StatusCode::BadRequest_400;
  2889. }
  2890. });
  2891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2892. auto se = detail::scope_exit([&] {
  2893. svr.stop();
  2894. thread.join();
  2895. ASSERT_FALSE(svr.is_running());
  2896. });
  2897. svr.wait_until_ready();
  2898. {
  2899. Client cli(HOST, PORT);
  2900. cli.set_path_encode(false);
  2901. auto res = cli.Get("/foo?a=explicitly+encoded");
  2902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. // This expects it back with a space, as the `+` won't have been
  2905. // url-encoded, and server-side the params get decoded turning `+`
  2906. // into spaces.
  2907. EXPECT_EQ("explicitly encoded", res->body);
  2908. }
  2909. }
  2910. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2911. // When path encoding is disabled the client must transmit the supplied
  2912. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2913. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2914. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2915. // than a space (0x20). Assert on the raw wire target to catch this.
  2916. Server svr;
  2917. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2918. svr.Get("/foo", [&](const Request &req, Response &res) {
  2919. EXPECT_EQ(expected_target, req.target);
  2920. res.status = StatusCode::OK_200;
  2921. });
  2922. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2923. auto se = detail::scope_exit([&] {
  2924. svr.stop();
  2925. thread.join();
  2926. ASSERT_FALSE(svr.is_running());
  2927. });
  2928. svr.wait_until_ready();
  2929. {
  2930. Client cli(HOST, PORT);
  2931. cli.set_path_encode(false);
  2932. auto res = cli.Get(expected_target.c_str());
  2933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2934. EXPECT_EQ(StatusCode::OK_200, res->status);
  2935. }
  2936. }
  2937. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2938. // `open_stream()` used to skip the path encoding that the buffered send
  2939. // path applies, so the same `path` produced different bytes in the request
  2940. // line depending on which API was used. Assert the two agree.
  2941. Server svr;
  2942. std::string target;
  2943. svr.Get(".*", [&](const Request &req, Response &res) {
  2944. target = req.target;
  2945. res.status = StatusCode::OK_200;
  2946. });
  2947. auto port = svr.bind_to_any_port(HOST);
  2948. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2949. auto se = detail::scope_exit([&] {
  2950. svr.stop();
  2951. thread.join();
  2952. ASSERT_FALSE(svr.is_running());
  2953. });
  2954. svr.wait_until_ready();
  2955. struct {
  2956. const char *path;
  2957. const char *expected;
  2958. } cases[] = {
  2959. {"/a b?x=1", "/a%20b?x=1"},
  2960. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2961. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2962. };
  2963. for (const auto &c : cases) {
  2964. Client cli(HOST, port);
  2965. target.clear();
  2966. auto res = cli.Get(c.path);
  2967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2968. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2969. auto buffered_target = target;
  2970. target.clear();
  2971. auto handle = cli.open_stream("GET", c.path);
  2972. EXPECT_TRUE(handle.is_valid())
  2973. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2974. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2975. }
  2976. }
  2977. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2978. // The `set_path_encode(false)` contract — transmit the supplied target
  2979. // verbatim — must hold for the streaming API too.
  2980. Server svr;
  2981. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2982. std::string target;
  2983. svr.Get("/foo", [&](const Request &req, Response &res) {
  2984. target = req.target;
  2985. res.status = StatusCode::OK_200;
  2986. });
  2987. auto port = svr.bind_to_any_port(HOST);
  2988. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2989. auto se = detail::scope_exit([&] {
  2990. svr.stop();
  2991. thread.join();
  2992. ASSERT_FALSE(svr.is_running());
  2993. });
  2994. svr.wait_until_ready();
  2995. {
  2996. Client cli(HOST, port);
  2997. cli.set_path_encode(false);
  2998. auto handle = cli.open_stream("GET", expected_target);
  2999. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3000. EXPECT_EQ(expected_target, target);
  3001. }
  3002. }
  3003. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3004. // With path encoding enabled a CR/LF in the target is percent-encoded
  3005. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3006. // write_request_line still backstops `set_path_encode(false)`, which is
  3007. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3008. Server svr;
  3009. // Captured before routing: the decoded path contains a newline, which a
  3010. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3011. std::string target;
  3012. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3013. target = req.target;
  3014. res.status = StatusCode::OK_200;
  3015. return Server::HandlerResponse::Handled;
  3016. });
  3017. auto port = svr.bind_to_any_port(HOST);
  3018. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3019. auto se = detail::scope_exit([&] {
  3020. svr.stop();
  3021. thread.join();
  3022. ASSERT_FALSE(svr.is_running());
  3023. });
  3024. svr.wait_until_ready();
  3025. {
  3026. Client cli(HOST, port);
  3027. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3028. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3029. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3030. }
  3031. }
  3032. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3033. // Nothing may reach the wire: a raw CR/LF target would split the request
  3034. // line and inject headers.
  3035. Server svr;
  3036. // Pre-routing so that "not called" means nothing reached the server at all,
  3037. // rather than merely failing to match a handler pattern.
  3038. auto handler_called = false;
  3039. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3040. handler_called = true;
  3041. res.status = StatusCode::OK_200;
  3042. return Server::HandlerResponse::Handled;
  3043. });
  3044. auto port = svr.bind_to_any_port(HOST);
  3045. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3046. auto se = detail::scope_exit([&] {
  3047. svr.stop();
  3048. thread.join();
  3049. ASSERT_FALSE(svr.is_running());
  3050. });
  3051. svr.wait_until_ready();
  3052. {
  3053. Client cli(HOST, port);
  3054. cli.set_path_encode(false);
  3055. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3056. EXPECT_FALSE(handle.is_valid());
  3057. EXPECT_EQ(Error::Write, handle.error);
  3058. EXPECT_FALSE(handler_called);
  3059. }
  3060. }
  3061. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3062. // Which of the two branches runs is decided by whether the query component
  3063. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3064. // an empty query and must still fall back to building one from
  3065. // `req.params`, while a non-empty query must win over `req.params`.
  3066. Server svr;
  3067. std::string target;
  3068. svr.Get("/foo", [&](const Request &req, Response &res) {
  3069. target = req.target;
  3070. res.status = StatusCode::OK_200;
  3071. });
  3072. auto port = svr.bind_to_any_port(HOST);
  3073. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3074. auto se = detail::scope_exit([&] {
  3075. svr.stop();
  3076. thread.join();
  3077. ASSERT_FALSE(svr.is_running());
  3078. });
  3079. svr.wait_until_ready();
  3080. {
  3081. // Trailing `?` -> empty query component -> `req.params` is used.
  3082. Client cli(HOST, port);
  3083. Request req;
  3084. req.method = "GET";
  3085. req.path = "/foo?";
  3086. req.params.emplace("a", "1");
  3087. target.clear();
  3088. auto res = cli.send(req);
  3089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3090. EXPECT_EQ("/foo?a=1", target);
  3091. }
  3092. {
  3093. // Non-empty query in `req.path` -> `req.params` is not appended.
  3094. Client cli(HOST, port);
  3095. Request req;
  3096. req.method = "GET";
  3097. req.path = "/foo?b=2";
  3098. req.params.emplace("a", "1");
  3099. target.clear();
  3100. auto res = cli.send(req);
  3101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3102. EXPECT_EQ("/foo?b=2", target);
  3103. }
  3104. }
  3105. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3106. Server svr;
  3107. svr.Get("/", [](const Request &req, Response &) {
  3108. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3109. });
  3110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3111. auto se = detail::scope_exit([&] {
  3112. svr.stop();
  3113. thread.join();
  3114. ASSERT_FALSE(svr.is_running());
  3115. });
  3116. svr.wait_until_ready();
  3117. {
  3118. Client cli(HOST, PORT);
  3119. cli.set_path_encode(false);
  3120. auto res = cli.Get("/?something=%0A");
  3121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3122. EXPECT_EQ(StatusCode::OK_200, res->status);
  3123. }
  3124. }
  3125. TEST(BindServerTest, BindDualStack) {
  3126. Server svr;
  3127. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3128. res.set_content("Hello World!", "text/plain");
  3129. });
  3130. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3131. auto se = detail::scope_exit([&] {
  3132. svr.stop();
  3133. thread.join();
  3134. ASSERT_FALSE(svr.is_running());
  3135. });
  3136. svr.wait_until_ready();
  3137. {
  3138. Client cli("127.0.0.1", PORT);
  3139. auto res = cli.Get("/1");
  3140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("Hello World!", res->body);
  3143. }
  3144. {
  3145. Client cli("::1", PORT);
  3146. auto res = cli.Get("/1");
  3147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3148. EXPECT_EQ(StatusCode::OK_200, res->status);
  3149. EXPECT_EQ("Hello World!", res->body);
  3150. }
  3151. }
  3152. TEST(BindServerTest, BindAndListenSeparately) {
  3153. Server svr;
  3154. int port = svr.bind_to_any_port("0.0.0.0");
  3155. ASSERT_TRUE(svr.is_valid());
  3156. ASSERT_TRUE(port > 0);
  3157. svr.stop();
  3158. }
  3159. // Reports whether anything is still listening on a loopback port. A plain
  3160. // connect() is used instead of a Client request because a socket left bound by
  3161. // mistake accepts the connection into its backlog and never answers, which
  3162. // would hang the test instead of failing it.
  3163. static bool is_loopback_port_accepting(int port) {
  3164. sockaddr_in addr{};
  3165. addr.sin_family = AF_INET;
  3166. addr.sin_port = htons(static_cast<uint16_t>(port));
  3167. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3168. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3169. EXPECT_NE(sock, INVALID_SOCKET);
  3170. if (sock == INVALID_SOCKET) { return false; }
  3171. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3172. static_cast<socklen_t>(sizeof(addr)));
  3173. detail::close_socket(sock);
  3174. return ret == 0;
  3175. }
  3176. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3177. Server svr;
  3178. auto port = svr.bind_to_any_port("127.0.0.1");
  3179. ASSERT_TRUE(port > 0);
  3180. svr.stop();
  3181. // bind_to_any_port() already called listen(2), so until stop() closed the
  3182. // descriptor the port kept accepting connections into the backlog. ASSERT
  3183. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3184. // below blocks forever in the accept loop.
  3185. ASSERT_FALSE(is_loopback_port_accepting(port));
  3186. // Nothing is left to accept on, so listen_after_bind() must report failure
  3187. // instead of returning success without ever serving.
  3188. EXPECT_FALSE(svr.listen_after_bind());
  3189. // The failed listen marks the server decommissioned, so a waiter returns
  3190. // instead of spinning forever.
  3191. svr.wait_until_ready();
  3192. }
  3193. #ifdef CPPHTTPLIB_SSL_ENABLED
  3194. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3195. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3196. CLIENT_CA_CERT_DIR);
  3197. int port = svr.bind_to_any_port("0.0.0.0");
  3198. ASSERT_TRUE(svr.is_valid());
  3199. ASSERT_TRUE(port > 0);
  3200. svr.stop();
  3201. }
  3202. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3203. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3204. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3205. int port = svr.bind_to_any_port("0.0.0.0");
  3206. ASSERT_TRUE(svr.is_valid());
  3207. ASSERT_TRUE(port > 0);
  3208. svr.stop();
  3209. }
  3210. TEST(BindServerTest, UpdateCertsPem) {
  3211. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3212. int port = svr.bind_to_any_port("0.0.0.0");
  3213. ASSERT_TRUE(svr.is_valid());
  3214. ASSERT_TRUE(port > 0);
  3215. // Read PEM files
  3216. std::string cert_pem, key_pem, ca_pem;
  3217. read_file(SERVER_CERT_FILE, cert_pem);
  3218. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3219. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3220. // Update server certificates using PEM API
  3221. ASSERT_TRUE(
  3222. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3223. ASSERT_TRUE(svr.is_valid());
  3224. svr.stop();
  3225. }
  3226. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3227. // Start server with client CA (enables client auth)
  3228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3229. ASSERT_TRUE(svr.is_valid());
  3230. bool handler_called = false;
  3231. svr.Get("/test", [&](const Request &req, Response &res) {
  3232. handler_called = true;
  3233. // Verify client certificate is present
  3234. auto cert = req.peer_cert();
  3235. EXPECT_TRUE(static_cast<bool>(cert));
  3236. res.set_content("ok", "text/plain");
  3237. });
  3238. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3239. auto se = detail::scope_exit([&] {
  3240. svr.stop();
  3241. t.join();
  3242. ASSERT_FALSE(svr.is_running());
  3243. });
  3244. svr.wait_until_ready();
  3245. // Read PEM files
  3246. std::string cert_pem, key_pem, ca_pem;
  3247. read_file(SERVER_CERT_FILE, cert_pem);
  3248. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3249. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3250. // Update server certificates and client CA using PEM API while server running
  3251. ASSERT_TRUE(
  3252. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3253. // Connect with client certificate
  3254. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3255. cli.enable_server_certificate_verification(false);
  3256. cli.set_connection_timeout(30);
  3257. auto res = cli.Get("/test");
  3258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3259. ASSERT_EQ(StatusCode::OK_200, res->status);
  3260. ASSERT_TRUE(handler_called);
  3261. EXPECT_EQ("ok", res->body);
  3262. }
  3263. #endif
  3264. TEST(ErrorHandlerTest, ContentLength) {
  3265. Server svr;
  3266. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3267. res.status = StatusCode::OK_200;
  3268. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3269. "text/html"); // <= Content-Length still 13
  3270. });
  3271. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3272. res.set_content("Hello World!\n", "text/plain");
  3273. res.status = 524;
  3274. });
  3275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3276. auto se = detail::scope_exit([&] {
  3277. svr.stop();
  3278. thread.join();
  3279. ASSERT_FALSE(svr.is_running());
  3280. });
  3281. svr.wait_until_ready();
  3282. {
  3283. Client cli(HOST, PORT);
  3284. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3288. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3289. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3290. }
  3291. }
  3292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3293. TEST(ExceptionTest, WithoutExceptionHandler) {
  3294. Server svr;
  3295. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3296. throw std::runtime_error("exception...");
  3297. });
  3298. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3299. throw std::runtime_error("exception\r\n...");
  3300. });
  3301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3302. auto se = detail::scope_exit([&] {
  3303. svr.stop();
  3304. listen_thread.join();
  3305. ASSERT_FALSE(svr.is_running());
  3306. });
  3307. svr.wait_until_ready();
  3308. Client cli("localhost", PORT);
  3309. {
  3310. auto res = cli.Get("/exception");
  3311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3312. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3313. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3314. }
  3315. {
  3316. auto res = cli.Get("/unknown");
  3317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3318. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3319. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3320. }
  3321. }
  3322. TEST(ExceptionTest, WithExceptionHandler) {
  3323. Server svr;
  3324. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3325. std::exception_ptr ep) {
  3326. EXPECT_FALSE(ep == nullptr);
  3327. try {
  3328. std::rethrow_exception(ep);
  3329. } catch (std::exception &e) {
  3330. EXPECT_EQ("abc", std::string(e.what()));
  3331. } catch (...) {}
  3332. res.status = StatusCode::InternalServerError_500;
  3333. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3334. "text/html"); // <= Content-Length still 13 at this point
  3335. });
  3336. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3337. res.set_content("Hello World!\n", "text/plain");
  3338. throw std::runtime_error("abc");
  3339. });
  3340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. for (size_t i = 0; i < 10; i++) {
  3348. Client cli(HOST, PORT);
  3349. for (size_t j = 0; j < 100; j++) {
  3350. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3352. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3353. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3354. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3355. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3356. }
  3357. cli.set_keep_alive(true);
  3358. for (size_t j = 0; j < 100; j++) {
  3359. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3361. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3362. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3363. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3364. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3365. }
  3366. }
  3367. }
  3368. TEST(ExceptionTest, AndErrorHandler) {
  3369. Server svr;
  3370. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3371. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3372. });
  3373. svr.set_exception_handler(
  3374. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3375. EXPECT_FALSE(ep == nullptr);
  3376. try {
  3377. std::rethrow_exception(ep);
  3378. } catch (std::exception &e) {
  3379. res.set_content(e.what(), "text/html");
  3380. } catch (...) {}
  3381. res.status = StatusCode::InternalServerError_500;
  3382. });
  3383. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3384. throw std::runtime_error("EXCEPTION");
  3385. });
  3386. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3387. res.set_content("ERROR", "text/html");
  3388. res.status = StatusCode::InternalServerError_500;
  3389. });
  3390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3391. auto se = detail::scope_exit([&] {
  3392. svr.stop();
  3393. thread.join();
  3394. ASSERT_FALSE(svr.is_running());
  3395. });
  3396. svr.wait_until_ready();
  3397. Client cli(HOST, PORT);
  3398. {
  3399. auto res = cli.Get("/exception");
  3400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3401. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3402. EXPECT_EQ("EXCEPTION", res->body);
  3403. }
  3404. {
  3405. auto res = cli.Get("/error");
  3406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3407. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3408. EXPECT_EQ("ERROR", res->body);
  3409. }
  3410. {
  3411. auto res = cli.Get("/invalid");
  3412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3413. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3414. EXPECT_EQ("NOT_FOUND", res->body);
  3415. }
  3416. }
  3417. #endif
  3418. TEST(NoContentTest, ContentLength) {
  3419. Server svr;
  3420. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3421. res.status = StatusCode::NoContent_204;
  3422. });
  3423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3424. auto se = detail::scope_exit([&] {
  3425. svr.stop();
  3426. thread.join();
  3427. ASSERT_FALSE(svr.is_running());
  3428. });
  3429. svr.wait_until_ready();
  3430. {
  3431. Client cli(HOST, PORT);
  3432. auto res = cli.Get("/hi");
  3433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3434. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3435. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3436. }
  3437. }
  3438. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3439. #ifdef CPPHTTPLIB_SSL_ENABLED
  3440. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3441. ASSERT_TRUE(svr.is_valid());
  3442. #else
  3443. Server svr;
  3444. #endif
  3445. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3446. if (req.path == "/routing_handler") {
  3447. res.set_header("PRE_ROUTING", "on");
  3448. res.set_content("Routing Handler", "text/plain");
  3449. return httplib::Server::HandlerResponse::Handled;
  3450. }
  3451. return httplib::Server::HandlerResponse::Unhandled;
  3452. });
  3453. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3454. res.set_content("Error", "text/html");
  3455. });
  3456. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3457. if (req.path == "/routing_handler") {
  3458. res.set_header("POST_ROUTING", "on");
  3459. }
  3460. });
  3461. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3462. res.set_content("Hello World!\n", "text/plain");
  3463. });
  3464. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3465. auto se = detail::scope_exit([&] {
  3466. svr.stop();
  3467. thread.join();
  3468. ASSERT_FALSE(svr.is_running());
  3469. });
  3470. svr.wait_until_ready();
  3471. {
  3472. #ifdef CPPHTTPLIB_SSL_ENABLED
  3473. SSLClient cli(HOST, PORT);
  3474. cli.enable_server_certificate_verification(false);
  3475. #else
  3476. Client cli(HOST, PORT);
  3477. #endif
  3478. auto res = cli.Get("/routing_handler");
  3479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3480. EXPECT_EQ(StatusCode::OK_200, res->status);
  3481. EXPECT_EQ("Routing Handler", res->body);
  3482. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3483. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3484. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3485. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3486. }
  3487. {
  3488. #ifdef CPPHTTPLIB_SSL_ENABLED
  3489. SSLClient cli(HOST, PORT);
  3490. cli.enable_server_certificate_verification(false);
  3491. #else
  3492. Client cli(HOST, PORT);
  3493. #endif
  3494. auto res = cli.Get("/hi");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("Hello World!\n", res->body);
  3498. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3499. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3500. }
  3501. {
  3502. #ifdef CPPHTTPLIB_SSL_ENABLED
  3503. SSLClient cli(HOST, PORT);
  3504. cli.enable_server_certificate_verification(false);
  3505. #else
  3506. Client cli(HOST, PORT);
  3507. #endif
  3508. auto res = cli.Get("/aaa");
  3509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3511. EXPECT_EQ("Error", res->body);
  3512. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3513. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3514. }
  3515. }
  3516. TEST(RequestHandlerTest, PreRequestHandler) {
  3517. auto route_path = "/user/:user";
  3518. Server svr;
  3519. svr.Get("/hi", [](const Request &, Response &res) {
  3520. res.set_content("hi", "text/plain");
  3521. });
  3522. svr.Get(route_path, [](const Request &req, Response &res) {
  3523. res.set_content(req.path_params.at("user"), "text/plain");
  3524. });
  3525. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3526. if (req.matched_route == route_path) {
  3527. auto user = req.path_params.at("user");
  3528. if (user != "john") {
  3529. res.status = StatusCode::Forbidden_403;
  3530. res.set_content("error", "text/html");
  3531. return Server::HandlerResponse::Handled;
  3532. }
  3533. }
  3534. return Server::HandlerResponse::Unhandled;
  3535. });
  3536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(HOST, PORT);
  3544. {
  3545. auto res = cli.Get("/hi");
  3546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3547. EXPECT_EQ(StatusCode::OK_200, res->status);
  3548. EXPECT_EQ("hi", res->body);
  3549. }
  3550. {
  3551. auto res = cli.Get("/user/john");
  3552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3553. EXPECT_EQ(StatusCode::OK_200, res->status);
  3554. EXPECT_EQ("john", res->body);
  3555. }
  3556. {
  3557. auto res = cli.Get("/user/invalid-user");
  3558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3559. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3560. EXPECT_EQ("error", res->body);
  3561. }
  3562. }
  3563. // The pre-request handler must run before the request body is read, so a
  3564. // rejected request never forces the server to buffer a (potentially large)
  3565. // body. Here the posted body is larger than the payload limit: if the body
  3566. // were read first the server would answer 413, but because the pre-request
  3567. // handler runs first it answers 403 and the body is never read.
  3568. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3569. Server svr;
  3570. svr.set_payload_max_length(8);
  3571. auto handler_ran = false;
  3572. svr.Post("/reject", [&](const Request &req, Response &res) {
  3573. handler_ran = true;
  3574. res.set_content(req.body, "text/plain");
  3575. });
  3576. svr.Post("/accept", [](const Request &req, Response &res) {
  3577. res.set_content(req.body, "text/plain");
  3578. });
  3579. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3580. if (req.matched_route == "/reject") {
  3581. res.status = StatusCode::Forbidden_403;
  3582. res.set_content("denied", "text/plain");
  3583. return Server::HandlerResponse::Handled;
  3584. }
  3585. return Server::HandlerResponse::Unhandled;
  3586. });
  3587. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3588. auto se = detail::scope_exit([&] {
  3589. svr.stop();
  3590. thread.join();
  3591. ASSERT_FALSE(svr.is_running());
  3592. });
  3593. svr.wait_until_ready();
  3594. Client cli(HOST, PORT);
  3595. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3596. // rejects with 403 before the body is read, so 413 is never reached.
  3597. {
  3598. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3600. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3601. EXPECT_EQ("denied", res->body);
  3602. EXPECT_FALSE(handler_ran);
  3603. }
  3604. // An approved route still reads the body and enforces the payload limit.
  3605. {
  3606. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3608. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3609. }
  3610. }
  3611. TEST(UserDataTest, BasicOperations) {
  3612. httplib::UserData ud;
  3613. // Initially empty
  3614. EXPECT_FALSE(ud.has("key"));
  3615. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3616. // set and get
  3617. ud.set("key", 42);
  3618. EXPECT_TRUE(ud.has("key"));
  3619. auto *p = ud.get<int>("key");
  3620. ASSERT_NE(nullptr, p);
  3621. EXPECT_EQ(42, *p);
  3622. // Type mismatch → nullptr
  3623. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3624. // Overwrite with different type
  3625. ud.set("key", std::string("hello"));
  3626. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3627. auto *s = ud.get<std::string>("key");
  3628. ASSERT_NE(nullptr, s);
  3629. EXPECT_EQ("hello", *s);
  3630. // erase
  3631. ud.erase("key");
  3632. EXPECT_FALSE(ud.has("key"));
  3633. // clear
  3634. ud.set("a", 1);
  3635. ud.set("b", 2);
  3636. ud.clear();
  3637. EXPECT_FALSE(ud.has("a"));
  3638. EXPECT_FALSE(ud.has("b"));
  3639. }
  3640. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3641. struct AuthCtx {
  3642. std::string user_id;
  3643. };
  3644. Server svr;
  3645. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3646. res.user_data.set("auth", AuthCtx{"alice"});
  3647. return Server::HandlerResponse::Unhandled;
  3648. });
  3649. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3650. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3651. ASSERT_NE(nullptr, ctx);
  3652. res.set_content("Hello " + ctx->user_id, "text/plain");
  3653. });
  3654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3655. auto se = detail::scope_exit([&] {
  3656. svr.stop();
  3657. thread.join();
  3658. ASSERT_FALSE(svr.is_running());
  3659. });
  3660. svr.wait_until_ready();
  3661. Client cli(HOST, PORT);
  3662. auto res = cli.Get("/me");
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::OK_200, res->status);
  3665. EXPECT_EQ("Hello alice", res->body);
  3666. }
  3667. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3668. struct RoleCtx {
  3669. std::string role;
  3670. };
  3671. Server svr;
  3672. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3673. res.user_data.set("role", RoleCtx{"admin"});
  3674. return Server::HandlerResponse::Unhandled;
  3675. });
  3676. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3677. auto *ctx = res.user_data.get<RoleCtx>("role");
  3678. ASSERT_NE(nullptr, ctx);
  3679. res.set_content(ctx->role, "text/plain");
  3680. });
  3681. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3682. auto se = detail::scope_exit([&] {
  3683. svr.stop();
  3684. thread.join();
  3685. ASSERT_FALSE(svr.is_running());
  3686. });
  3687. svr.wait_until_ready();
  3688. Client cli(HOST, PORT);
  3689. auto res = cli.Get("/role");
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. EXPECT_EQ("admin", res->body);
  3693. }
  3694. TEST(InvalidFormatTest, StatusCode) {
  3695. Server svr;
  3696. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3697. res.set_content("Hello World!\n", "text/plain");
  3698. res.status = 9999; // Status should be a three-digit code...
  3699. });
  3700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, PORT);
  3709. auto res = cli.Get("/hi");
  3710. ASSERT_FALSE(res);
  3711. }
  3712. }
  3713. TEST(URLFragmentTest, WithFragment) {
  3714. Server svr;
  3715. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3716. EXPECT_TRUE(req.target == "/hi");
  3717. });
  3718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3719. auto se = detail::scope_exit([&] {
  3720. svr.stop();
  3721. thread.join();
  3722. ASSERT_FALSE(svr.is_running());
  3723. });
  3724. svr.wait_until_ready();
  3725. {
  3726. Client cli(HOST, PORT);
  3727. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3728. EXPECT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::OK_200, res->status);
  3730. res = cli.Get("/hi%23key1=val1=key2=val2");
  3731. EXPECT_TRUE(res);
  3732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3733. }
  3734. }
  3735. TEST(HeaderWriter, SetHeaderWriter) {
  3736. Server svr;
  3737. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3738. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3739. return detail::write_headers(strm, hdrs);
  3740. });
  3741. svr.Get("/hi", [](const Request &req, Response &res) {
  3742. auto it = req.headers.find("CustomClientHeader");
  3743. EXPECT_TRUE(it != req.headers.end());
  3744. EXPECT_EQ(it->second, "CustomClientValue");
  3745. res.set_content("Hello World!\n", "text/plain");
  3746. });
  3747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3748. auto se = detail::scope_exit([&] {
  3749. svr.stop();
  3750. thread.join();
  3751. ASSERT_FALSE(svr.is_running());
  3752. });
  3753. svr.wait_until_ready();
  3754. {
  3755. Client cli(HOST, PORT);
  3756. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3757. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3758. return detail::write_headers(strm, hdrs);
  3759. });
  3760. auto res = cli.Get("/hi");
  3761. EXPECT_TRUE(res);
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. auto it = res->headers.find("CustomServerHeader");
  3764. EXPECT_TRUE(it != res->headers.end());
  3765. EXPECT_EQ(it->second, "CustomServerValue");
  3766. }
  3767. }
  3768. class ServerTest : public ::testing::Test {
  3769. protected:
  3770. ServerTest()
  3771. : cli_(HOST, PORT)
  3772. #ifdef CPPHTTPLIB_SSL_ENABLED
  3773. ,
  3774. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3775. #endif
  3776. {
  3777. #ifdef CPPHTTPLIB_SSL_ENABLED
  3778. cli_.enable_server_certificate_verification(false);
  3779. #endif
  3780. // Allow LARGE_DATA (100MB) responses
  3781. cli_.set_payload_max_length(200 * 1024 * 1024);
  3782. }
  3783. virtual void SetUp() {
  3784. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3785. svr_.set_payload_max_length(200 * 1024 * 1024);
  3786. svr_.set_mount_point("/", "./www");
  3787. svr_.set_mount_point("/mount", "./www2");
  3788. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3789. svr_.Get("/hi",
  3790. [&](const Request & /*req*/, Response &res) {
  3791. res.set_content("Hello World!", "text/plain");
  3792. })
  3793. .Get("/file_content",
  3794. [&](const Request & /*req*/, Response &res) {
  3795. res.set_file_content("./www/dir/test.html");
  3796. })
  3797. .Get("/file_content_with_content_type",
  3798. [&](const Request & /*req*/, Response &res) {
  3799. res.set_file_content("./www/file", "text/plain");
  3800. })
  3801. .Get("/invalid_file_content",
  3802. [&](const Request & /*req*/, Response &res) {
  3803. res.set_file_content("./www/dir/invalid_file_path");
  3804. })
  3805. .Get("/http_response_splitting",
  3806. [&](const Request & /*req*/, Response &res) {
  3807. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3808. EXPECT_EQ(0U, res.headers.size());
  3809. EXPECT_FALSE(res.has_header("a"));
  3810. res.set_header("a", "1\nSet-Cookie: a=1");
  3811. EXPECT_EQ(0U, res.headers.size());
  3812. EXPECT_FALSE(res.has_header("a"));
  3813. res.set_header("a", "1\rSet-Cookie: a=1");
  3814. EXPECT_EQ(0U, res.headers.size());
  3815. EXPECT_FALSE(res.has_header("a"));
  3816. res.set_header("a\r\nb", "0");
  3817. EXPECT_EQ(0U, res.headers.size());
  3818. EXPECT_FALSE(res.has_header("a"));
  3819. res.set_header("a\rb", "0");
  3820. EXPECT_EQ(0U, res.headers.size());
  3821. EXPECT_FALSE(res.has_header("a"));
  3822. res.set_header("a\nb", "0");
  3823. EXPECT_EQ(0U, res.headers.size());
  3824. EXPECT_FALSE(res.has_header("a"));
  3825. res.set_redirect("1\r\nSet-Cookie: a=1");
  3826. EXPECT_EQ(0U, res.headers.size());
  3827. EXPECT_FALSE(res.has_header("Location"));
  3828. })
  3829. .Get("/slow",
  3830. [&](const Request & /*req*/, Response &res) {
  3831. std::this_thread::sleep_for(std::chrono::seconds(4));
  3832. res.set_content("slow", "text/plain");
  3833. })
  3834. #if 0
  3835. .Post("/slowpost",
  3836. [&](const Request & /*req*/, Response &res) {
  3837. std::this_thread::sleep_for(std::chrono::seconds(2));
  3838. res.set_content("slow", "text/plain");
  3839. })
  3840. #endif
  3841. .Get("/remote_addr",
  3842. [&](const Request &req, Response &res) {
  3843. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3844. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3845. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3846. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3847. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3848. #endif
  3849. res.set_content(req.remote_addr, "text/plain");
  3850. })
  3851. .Get("/local_addr",
  3852. [&](const Request &req, Response &res) {
  3853. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3854. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3855. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3856. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3857. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3858. #endif
  3859. auto local_addr = req.local_addr;
  3860. auto local_port = std::to_string(req.local_port);
  3861. res.set_content(local_addr.append(":").append(local_port),
  3862. "text/plain");
  3863. })
  3864. .Get("/endwith%",
  3865. [&](const Request & /*req*/, Response &res) {
  3866. res.set_content("Hello World!", "text/plain");
  3867. })
  3868. .Get("/a\\+\\+b",
  3869. [&](const Request &req, Response &res) {
  3870. ASSERT_TRUE(req.has_param("a +b"));
  3871. auto val = req.get_param_value("a +b");
  3872. res.set_content(val, "text/plain");
  3873. })
  3874. .Get("/", [&](const Request & /*req*/,
  3875. Response &res) { res.set_redirect("/hi"); })
  3876. .Post("/1",
  3877. [](const Request & /*req*/, Response &res) {
  3878. res.set_redirect("/2", StatusCode::SeeOther_303);
  3879. })
  3880. .Get("/2",
  3881. [](const Request & /*req*/, Response &res) {
  3882. res.set_content("redirected.", "text/plain");
  3883. res.status = StatusCode::OK_200;
  3884. })
  3885. .Post("/person",
  3886. [&](const Request &req, Response &res) {
  3887. if (req.has_param("name") && req.has_param("note")) {
  3888. persons_[req.get_param_value("name")] =
  3889. req.get_param_value("note");
  3890. } else {
  3891. res.status = StatusCode::BadRequest_400;
  3892. }
  3893. })
  3894. .Put("/person",
  3895. [&](const Request &req, Response &res) {
  3896. if (req.has_param("name") && req.has_param("note")) {
  3897. persons_[req.get_param_value("name")] =
  3898. req.get_param_value("note");
  3899. } else {
  3900. res.status = StatusCode::BadRequest_400;
  3901. }
  3902. })
  3903. .Get("/person/(.*)",
  3904. [&](const Request &req, Response &res) {
  3905. string name = req.matches[1];
  3906. if (persons_.find(name) != persons_.end()) {
  3907. auto note = persons_[name];
  3908. res.set_content(note, "text/plain");
  3909. } else {
  3910. res.status = StatusCode::NotFound_404;
  3911. }
  3912. })
  3913. .Delete("/person",
  3914. [&](const Request &req, Response &res) {
  3915. if (req.has_param("name")) {
  3916. string name = req.get_param_value("name");
  3917. if (persons_.find(name) != persons_.end()) {
  3918. persons_.erase(name);
  3919. res.set_content("DELETED", "text/plain");
  3920. } else {
  3921. res.status = StatusCode::NotFound_404;
  3922. }
  3923. } else {
  3924. res.status = StatusCode::BadRequest_400;
  3925. }
  3926. })
  3927. .Post("/x-www-form-urlencoded-json",
  3928. [&](const Request &req, Response &res) {
  3929. auto json = req.get_param_value("json");
  3930. ASSERT_EQ(JSON_DATA, json);
  3931. res.set_content(json, "appliation/json");
  3932. res.status = StatusCode::OK_200;
  3933. })
  3934. .Get("/streamed-chunked",
  3935. [&](const Request & /*req*/, Response &res) {
  3936. res.set_chunked_content_provider(
  3937. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3938. sink.os << "123";
  3939. sink.os << "456";
  3940. sink.os << "789";
  3941. sink.done();
  3942. return true;
  3943. });
  3944. })
  3945. .Get("/streamed-chunked-with-prohibited-trailer",
  3946. [&](const Request & /*req*/, Response &res) {
  3947. auto i = new int(0);
  3948. // Declare both a prohibited trailer (Content-Length) and an
  3949. // allowed one
  3950. res.set_header("Trailer", "Content-Length, X-Allowed");
  3951. res.set_chunked_content_provider(
  3952. "text/plain",
  3953. [i](size_t /*offset*/, DataSink &sink) {
  3954. switch (*i) {
  3955. case 0: sink.os << "123"; break;
  3956. case 1: sink.os << "456"; break;
  3957. case 2: sink.os << "789"; break;
  3958. case 3: {
  3959. sink.done_with_trailer(
  3960. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3961. } break;
  3962. }
  3963. (*i)++;
  3964. return true;
  3965. },
  3966. [i](bool success) {
  3967. EXPECT_TRUE(success);
  3968. delete i;
  3969. });
  3970. })
  3971. .Get("/streamed-chunked2",
  3972. [&](const Request & /*req*/, Response &res) {
  3973. auto i = new int(0);
  3974. res.set_chunked_content_provider(
  3975. "text/plain",
  3976. [i](size_t /*offset*/, DataSink &sink) {
  3977. switch (*i) {
  3978. case 0: sink.os << "123"; break;
  3979. case 1: sink.os << "456"; break;
  3980. case 2: sink.os << "789"; break;
  3981. case 3: sink.done(); break;
  3982. }
  3983. (*i)++;
  3984. return true;
  3985. },
  3986. [i](bool success) {
  3987. EXPECT_TRUE(success);
  3988. delete i;
  3989. });
  3990. })
  3991. .Get("/streamed-chunked-with-trailer",
  3992. [&](const Request & /*req*/, Response &res) {
  3993. auto i = new int(0);
  3994. res.set_header("Trailer", "Dummy1, Dummy2");
  3995. res.set_chunked_content_provider(
  3996. "text/plain",
  3997. [i](size_t /*offset*/, DataSink &sink) {
  3998. switch (*i) {
  3999. case 0: sink.os << "123"; break;
  4000. case 1: sink.os << "456"; break;
  4001. case 2: sink.os << "789"; break;
  4002. case 3: {
  4003. sink.done_with_trailer(
  4004. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4005. } break;
  4006. }
  4007. (*i)++;
  4008. return true;
  4009. },
  4010. [i](bool success) {
  4011. EXPECT_TRUE(success);
  4012. delete i;
  4013. });
  4014. })
  4015. .Get("/streamed",
  4016. [&](const Request & /*req*/, Response &res) {
  4017. res.set_content_provider(
  4018. 6, "text/plain",
  4019. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4020. sink.os << (offset < 3 ? "a" : "b");
  4021. return true;
  4022. });
  4023. })
  4024. .Get("/streamed-without-length",
  4025. [&](const Request & /*req*/, Response &res) {
  4026. auto data = new std::string("abcdefg");
  4027. res.set_content_provider(
  4028. "text/plain",
  4029. [data](size_t offset, DataSink &sink) {
  4030. if (offset < data->size()) {
  4031. sink.os << data->substr(offset);
  4032. }
  4033. sink.done();
  4034. return true;
  4035. },
  4036. [data](bool success) {
  4037. EXPECT_TRUE(success);
  4038. delete data;
  4039. });
  4040. })
  4041. .Get("/streamed-with-range",
  4042. [&](const Request &req, Response &res) {
  4043. auto data = new std::string("abcdefg");
  4044. // An explicit status keeps the server from picking the 206 it
  4045. // would otherwise choose for a ranged request, so the response
  4046. // is not a partial representation.
  4047. auto status = req.get_param_value("status");
  4048. if (status == "200") {
  4049. res.status = StatusCode::OK_200;
  4050. } else if (status == "403") {
  4051. res.status = StatusCode::Forbidden_403;
  4052. }
  4053. res.set_content_provider(
  4054. data->size(), "text/plain",
  4055. [data](size_t offset, size_t length, DataSink &sink) {
  4056. size_t DATA_CHUNK_SIZE = 4;
  4057. const auto &d = *data;
  4058. auto out_len =
  4059. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4060. auto ret =
  4061. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4062. EXPECT_TRUE(ret);
  4063. return true;
  4064. },
  4065. [data, &req](bool success) {
  4066. EXPECT_EQ(success, !req.has_param("error"));
  4067. delete data;
  4068. });
  4069. })
  4070. .Get("/streamed-cancel",
  4071. [&](const Request & /*req*/, Response &res) {
  4072. res.set_content_provider(
  4073. size_t(-1), "text/plain",
  4074. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4075. sink.os << "data_chunk";
  4076. return true;
  4077. });
  4078. })
  4079. .Get("/regex-with-delimiter",
  4080. [&](const Request &req, Response & /*res*/) {
  4081. ASSERT_TRUE(req.has_param("key"));
  4082. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4083. })
  4084. .Get("/with-range",
  4085. [&](const Request & /*req*/, Response &res) {
  4086. res.set_content("abcdefg", "text/plain");
  4087. })
  4088. .Get("/test-start-time",
  4089. [&](const Request &req, Response & /*res*/) {
  4090. EXPECT_NE(req.start_time_,
  4091. std::chrono::steady_clock::time_point::min());
  4092. })
  4093. .Get("/with-range-customized-response",
  4094. [&](const Request & /*req*/, Response &res) {
  4095. res.status = StatusCode::BadRequest_400;
  4096. res.set_content(JSON_DATA, "application/json");
  4097. })
  4098. .Post("/chunked",
  4099. [&](const Request &req, Response & /*res*/) {
  4100. EXPECT_EQ(req.body, "dechunked post body");
  4101. })
  4102. .Post("/large-chunked",
  4103. [&](const Request &req, Response & /*res*/) {
  4104. std::string expected(6 * 30 * 1024u, 'a');
  4105. EXPECT_EQ(req.body, expected);
  4106. })
  4107. .Post("/multipart",
  4108. [&](const Request &req, Response & /*res*/) {
  4109. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4110. req.form.get_field_count("text2") +
  4111. req.form.get_field_count("file3") +
  4112. req.form.get_field_count("file4"));
  4113. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4114. req.form.get_file_count("file2"));
  4115. ASSERT_TRUE(!req.form.has_file("???"));
  4116. ASSERT_TRUE(!req.form.has_field("???"));
  4117. ASSERT_TRUE(req.body.empty());
  4118. {
  4119. const auto &text = req.form.get_field("text1");
  4120. EXPECT_EQ("text default", text);
  4121. }
  4122. {
  4123. const auto &text = req.form.get_field("text2");
  4124. EXPECT_EQ("aωb", text);
  4125. }
  4126. {
  4127. const auto &file = req.form.get_file("file1");
  4128. EXPECT_EQ("hello.txt", file.filename);
  4129. EXPECT_EQ("text/plain", file.content_type);
  4130. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4131. }
  4132. {
  4133. const auto &file = req.form.get_file("file2");
  4134. EXPECT_EQ("world.json", file.filename);
  4135. EXPECT_EQ("application/json", file.content_type);
  4136. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4137. }
  4138. {
  4139. const auto &text = req.form.get_field("file3");
  4140. EXPECT_EQ(0u, text.size());
  4141. }
  4142. {
  4143. const auto &text = req.form.get_field("file4");
  4144. EXPECT_EQ(0u, text.size());
  4145. }
  4146. })
  4147. .Post("/multipart/multi_file_values",
  4148. [&](const Request &req, Response & /*res*/) {
  4149. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4150. req.form.get_field_count("multi_text1"));
  4151. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4152. ASSERT_TRUE(!req.form.has_file("???"));
  4153. ASSERT_TRUE(!req.form.has_field("???"));
  4154. ASSERT_TRUE(req.body.empty());
  4155. {
  4156. const auto &text = req.form.get_field("text");
  4157. EXPECT_EQ("default text", text);
  4158. }
  4159. {
  4160. const auto &text1_values = req.form.get_fields("multi_text1");
  4161. EXPECT_EQ(2u, text1_values.size());
  4162. EXPECT_EQ("aaaaa", text1_values[0]);
  4163. EXPECT_EQ("bbbbb", text1_values[1]);
  4164. }
  4165. {
  4166. const auto &file1_values = req.form.get_files("multi_file1");
  4167. EXPECT_EQ(2u, file1_values.size());
  4168. auto file1 = file1_values[0];
  4169. EXPECT_EQ(file1.filename, "hello.txt");
  4170. EXPECT_EQ(file1.content_type, "text/plain");
  4171. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4172. auto file2 = file1_values[1];
  4173. EXPECT_EQ(file2.filename, "world.json");
  4174. EXPECT_EQ(file2.content_type, "application/json");
  4175. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4176. }
  4177. })
  4178. .Post("/empty",
  4179. [&](const Request &req, Response &res) {
  4180. EXPECT_EQ(req.body, "");
  4181. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4182. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4183. res.set_content("empty", "text/plain");
  4184. })
  4185. .Post("/empty-no-content-type",
  4186. [&](const Request &req, Response &res) {
  4187. EXPECT_EQ(req.body, "");
  4188. EXPECT_FALSE(req.has_header("Content-Type"));
  4189. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4190. res.set_content("empty-no-content-type", "text/plain");
  4191. })
  4192. .Post("/path-only",
  4193. [&](const Request &req, Response &res) {
  4194. EXPECT_EQ(req.body, "");
  4195. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4196. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4197. res.set_content("path-only", "text/plain");
  4198. })
  4199. .Post("/path-headers-only",
  4200. [&](const Request &req, Response &res) {
  4201. EXPECT_EQ(req.body, "");
  4202. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4203. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4204. EXPECT_EQ("world", req.get_header_value("hello"));
  4205. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4206. res.set_content("path-headers-only", "text/plain");
  4207. })
  4208. .Post("/post-large",
  4209. [&](const Request &req, Response &res) {
  4210. EXPECT_EQ(req.body, LARGE_DATA);
  4211. res.set_content(req.body, "text/plain");
  4212. })
  4213. .Post("/post-loopback",
  4214. [&](const Request &, Response &res,
  4215. ContentReader const &content_reader) {
  4216. std::string body;
  4217. content_reader([&](const char *data, size_t data_length) {
  4218. body.append(data, data_length);
  4219. return true;
  4220. });
  4221. res.set_content(body, "text/plain");
  4222. })
  4223. .Put("/put-loopback",
  4224. [&](const Request &, Response &res,
  4225. ContentReader const &content_reader) {
  4226. std::string body;
  4227. content_reader([&](const char *data, size_t data_length) {
  4228. body.append(data, data_length);
  4229. return true;
  4230. });
  4231. res.set_content(body, "text/plain");
  4232. })
  4233. .Patch("/patch-loopback",
  4234. [&](const Request &, Response &res,
  4235. ContentReader const &content_reader) {
  4236. std::string body;
  4237. content_reader([&](const char *data, size_t data_length) {
  4238. body.append(data, data_length);
  4239. return true;
  4240. });
  4241. res.set_content(body, "text/plain");
  4242. })
  4243. .Put("/empty-no-content-type",
  4244. [&](const Request &req, Response &res) {
  4245. EXPECT_EQ(req.body, "");
  4246. EXPECT_FALSE(req.has_header("Content-Type"));
  4247. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4248. res.set_content("empty-no-content-type", "text/plain");
  4249. })
  4250. .Put("/put",
  4251. [&](const Request &req, Response &res) {
  4252. EXPECT_EQ(req.body, "PUT");
  4253. res.set_content(req.body, "text/plain");
  4254. })
  4255. .Put("/put-large",
  4256. [&](const Request &req, Response &res) {
  4257. EXPECT_EQ(req.body, LARGE_DATA);
  4258. res.set_content(req.body, "text/plain");
  4259. })
  4260. .Patch("/patch",
  4261. [&](const Request &req, Response &res) {
  4262. EXPECT_EQ(req.body, "PATCH");
  4263. res.set_content(req.body, "text/plain");
  4264. })
  4265. .Delete("/delete",
  4266. [&](const Request & /*req*/, Response &res) {
  4267. res.set_content("DELETE", "text/plain");
  4268. })
  4269. .Delete("/delete-body",
  4270. [&](const Request &req, Response &res) {
  4271. EXPECT_EQ(req.body, "content");
  4272. res.set_content(req.body, "text/plain");
  4273. })
  4274. .Options(R"(\*)",
  4275. [&](const Request & /*req*/, Response &res) {
  4276. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4277. })
  4278. .Get("/request-target",
  4279. [&](const Request &req, Response & /*res*/) {
  4280. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4281. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4282. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4283. })
  4284. .Get("/long-query-value",
  4285. [&](const Request &req, Response & /*res*/) {
  4286. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4287. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4288. })
  4289. .Get("/too-long-query-value",
  4290. [&](const Request &req, Response & /*res*/) {
  4291. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4292. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4293. })
  4294. .Get("/array-param",
  4295. [&](const Request &req, Response & /*res*/) {
  4296. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4297. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4298. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4299. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4300. })
  4301. .Get("/array-param-values",
  4302. [&](const Request &req, Response & /*res*/) {
  4303. auto values = req.get_param_values("array");
  4304. EXPECT_EQ(3u, values.size());
  4305. EXPECT_EQ("value1", values[0]);
  4306. EXPECT_EQ("value2", values[1]);
  4307. EXPECT_EQ("value3", values[2]);
  4308. auto empty = req.get_param_values("nonexistent");
  4309. EXPECT_TRUE(empty.empty());
  4310. })
  4311. .Post("/validate-no-multiple-headers",
  4312. [&](const Request &req, Response & /*res*/) {
  4313. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4314. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4315. })
  4316. .Post("/content_receiver",
  4317. [&](const Request &req, Response &res,
  4318. const ContentReader &content_reader) {
  4319. if (req.is_multipart_form_data()) {
  4320. std::vector<FormData> items;
  4321. content_reader(
  4322. [&](const FormData &file) {
  4323. items.push_back(file);
  4324. return true;
  4325. },
  4326. [&](const char *data, size_t data_length) {
  4327. items.back().content.append(data, data_length);
  4328. return true;
  4329. });
  4330. EXPECT_EQ(5u, items.size());
  4331. {
  4332. const auto &file = get_file_value(items, "text1");
  4333. EXPECT_TRUE(file.filename.empty());
  4334. EXPECT_EQ("text default", file.content);
  4335. }
  4336. {
  4337. const auto &file = get_file_value(items, "text2");
  4338. EXPECT_TRUE(file.filename.empty());
  4339. EXPECT_EQ("aωb", file.content);
  4340. }
  4341. {
  4342. const auto &file = get_file_value(items, "file1");
  4343. EXPECT_EQ("hello.txt", file.filename);
  4344. EXPECT_EQ("text/plain", file.content_type);
  4345. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4346. }
  4347. {
  4348. const auto &file = get_file_value(items, "file2");
  4349. EXPECT_EQ("world.json", file.filename);
  4350. EXPECT_EQ("application/json", file.content_type);
  4351. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4352. }
  4353. {
  4354. const auto &file = get_file_value(items, "file3");
  4355. EXPECT_TRUE(file.filename.empty());
  4356. EXPECT_EQ("application/octet-stream", file.content_type);
  4357. EXPECT_EQ(0u, file.content.size());
  4358. }
  4359. } else {
  4360. std::string body;
  4361. content_reader([&](const char *data, size_t data_length) {
  4362. EXPECT_EQ(7U, data_length);
  4363. body.append(data, data_length);
  4364. return true;
  4365. });
  4366. EXPECT_EQ(body, "content");
  4367. res.set_content(body, "text/plain");
  4368. }
  4369. })
  4370. .Put("/content_receiver",
  4371. [&](const Request & /*req*/, Response &res,
  4372. const ContentReader &content_reader) {
  4373. std::string body;
  4374. content_reader([&](const char *data, size_t data_length) {
  4375. body.append(data, data_length);
  4376. return true;
  4377. });
  4378. EXPECT_EQ(body, "content");
  4379. res.set_content(body, "text/plain");
  4380. })
  4381. .Patch("/content_receiver",
  4382. [&](const Request & /*req*/, Response &res,
  4383. const ContentReader &content_reader) {
  4384. std::string body;
  4385. content_reader([&](const char *data, size_t data_length) {
  4386. body.append(data, data_length);
  4387. return true;
  4388. });
  4389. EXPECT_EQ(body, "content");
  4390. res.set_content(body, "text/plain");
  4391. })
  4392. .Post("/query-string-and-body",
  4393. [&](const Request &req, Response & /*res*/) {
  4394. ASSERT_TRUE(req.has_param("key"));
  4395. EXPECT_EQ(req.get_param_value("key"), "value");
  4396. EXPECT_EQ(req.body, "content");
  4397. })
  4398. .Get("/last-request",
  4399. [&](const Request &req, Response & /*res*/) {
  4400. EXPECT_EQ("close", req.get_header_value("Connection"));
  4401. })
  4402. .Get(R"(/redirect/(\d+))",
  4403. [&](const Request &req, Response &res) {
  4404. auto num = std::stoi(req.matches[1]) + 1;
  4405. std::string url = "/redirect/" + std::to_string(num);
  4406. res.set_redirect(url);
  4407. })
  4408. .Post("/binary",
  4409. [&](const Request &req, Response &res) {
  4410. EXPECT_EQ(4U, req.body.size());
  4411. EXPECT_EQ("application/octet-stream",
  4412. req.get_header_value("Content-Type"));
  4413. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4414. res.set_content(req.body, "application/octet-stream");
  4415. })
  4416. .Put("/binary",
  4417. [&](const Request &req, Response &res) {
  4418. EXPECT_EQ(4U, req.body.size());
  4419. EXPECT_EQ("application/octet-stream",
  4420. req.get_header_value("Content-Type"));
  4421. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4422. res.set_content(req.body, "application/octet-stream");
  4423. })
  4424. .Patch("/binary",
  4425. [&](const Request &req, Response &res) {
  4426. EXPECT_EQ(4U, req.body.size());
  4427. EXPECT_EQ("application/octet-stream",
  4428. req.get_header_value("Content-Type"));
  4429. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4430. res.set_content(req.body, "application/octet-stream");
  4431. })
  4432. .Delete("/binary",
  4433. [&](const Request &req, Response &res) {
  4434. EXPECT_EQ(4U, req.body.size());
  4435. EXPECT_EQ("application/octet-stream",
  4436. req.get_header_value("Content-Type"));
  4437. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4438. res.set_content(req.body, "application/octet-stream");
  4439. })
  4440. .Get("/issue1772",
  4441. [&](const Request & /*req*/, Response &res) {
  4442. res.status = 401;
  4443. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4444. })
  4445. .Delete("/issue609",
  4446. [](const httplib::Request &, httplib::Response &res,
  4447. const httplib::ContentReader &) {
  4448. res.set_content("ok", "text/plain");
  4449. })
  4450. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4451. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4452. .Get("/compress",
  4453. [&](const Request & /*req*/, Response &res) {
  4454. res.set_content(
  4455. "12345678901234567890123456789012345678901234567890123456789"
  4456. "01234567890123456789012345678901234567890",
  4457. "text/plain");
  4458. })
  4459. .Get("/compress-with-charset",
  4460. [&](const Request & /*req*/, Response &res) {
  4461. res.set_content(
  4462. "12345678901234567890123456789012345678901234567890123456789"
  4463. "01234567890123456789012345678901234567890",
  4464. "application/json; charset=utf-8");
  4465. })
  4466. .Get("/nocompress",
  4467. [&](const Request & /*req*/, Response &res) {
  4468. res.set_content(
  4469. "12345678901234567890123456789012345678901234567890123456789"
  4470. "01234567890123456789012345678901234567890",
  4471. "application/octet-stream");
  4472. })
  4473. .Post("/compress-multipart",
  4474. [&](const Request &req, Response & /*res*/) {
  4475. EXPECT_EQ(2u, req.form.fields.size());
  4476. ASSERT_TRUE(!req.form.has_field("???"));
  4477. {
  4478. const auto &text = req.form.get_field("key1");
  4479. EXPECT_EQ("test", text);
  4480. }
  4481. {
  4482. const auto &text = req.form.get_field("key2");
  4483. EXPECT_EQ("--abcdefg123", text);
  4484. }
  4485. })
  4486. #endif
  4487. ;
  4488. persons_["john"] = "programmer";
  4489. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4490. svr_.wait_until_ready();
  4491. }
  4492. virtual void TearDown() {
  4493. svr_.stop();
  4494. if (!request_threads_.empty()) {
  4495. std::this_thread::sleep_for(std::chrono::seconds(1));
  4496. for (auto &t : request_threads_) {
  4497. t.join();
  4498. }
  4499. }
  4500. t_.join();
  4501. }
  4502. map<string, string> persons_;
  4503. #ifdef CPPHTTPLIB_SSL_ENABLED
  4504. SSLClient cli_;
  4505. SSLServer svr_;
  4506. #else
  4507. Client cli_;
  4508. Server svr_;
  4509. #endif
  4510. thread t_;
  4511. std::vector<thread> request_threads_;
  4512. };
  4513. TEST_F(ServerTest, GetMethod200) {
  4514. auto res = cli_.Get("/hi");
  4515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4516. EXPECT_EQ("HTTP/1.1", res->version);
  4517. EXPECT_EQ(StatusCode::OK_200, res->status);
  4518. EXPECT_EQ("OK", res->reason);
  4519. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4520. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4521. EXPECT_EQ("Hello World!", res->body);
  4522. }
  4523. TEST_F(ServerTest, GetEmptyFile) {
  4524. auto res = cli_.Get("/empty_file");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ(StatusCode::OK_200, res->status);
  4527. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4528. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4529. EXPECT_EQ("", res->body);
  4530. }
  4531. TEST_F(ServerTest, GetFileContent) {
  4532. auto res = cli_.Get("/file_content");
  4533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4536. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4537. EXPECT_EQ("test.html", res->body);
  4538. }
  4539. TEST_F(ServerTest, GetFileContentWithRange) {
  4540. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4542. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4544. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4545. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4546. EXPECT_EQ("est", res->body);
  4547. }
  4548. TEST_F(ServerTest, GetFileContentWithContentType) {
  4549. auto res = cli_.Get("/file_content_with_content_type");
  4550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4551. EXPECT_EQ(StatusCode::OK_200, res->status);
  4552. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4553. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4554. EXPECT_EQ("file\n", res->body);
  4555. }
  4556. TEST_F(ServerTest, GetInvalidFileContent) {
  4557. auto res = cli_.Get("/invalid_file_content");
  4558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4560. }
  4561. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4562. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ("HTTP/1.1", res->version);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4567. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4568. EXPECT_EQ("Hello World!", res->body);
  4569. }
  4570. TEST_F(ServerTest, GetMethod302) {
  4571. auto res = cli_.Get("/");
  4572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4573. EXPECT_EQ(StatusCode::Found_302, res->status);
  4574. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4575. }
  4576. TEST_F(ServerTest, GetMethod302Redirect) {
  4577. cli_.set_follow_location(true);
  4578. auto res = cli_.Get("/");
  4579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. EXPECT_EQ("Hello World!", res->body);
  4582. EXPECT_EQ("/hi", res->location);
  4583. }
  4584. TEST_F(ServerTest, GetMethod404) {
  4585. auto res = cli_.Get("/invalid");
  4586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4588. }
  4589. TEST_F(ServerTest, HeadMethod200) {
  4590. auto res = cli_.Head("/hi");
  4591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4594. EXPECT_TRUE(res->body.empty());
  4595. }
  4596. TEST_F(ServerTest, HeadMethod200Static) {
  4597. auto res = cli_.Head("/mount/dir/index.html");
  4598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4601. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4602. EXPECT_TRUE(res->body.empty());
  4603. }
  4604. TEST_F(ServerTest, HeadMethod404) {
  4605. auto res = cli_.Head("/invalid");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4608. EXPECT_TRUE(res->body.empty());
  4609. }
  4610. TEST_F(ServerTest, GetMethodPersonJohn) {
  4611. auto res = cli_.Get("/person/john");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4615. EXPECT_EQ("programmer", res->body);
  4616. }
  4617. TEST_F(ServerTest, PostMethod1) {
  4618. auto res = cli_.Get("/person/john1");
  4619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4620. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4621. res = cli_.Post("/person", "name=john1&note=coder",
  4622. "application/x-www-form-urlencoded");
  4623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4624. ASSERT_EQ(StatusCode::OK_200, res->status);
  4625. res = cli_.Get("/person/john1");
  4626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4627. ASSERT_EQ(StatusCode::OK_200, res->status);
  4628. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4629. ASSERT_EQ("coder", res->body);
  4630. }
  4631. TEST_F(ServerTest, PostMethod2) {
  4632. auto res = cli_.Get("/person/john2");
  4633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4634. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4635. Params params;
  4636. params.emplace("name", "john2");
  4637. params.emplace("note", "coder");
  4638. res = cli_.Post("/person", params);
  4639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4640. ASSERT_EQ(StatusCode::OK_200, res->status);
  4641. res = cli_.Get("/person/john2");
  4642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4643. ASSERT_EQ(StatusCode::OK_200, res->status);
  4644. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4645. ASSERT_EQ("coder", res->body);
  4646. }
  4647. TEST_F(ServerTest, PutMethod3) {
  4648. auto res = cli_.Get("/person/john3");
  4649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4650. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4651. Params params;
  4652. params.emplace("name", "john3");
  4653. params.emplace("note", "coder");
  4654. res = cli_.Put("/person", params);
  4655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4656. ASSERT_EQ(StatusCode::OK_200, res->status);
  4657. res = cli_.Get("/person/john3");
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. ASSERT_EQ(StatusCode::OK_200, res->status);
  4660. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4661. ASSERT_EQ("coder", res->body);
  4662. }
  4663. TEST_F(ServerTest, DeleteMethod1) {
  4664. auto res = cli_.Get("/person/john4");
  4665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4666. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4667. Params params;
  4668. params.emplace("name", "john4");
  4669. params.emplace("note", "coder");
  4670. res = cli_.Post("/person", params);
  4671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4672. ASSERT_EQ(StatusCode::OK_200, res->status);
  4673. res = cli_.Get("/person/john4");
  4674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4675. ASSERT_EQ(StatusCode::OK_200, res->status);
  4676. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4677. ASSERT_EQ("coder", res->body);
  4678. Params delete_params;
  4679. delete_params.emplace("name", "john4");
  4680. res = cli_.Delete("/person", delete_params);
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. ASSERT_EQ(StatusCode::OK_200, res->status);
  4683. ASSERT_EQ("DELETED", res->body);
  4684. res = cli_.Get("/person/john4");
  4685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4686. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4687. }
  4688. TEST_F(ServerTest, DeleteMethod2) {
  4689. auto res = cli_.Get("/person/john5");
  4690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4691. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4692. Params params;
  4693. params.emplace("name", "john5");
  4694. params.emplace("note", "developer");
  4695. res = cli_.Post("/person", params);
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. ASSERT_EQ(StatusCode::OK_200, res->status);
  4698. res = cli_.Get("/person/john5");
  4699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4700. ASSERT_EQ(StatusCode::OK_200, res->status);
  4701. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4702. ASSERT_EQ("developer", res->body);
  4703. Params delete_params;
  4704. delete_params.emplace("name", "john5");
  4705. Headers headers;
  4706. headers.emplace("Custom-Header", "test-value");
  4707. res = cli_.Delete("/person", headers, delete_params);
  4708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4709. ASSERT_EQ(StatusCode::OK_200, res->status);
  4710. ASSERT_EQ("DELETED", res->body);
  4711. res = cli_.Get("/person/john5");
  4712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4713. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4714. }
  4715. TEST_F(ServerTest, DeleteMethod3) {
  4716. auto res = cli_.Get("/person/john6");
  4717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4718. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4719. Params params;
  4720. params.emplace("name", "john6");
  4721. params.emplace("note", "tester");
  4722. res = cli_.Post("/person", params);
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. ASSERT_EQ(StatusCode::OK_200, res->status);
  4725. res = cli_.Get("/person/john6");
  4726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4727. ASSERT_EQ(StatusCode::OK_200, res->status);
  4728. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4729. ASSERT_EQ("tester", res->body);
  4730. Params delete_params;
  4731. delete_params.emplace("name", "john6");
  4732. Headers headers;
  4733. headers.emplace("Custom-Header", "test-value");
  4734. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4736. ASSERT_EQ(StatusCode::OK_200, res->status);
  4737. ASSERT_EQ("DELETED", res->body);
  4738. res = cli_.Get("/person/john6");
  4739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4740. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4741. }
  4742. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4743. Params params;
  4744. params.emplace("json", JSON_DATA);
  4745. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4747. ASSERT_EQ(StatusCode::OK_200, res->status);
  4748. ASSERT_EQ(JSON_DATA, res->body);
  4749. }
  4750. TEST_F(ServerTest, PostEmptyContent) {
  4751. auto res = cli_.Post("/empty", "", "text/plain");
  4752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4753. ASSERT_EQ(StatusCode::OK_200, res->status);
  4754. ASSERT_EQ("empty", res->body);
  4755. }
  4756. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4757. auto res = cli_.Post("/empty-no-content-type");
  4758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4759. ASSERT_EQ(StatusCode::OK_200, res->status);
  4760. ASSERT_EQ("empty-no-content-type", res->body);
  4761. }
  4762. TEST_F(ServerTest, PostPathOnly) {
  4763. auto res = cli_.Post("/path-only");
  4764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4765. ASSERT_EQ(StatusCode::OK_200, res->status);
  4766. ASSERT_EQ("path-only", res->body);
  4767. }
  4768. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4769. auto res = cli_.Post("/path-headers-only",
  4770. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4772. ASSERT_EQ(StatusCode::OK_200, res->status);
  4773. ASSERT_EQ("path-headers-only", res->body);
  4774. }
  4775. TEST_F(ServerTest, PostLarge) {
  4776. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4778. ASSERT_EQ(StatusCode::OK_200, res->status);
  4779. EXPECT_EQ(LARGE_DATA, res->body);
  4780. }
  4781. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4782. auto res = cli_.Put("/empty-no-content-type");
  4783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4784. ASSERT_EQ(StatusCode::OK_200, res->status);
  4785. ASSERT_EQ("empty-no-content-type", res->body);
  4786. }
  4787. TEST_F(ServerTest, GetMethodDir) {
  4788. auto res = cli_.Get("/dir/");
  4789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4792. auto body = R"(<html>
  4793. <head>
  4794. </head>
  4795. <body>
  4796. <a href="/dir/test.html">Test</a>
  4797. <a href="/hi">hi</a>
  4798. </body>
  4799. </html>
  4800. )";
  4801. EXPECT_EQ(body, res->body);
  4802. }
  4803. TEST_F(ServerTest, GetMethodDirTest) {
  4804. auto res = cli_.Get("/dir/test.html");
  4805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4806. EXPECT_EQ(StatusCode::OK_200, res->status);
  4807. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4808. EXPECT_EQ("test.html", res->body);
  4809. }
  4810. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4811. auto res = cli_.Get("/dir/../dir/test.html");
  4812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4813. EXPECT_EQ(StatusCode::OK_200, res->status);
  4814. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4815. EXPECT_EQ("test.html", res->body);
  4816. }
  4817. TEST_F(ServerTest, GetMethodInvalidPath) {
  4818. auto res = cli_.Get("/dir/../test.html");
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4821. }
  4822. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4823. auto res = cli_.Get("/../www/dir/test.html");
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4826. }
  4827. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4828. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4831. }
  4832. TEST_F(ServerTest, GetMethodDirMountTest) {
  4833. auto res = cli_.Get("/mount/dir/test.html");
  4834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4835. EXPECT_EQ(StatusCode::OK_200, res->status);
  4836. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4837. EXPECT_EQ("test.html", res->body);
  4838. }
  4839. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4840. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. EXPECT_EQ(StatusCode::OK_200, res->status);
  4843. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4844. EXPECT_EQ("test.html", res->body);
  4845. }
  4846. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4847. auto res = cli_.Get("/mount/dir/../test.html");
  4848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4850. }
  4851. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4852. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4855. }
  4856. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4857. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4860. }
  4861. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4862. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4865. }
  4866. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4867. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4870. }
  4871. TEST_F(ServerTest, PostMethod303) {
  4872. auto res = cli_.Post("/1", "body", "text/plain");
  4873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4874. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4875. EXPECT_EQ("/2", res->get_header_value("Location"));
  4876. }
  4877. TEST_F(ServerTest, PostMethod303Redirect) {
  4878. cli_.set_follow_location(true);
  4879. auto res = cli_.Post("/1", "body", "text/plain");
  4880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. EXPECT_EQ("redirected.", res->body);
  4883. EXPECT_EQ("/2", res->location);
  4884. }
  4885. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4886. auto res = cli_.Get("/dir/test.abcde");
  4887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4888. EXPECT_EQ(StatusCode::OK_200, res->status);
  4889. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4890. EXPECT_EQ("abcde", res->body);
  4891. }
  4892. TEST_F(ServerTest, StaticFileRange) {
  4893. auto res =
  4894. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4897. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4898. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4899. EXPECT_EQ(true, res->has_header("Content-Range"));
  4900. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4901. EXPECT_EQ(std::string("cd"), res->body);
  4902. }
  4903. TEST_F(ServerTest, StaticFileRanges) {
  4904. auto res = cli_.Get("/dir/test.abcde",
  4905. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4908. EXPECT_TRUE(
  4909. res->get_header_value("Content-Type")
  4910. .find(
  4911. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4912. 0);
  4913. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4914. }
  4915. TEST_F(ServerTest, StaticFileRangeHead) {
  4916. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4919. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4920. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4921. EXPECT_EQ(true, res->has_header("Content-Range"));
  4922. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4923. }
  4924. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4925. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4929. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4930. EXPECT_EQ(true, res->has_header("Content-Range"));
  4931. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4932. res->get_header_value("Content-Range"));
  4933. EXPECT_EQ("LAST\n", res->body);
  4934. }
  4935. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4936. auto res =
  4937. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4939. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4941. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4942. EXPECT_EQ(true, res->has_header("Content-Range"));
  4943. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4944. }
  4945. TEST_F(ServerTest, StaticFileBigFile) {
  4946. auto res = cli_.Get("/dir/1MB.txt");
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. EXPECT_EQ(StatusCode::OK_200, res->status);
  4949. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4950. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4951. }
  4952. TEST_F(ServerTest, InvalidBaseDirMount) {
  4953. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4954. }
  4955. TEST_F(ServerTest, Binary) {
  4956. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4957. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4958. "application/octet-stream");
  4959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4960. ASSERT_EQ(StatusCode::OK_200, res->status);
  4961. ASSERT_EQ(4U, res->body.size());
  4962. res = cli_.Put("/binary", binary.data(), binary.size(),
  4963. "application/octet-stream");
  4964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4965. ASSERT_EQ(StatusCode::OK_200, res->status);
  4966. ASSERT_EQ(4U, res->body.size());
  4967. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4968. "application/octet-stream");
  4969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4970. ASSERT_EQ(StatusCode::OK_200, res->status);
  4971. ASSERT_EQ(4U, res->body.size());
  4972. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4973. "application/octet-stream");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. ASSERT_EQ(StatusCode::OK_200, res->status);
  4976. ASSERT_EQ(4U, res->body.size());
  4977. }
  4978. TEST_F(ServerTest, BinaryString) {
  4979. auto binary = std::string("\x00\x01\x02\x03", 4);
  4980. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4982. ASSERT_EQ(StatusCode::OK_200, res->status);
  4983. ASSERT_EQ(4U, res->body.size());
  4984. res = cli_.Put("/binary", binary, "application/octet-stream");
  4985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4986. ASSERT_EQ(StatusCode::OK_200, res->status);
  4987. ASSERT_EQ(4U, res->body.size());
  4988. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. ASSERT_EQ(StatusCode::OK_200, res->status);
  4991. ASSERT_EQ(4U, res->body.size());
  4992. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4994. ASSERT_EQ(StatusCode::OK_200, res->status);
  4995. ASSERT_EQ(4U, res->body.size());
  4996. }
  4997. TEST_F(ServerTest, EmptyRequest) {
  4998. auto res = cli_.Get("");
  4999. ASSERT_TRUE(!res);
  5000. EXPECT_EQ(Error::Connection, res.error());
  5001. }
  5002. TEST_F(ServerTest, LongRequest) {
  5003. std::string request;
  5004. for (size_t i = 0; i < 545; i++) {
  5005. request += "/TooLongRequest";
  5006. }
  5007. request += "OK";
  5008. auto res = cli_.Get(request.c_str());
  5009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5010. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5011. }
  5012. TEST_F(ServerTest, TooLongRequest) {
  5013. std::string request;
  5014. for (size_t i = 0; i < 546; i++) {
  5015. request += "/TooLongRequest";
  5016. }
  5017. request += "_NG";
  5018. auto start = std::chrono::high_resolution_clock::now();
  5019. cli_.set_keep_alive(true);
  5020. auto res = cli_.Get(request.c_str());
  5021. auto end = std::chrono::high_resolution_clock::now();
  5022. auto elapsed =
  5023. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5024. .count();
  5025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5026. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5027. EXPECT_LE(elapsed, 1000);
  5028. EXPECT_EQ("close", res->get_header_value("Connection"));
  5029. EXPECT_FALSE(cli_.is_socket_open());
  5030. }
  5031. TEST_F(ServerTest, AlmostTooLongRequest) {
  5032. // test for #2046 - URI length check shouldn't include other content on req
  5033. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5034. // leading /, space, HTTP/1.1)
  5035. std::string request =
  5036. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5037. auto res = cli_.Get(request.c_str());
  5038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5039. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5040. }
  5041. TEST_F(ServerTest, LongHeader) {
  5042. Request req;
  5043. req.method = "GET";
  5044. req.path = "/hi";
  5045. std::string host_and_port;
  5046. host_and_port += HOST;
  5047. host_and_port += ":";
  5048. host_and_port += std::to_string(PORT);
  5049. req.headers.emplace("Host", host_and_port.c_str());
  5050. req.headers.emplace("Accept", "*/*");
  5051. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5052. req.headers.emplace(
  5053. "Header-Name",
  5054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5082. "@@@@@@@@@@@@@@@@");
  5083. auto res = std::make_shared<Response>();
  5084. auto error = Error::Success;
  5085. auto ret = cli_.send(req, *res, error);
  5086. ASSERT_TRUE(ret);
  5087. EXPECT_EQ(StatusCode::OK_200, res->status);
  5088. }
  5089. TEST_F(ServerTest, LongQueryValue) {
  5090. auto start = std::chrono::high_resolution_clock::now();
  5091. cli_.set_keep_alive(true);
  5092. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5093. auto end = std::chrono::high_resolution_clock::now();
  5094. auto elapsed =
  5095. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5096. .count();
  5097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5098. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5099. EXPECT_LE(elapsed, 1000);
  5100. EXPECT_EQ("close", res->get_header_value("Connection"));
  5101. EXPECT_FALSE(cli_.is_socket_open());
  5102. }
  5103. TEST_F(ServerTest, TooLongQueryValue) {
  5104. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5105. ASSERT_FALSE(res);
  5106. EXPECT_EQ(Error::Read, res.error());
  5107. }
  5108. TEST_F(ServerTest, TooLongHeader) {
  5109. Request req;
  5110. req.method = "GET";
  5111. req.path = "/hi";
  5112. std::string host_and_port;
  5113. host_and_port += HOST;
  5114. host_and_port += ":";
  5115. host_and_port += std::to_string(PORT);
  5116. req.headers.emplace("Host", host_and_port.c_str());
  5117. req.headers.emplace("Accept", "*/*");
  5118. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5119. req.headers.emplace(
  5120. "Header-Name",
  5121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5149. "@@@@@@@@@@@@@@@@@");
  5150. auto res = std::make_shared<Response>();
  5151. auto error = Error::Success;
  5152. auto ret = cli_.send(req, *res, error);
  5153. ASSERT_TRUE(ret);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. }
  5156. TEST_F(ServerTest, HeaderCountAtLimit) {
  5157. // Test with headers just under the 100 limit
  5158. httplib::Headers headers;
  5159. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5160. // This should keep us just under the 100 header limit
  5161. for (int i = 0; i < 95; i++) {
  5162. std::string name = "X-Test-Header-" + std::to_string(i);
  5163. std::string value = "value" + std::to_string(i);
  5164. headers.emplace(name, value);
  5165. }
  5166. // This should work fine as we're under the limit
  5167. auto res = cli_.Get("/hi", headers);
  5168. EXPECT_TRUE(res);
  5169. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5170. }
  5171. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5172. // Test with many headers to exceed the 100 limit
  5173. httplib::Headers headers;
  5174. // Add 150 headers to definitely exceed the 100 limit
  5175. for (int i = 0; i < 150; i++) {
  5176. std::string name = "X-Test-Header-" + std::to_string(i);
  5177. std::string value = "value" + std::to_string(i);
  5178. headers.emplace(name, value);
  5179. }
  5180. // This should fail due to exceeding header count limit
  5181. cli_.set_keep_alive(true);
  5182. auto res = cli_.Get("/hi", headers);
  5183. // The server should respond with 400 Bad Request
  5184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5185. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5186. EXPECT_EQ("close", res->get_header_value("Connection"));
  5187. EXPECT_FALSE(cli_.is_socket_open());
  5188. }
  5189. TEST_F(ServerTest, PercentEncoding) {
  5190. auto res = cli_.Get("/e%6edwith%");
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. EXPECT_EQ(StatusCode::OK_200, res->status);
  5193. }
  5194. TEST_F(ServerTest, PercentEncodingUnicode) {
  5195. auto res = cli_.Get("/e%u006edwith%");
  5196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. }
  5199. TEST_F(ServerTest, InvalidPercentEncoding) {
  5200. auto res = cli_.Get("/%endwith%");
  5201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5203. }
  5204. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5205. auto res = cli_.Get("/%uendwith%");
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5208. }
  5209. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5210. auto res = cli_.Get("/hello?aaa=bbb%");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5213. }
  5214. TEST_F(ServerTest, PlusSignEncoding) {
  5215. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5217. EXPECT_EQ(StatusCode::OK_200, res->status);
  5218. EXPECT_EQ("a +b", res->body);
  5219. }
  5220. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5221. // This test simulates a potential DoS attack using many headers
  5222. // to verify our security fix prevents memory exhaustion
  5223. httplib::Headers attack_headers;
  5224. // Attempt to add many headers like an attacker would (200 headers to far
  5225. // exceed limit)
  5226. for (int i = 0; i < 200; i++) {
  5227. std::string name = "X-Attack-Header-" + std::to_string(i);
  5228. std::string value = "attack_payload_" + std::to_string(i);
  5229. attack_headers.emplace(name, value);
  5230. }
  5231. // Try to POST with excessive headers
  5232. cli_.set_keep_alive(true);
  5233. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5234. // Should either fail or return 400 Bad Request due to security limit
  5235. if (res) {
  5236. // If we get a response, it should be 400 Bad Request
  5237. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5238. EXPECT_EQ("close", res->get_header_value("Connection"));
  5239. }
  5240. EXPECT_FALSE(cli_.is_socket_open());
  5241. }
  5242. TEST_F(ServerTest, MultipartFormData) {
  5243. UploadFormDataItems items = {
  5244. {"text1", "text default", "", ""},
  5245. {"text2", "aωb", "", ""},
  5246. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5247. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5248. {"file3", "", "", "application/octet-stream"},
  5249. {"file4", "", "", " application/json tmp-string "}};
  5250. auto res = cli_.Post("/multipart", items);
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. }
  5254. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5255. UploadFormDataItems items = {
  5256. {"text", "default text", "", ""},
  5257. {"multi_text1", "aaaaa", "", ""},
  5258. {"multi_text1", "bbbbb", "", ""},
  5259. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5260. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5261. "application/json"},
  5262. };
  5263. auto res = cli_.Post("/multipart/multi_file_values", items);
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. }
  5267. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5268. auto res = cli_.Get("/hi");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5272. EXPECT_EQ("Hello World!", res->body);
  5273. }
  5274. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5275. Request req;
  5276. req.method = "POST";
  5277. req.path = "/chunked";
  5278. std::string host_and_port;
  5279. host_and_port += HOST;
  5280. host_and_port += ":";
  5281. host_and_port += std::to_string(PORT);
  5282. req.headers.emplace("Host", host_and_port.c_str());
  5283. req.headers.emplace("Accept", "*/*");
  5284. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5285. req.headers.emplace("Content-Type", "text/plain");
  5286. req.headers.emplace("Content-Length", "0");
  5287. req.headers.emplace(
  5288. "Transfer-Encoding",
  5289. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5290. // Client does not chunk, so make a chunked body manually.
  5291. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5292. auto res = std::make_shared<Response>();
  5293. auto error = Error::Success;
  5294. auto ret = cli_.send(req, *res, error);
  5295. ASSERT_TRUE(ret);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. }
  5298. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5299. // rather than treat them as valid lengths.
  5300. template <typename ClientT>
  5301. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5302. Request req;
  5303. req.method = "POST";
  5304. req.path = "/chunked";
  5305. std::string host_and_port;
  5306. host_and_port += HOST;
  5307. host_and_port += ":";
  5308. host_and_port += std::to_string(PORT);
  5309. req.headers.emplace("Host", host_and_port.c_str());
  5310. req.headers.emplace("Content-Length", "0");
  5311. req.headers.emplace("Transfer-Encoding", "chunked");
  5312. req.body = body;
  5313. auto res = std::make_shared<Response>();
  5314. auto error = Error::Success;
  5315. ASSERT_TRUE(cli.send(req, *res, error));
  5316. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5317. }
  5318. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5319. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5320. }
  5321. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5322. expect_chunked_body_rejected(
  5323. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5324. }
  5325. TEST_F(ServerTest, GetStreamed2) {
  5326. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5329. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5330. EXPECT_EQ(true, res->has_header("Content-Range"));
  5331. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5332. EXPECT_EQ(std::string("ab"), res->body);
  5333. }
  5334. TEST_F(ServerTest, GetStreamed) {
  5335. auto res = cli_.Get("/streamed");
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. EXPECT_EQ(StatusCode::OK_200, res->status);
  5338. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5339. EXPECT_EQ(std::string("aaabbb"), res->body);
  5340. }
  5341. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5342. auto res = cli_.Get("/streamed-without-length",
  5343. Headers{make_range_header({{0, -1}})});
  5344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5345. EXPECT_EQ(StatusCode::OK_200, res->status);
  5346. EXPECT_EQ(false, res->has_header("Content-Length"));
  5347. EXPECT_EQ(false, res->has_header("Content-Range"));
  5348. EXPECT_EQ(std::string("abcdefg"), res->body);
  5349. }
  5350. TEST_F(ServerTest, GetStreamedWithRange1) {
  5351. auto res =
  5352. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5355. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5356. EXPECT_EQ(true, res->has_header("Content-Range"));
  5357. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5358. EXPECT_EQ(std::string("def"), res->body);
  5359. }
  5360. TEST_F(ServerTest, GetStreamedWithRange2) {
  5361. auto res =
  5362. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5364. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5365. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5366. EXPECT_EQ(true, res->has_header("Content-Range"));
  5367. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5368. EXPECT_EQ(std::string("bcdefg"), res->body);
  5369. }
  5370. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5371. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5374. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5375. EXPECT_EQ(true, res->has_header("Content-Range"));
  5376. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5377. EXPECT_EQ(std::string("efg"), res->body);
  5378. }
  5379. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5380. auto res =
  5381. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5384. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5385. EXPECT_EQ(false, res->has_header("Content-Range"));
  5386. EXPECT_EQ(0U, res->body.size());
  5387. }
  5388. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5389. // Only a 206 is served as a partial representation. Under any other status
  5390. // `apply_ranges()` reported the full content length, so the body must match
  5391. // that header, and the content provider must never be asked for an offset
  5392. // outside the representation.
  5393. auto check = [&](int status, const char *range) {
  5394. auto path =
  5395. std::string("/streamed-with-range?status=") + std::to_string(status);
  5396. auto ctx = path + " Range: " + range;
  5397. auto res = cli_.Get(path, Headers{{"Range", range}});
  5398. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5399. EXPECT_EQ(status, res->status) << ctx;
  5400. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5402. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5403. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5404. };
  5405. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5406. check(403, "bytes=3-5");
  5407. // The offset is far past the representation.
  5408. check(403, "bytes=100000-100200");
  5409. // `first_pos` is still -1 here, and the bounds asserts in
  5410. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5411. check(403, "bytes=-3");
  5412. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5413. // multipart branch would have written one that is empty.
  5414. check(403, "bytes=1-2, 4-5");
  5415. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5416. // covers the whole representation.
  5417. check(200, "bytes=3-5");
  5418. check(200, "bytes=1-2, 4-5");
  5419. }
  5420. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5421. auto res =
  5422. cli_.Get("/streamed-with-range",
  5423. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5424. "92233720368547758079223372036854775807"}});
  5425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5426. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5427. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5428. EXPECT_EQ(false, res->has_header("Content-Range"));
  5429. EXPECT_EQ(0U, res->body.size());
  5430. }
  5431. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5432. auto res = cli_.Get(
  5433. "/with-range",
  5434. Headers{{"Range",
  5435. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5436. {"Accept-Encoding", ""}});
  5437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5438. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5439. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5440. EXPECT_EQ(true, res->has_header("Content-Range"));
  5441. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5442. EXPECT_EQ(std::string("abcdefg"), res->body);
  5443. }
  5444. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5445. auto res = cli_.Get("/with-range", Headers{
  5446. {"Range", "bytes=0-"},
  5447. {"Accept-Encoding", ""},
  5448. });
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5451. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5452. EXPECT_EQ(true, res->has_header("Content-Range"));
  5453. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5454. EXPECT_EQ(std::string("abcdefg"), res->body);
  5455. }
  5456. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5457. auto res = cli_.Get("/streamed-with-range",
  5458. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5460. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5461. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5462. EXPECT_EQ(false, res->has_header("Content-Range"));
  5463. EXPECT_EQ(267U, res->body.size());
  5464. // Check that both range contents are present
  5465. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5466. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5467. // Check that Content-Range headers are present for both ranges
  5468. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5469. std::string::npos);
  5470. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5471. std::string::npos);
  5472. }
  5473. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5474. Ranges ranges;
  5475. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5476. ranges.emplace_back(0, -1);
  5477. }
  5478. auto res = cli_.Get("/streamed-with-range?error",
  5479. Headers{{make_range_header(ranges)}});
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5482. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5483. EXPECT_EQ(false, res->has_header("Content-Range"));
  5484. EXPECT_EQ(0U, res->body.size());
  5485. }
  5486. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5487. auto res = cli_.Get("/streamed-with-range",
  5488. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5491. EXPECT_EQ(5U, res->body.size());
  5492. // Check that overlapping ranges are coalesced into a single range
  5493. EXPECT_EQ("bcdef", res->body);
  5494. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5495. // Should be single range, not multipart
  5496. EXPECT_TRUE(res->has_header("Content-Range"));
  5497. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5498. }
  5499. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5500. auto res = cli_.Get("/streamed-with-range",
  5501. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5504. EXPECT_EQ(268U, res->body.size());
  5505. // Check that both range contents are present
  5506. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5507. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5508. // Check that Content-Range headers are present for both ranges
  5509. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5510. std::string::npos);
  5511. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5512. std::string::npos);
  5513. }
  5514. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5515. auto res = cli_.Get("/streamed-with-range",
  5516. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5519. EXPECT_EQ(269U, res->body.size());
  5520. // Check that both duplicate range contents are present
  5521. size_t first_abc = res->body.find("abc\r\n");
  5522. EXPECT_TRUE(first_abc != std::string::npos);
  5523. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5524. EXPECT_TRUE(second_abc != std::string::npos);
  5525. // Check that Content-Range headers are present for both ranges
  5526. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5527. EXPECT_TRUE(first_range != std::string::npos);
  5528. size_t second_range =
  5529. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5530. EXPECT_TRUE(second_range != std::string::npos);
  5531. }
  5532. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5533. auto res =
  5534. cli_.Get("/streamed-with-range?error",
  5535. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5537. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5538. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5539. EXPECT_EQ(false, res->has_header("Content-Range"));
  5540. EXPECT_EQ(0U, res->body.size());
  5541. }
  5542. TEST_F(ServerTest, GetStreamedEndless) {
  5543. uint64_t offset = 0;
  5544. auto res = cli_.Get("/streamed-cancel",
  5545. [&](const char * /*data*/, uint64_t data_length) {
  5546. if (offset < 100) {
  5547. offset += data_length;
  5548. return true;
  5549. }
  5550. return false;
  5551. });
  5552. ASSERT_TRUE(!res);
  5553. EXPECT_EQ(Error::Canceled, res.error());
  5554. }
  5555. TEST_F(ServerTest, ClientStop) {
  5556. std::atomic_size_t count{4};
  5557. std::vector<std::thread> threads;
  5558. for (auto i = count.load(); i != 0; --i) {
  5559. threads.emplace_back([&]() {
  5560. auto res = cli_.Get("/streamed-cancel",
  5561. [&](const char *, uint64_t) { return true; });
  5562. --count;
  5563. ASSERT_TRUE(!res);
  5564. EXPECT_TRUE(res.error() == Error::Canceled ||
  5565. res.error() == Error::Read || res.error() == Error::Write);
  5566. });
  5567. }
  5568. std::this_thread::sleep_for(std::chrono::seconds(2));
  5569. while (count != 0) {
  5570. cli_.stop();
  5571. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5572. }
  5573. for (auto &t : threads) {
  5574. t.join();
  5575. }
  5576. }
  5577. TEST_F(ServerTest, GetWithRange1) {
  5578. auto res = cli_.Get("/with-range", Headers{
  5579. make_range_header({{3, 5}}),
  5580. {"Accept-Encoding", ""},
  5581. });
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5584. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5585. EXPECT_EQ(true, res->has_header("Content-Range"));
  5586. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5587. EXPECT_EQ(std::string("def"), res->body);
  5588. }
  5589. TEST_F(ServerTest, GetWithRange2) {
  5590. auto res = cli_.Get("/with-range", Headers{
  5591. make_range_header({{1, -1}}),
  5592. {"Accept-Encoding", ""},
  5593. });
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5596. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5597. EXPECT_EQ(true, res->has_header("Content-Range"));
  5598. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5599. EXPECT_EQ(std::string("bcdefg"), res->body);
  5600. }
  5601. TEST_F(ServerTest, GetWithRange3) {
  5602. auto res = cli_.Get("/with-range", Headers{
  5603. make_range_header({{0, 0}}),
  5604. {"Accept-Encoding", ""},
  5605. });
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5608. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5609. EXPECT_EQ(true, res->has_header("Content-Range"));
  5610. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5611. EXPECT_EQ(std::string("a"), res->body);
  5612. }
  5613. TEST_F(ServerTest, GetWithRange4) {
  5614. auto res = cli_.Get("/with-range", Headers{
  5615. make_range_header({{-1, 2}}),
  5616. {"Accept-Encoding", ""},
  5617. });
  5618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5620. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5621. EXPECT_EQ(true, res->has_header("Content-Range"));
  5622. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5623. EXPECT_EQ(std::string("fg"), res->body);
  5624. }
  5625. TEST_F(ServerTest, GetWithRange5) {
  5626. auto res = cli_.Get("/with-range", Headers{
  5627. make_range_header({{0, 5}}),
  5628. {"Accept-Encoding", ""},
  5629. });
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5632. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ(true, res->has_header("Content-Range"));
  5634. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5635. EXPECT_EQ(std::string("abcdef"), res->body);
  5636. }
  5637. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5638. auto res =
  5639. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5641. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5642. }
  5643. TEST_F(ServerTest, GetWithRangeMultipart) {
  5644. auto res =
  5645. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5647. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5648. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5649. EXPECT_EQ(false, res->has_header("Content-Range"));
  5650. EXPECT_EQ(267U, res->body.size());
  5651. }
  5652. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5653. auto res = cli_.Get("/with-range",
  5654. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5657. }
  5658. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5659. auto res = cli_.Get("/with-range-customized-response",
  5660. Headers{{make_range_header({{1, 2}})}});
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5663. EXPECT_EQ(true, res->has_header("Content-Length"));
  5664. EXPECT_EQ(false, res->has_header("Content-Range"));
  5665. EXPECT_EQ(JSON_DATA, res->body);
  5666. }
  5667. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5668. auto res = cli_.Get("/with-range-customized-response",
  5669. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5672. EXPECT_EQ(true, res->has_header("Content-Length"));
  5673. EXPECT_EQ(false, res->has_header("Content-Range"));
  5674. EXPECT_EQ(JSON_DATA, res->body);
  5675. }
  5676. TEST_F(ServerTest, Issue1772) {
  5677. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5680. }
  5681. TEST_F(ServerTest, Issue609) {
  5682. auto res = cli_.Delete("/issue609");
  5683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5684. EXPECT_EQ(StatusCode::OK_200, res->status);
  5685. EXPECT_EQ(std::string("ok"), res->body);
  5686. }
  5687. TEST_F(ServerTest, GetStreamedChunked) {
  5688. auto res = cli_.Get("/streamed-chunked");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ(std::string("123456789"), res->body);
  5692. }
  5693. TEST_F(ServerTest, GetStreamedChunked2) {
  5694. auto res = cli_.Get("/streamed-chunked2");
  5695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5696. EXPECT_EQ(StatusCode::OK_200, res->status);
  5697. EXPECT_EQ(std::string("123456789"), res->body);
  5698. }
  5699. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5700. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::OK_200, res->status);
  5703. EXPECT_EQ(std::string("123456789"), res->body);
  5704. EXPECT_TRUE(res->has_header("Trailer"));
  5705. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5706. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5707. // Trailers are now stored separately from headers (security fix)
  5708. EXPECT_EQ(2U, res->trailers.size());
  5709. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5710. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5711. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5712. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5713. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5714. // Verify trailers are NOT in headers (security verification)
  5715. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5716. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5717. }
  5718. TEST_F(ServerTest, LargeChunkedPost) {
  5719. Request req;
  5720. req.method = "POST";
  5721. req.path = "/large-chunked";
  5722. std::string host_and_port;
  5723. host_and_port += HOST;
  5724. host_and_port += ":";
  5725. host_and_port += std::to_string(PORT);
  5726. req.headers.emplace("Host", host_and_port.c_str());
  5727. req.headers.emplace("Accept", "*/*");
  5728. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5729. req.headers.emplace("Content-Type", "text/plain");
  5730. req.headers.emplace("Content-Length", "0");
  5731. req.headers.emplace("Transfer-Encoding", "chunked");
  5732. std::string long_string(30 * 1024u, 'a');
  5733. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5734. // Attempt to make a large enough post to exceed OS buffers, to test that
  5735. // the server handles short reads if the full chunk data isn't available.
  5736. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5737. auto res = std::make_shared<Response>();
  5738. auto error = Error::Success;
  5739. auto ret = cli_.send(req, *res, error);
  5740. ASSERT_TRUE(ret);
  5741. EXPECT_EQ(StatusCode::OK_200, res->status);
  5742. }
  5743. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5744. auto res = cli_.Get("/remote_addr");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5748. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5749. }
  5750. TEST_F(ServerTest, GetMethodLocalAddr) {
  5751. auto res = cli_.Get("/local_addr");
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. EXPECT_EQ(StatusCode::OK_200, res->status);
  5754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5755. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5756. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5757. }
  5758. TEST_F(ServerTest, HTTPResponseSplitting) {
  5759. auto res = cli_.Get("/http_response_splitting");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. }
  5763. TEST_F(ServerTest, SlowRequest) {
  5764. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5765. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5766. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5767. }
  5768. #if 0
  5769. TEST_F(ServerTest, SlowPost) {
  5770. char buffer[64 * 1024];
  5771. memset(buffer, 0x42, sizeof(buffer));
  5772. auto res = cli_.Post(
  5773. "/slowpost", 64 * 1024 * 1024,
  5774. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5775. auto ret = sink.write(buffer, sizeof(buffer));
  5776. EXPECT_TRUE(ret);
  5777. return true;
  5778. },
  5779. "text/plain");
  5780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5781. EXPECT_EQ(StatusCode::OK_200, res->status);
  5782. }
  5783. TEST_F(ServerTest, SlowPostFail) {
  5784. char buffer[64 * 1024];
  5785. memset(buffer, 0x42, sizeof(buffer));
  5786. cli_.set_write_timeout(std::chrono::seconds(0));
  5787. auto res = cli_.Post(
  5788. "/slowpost", 64 * 1024 * 1024,
  5789. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5790. sink.write(buffer, sizeof(buffer));
  5791. return true;
  5792. },
  5793. "text/plain");
  5794. ASSERT_TRUE(!res);
  5795. EXPECT_EQ(Error::Write, res.error());
  5796. }
  5797. #endif
  5798. TEST_F(ServerTest, Put) {
  5799. auto res = cli_.Put("/put", "PUT", "text/plain");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. EXPECT_EQ("PUT", res->body);
  5803. }
  5804. TEST_F(ServerTest, PutWithContentProvider) {
  5805. auto res = cli_.Put(
  5806. "/put", 3,
  5807. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5808. sink.os << "PUT";
  5809. return true;
  5810. },
  5811. "text/plain");
  5812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. EXPECT_EQ("PUT", res->body);
  5815. }
  5816. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5817. auto res = cli_.Post(
  5818. "/post", 42,
  5819. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5820. return false;
  5821. },
  5822. "text/plain");
  5823. ASSERT_TRUE(!res);
  5824. EXPECT_EQ(Error::Canceled, res.error());
  5825. }
  5826. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5827. auto res = cli_.Put(
  5828. "/put",
  5829. [](size_t /*offset*/, DataSink &sink) {
  5830. sink.os << "PUT";
  5831. sink.done();
  5832. return true;
  5833. },
  5834. "text/plain");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. EXPECT_EQ("PUT", res->body);
  5838. }
  5839. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5840. auto res = cli_.Post(
  5841. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5842. "text/plain");
  5843. ASSERT_TRUE(!res);
  5844. EXPECT_EQ(Error::Canceled, res.error());
  5845. }
  5846. TEST_F(ServerTest, PostLoopBack) {
  5847. std::string body;
  5848. auto res = cli_.Post(
  5849. "/post-loopback", 9,
  5850. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5851. EXPECT_EQ(9u, length);
  5852. sink.write("123", 3);
  5853. sink.write("456", 3);
  5854. sink.write("789", 3);
  5855. return true;
  5856. },
  5857. "text/plain",
  5858. [&body](const char *data, size_t data_length) {
  5859. body.append(data, data_length);
  5860. return true;
  5861. });
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. EXPECT_EQ(StatusCode::OK_200, res->status);
  5864. EXPECT_EQ("123456789", body);
  5865. }
  5866. TEST_F(ServerTest, PutLoopBack) {
  5867. std::string body;
  5868. auto res = cli_.Put(
  5869. "/put-loopback", 9,
  5870. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5871. EXPECT_EQ(9u, length);
  5872. sink.write("123", 3);
  5873. sink.write("456", 3);
  5874. sink.write("789", 3);
  5875. return true;
  5876. },
  5877. "text/plain",
  5878. [&body](const char *data, size_t data_length) {
  5879. body.append(data, data_length);
  5880. return true;
  5881. });
  5882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5883. EXPECT_EQ(StatusCode::OK_200, res->status);
  5884. EXPECT_EQ("123456789", body);
  5885. }
  5886. TEST_F(ServerTest, PatchLoopBack) {
  5887. std::string body;
  5888. auto res = cli_.Patch(
  5889. "/patch-loopback", 9,
  5890. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5891. EXPECT_EQ(9u, length);
  5892. sink.write("123", 3);
  5893. sink.write("456", 3);
  5894. sink.write("789", 3);
  5895. return true;
  5896. },
  5897. "text/plain",
  5898. [&body](const char *data, size_t data_length) {
  5899. body.append(data, data_length);
  5900. return true;
  5901. });
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::OK_200, res->status);
  5904. EXPECT_EQ("123456789", body);
  5905. }
  5906. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5907. std::string body;
  5908. auto res = cli_.Post(
  5909. "/post-loopback",
  5910. [](size_t /*offset*/, DataSink &sink) {
  5911. sink.write("123", 3);
  5912. sink.write("456", 3);
  5913. sink.write("789", 3);
  5914. sink.done();
  5915. return true;
  5916. },
  5917. "text/plain",
  5918. [&body](const char *data, size_t data_length) {
  5919. body.append(data, data_length);
  5920. return true;
  5921. });
  5922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5923. EXPECT_EQ(StatusCode::OK_200, res->status);
  5924. EXPECT_EQ("123456789", body);
  5925. }
  5926. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5927. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5928. cli_.set_compress(true);
  5929. auto res = cli_.Put(
  5930. "/put", 3,
  5931. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5932. sink.os << "PUT";
  5933. return true;
  5934. },
  5935. "text/plain");
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. EXPECT_EQ(StatusCode::OK_200, res->status);
  5938. EXPECT_EQ("PUT", res->body);
  5939. }
  5940. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5941. cli_.set_compress(true);
  5942. auto res = cli_.Post(
  5943. "/post", 42,
  5944. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5945. return false;
  5946. },
  5947. "text/plain");
  5948. ASSERT_TRUE(!res);
  5949. EXPECT_EQ(Error::Canceled, res.error());
  5950. }
  5951. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5952. cli_.set_compress(true);
  5953. auto res = cli_.Put(
  5954. "/put",
  5955. [](size_t /*offset*/, DataSink &sink) {
  5956. sink.os << "PUT";
  5957. sink.done();
  5958. return true;
  5959. },
  5960. "text/plain");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. EXPECT_EQ(StatusCode::OK_200, res->status);
  5963. EXPECT_EQ("PUT", res->body);
  5964. }
  5965. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5966. cli_.set_compress(true);
  5967. auto res = cli_.Post(
  5968. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5969. "text/plain");
  5970. ASSERT_TRUE(!res);
  5971. EXPECT_EQ(Error::Canceled, res.error());
  5972. }
  5973. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5974. cli_.set_compress(true);
  5975. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. EXPECT_EQ(LARGE_DATA, res->body);
  5979. }
  5980. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5981. #ifdef CPPHTTPLIB_SSL_ENABLED
  5982. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5983. Client cli(s.c_str());
  5984. cli.enable_server_certificate_verification(false);
  5985. #else
  5986. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5987. Client cli(s.c_str());
  5988. #endif
  5989. cli.set_compress(true);
  5990. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. EXPECT_EQ(LARGE_DATA, res->body);
  5994. // The compressed size should be less than a 10th of the original. May vary
  5995. // depending on the zlib library.
  5996. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5997. static_cast<uint64_t>(10 * 1024 * 1024));
  5998. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5999. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6000. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6001. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6002. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6003. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6004. #endif
  6005. }
  6006. TEST_F(ServerTest, PutContentWithDeflate) {
  6007. cli_.set_compress(false);
  6008. Headers headers;
  6009. headers.emplace("Content-Encoding", "deflate");
  6010. // PUT in deflate format:
  6011. auto res = cli_.Put("/put", headers,
  6012. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. EXPECT_EQ(StatusCode::OK_200, res->status);
  6015. EXPECT_EQ("PUT", res->body);
  6016. }
  6017. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6018. Headers headers;
  6019. headers.emplace("Accept-Encoding", "gzip, deflate");
  6020. auto res = cli_.Get("/streamed-chunked", headers);
  6021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6022. EXPECT_EQ(StatusCode::OK_200, res->status);
  6023. EXPECT_EQ(std::string("123456789"), res->body);
  6024. }
  6025. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6026. Headers headers;
  6027. headers.emplace("Accept-Encoding", "gzip, deflate");
  6028. auto res = cli_.Get("/streamed-chunked2", headers);
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::OK_200, res->status);
  6031. EXPECT_EQ(std::string("123456789"), res->body);
  6032. }
  6033. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6034. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. }
  6038. TEST(GzipDecompressor, ChunkedDecompression) {
  6039. std::string data;
  6040. for (size_t i = 0; i < 32 * 1024; ++i) {
  6041. data.push_back(static_cast<char>('a' + i % 26));
  6042. }
  6043. std::string compressed_data;
  6044. {
  6045. httplib::detail::gzip_compressor compressor;
  6046. bool result = compressor.compress(
  6047. data.data(), data.size(),
  6048. /*last=*/true,
  6049. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6050. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6051. compressed_data_size);
  6052. return true;
  6053. });
  6054. ASSERT_TRUE(result);
  6055. }
  6056. std::string decompressed_data;
  6057. {
  6058. httplib::detail::gzip_decompressor decompressor;
  6059. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6060. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6061. size_t chunk_size = 130;
  6062. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6063. chunk_begin += chunk_size) {
  6064. size_t current_chunk_size =
  6065. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6066. bool result = decompressor.decompress(
  6067. compressed_data.data() + chunk_begin, current_chunk_size,
  6068. [&](const char *decompressed_data_chunk,
  6069. size_t decompressed_data_chunk_size) {
  6070. decompressed_data.insert(decompressed_data.size(),
  6071. decompressed_data_chunk,
  6072. decompressed_data_chunk_size);
  6073. return true;
  6074. });
  6075. ASSERT_TRUE(result);
  6076. }
  6077. }
  6078. ASSERT_EQ(data, decompressed_data);
  6079. }
  6080. TEST(GzipDecompressor, DeflateDecompression) {
  6081. std::string original_text = "Raw deflate without gzip";
  6082. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6083. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6084. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6085. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6086. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6087. std::string decompressed_data;
  6088. {
  6089. httplib::detail::gzip_decompressor decompressor;
  6090. bool result = decompressor.decompress(
  6091. compressed_data.data(), compressed_data.size(),
  6092. [&](const char *decompressed_data_chunk,
  6093. size_t decompressed_data_chunk_size) {
  6094. decompressed_data.insert(decompressed_data.size(),
  6095. decompressed_data_chunk,
  6096. decompressed_data_chunk_size);
  6097. return true;
  6098. });
  6099. ASSERT_TRUE(result);
  6100. }
  6101. ASSERT_EQ(original_text, decompressed_data);
  6102. }
  6103. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6104. std::string original_text = "Raw deflate without gzip";
  6105. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6106. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6107. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6108. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6109. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6110. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6111. std::string decompressed_data;
  6112. {
  6113. httplib::detail::gzip_decompressor decompressor;
  6114. bool result = decompressor.decompress(
  6115. compressed_data.data(), compressed_data.size(),
  6116. [&](const char *decompressed_data_chunk,
  6117. size_t decompressed_data_chunk_size) {
  6118. decompressed_data.insert(decompressed_data.size(),
  6119. decompressed_data_chunk,
  6120. decompressed_data_chunk_size);
  6121. return true;
  6122. });
  6123. ASSERT_TRUE(result);
  6124. }
  6125. ASSERT_EQ(original_text, decompressed_data);
  6126. }
  6127. #endif
  6128. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6129. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6130. Headers headers;
  6131. headers.emplace("Accept-Encoding", "br");
  6132. auto res = cli_.Get("/streamed-chunked", headers);
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::OK_200, res->status);
  6135. EXPECT_EQ(std::string("123456789"), res->body);
  6136. }
  6137. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6138. Headers headers;
  6139. headers.emplace("Accept-Encoding", "br");
  6140. auto res = cli_.Get("/streamed-chunked2", headers);
  6141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6142. EXPECT_EQ(StatusCode::OK_200, res->status);
  6143. EXPECT_EQ(std::string("123456789"), res->body);
  6144. }
  6145. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6146. cli_.set_compress(true);
  6147. auto res = cli_.Put(
  6148. "/put", 3,
  6149. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6150. sink.os << "PUT";
  6151. return true;
  6152. },
  6153. "text/plain");
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. EXPECT_EQ(StatusCode::OK_200, res->status);
  6156. EXPECT_EQ("PUT", res->body);
  6157. }
  6158. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6159. cli_.set_compress(true);
  6160. auto res = cli_.Put(
  6161. "/put",
  6162. [](size_t /*offset*/, DataSink &sink) {
  6163. sink.os << "PUT";
  6164. sink.done();
  6165. return true;
  6166. },
  6167. "text/plain");
  6168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6169. EXPECT_EQ(StatusCode::OK_200, res->status);
  6170. EXPECT_EQ("PUT", res->body);
  6171. }
  6172. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6173. cli_.set_compress(true);
  6174. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. EXPECT_EQ(LARGE_DATA, res->body);
  6178. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6179. }
  6180. #endif
  6181. TEST_F(ServerTest, Patch) {
  6182. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. EXPECT_EQ("PATCH", res->body);
  6186. }
  6187. TEST_F(ServerTest, Delete) {
  6188. auto res = cli_.Delete("/delete");
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. EXPECT_EQ(StatusCode::OK_200, res->status);
  6191. EXPECT_EQ("DELETE", res->body);
  6192. }
  6193. TEST_F(ServerTest, DeleteContentReceiver) {
  6194. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6196. EXPECT_EQ(StatusCode::OK_200, res->status);
  6197. EXPECT_EQ("content", res->body);
  6198. }
  6199. TEST_F(ServerTest, Options) {
  6200. auto res = cli_.Options("*");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6204. EXPECT_TRUE(res->body.empty());
  6205. }
  6206. TEST_F(ServerTest, URL) {
  6207. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::OK_200, res->status);
  6210. }
  6211. TEST_F(ServerTest, ArrayParam) {
  6212. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. TEST_F(ServerTest, ArrayParamValues) {
  6217. auto res =
  6218. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::OK_200, res->status);
  6221. }
  6222. TEST_F(ServerTest, NoMultipleHeaders) {
  6223. Headers headers = {{"Content-Length", "5"}};
  6224. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6225. "text/plain");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::OK_200, res->status);
  6228. }
  6229. TEST_F(ServerTest, PostContentReceiver) {
  6230. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ("content", res->body);
  6234. }
  6235. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6236. UploadFormDataItems items = {
  6237. {"text1", "text default", "", ""},
  6238. {"text2", "aωb", "", ""},
  6239. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6240. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6241. {"file3", "", "", "application/octet-stream"},
  6242. };
  6243. auto res = cli_.Post("/content_receiver", items);
  6244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6245. EXPECT_EQ(StatusCode::OK_200, res->status);
  6246. }
  6247. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6248. UploadFormDataItems items = {
  6249. {"text1", "text default", "", ""},
  6250. {"text2", "aωb", "", ""},
  6251. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6252. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6253. {"file3", "", "", "application/octet-stream"},
  6254. };
  6255. auto boundary = std::string("+++++");
  6256. std::string body;
  6257. for (const auto &item : items) {
  6258. body += "--" + boundary + "\r\n";
  6259. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6260. if (!item.filename.empty()) {
  6261. body += "; filename=\"" + item.filename + "\"";
  6262. }
  6263. body += "\r\n";
  6264. if (!item.content_type.empty()) {
  6265. body += "Content-Type: " + item.content_type + "\r\n";
  6266. }
  6267. body += "\r\n";
  6268. body += item.content + "\r\n";
  6269. }
  6270. body += "--" + boundary + "--\r\n";
  6271. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6272. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. TEST(MultipartFormDataTest, FieldEscaping) {
  6277. Server svr;
  6278. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6279. const ContentReader &content_reader) {
  6280. ASSERT_TRUE(req.is_multipart_form_data());
  6281. std::vector<FormData> received;
  6282. content_reader(
  6283. [&](const FormData &file) {
  6284. received.push_back(file);
  6285. return true;
  6286. },
  6287. [&](const char *data, size_t data_length) {
  6288. received.back().content.append(data, data_length);
  6289. return true;
  6290. });
  6291. // '"', CR and LF in names and filenames are escaped following the
  6292. // WHATWG HTML standard, so each part still parses as a single part
  6293. // with no injected headers. Content types get CR/LF escaped too,
  6294. // while '"' (legal there, e.g. quoted charset) is preserved.
  6295. ASSERT_EQ(4U, received.size());
  6296. EXPECT_EQ("na%22me", received[0].name);
  6297. EXPECT_EQ("quoted name", received[0].content);
  6298. EXPECT_EQ("file", received[1].name);
  6299. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6300. received[1].filename);
  6301. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6302. EXPECT_EQ("injected", received[1].content);
  6303. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6304. EXPECT_EQ("my%22file.txt", received[2].filename);
  6305. EXPECT_EQ("cr lf name", received[2].content);
  6306. EXPECT_EQ("typed", received[3].name);
  6307. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6308. received[3].content_type);
  6309. EXPECT_EQ("typed content", received[3].content);
  6310. });
  6311. auto port = svr.bind_to_any_port("localhost");
  6312. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6313. auto se = detail::scope_exit([&] {
  6314. svr.stop();
  6315. t.join();
  6316. ASSERT_FALSE(svr.is_running());
  6317. });
  6318. svr.wait_until_ready();
  6319. Client cli("localhost", port);
  6320. UploadFormDataItems items = {
  6321. {"na\"me", "quoted name", "", ""},
  6322. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6323. "application/octet-stream"},
  6324. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6325. {"typed", "typed content", "",
  6326. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6327. };
  6328. auto res = cli.Post("/post", items);
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::OK_200, res->status);
  6331. }
  6332. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6333. const UploadFormDataItems items = {
  6334. {"name1", "Content 1", "", ""},
  6335. {"name2", "Content 2", "file2.txt", "text/plain"},
  6336. };
  6337. Server svr;
  6338. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6339. const ContentReader &content_reader) {
  6340. ASSERT_TRUE(req.is_multipart_form_data());
  6341. std::vector<FormData> received;
  6342. content_reader(
  6343. [&](const FormData &file) {
  6344. received.push_back(file);
  6345. return true;
  6346. },
  6347. [&](const char *data, size_t data_length) {
  6348. received.back().content.append(data, data_length);
  6349. return true;
  6350. });
  6351. ASSERT_EQ(2U, received.size());
  6352. EXPECT_EQ("name1", received[0].name);
  6353. EXPECT_EQ("Content 1", received[0].content);
  6354. EXPECT_EQ("name2", received[1].name);
  6355. EXPECT_EQ("Content 2", received[1].content);
  6356. EXPECT_EQ("file2.txt", received[1].filename);
  6357. EXPECT_EQ("text/plain", received[1].content_type);
  6358. });
  6359. auto port = svr.bind_to_any_port("localhost");
  6360. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6361. auto se = detail::scope_exit([&] {
  6362. svr.stop();
  6363. t.join();
  6364. ASSERT_FALSE(svr.is_running());
  6365. });
  6366. svr.wait_until_ready();
  6367. Client cli("localhost", port);
  6368. // Whole-body serialization with a generated boundary
  6369. {
  6370. MultipartFormDataWriter writer;
  6371. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6372. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6373. writer.content_type());
  6374. auto body = writer.serialize(items);
  6375. EXPECT_EQ(body.size(), writer.content_length(items));
  6376. auto res = cli.Post("/post", body, writer.content_type());
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. }
  6380. // Per-part framing with a custom boundary via a content provider
  6381. {
  6382. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6383. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6384. MultipartFormDataWriter writer("custom-boundary_123");
  6385. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6386. std::string body;
  6387. for (const auto &item : items) {
  6388. body += writer.item_begin(item);
  6389. body += item.content;
  6390. body += MultipartFormDataWriter::item_end();
  6391. }
  6392. body += writer.finish();
  6393. EXPECT_EQ(body.size(), writer.content_length(items));
  6394. auto res = cli.Post(
  6395. "/post", body.size(),
  6396. [&](size_t offset, size_t length, DataSink &sink) {
  6397. sink.write(body.data() + offset, length);
  6398. return true;
  6399. },
  6400. writer.content_type());
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. EXPECT_EQ(StatusCode::OK_200, res->status);
  6403. }
  6404. }
  6405. TEST_F(ServerTest, PostContentReceiverGzip) {
  6406. cli_.set_compress(true);
  6407. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. ASSERT_EQ(StatusCode::OK_200, res->status);
  6410. ASSERT_EQ("content", res->body);
  6411. }
  6412. TEST_F(ServerTest, PutContentReceiver) {
  6413. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6415. ASSERT_EQ(StatusCode::OK_200, res->status);
  6416. ASSERT_EQ("content", res->body);
  6417. }
  6418. TEST_F(ServerTest, PatchContentReceiver) {
  6419. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. ASSERT_EQ(StatusCode::OK_200, res->status);
  6422. ASSERT_EQ("content", res->body);
  6423. }
  6424. template <typename ClientType>
  6425. void TestWithHeadersAndContentReceiver(
  6426. ClientType &cli,
  6427. std::function<Result(ClientType &, const std::string &, const Headers &,
  6428. const std::string &, const std::string &,
  6429. ContentReceiver, DownloadProgress)>
  6430. request_func) {
  6431. Headers headers;
  6432. headers.emplace("X-Custom-Header", "test-value");
  6433. std::string received_body;
  6434. auto res = request_func(
  6435. cli, "/content_receiver", headers, "content", "application/json",
  6436. [&](const char *data, size_t data_length) {
  6437. received_body.append(data, data_length);
  6438. return true;
  6439. },
  6440. nullptr);
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ("content", received_body);
  6444. }
  6445. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6446. #ifdef CPPHTTPLIB_SSL_ENABLED
  6447. using ClientT = SSLClient;
  6448. #else
  6449. using ClientT = Client;
  6450. #endif
  6451. TestWithHeadersAndContentReceiver<ClientT>(
  6452. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6453. const std::string &body, const std::string &content_type,
  6454. ContentReceiver receiver, DownloadProgress progress) {
  6455. return cli.Post(path, headers, body, content_type, receiver, progress);
  6456. });
  6457. }
  6458. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6459. #ifdef CPPHTTPLIB_SSL_ENABLED
  6460. using ClientT = SSLClient;
  6461. #else
  6462. using ClientT = Client;
  6463. #endif
  6464. TestWithHeadersAndContentReceiver<ClientT>(
  6465. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6466. const std::string &body, const std::string &content_type,
  6467. ContentReceiver receiver, DownloadProgress progress) {
  6468. return cli.Put(path, headers, body, content_type, receiver, progress);
  6469. });
  6470. }
  6471. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6472. #ifdef CPPHTTPLIB_SSL_ENABLED
  6473. using ClientT = SSLClient;
  6474. #else
  6475. using ClientT = Client;
  6476. #endif
  6477. TestWithHeadersAndContentReceiver<ClientT>(
  6478. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6479. const std::string &body, const std::string &content_type,
  6480. ContentReceiver receiver, DownloadProgress progress) {
  6481. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6482. });
  6483. }
  6484. template <typename ClientType>
  6485. void TestWithHeadersAndContentReceiverWithProgress(
  6486. ClientType &cli,
  6487. std::function<Result(ClientType &, const std::string &, const Headers &,
  6488. const std::string &, const std::string &,
  6489. ContentReceiver, DownloadProgress)>
  6490. request_func) {
  6491. Headers headers;
  6492. headers.emplace("X-Test-Header", "progress-test");
  6493. std::string received_body;
  6494. auto progress_called = false;
  6495. auto res = request_func(
  6496. cli, "/content_receiver", headers, "content", "text/plain",
  6497. [&](const char *data, size_t data_length) {
  6498. received_body.append(data, data_length);
  6499. return true;
  6500. },
  6501. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6502. progress_called = true;
  6503. return true;
  6504. });
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::OK_200, res->status);
  6507. EXPECT_EQ("content", received_body);
  6508. EXPECT_TRUE(progress_called);
  6509. }
  6510. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6511. #ifdef CPPHTTPLIB_SSL_ENABLED
  6512. using ClientT = SSLClient;
  6513. #else
  6514. using ClientT = Client;
  6515. #endif
  6516. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6517. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6518. const std::string &body, const std::string &content_type,
  6519. ContentReceiver receiver, DownloadProgress progress) {
  6520. return cli.Post(path, headers, body, content_type, receiver, progress);
  6521. });
  6522. }
  6523. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6524. #ifdef CPPHTTPLIB_SSL_ENABLED
  6525. using ClientT = SSLClient;
  6526. #else
  6527. using ClientT = Client;
  6528. #endif
  6529. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6530. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6531. const std::string &body, const std::string &content_type,
  6532. ContentReceiver receiver, DownloadProgress progress) {
  6533. return cli.Put(path, headers, body, content_type, receiver, progress);
  6534. });
  6535. }
  6536. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6537. #ifdef CPPHTTPLIB_SSL_ENABLED
  6538. using ClientT = SSLClient;
  6539. #else
  6540. using ClientT = Client;
  6541. #endif
  6542. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6543. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6544. const std::string &body, const std::string &content_type,
  6545. ContentReceiver receiver, DownloadProgress progress) {
  6546. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6547. });
  6548. }
  6549. template <typename ClientType>
  6550. void TestWithHeadersAndContentReceiverError(
  6551. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6552. const Headers &, const std::string &,
  6553. const std::string &, ContentReceiver)>
  6554. request_func) {
  6555. Headers headers;
  6556. headers.emplace("X-Error-Test", "true");
  6557. std::string received_body;
  6558. auto receiver_failed = false;
  6559. auto res =
  6560. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6561. [&](const char *data, size_t data_length) {
  6562. received_body.append(data, data_length);
  6563. receiver_failed = true;
  6564. return false;
  6565. });
  6566. ASSERT_FALSE(res);
  6567. EXPECT_TRUE(receiver_failed);
  6568. }
  6569. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6570. #ifdef CPPHTTPLIB_SSL_ENABLED
  6571. using ClientT = SSLClient;
  6572. #else
  6573. using ClientT = Client;
  6574. #endif
  6575. TestWithHeadersAndContentReceiverError<ClientT>(
  6576. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6577. const std::string &body, const std::string &content_type,
  6578. ContentReceiver receiver) {
  6579. return cli.Post(path, headers, body, content_type, receiver);
  6580. });
  6581. }
  6582. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6583. #ifdef CPPHTTPLIB_SSL_ENABLED
  6584. using ClientT = SSLClient;
  6585. #else
  6586. using ClientT = Client;
  6587. #endif
  6588. TestWithHeadersAndContentReceiverError<ClientT>(
  6589. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6590. const std::string &body, const std::string &content_type,
  6591. ContentReceiver receiver) {
  6592. return cli.Put(path, headers, body, content_type, receiver);
  6593. });
  6594. }
  6595. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6596. #ifdef CPPHTTPLIB_SSL_ENABLED
  6597. using ClientT = SSLClient;
  6598. #else
  6599. using ClientT = Client;
  6600. #endif
  6601. TestWithHeadersAndContentReceiverError<ClientT>(
  6602. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6603. const std::string &body, const std::string &content_type,
  6604. ContentReceiver receiver) {
  6605. return cli.Patch(path, headers, body, content_type, receiver);
  6606. });
  6607. }
  6608. TEST_F(ServerTest, PostQueryStringAndBody) {
  6609. auto res =
  6610. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. ASSERT_EQ(StatusCode::OK_200, res->status);
  6613. }
  6614. TEST_F(ServerTest, HTTP2Magic) {
  6615. Request req;
  6616. req.method = "PRI";
  6617. req.path = "*";
  6618. req.body = "SM";
  6619. auto res = std::make_shared<Response>();
  6620. auto error = Error::Success;
  6621. auto ret = cli_.send(req, *res, error);
  6622. ASSERT_TRUE(ret);
  6623. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6624. }
  6625. TEST_F(ServerTest, KeepAlive) {
  6626. auto res = cli_.Get("/hi");
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::OK_200, res->status);
  6629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6630. EXPECT_EQ("Hello World!", res->body);
  6631. res = cli_.Get("/hi");
  6632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6633. EXPECT_EQ(StatusCode::OK_200, res->status);
  6634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6635. EXPECT_EQ("Hello World!", res->body);
  6636. res = cli_.Get("/hi");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6640. EXPECT_EQ("Hello World!", res->body);
  6641. res = cli_.Get("/not-exist");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6644. res = cli_.Post("/empty", "", "text/plain");
  6645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6648. EXPECT_EQ("empty", res->body);
  6649. EXPECT_EQ("close", res->get_header_value("Connection"));
  6650. res = cli_.Post(
  6651. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6652. "text/plain");
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::OK_200, res->status);
  6655. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6656. EXPECT_EQ("empty", res->body);
  6657. cli_.set_keep_alive(false);
  6658. res = cli_.Get("/last-request");
  6659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. EXPECT_EQ("close", res->get_header_value("Connection"));
  6662. }
  6663. TEST_F(ServerTest, TooManyRedirect) {
  6664. cli_.set_follow_location(true);
  6665. auto res = cli_.Get("/redirect/0");
  6666. ASSERT_TRUE(!res);
  6667. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6668. }
  6669. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6670. Request req;
  6671. req.method = "FOOBAR";
  6672. req.path = "/hi";
  6673. cli_.set_keep_alive(true);
  6674. auto res = cli_.send(req);
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6677. EXPECT_EQ("close", res->get_header_value("Connection"));
  6678. EXPECT_FALSE(cli_.is_socket_open());
  6679. }
  6680. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6682. TEST_F(ServerTest, Gzip) {
  6683. Headers headers;
  6684. headers.emplace("Accept-Encoding", "gzip, deflate");
  6685. auto res = cli_.Get("/compress", headers);
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6689. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6690. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6691. "7890123456789012345678901234567890",
  6692. res->body);
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6696. Headers headers;
  6697. headers.emplace("Accept-Encoding", "gzip, deflate");
  6698. auto res = cli_.Get("/compress-with-charset", headers);
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6701. EXPECT_EQ("application/json; charset=utf-8",
  6702. res->get_header_value("Content-Type"));
  6703. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6704. "7890123456789012345678901234567890",
  6705. res->body);
  6706. EXPECT_EQ(StatusCode::OK_200, res->status);
  6707. }
  6708. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6709. Headers headers;
  6710. headers.emplace("Accept-Encoding", "");
  6711. auto res = cli_.Get("/compress", headers);
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6714. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6715. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6716. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6717. "7890123456789012345678901234567890",
  6718. res->body);
  6719. EXPECT_EQ(StatusCode::OK_200, res->status);
  6720. }
  6721. TEST_F(ServerTest, GzipWithContentReceiver) {
  6722. Headers headers;
  6723. headers.emplace("Accept-Encoding", "gzip, deflate");
  6724. std::string body;
  6725. auto res = cli_.Get("/compress", headers,
  6726. [&](const char *data, uint64_t data_length) {
  6727. EXPECT_EQ(100U, data_length);
  6728. body.append(data, data_length);
  6729. return true;
  6730. });
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6733. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6734. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6735. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6736. "7890123456789012345678901234567890",
  6737. body);
  6738. EXPECT_EQ(StatusCode::OK_200, res->status);
  6739. }
  6740. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6741. Headers headers;
  6742. headers.emplace("Accept-Encoding", "gzip, deflate");
  6743. cli_.set_decompress(false);
  6744. auto res = cli_.Get("/compress", headers);
  6745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6746. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6747. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6748. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6749. EXPECT_EQ(33U, res->body.size());
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. }
  6752. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6753. Headers headers;
  6754. headers.emplace("Accept-Encoding", "");
  6755. std::string body;
  6756. auto res = cli_.Get("/compress", headers,
  6757. [&](const char *data, uint64_t data_length) {
  6758. EXPECT_EQ(100U, data_length);
  6759. body.append(data, data_length);
  6760. return true;
  6761. });
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6764. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6765. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6766. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6767. "7890123456789012345678901234567890",
  6768. body);
  6769. EXPECT_EQ(StatusCode::OK_200, res->status);
  6770. }
  6771. TEST_F(ServerTest, NoGzip) {
  6772. Headers headers;
  6773. headers.emplace("Accept-Encoding", "gzip, deflate");
  6774. auto res = cli_.Get("/nocompress", headers);
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6777. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6778. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6779. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6780. "7890123456789012345678901234567890",
  6781. res->body);
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. }
  6784. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6785. Headers headers;
  6786. headers.emplace("Accept-Encoding", "gzip, deflate");
  6787. std::string body;
  6788. auto res = cli_.Get("/nocompress", headers,
  6789. [&](const char *data, uint64_t data_length) {
  6790. EXPECT_EQ(100U, data_length);
  6791. body.append(data, data_length);
  6792. return true;
  6793. });
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6796. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6797. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6798. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6799. "7890123456789012345678901234567890",
  6800. body);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, MultipartFormDataGzip) {
  6804. UploadFormDataItems items = {
  6805. {"key1", "test", "", ""},
  6806. {"key2", "--abcdefg123", "", ""},
  6807. };
  6808. cli_.set_compress(true);
  6809. auto res = cli_.Post("/compress-multipart", items);
  6810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6811. EXPECT_EQ(StatusCode::OK_200, res->status);
  6812. }
  6813. #endif
  6814. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6815. TEST_F(ServerTest, Brotli) {
  6816. Headers headers;
  6817. headers.emplace("Accept-Encoding", "br");
  6818. auto res = cli_.Get("/compress", headers);
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6821. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6822. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6823. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6824. "7890123456789012345678901234567890",
  6825. res->body);
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. }
  6828. #endif
  6829. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6830. TEST_F(ServerTest, Zstd) {
  6831. Headers headers;
  6832. headers.emplace("Accept-Encoding", "zstd");
  6833. auto res = cli_.Get("/compress", headers);
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6837. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6838. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6839. "7890123456789012345678901234567890",
  6840. res->body);
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6844. Headers headers;
  6845. headers.emplace("Accept-Encoding", "");
  6846. auto res = cli_.Get("/compress", headers);
  6847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6848. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6850. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6851. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6852. "7890123456789012345678901234567890",
  6853. res->body);
  6854. EXPECT_EQ(StatusCode::OK_200, res->status);
  6855. }
  6856. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6857. Headers headers;
  6858. headers.emplace("Accept-Encoding", "zstd");
  6859. std::string body;
  6860. auto res = cli_.Get("/compress", headers,
  6861. [&](const char *data, uint64_t data_length) {
  6862. EXPECT_EQ(100U, data_length);
  6863. body.append(data, data_length);
  6864. return true;
  6865. });
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6868. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6869. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6870. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6871. "7890123456789012345678901234567890",
  6872. body);
  6873. EXPECT_EQ(StatusCode::OK_200, res->status);
  6874. }
  6875. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6876. Headers headers;
  6877. headers.emplace("Accept-Encoding", "zstd");
  6878. cli_.set_decompress(false);
  6879. auto res = cli_.Get("/compress", headers);
  6880. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6881. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6882. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6883. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6887. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. ASSERT_EQ(26U, res->body.size());
  6890. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6891. 0);
  6892. }
  6893. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6894. Headers headers;
  6895. headers.emplace("Accept-Encoding", "");
  6896. std::string body;
  6897. auto res = cli_.Get("/compress", headers,
  6898. [&](const char *data, uint64_t data_length) {
  6899. EXPECT_EQ(100U, data_length);
  6900. body.append(data, data_length);
  6901. return true;
  6902. });
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6906. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6907. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6908. "7890123456789012345678901234567890",
  6909. body);
  6910. EXPECT_EQ(StatusCode::OK_200, res->status);
  6911. }
  6912. TEST_F(ServerTest, NoZstd) {
  6913. Headers headers;
  6914. headers.emplace("Accept-Encoding", "zstd");
  6915. auto res = cli_.Get("/nocompress", headers);
  6916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6917. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6918. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6919. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6921. "7890123456789012345678901234567890",
  6922. res->body);
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. }
  6925. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6926. Headers headers;
  6927. headers.emplace("Accept-Encoding", "zstd");
  6928. std::string body;
  6929. auto res = cli_.Get("/nocompress", headers,
  6930. [&](const char *data, uint64_t data_length) {
  6931. EXPECT_EQ(100U, data_length);
  6932. body.append(data, data_length);
  6933. return true;
  6934. });
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6937. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6938. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6939. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6940. "7890123456789012345678901234567890",
  6941. body);
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. }
  6944. // TODO: How to enable zstd ??
  6945. TEST_F(ServerTest, MultipartFormDataZstd) {
  6946. UploadFormDataItems items = {
  6947. {"key1", "test", "", ""},
  6948. {"key2", "--abcdefg123", "", ""},
  6949. };
  6950. Headers headers;
  6951. headers.emplace("Accept-Encoding", "zstd");
  6952. cli_.set_compress(true);
  6953. auto res = cli_.Post("/compress-multipart", headers, items);
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. }
  6957. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6958. Headers headers;
  6959. headers.emplace("Accept-Encoding", "zstd");
  6960. cli_.set_compress(true);
  6961. auto res = cli_.Put(
  6962. "/put", headers, 3,
  6963. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6964. sink.os << "PUT";
  6965. return true;
  6966. },
  6967. "text/plain");
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. EXPECT_EQ(StatusCode::OK_200, res->status);
  6970. EXPECT_EQ("PUT", res->body);
  6971. }
  6972. // Pre-compression logging tests
  6973. TEST_F(ServerTest, PreCompressionLogging) {
  6974. // Test data for compression (matches the actual /compress endpoint content)
  6975. const std::string test_content =
  6976. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6977. "3456789012345678901234567890";
  6978. // Variables to capture logging data
  6979. std::string pre_compression_body;
  6980. std::string pre_compression_content_type;
  6981. std::string pre_compression_content_encoding;
  6982. std::string post_compression_body;
  6983. std::string post_compression_content_type;
  6984. std::string post_compression_content_encoding;
  6985. // Set up pre-compression logger
  6986. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6987. const Response &res) {
  6988. pre_compression_body = res.body;
  6989. pre_compression_content_type = res.get_header_value("Content-Type");
  6990. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6991. });
  6992. // Set up post-compression logger
  6993. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6994. post_compression_body = res.body;
  6995. post_compression_content_type = res.get_header_value("Content-Type");
  6996. post_compression_content_encoding =
  6997. res.get_header_value("Content-Encoding");
  6998. });
  6999. // Test with gzip compression
  7000. Headers headers;
  7001. headers.emplace("Accept-Encoding", "gzip");
  7002. auto res = cli_.Get("/compress", headers);
  7003. // Verify response was compressed
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7007. // Verify pre-compression logger captured uncompressed content
  7008. EXPECT_EQ(test_content, pre_compression_body);
  7009. EXPECT_EQ("text/plain", pre_compression_content_type);
  7010. EXPECT_TRUE(pre_compression_content_encoding
  7011. .empty()); // No encoding header before compression
  7012. // Verify post-compression logger captured compressed content
  7013. EXPECT_NE(test_content,
  7014. post_compression_body); // Should be different after compression
  7015. EXPECT_EQ("text/plain", post_compression_content_type);
  7016. EXPECT_EQ("gzip", post_compression_content_encoding);
  7017. // Verify compressed content is smaller
  7018. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7019. }
  7020. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  7021. const std::string test_content =
  7022. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7023. "3456789012345678901234567890";
  7024. std::string pre_compression_body;
  7025. std::string post_compression_body;
  7026. svr_.set_pre_compression_logger(
  7027. [&](const Request & /*req*/, const Response &res) {
  7028. pre_compression_body = res.body;
  7029. });
  7030. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7031. post_compression_body = res.body;
  7032. });
  7033. Headers headers;
  7034. headers.emplace("Accept-Encoding", "br");
  7035. auto res = cli_.Get("/compress", headers);
  7036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7039. // Verify pre-compression content is uncompressed
  7040. EXPECT_EQ(test_content, pre_compression_body);
  7041. // Verify post-compression content is compressed
  7042. EXPECT_NE(test_content, post_compression_body);
  7043. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  7044. }
  7045. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  7046. const std::string test_content =
  7047. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7048. "3456789012345678901234567890";
  7049. std::string pre_compression_body;
  7050. std::string post_compression_body;
  7051. svr_.set_pre_compression_logger(
  7052. [&](const Request & /*req*/, const Response &res) {
  7053. pre_compression_body = res.body;
  7054. });
  7055. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7056. post_compression_body = res.body;
  7057. });
  7058. // Request without compression (use /nocompress endpoint)
  7059. Headers headers;
  7060. auto res = cli_.Get("/nocompress", headers);
  7061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7064. // Pre-compression logger should not be called when no compression is applied
  7065. EXPECT_TRUE(
  7066. pre_compression_body.empty()); // Pre-compression logger not called
  7067. EXPECT_EQ(
  7068. test_content,
  7069. post_compression_body); // Post-compression logger captures final content
  7070. }
  7071. TEST_F(ServerTest, LoggerSeesContentLength) {
  7072. size_t logged_content_length = 0;
  7073. std::string logged_content_length_header;
  7074. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  7075. logged_content_length = res.content_length_;
  7076. logged_content_length_header = res.get_header_value("Content-Length");
  7077. });
  7078. auto res = cli_.Get("/nocompress");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ(res->body.size(), logged_content_length);
  7082. EXPECT_EQ(std::to_string(logged_content_length),
  7083. logged_content_length_header);
  7084. }
  7085. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  7086. const std::string test_content =
  7087. "123456789012345678901234567890123456789012345678901234567890123456789012"
  7088. "3456789012345678901234567890";
  7089. std::string pre_compression_body;
  7090. bool pre_logger_called = false;
  7091. // Set only pre-compression logger
  7092. svr_.set_pre_compression_logger(
  7093. [&](const Request & /*req*/, const Response &res) {
  7094. pre_compression_body = res.body;
  7095. pre_logger_called = true;
  7096. });
  7097. Headers headers;
  7098. headers.emplace("Accept-Encoding", "gzip");
  7099. auto res = cli_.Get("/compress", headers);
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ(StatusCode::OK_200, res->status);
  7102. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7103. // Verify pre-compression logger was called
  7104. EXPECT_TRUE(pre_logger_called);
  7105. EXPECT_EQ(test_content, pre_compression_body);
  7106. }
  7107. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  7108. {
  7109. // Test with Expect: 100-continue header - success case
  7110. // Server returns 100 Continue, client sends body, server returns 200 OK
  7111. Request req;
  7112. req.method = "POST";
  7113. req.path = "/post-large";
  7114. req.set_header("Expect", "100-continue");
  7115. req.body = LARGE_DATA;
  7116. Response res;
  7117. auto error = Error::Success;
  7118. cli_.set_keep_alive(true);
  7119. auto ret = cli_.send(req, res, error);
  7120. EXPECT_TRUE(ret);
  7121. EXPECT_EQ(StatusCode::OK_200, res.status);
  7122. EXPECT_EQ(LARGE_DATA, res.body);
  7123. }
  7124. {
  7125. // Test with Expect: 100-continue header - error case
  7126. // Client should not send the body when server returns an error
  7127. Request req;
  7128. req.method = "POST";
  7129. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  7130. req.set_header("Expect", "100-continue");
  7131. req.body = LARGE_DATA;
  7132. Response res;
  7133. auto error = Error::Success;
  7134. auto start = std::chrono::high_resolution_clock::now();
  7135. cli_.set_keep_alive(true);
  7136. auto ret = cli_.send(req, res, error);
  7137. auto end = std::chrono::high_resolution_clock::now();
  7138. auto elapsed =
  7139. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7140. .count();
  7141. // With Expect: 100-continue, request completes successfully but with error
  7142. EXPECT_TRUE(ret);
  7143. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  7144. EXPECT_EQ("close", res.get_header_value("Connection"));
  7145. EXPECT_FALSE(cli_.is_socket_open());
  7146. EXPECT_LE(elapsed, 2000);
  7147. }
  7148. {
  7149. // Send an extra GET request to ensure error recovery without hanging
  7150. Request req;
  7151. req.method = "GET";
  7152. req.path = "/hi";
  7153. auto start = std::chrono::high_resolution_clock::now();
  7154. auto res = cli_.send(req);
  7155. auto end = std::chrono::high_resolution_clock::now();
  7156. auto elapsed =
  7157. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7158. .count();
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ(StatusCode::OK_200, res->status);
  7161. EXPECT_EQ("Hello World!", res->body);
  7162. EXPECT_LE(elapsed, 500);
  7163. }
  7164. }
  7165. TEST(ZstdDecompressor, ChunkedDecompression) {
  7166. std::string data;
  7167. for (size_t i = 0; i < 32 * 1024; ++i) {
  7168. data.push_back(static_cast<char>('a' + i % 26));
  7169. }
  7170. std::string compressed_data;
  7171. {
  7172. httplib::detail::zstd_compressor compressor;
  7173. bool result = compressor.compress(
  7174. data.data(), data.size(),
  7175. /*last=*/true,
  7176. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7177. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7178. compressed_data_size);
  7179. return true;
  7180. });
  7181. ASSERT_TRUE(result);
  7182. }
  7183. std::string decompressed_data;
  7184. {
  7185. httplib::detail::zstd_decompressor decompressor;
  7186. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7187. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7188. size_t chunk_size = 130;
  7189. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7190. chunk_begin += chunk_size) {
  7191. size_t current_chunk_size =
  7192. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7193. bool result = decompressor.decompress(
  7194. compressed_data.data() + chunk_begin, current_chunk_size,
  7195. [&](const char *decompressed_data_chunk,
  7196. size_t decompressed_data_chunk_size) {
  7197. decompressed_data.insert(decompressed_data.size(),
  7198. decompressed_data_chunk,
  7199. decompressed_data_chunk_size);
  7200. return true;
  7201. });
  7202. ASSERT_TRUE(result);
  7203. }
  7204. }
  7205. ASSERT_EQ(data, decompressed_data);
  7206. }
  7207. TEST(ZstdDecompressor, Decompress) {
  7208. std::string original_text = "Compressed with ZSTD";
  7209. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  7210. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  7211. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  7212. 0x20, 0x5a, 0x53, 0x54, 0x44};
  7213. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7214. std::string decompressed_data;
  7215. {
  7216. httplib::detail::zstd_decompressor decompressor;
  7217. bool result = decompressor.decompress(
  7218. compressed_data.data(), compressed_data.size(),
  7219. [&](const char *decompressed_data_chunk,
  7220. size_t decompressed_data_chunk_size) {
  7221. decompressed_data.insert(decompressed_data.size(),
  7222. decompressed_data_chunk,
  7223. decompressed_data_chunk_size);
  7224. return true;
  7225. });
  7226. ASSERT_TRUE(result);
  7227. }
  7228. ASSERT_EQ(original_text, decompressed_data);
  7229. }
  7230. #endif
  7231. // Sends a raw request to a server listening at HOST:PORT.
  7232. static bool send_request(time_t read_timeout_sec, const std::string &req,
  7233. std::string *resp = nullptr, int port = PORT) {
  7234. auto error = Error::Success;
  7235. auto client_sock = detail::create_client_socket(
  7236. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  7237. /*connection_timeout_sec=*/5, 0,
  7238. /*read_timeout_sec=*/5, 0,
  7239. /*write_timeout_sec=*/5, 0, std::string(), error);
  7240. if (client_sock == INVALID_SOCKET) { return false; }
  7241. auto ret = detail::process_client_socket(
  7242. client_sock, read_timeout_sec, 0, 0, 0, 0,
  7243. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  7244. if (req.size() !=
  7245. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  7246. return false;
  7247. }
  7248. char buf[512];
  7249. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  7250. while (line_reader.getline()) {
  7251. if (resp) { *resp += line_reader.ptr(); }
  7252. }
  7253. return true;
  7254. });
  7255. detail::close_socket(client_sock);
  7256. return ret;
  7257. }
  7258. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  7259. Server svr;
  7260. std::string header_value;
  7261. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  7262. header_value = req.get_header_value("foo");
  7263. res.set_content("ok", "text/plain");
  7264. });
  7265. thread t = thread([&] { svr.listen(HOST, PORT); });
  7266. auto se = detail::scope_exit([&] {
  7267. svr.stop();
  7268. t.join();
  7269. ASSERT_FALSE(svr.is_running());
  7270. });
  7271. svr.wait_until_ready();
  7272. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7273. // like characters are not treated the same - use vertical tab and escape.
  7274. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7275. "foo: \t \v bar \x1B\t \r\n"
  7276. "Connection: close\r\n"
  7277. "\r\n";
  7278. std::string res;
  7279. ASSERT_TRUE(send_request(5, req, &res));
  7280. EXPECT_EQ(header_value, "");
  7281. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7282. }
  7283. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  7284. Server svr;
  7285. std::string received;
  7286. svr.Get("/order", [&](const Request &req, Response &res) {
  7287. received = entries_to_string(req.headers);
  7288. res.set_content("ok", "text/plain");
  7289. });
  7290. auto port = svr.bind_to_any_port(HOST);
  7291. thread t = thread([&] { svr.listen_after_bind(); });
  7292. auto se = detail::scope_exit([&] {
  7293. svr.stop();
  7294. t.join();
  7295. ASSERT_FALSE(svr.is_running());
  7296. });
  7297. svr.wait_until_ready();
  7298. const std::string req = "GET /order HTTP/1.1\r\n"
  7299. "X-First: 1\r\n"
  7300. "X-Dup: a\r\n"
  7301. "X-Second: 2\r\n"
  7302. "X-Dup: b\r\n"
  7303. "Connection: close\r\n"
  7304. "\r\n";
  7305. std::string res;
  7306. ASSERT_TRUE(send_request(5, req, &res, port));
  7307. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7308. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  7309. }
  7310. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  7311. Server svr;
  7312. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  7313. res.set_header("Set-Cookie", "first=1");
  7314. res.set_header("X-Between", "y");
  7315. res.set_header("Set-Cookie", "second=2");
  7316. res.set_content("ok", "text/plain");
  7317. });
  7318. auto port = svr.bind_to_any_port(HOST);
  7319. thread t = thread([&] { svr.listen_after_bind(); });
  7320. auto se = detail::scope_exit([&] {
  7321. svr.stop();
  7322. t.join();
  7323. ASSERT_FALSE(svr.is_running());
  7324. });
  7325. svr.wait_until_ready();
  7326. Client cli(HOST, port);
  7327. auto res = cli.Get("/cookies");
  7328. ASSERT_TRUE(res);
  7329. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  7330. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  7331. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  7332. }
  7333. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7334. Server svr;
  7335. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7336. auto i = new int(0);
  7337. res.set_header("Trailer", "X-Safe, X-Reflected");
  7338. res.set_chunked_content_provider(
  7339. "text/plain",
  7340. [i](size_t /*offset*/, DataSink &sink) {
  7341. if (*i == 0) {
  7342. sink.os << "body";
  7343. } else {
  7344. Headers trailer;
  7345. // A valid trailer that must survive.
  7346. trailer.emplace("X-Safe", "safe");
  7347. // Attacker-controlled value carrying CR/LF (response splitting).
  7348. trailer.emplace("X-Reflected",
  7349. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7350. // Attacker-controlled name carrying CR/LF.
  7351. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7352. sink.done_with_trailer(trailer);
  7353. }
  7354. (*i)++;
  7355. return true;
  7356. },
  7357. [i](bool /*success*/) { delete i; });
  7358. });
  7359. thread t = thread([&] { svr.listen(HOST, PORT); });
  7360. auto se = detail::scope_exit([&] {
  7361. svr.stop();
  7362. t.join();
  7363. ASSERT_FALSE(svr.is_running());
  7364. });
  7365. svr.wait_until_ready();
  7366. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7367. "Host: " + HOST +
  7368. "\r\n"
  7369. "Connection: close\r\n"
  7370. "\r\n";
  7371. std::string res;
  7372. ASSERT_TRUE(send_request(5, req, &res));
  7373. // The injected fields must not appear anywhere in the raw response.
  7374. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7375. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7376. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7377. // Invalid trailers are dropped entirely, matching set_header().
  7378. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7379. // The valid trailer still passes through.
  7380. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7381. }
  7382. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7383. Server svr;
  7384. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7385. // res.headers is a public field an application can populate directly,
  7386. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7387. // A valid header that must survive.
  7388. res.headers.emplace("X-Safe", "safe");
  7389. // Attacker-controlled value carrying CR/LF (response splitting).
  7390. res.headers.emplace("X-Reflected",
  7391. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7392. // Attacker-controlled name carrying CR/LF.
  7393. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7394. res.set_content("body", "text/plain");
  7395. });
  7396. thread t = thread([&] { svr.listen(HOST, PORT); });
  7397. auto se = detail::scope_exit([&] {
  7398. svr.stop();
  7399. t.join();
  7400. ASSERT_FALSE(svr.is_running());
  7401. });
  7402. svr.wait_until_ready();
  7403. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7404. "Host: " + HOST +
  7405. "\r\n"
  7406. "Connection: close\r\n"
  7407. "\r\n";
  7408. std::string res;
  7409. ASSERT_TRUE(send_request(5, req, &res));
  7410. // The injected fields must not appear anywhere in the raw response.
  7411. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7412. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7413. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7414. // Invalid headers are dropped entirely, matching set_header().
  7415. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7416. // The valid header still passes through.
  7417. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7418. }
  7419. // Forward declaration: in split builds split.py strips `inline` and moves the
  7420. // definition into httplib.cc, so detail::write_request_line is not visible from
  7421. // the public httplib.h. Re-declaring it here lets the tests link against the
  7422. // symbol in both header-only and split builds.
  7423. namespace httplib {
  7424. namespace detail {
  7425. ssize_t write_request_line(Stream &strm, const std::string &method,
  7426. const std::string &path);
  7427. } // namespace detail
  7428. } // namespace httplib
  7429. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7430. // A well-formed target is written verbatim.
  7431. {
  7432. detail::BufferStream strm;
  7433. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7434. EXPECT_GT(n, 0);
  7435. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7436. }
  7437. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7438. // otherwise it splits the request line and injects a header or a whole
  7439. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7440. // when path encoding is disabled.
  7441. const std::string evil_targets[] = {
  7442. "/a\r\nInjected: pwned",
  7443. "/a\rInjected",
  7444. "/a\nInjected",
  7445. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7446. };
  7447. for (const auto &evil : evil_targets) {
  7448. detail::BufferStream strm;
  7449. auto n = detail::write_request_line(strm, "GET", evil);
  7450. EXPECT_LT(n, 0);
  7451. EXPECT_TRUE(strm.get_buffer().empty());
  7452. }
  7453. }
  7454. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7455. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7456. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7457. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7458. // client must fail cleanly with Error::Write instead of putting a
  7459. // request-line-less, header-injecting request on the wire.
  7460. Server svr;
  7461. svr.Get("/a", [](const Request &, Response &res) {
  7462. res.set_content("ok", "text/plain");
  7463. });
  7464. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. thread.join();
  7468. ASSERT_FALSE(svr.is_running());
  7469. });
  7470. svr.wait_until_ready();
  7471. {
  7472. Client cli(HOST, PORT);
  7473. cli.set_path_encode(false);
  7474. // The request is rejected before anything is written, so the connection
  7475. // stays silent and the subsequent response read would otherwise block for
  7476. // the full default read timeout. Shorten it -- the assertion is on the
  7477. // error, not the timeout.
  7478. cli.set_read_timeout(1, 0);
  7479. auto res = cli.Get("/a\r\nInjected: pwned");
  7480. EXPECT_FALSE(res);
  7481. EXPECT_EQ(Error::Write, res.error());
  7482. }
  7483. }
  7484. // Sends a raw request and verifies that there isn't a crash or exception.
  7485. static void test_raw_request(const std::string &req,
  7486. std::string *out = nullptr) {
  7487. Server svr;
  7488. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7489. res.set_content("ok", "text/plain");
  7490. });
  7491. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7492. res.set_content("ok", "text/plain");
  7493. });
  7494. svr.Get("/header_field_value_check",
  7495. [&](const Request & /*req*/, Response &res) {
  7496. res.set_content("ok", "text/plain");
  7497. });
  7498. // Server read timeout must be longer than the client read timeout for the
  7499. // bug to reproduce, probably to force the server to process a request
  7500. // without a trailing blank line.
  7501. const time_t client_read_timeout_sec = 1;
  7502. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7503. bool listen_thread_ok = false;
  7504. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7505. auto se = detail::scope_exit([&] {
  7506. svr.stop();
  7507. t.join();
  7508. ASSERT_FALSE(svr.is_running());
  7509. EXPECT_TRUE(listen_thread_ok);
  7510. });
  7511. svr.wait_until_ready();
  7512. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7513. }
  7514. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7515. // A certain header line causes an exception if the header property is parsed
  7516. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7517. test_raw_request(
  7518. "GET /hi HTTP/1.1\r\n"
  7519. " : "
  7520. " "
  7521. " ");
  7522. }
  7523. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7524. // A certain header line causes an exception if the header property *name* is
  7525. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7526. // greedy matcher and requires backtracking when there are a lot of ":"
  7527. // characters.
  7528. // This occurs with libc++ but not libstdc++.
  7529. test_raw_request(
  7530. "GET /hi HTTP/1.1\r\n"
  7531. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7532. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7533. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7534. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7535. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7536. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7537. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7538. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7539. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7540. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7541. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7542. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7543. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7544. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7545. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7546. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7547. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7548. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7549. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7550. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7551. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7552. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7553. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7554. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7555. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7556. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7557. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7558. "&&&%%%");
  7559. }
  7560. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7561. // Make sure this doesn't crash the server.
  7562. // In a previous version of the header line regex, the "\r" rendered the line
  7563. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7564. // a new position where the leading white space ended and the field value
  7565. // began.
  7566. // The crash occurs with libc++ but not libstdc++.
  7567. test_raw_request("GET /hi HTTP/1.1\r\n"
  7568. "a:" +
  7569. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7570. "\r\n"
  7571. "\r\n");
  7572. }
  7573. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7574. std::string out;
  7575. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7576. "Content-Type: text/plain\r\n"
  7577. "Transfer-Encoding: chunked\r\n"
  7578. "\r\n"
  7579. "nothex\r\n",
  7580. &out);
  7581. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7582. }
  7583. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7584. std::string out;
  7585. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7586. "Content-Type: text/plain\r\n"
  7587. "Transfer-Encoding: chunked\r\n"
  7588. "\r\n"
  7589. "3\r\n"
  7590. "xyz\r\n"
  7591. "NaN\r\n",
  7592. &out);
  7593. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7594. }
  7595. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7596. std::string out;
  7597. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7598. "Content-Type: text/plain\r\n"
  7599. "Transfer-Encoding: chunked\r\n"
  7600. "\r\n"
  7601. // Length is too large for 64 bits.
  7602. "1ffffffffffffffff\r\n"
  7603. "xyz\r\n",
  7604. &out);
  7605. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7606. }
  7607. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7608. test_raw_request("GET /hi HTTP/1.1\r\n"
  7609. "Content-Type: text/plain\r\n\r");
  7610. }
  7611. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7612. std::string out;
  7613. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7614. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7615. }
  7616. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7617. Server svr;
  7618. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7619. EXPECT_TRUE(!req.remote_addr.empty());
  7620. });
  7621. thread t = thread([&] { svr.listen(HOST, PORT); });
  7622. auto se = detail::scope_exit([&] {
  7623. svr.stop();
  7624. t.join();
  7625. ASSERT_FALSE(svr.is_running());
  7626. });
  7627. svr.wait_until_ready();
  7628. // Send an invalid request line to trigger Bad Request
  7629. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7630. std::string out;
  7631. ASSERT_TRUE(send_request(5, bad_req, &out));
  7632. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7633. }
  7634. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7635. std::string out;
  7636. std::string request(
  7637. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7638. test_raw_request(request, &out);
  7639. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7640. }
  7641. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7642. std::string out;
  7643. std::string request(
  7644. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7645. test_raw_request(request, &out);
  7646. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7647. }
  7648. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7649. std::string out;
  7650. std::string request(
  7651. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7652. test_raw_request(request, &out);
  7653. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7654. }
  7655. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7656. std::string out;
  7657. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7658. "Test: \r\n\r\n",
  7659. &out);
  7660. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7661. }
  7662. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7663. Server svr;
  7664. std::string x_custom;
  7665. std::string cookie;
  7666. std::string xff;
  7667. std::string x_unicode;
  7668. std::string x_iis;
  7669. svr.Get("/check", [&](const Request &req, Response &res) {
  7670. x_custom = req.get_header_value("X-Custom");
  7671. cookie = req.get_header_value("Cookie");
  7672. xff = req.get_header_value("X-Forwarded-For");
  7673. x_unicode = req.get_header_value("X-Unicode");
  7674. x_iis = req.get_header_value("X-IIS");
  7675. res.set_content("ok", "text/plain");
  7676. });
  7677. thread t = thread([&] { svr.listen(HOST, PORT); });
  7678. auto se = detail::scope_exit([&] {
  7679. svr.stop();
  7680. t.join();
  7681. ASSERT_FALSE(svr.is_running());
  7682. });
  7683. svr.wait_until_ready();
  7684. const std::string req = "GET /check HTTP/1.1\r\n"
  7685. "Host: localhost\r\n"
  7686. "X-Custom: a%0D%0AInjected: b\r\n"
  7687. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7688. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7689. "X-Unicode: %E3%81%82\r\n"
  7690. "X-IIS: %u00E9\r\n"
  7691. "Connection: close\r\n"
  7692. "\r\n";
  7693. std::string res;
  7694. ASSERT_TRUE(send_request(5, req, &res));
  7695. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7696. // Every value must be returned verbatim (wire form), with no decoding.
  7697. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7698. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7699. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7700. EXPECT_EQ("%E3%81%82", x_unicode);
  7701. EXPECT_EQ("%u00E9", x_iis);
  7702. }
  7703. // Applications that previously relied on automatic percent-decoding can
  7704. // reproduce the old behavior by explicitly calling decode_path_component()
  7705. // or, for RFC 3986 conformance, decode_uri_component().
  7706. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7707. Server svr;
  7708. std::string decoded;
  7709. svr.Get("/check", [&](const Request &req, Response &res) {
  7710. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7711. res.set_content("ok", "text/plain");
  7712. });
  7713. thread t = thread([&] { svr.listen(HOST, PORT); });
  7714. auto se = detail::scope_exit([&] {
  7715. svr.stop();
  7716. t.join();
  7717. ASSERT_FALSE(svr.is_running());
  7718. });
  7719. svr.wait_until_ready();
  7720. const std::string req = "GET /check HTTP/1.1\r\n"
  7721. "Host: localhost\r\n"
  7722. "X-Custom: hello%20world\r\n"
  7723. "Connection: close\r\n"
  7724. "\r\n";
  7725. std::string res;
  7726. ASSERT_TRUE(send_request(5, req, &res));
  7727. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7728. EXPECT_EQ("hello world", decoded);
  7729. }
  7730. // Regression test for #2033. Browsers send Referer values that include
  7731. // percent-encoded characters such as %0A inside the URL. Decoding the
  7732. // header value would either trip the post-decode CR/LF/NUL guard (the
  7733. // original bug, returning 400) or, after that guard was relaxed, silently
  7734. // store a literal LF — both unacceptable. The wire form must round-trip.
  7735. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7736. Server svr;
  7737. std::string referer;
  7738. svr.Get("/check", [&](const Request &req, Response &res) {
  7739. referer = req.get_header_value("Referer");
  7740. res.set_content("ok", "text/plain");
  7741. });
  7742. thread t = thread([&] { svr.listen(HOST, PORT); });
  7743. auto se = detail::scope_exit([&] {
  7744. svr.stop();
  7745. t.join();
  7746. ASSERT_FALSE(svr.is_running());
  7747. });
  7748. svr.wait_until_ready();
  7749. const std::string req = "GET /check HTTP/1.1\r\n"
  7750. "Host: localhost\r\n"
  7751. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7752. "Connection: close\r\n"
  7753. "\r\n";
  7754. std::string res;
  7755. ASSERT_TRUE(send_request(5, req, &res));
  7756. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7757. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7758. }
  7759. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7760. Server svr;
  7761. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7762. res.set_header("Cache-Control", "no-cache");
  7763. res.set_chunked_content_provider(
  7764. "text/event-stream", [](size_t offset, DataSink &sink) {
  7765. std::string s = "data:";
  7766. s += std::to_string(offset);
  7767. s += "\n\n";
  7768. auto ret = sink.write(s.data(), s.size());
  7769. EXPECT_TRUE(ret);
  7770. std::this_thread::sleep_for(std::chrono::seconds(1));
  7771. return true;
  7772. });
  7773. });
  7774. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7775. svr.wait_until_ready();
  7776. Client client(HOST, PORT);
  7777. const Headers headers = {{"Accept", "text/event-stream"}};
  7778. auto get_thread = std::thread([&client, &headers]() {
  7779. auto res = client.Get(
  7780. "/events", headers,
  7781. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7782. });
  7783. auto se = detail::scope_exit([&] {
  7784. svr.stop();
  7785. get_thread.join();
  7786. listen_thread.join();
  7787. ASSERT_FALSE(svr.is_running());
  7788. });
  7789. // Give GET time to get a few messages.
  7790. std::this_thread::sleep_for(std::chrono::seconds(2));
  7791. }
  7792. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7793. httplib::Server svr;
  7794. svr.Post("/hi",
  7795. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7796. res.status = StatusCode::OK_200;
  7797. });
  7798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7799. svr.wait_until_ready();
  7800. Client cli(HOST, PORT);
  7801. auto res = cli.Post("/hi", "data", "text/plain");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. svr.stop();
  7805. thread.join();
  7806. ASSERT_FALSE(svr.is_running());
  7807. res = cli.Post("/hi", "data", "text/plain");
  7808. ASSERT_FALSE(res);
  7809. }
  7810. TEST(ServerStopTest, ListenFailure) {
  7811. Server svr;
  7812. auto t = thread([&]() {
  7813. auto ret = svr.listen("????", PORT);
  7814. EXPECT_FALSE(ret);
  7815. });
  7816. svr.wait_until_ready();
  7817. svr.stop();
  7818. t.join();
  7819. }
  7820. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7821. TEST(ServerStopTest, Decommision) {
  7822. Server svr;
  7823. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7824. for (int i = 0; i < 4; i++) {
  7825. auto is_even = !(i % 2);
  7826. std::thread t{[&] {
  7827. try {
  7828. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7829. if (is_even) {
  7830. throw std::runtime_error("Some thing that happens to go wrong.");
  7831. }
  7832. svr.listen(HOST, PORT);
  7833. } catch (...) { svr.decommission(); }
  7834. }};
  7835. svr.wait_until_ready();
  7836. // Server is up
  7837. {
  7838. Client cli(HOST, PORT);
  7839. auto res = cli.Get("/hi");
  7840. if (is_even) {
  7841. EXPECT_FALSE(res);
  7842. } else {
  7843. EXPECT_TRUE(res);
  7844. EXPECT_EQ("hi...", res->body);
  7845. }
  7846. }
  7847. svr.stop();
  7848. t.join();
  7849. // Server is down...
  7850. {
  7851. Client cli(HOST, PORT);
  7852. auto res = cli.Get("/hi");
  7853. EXPECT_FALSE(res);
  7854. }
  7855. }
  7856. }
  7857. #endif
  7858. // Helper function for string body upload progress tests
  7859. template <typename SetupHandler, typename ClientCall>
  7860. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7861. ClientCall &&client_call,
  7862. const string &body) {
  7863. Server svr;
  7864. setup_handler(svr);
  7865. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7866. auto se = detail::scope_exit([&] {
  7867. svr.stop();
  7868. t.join();
  7869. });
  7870. svr.wait_until_ready();
  7871. Client cli(HOST, PORT);
  7872. vector<uint64_t> progress_values;
  7873. bool progress_called = false;
  7874. auto res =
  7875. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7876. progress_values.push_back(current);
  7877. progress_called = true;
  7878. return true;
  7879. });
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(200, res->status);
  7882. EXPECT_TRUE(progress_called);
  7883. }
  7884. TEST(UploadProgressTest, PostStringBodyBasic) {
  7885. TestStringBodyUploadProgress(
  7886. [](Server &svr) {
  7887. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7888. res.set_content("received", "text/plain");
  7889. });
  7890. },
  7891. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7892. return cli.Post("/test", body, "text/plain", progress_callback);
  7893. },
  7894. "test data for upload progress");
  7895. }
  7896. TEST(UploadProgressTest, PutStringBodyBasic) {
  7897. TestStringBodyUploadProgress(
  7898. [](Server &svr) {
  7899. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7900. res.set_content("put received", "text/plain");
  7901. });
  7902. },
  7903. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7904. return cli.Put("/test", body, "text/plain", progress_callback);
  7905. },
  7906. "put test data for upload progress");
  7907. }
  7908. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7909. TestStringBodyUploadProgress(
  7910. [](Server &svr) {
  7911. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7912. res.set_content("patch received", "text/plain");
  7913. });
  7914. },
  7915. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7916. return cli.Patch("/test", body, "text/plain", progress_callback);
  7917. },
  7918. "patch test data for upload progress");
  7919. }
  7920. // Helper function for content provider upload progress tests
  7921. template <typename SetupHandler, typename ClientCall>
  7922. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7923. ClientCall &&client_call) {
  7924. Server svr;
  7925. setup_handler(svr);
  7926. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7927. auto se = detail::scope_exit([&] {
  7928. svr.stop();
  7929. t.join();
  7930. });
  7931. svr.wait_until_ready();
  7932. Client cli(HOST, PORT);
  7933. vector<uint64_t> progress_values;
  7934. auto res =
  7935. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7936. progress_values.push_back(current);
  7937. return true;
  7938. });
  7939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7940. EXPECT_EQ(200, res->status);
  7941. EXPECT_FALSE(progress_values.empty());
  7942. }
  7943. TEST(UploadProgressTest, PostContentProviderProgress) {
  7944. TestContentProviderUploadProgress(
  7945. [](Server &svr) {
  7946. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7947. res.set_content("provider received", "text/plain");
  7948. });
  7949. },
  7950. [](Client &cli, UploadProgress progress_callback) {
  7951. return cli.Post(
  7952. "/test", 10,
  7953. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7954. sink.os << "test data";
  7955. return true;
  7956. },
  7957. "text/plain", progress_callback);
  7958. });
  7959. }
  7960. // Helper function for multipart upload progress tests
  7961. template <typename SetupHandler, typename ClientCall>
  7962. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7963. ClientCall &&client_call,
  7964. const string &endpoint) {
  7965. Server svr;
  7966. setup_handler(svr);
  7967. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7968. auto se = detail::scope_exit([&] {
  7969. svr.stop();
  7970. t.join();
  7971. });
  7972. svr.wait_until_ready();
  7973. Client cli(HOST, PORT);
  7974. vector<uint64_t> progress_values;
  7975. UploadFormDataItems items = {
  7976. {"field1", "value1", "", ""},
  7977. {"field2", "longer value for progress tracking test", "", ""},
  7978. {"file1", "file content data for upload progress", "test.txt",
  7979. "text/plain"}};
  7980. auto res = client_call(cli, endpoint, items,
  7981. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7982. progress_values.push_back(current);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(200, res->status);
  7987. EXPECT_FALSE(progress_values.empty());
  7988. }
  7989. TEST(UploadProgressTest, PostMultipartProgress) {
  7990. TestMultipartUploadProgress(
  7991. [](Server &svr) {
  7992. svr.Post("/multipart", [](const Request &req, Response &res) {
  7993. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7994. res.set_content("multipart received", "text/plain");
  7995. });
  7996. },
  7997. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7998. UploadProgress progress_callback) {
  7999. return cli.Post(endpoint, items, progress_callback);
  8000. },
  8001. "/multipart");
  8002. }
  8003. // Helper function for basic download progress tests
  8004. template <typename SetupHandler, typename ClientCall>
  8005. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  8006. ClientCall &&client_call, const string &endpoint,
  8007. size_t expected_content_size) {
  8008. Server svr;
  8009. setup_handler(svr);
  8010. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8011. auto se = detail::scope_exit([&] {
  8012. svr.stop();
  8013. t.join();
  8014. });
  8015. svr.wait_until_ready();
  8016. Client cli(HOST, PORT);
  8017. vector<uint64_t> progress_values;
  8018. auto res = client_call(cli, endpoint,
  8019. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8020. progress_values.push_back(current);
  8021. return true;
  8022. });
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(200, res->status);
  8025. EXPECT_FALSE(progress_values.empty());
  8026. EXPECT_EQ(expected_content_size, res->body.size());
  8027. }
  8028. TEST(DownloadProgressTest, GetBasic) {
  8029. TestBasicDownloadProgress(
  8030. [](Server &svr) {
  8031. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  8032. string content(1000, 'D');
  8033. res.set_content(content, "text/plain");
  8034. });
  8035. },
  8036. [](Client &cli, const string &endpoint,
  8037. DownloadProgress progress_callback) {
  8038. return cli.Get(endpoint, progress_callback);
  8039. },
  8040. "/download", 1000u);
  8041. }
  8042. // Helper function for content receiver download progress tests
  8043. template <typename SetupHandler, typename ClientCall>
  8044. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  8045. ClientCall &&client_call,
  8046. const string &endpoint,
  8047. size_t expected_content_size) {
  8048. Server svr;
  8049. setup_handler(svr);
  8050. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8051. auto se = detail::scope_exit([&] {
  8052. svr.stop();
  8053. t.join();
  8054. });
  8055. svr.wait_until_ready();
  8056. Client cli(HOST, PORT);
  8057. vector<uint64_t> progress_values;
  8058. string received_body;
  8059. auto res = client_call(
  8060. cli, endpoint,
  8061. [&](const char *data, size_t data_length) -> bool {
  8062. received_body.append(data, data_length);
  8063. return true;
  8064. },
  8065. [&](uint64_t current, uint64_t /*total*/) -> bool {
  8066. progress_values.push_back(current);
  8067. return true;
  8068. });
  8069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8070. EXPECT_EQ(200, res->status);
  8071. EXPECT_FALSE(progress_values.empty());
  8072. EXPECT_EQ(expected_content_size, received_body.size());
  8073. EXPECT_TRUE(res->body.empty());
  8074. }
  8075. TEST(DownloadProgressTest, GetWithContentReceiver) {
  8076. TestContentReceiverDownloadProgress(
  8077. [](Server &svr) {
  8078. svr.Get("/download-receiver",
  8079. [](const Request & /*req*/, Response &res) {
  8080. string content(2000, 'R');
  8081. res.set_content(content, "text/plain");
  8082. });
  8083. },
  8084. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  8085. DownloadProgress progress_callback) {
  8086. return cli.Get(endpoint, content_receiver, progress_callback);
  8087. },
  8088. "/download-receiver", 2000u);
  8089. }
  8090. TEST(StreamingTest, NoContentLengthStreaming) {
  8091. Server svr;
  8092. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  8093. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  8094. if (offset < 6) {
  8095. sink.os << (offset < 3 ? "a" : "b");
  8096. } else {
  8097. sink.done();
  8098. }
  8099. return true;
  8100. });
  8101. });
  8102. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8103. auto listen_se = detail::scope_exit([&] {
  8104. svr.stop();
  8105. listen_thread.join();
  8106. ASSERT_FALSE(svr.is_running());
  8107. });
  8108. svr.wait_until_ready();
  8109. Client client(HOST, PORT);
  8110. auto get_thread = std::thread([&client]() {
  8111. std::string s;
  8112. auto res =
  8113. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  8114. s += std::string(data, len);
  8115. return true;
  8116. });
  8117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8118. EXPECT_EQ(StatusCode::OK_200, res->status);
  8119. EXPECT_EQ("aaabbb", s);
  8120. });
  8121. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  8122. // Give GET time to get a few messages.
  8123. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8124. }
  8125. TEST(MountTest, Unmount) {
  8126. Server svr;
  8127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8128. auto se = detail::scope_exit([&] {
  8129. svr.stop();
  8130. listen_thread.join();
  8131. ASSERT_FALSE(svr.is_running());
  8132. });
  8133. svr.wait_until_ready();
  8134. Client cli("localhost", PORT);
  8135. svr.set_mount_point("/mount2", "./www2");
  8136. auto res = cli.Get("/");
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8139. res = cli.Get("/mount2/dir/test.html");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. svr.set_mount_point("/", "./www");
  8143. res = cli.Get("/dir/");
  8144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8145. EXPECT_EQ(StatusCode::OK_200, res->status);
  8146. svr.remove_mount_point("/");
  8147. res = cli.Get("/dir/");
  8148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8150. svr.remove_mount_point("/mount2");
  8151. res = cli.Get("/mount2/dir/test.html");
  8152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8154. }
  8155. TEST(MountTest, PathSegmentBoundary) {
  8156. Server svr;
  8157. svr.set_mount_point("/mount2", "./www2");
  8158. svr.set_mount_point("/", "./www");
  8159. auto port = svr.bind_to_any_port(HOST);
  8160. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8161. auto se = detail::scope_exit([&] {
  8162. svr.stop();
  8163. listen_thread.join();
  8164. ASSERT_FALSE(svr.is_running());
  8165. });
  8166. svr.wait_until_ready();
  8167. Client cli(HOST, port);
  8168. auto res = cli.Get("/mount2/dir/test.html");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. // "/mount2" must not match part-way through a path segment.
  8172. res = cli.Get("/mount2dir/test.html");
  8173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8175. // A mount point ending in '/' keeps matching every path below it.
  8176. res = cli.Get("/dir/test.html");
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. }
  8180. TEST(MountTest, Redicect) {
  8181. Server svr;
  8182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8183. auto se = detail::scope_exit([&] {
  8184. svr.stop();
  8185. listen_thread.join();
  8186. ASSERT_FALSE(svr.is_running());
  8187. });
  8188. svr.set_mount_point("/", "./www");
  8189. svr.wait_until_ready();
  8190. Client cli("localhost", PORT);
  8191. auto res = cli.Get("/dir/");
  8192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. res = cli.Get("/dir");
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8197. res = cli.Get("/file");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. res = cli.Get("/file/");
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8203. cli.set_follow_location(true);
  8204. res = cli.Get("/dir");
  8205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8206. EXPECT_EQ(StatusCode::OK_200, res->status);
  8207. }
  8208. TEST(MountTest, MultibytesPathName) {
  8209. Server svr;
  8210. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8211. auto se = detail::scope_exit([&] {
  8212. svr.stop();
  8213. listen_thread.join();
  8214. ASSERT_FALSE(svr.is_running());
  8215. });
  8216. svr.set_mount_point("/", "./www");
  8217. svr.wait_until_ready();
  8218. Client cli("localhost", PORT);
  8219. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  8223. }
  8224. #ifdef _WIN32
  8225. // Issue #2435: mmap::open() must succeed even when another handle holds
  8226. // the file open for writing (e.g. an active log file).
  8227. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  8228. const char *path = "mmap_concurrent_writer_test.txt";
  8229. const char *content = "hello";
  8230. {
  8231. std::ofstream f(path, std::ios::binary);
  8232. f.write(content, static_cast<std::streamsize>(strlen(content)));
  8233. }
  8234. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  8235. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  8236. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8237. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  8238. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  8239. detail::mmap m(path);
  8240. ASSERT_TRUE(m.is_open());
  8241. EXPECT_EQ(strlen(content), m.size());
  8242. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  8243. }
  8244. #endif
  8245. #ifndef _WIN32
  8246. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  8247. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  8248. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  8249. TEST(MmapTest, FailedMappingIsNotOpen) {
  8250. const char *path = "./mmap_failed_mapping_test_dir";
  8251. ASSERT_EQ(0, ::mkdir(path, 0755));
  8252. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  8253. detail::mmap m(path);
  8254. EXPECT_FALSE(m.is_open());
  8255. EXPECT_EQ(0U, m.size());
  8256. EXPECT_NE(static_cast<const void *>(m.data()),
  8257. static_cast<const void *>(MAP_FAILED));
  8258. }
  8259. #endif
  8260. TEST(KeepAliveTest, ReadTimeout) {
  8261. Server svr;
  8262. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8263. std::this_thread::sleep_for(std::chrono::seconds(2));
  8264. res.set_content("a", "text/plain");
  8265. });
  8266. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8267. res.set_content("b", "text/plain");
  8268. });
  8269. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8270. auto se = detail::scope_exit([&] {
  8271. svr.stop();
  8272. listen_thread.join();
  8273. ASSERT_FALSE(svr.is_running());
  8274. });
  8275. svr.wait_until_ready();
  8276. Client cli("localhost", PORT);
  8277. cli.set_keep_alive(true);
  8278. cli.set_read_timeout(std::chrono::seconds(1));
  8279. auto resa = cli.Get("/a");
  8280. ASSERT_FALSE(resa);
  8281. EXPECT_EQ(Error::Read, resa.error());
  8282. auto resb = cli.Get("/b");
  8283. ASSERT_TRUE(resb);
  8284. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8285. EXPECT_EQ("b", resb->body);
  8286. }
  8287. TEST(KeepAliveTest, MaxCount) {
  8288. size_t keep_alive_max_count = 3;
  8289. Server svr;
  8290. svr.set_keep_alive_max_count(keep_alive_max_count);
  8291. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8292. res.set_content("Hello World!", "text/plain");
  8293. });
  8294. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8295. auto se = detail::scope_exit([&] {
  8296. svr.stop();
  8297. listen_thread.join();
  8298. ASSERT_FALSE(svr.is_running());
  8299. });
  8300. svr.wait_until_ready();
  8301. Client cli(HOST, PORT);
  8302. cli.set_keep_alive(true);
  8303. for (size_t i = 0; i < 5; i++) {
  8304. auto result = cli.Get("/hi");
  8305. ASSERT_TRUE(result);
  8306. EXPECT_EQ(StatusCode::OK_200, result->status);
  8307. if (i == keep_alive_max_count - 1) {
  8308. EXPECT_EQ("close", result->get_header_value("Connection"));
  8309. } else {
  8310. EXPECT_FALSE(result->has_header("Connection"));
  8311. }
  8312. }
  8313. }
  8314. TEST(KeepAliveTest, Issue1041) {
  8315. Server svr;
  8316. svr.set_keep_alive_timeout(3);
  8317. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8318. res.set_content("Hello World!", "text/plain");
  8319. });
  8320. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8321. auto se = detail::scope_exit([&] {
  8322. svr.stop();
  8323. listen_thread.join();
  8324. ASSERT_FALSE(svr.is_running());
  8325. });
  8326. svr.wait_until_ready();
  8327. Client cli(HOST, PORT);
  8328. cli.set_keep_alive(true);
  8329. auto result = cli.Get("/hi");
  8330. ASSERT_TRUE(result);
  8331. EXPECT_EQ(StatusCode::OK_200, result->status);
  8332. std::this_thread::sleep_for(std::chrono::seconds(5));
  8333. result = cli.Get("/hi");
  8334. ASSERT_TRUE(result);
  8335. EXPECT_EQ(StatusCode::OK_200, result->status);
  8336. }
  8337. TEST(KeepAliveTest, Issue1959) {
  8338. Server svr;
  8339. svr.set_keep_alive_timeout(5);
  8340. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8341. res.set_content("a", "text/plain");
  8342. });
  8343. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8344. auto se = detail::scope_exit([&] {
  8345. if (!svr.is_running()) return;
  8346. svr.stop();
  8347. listen_thread.join();
  8348. ASSERT_FALSE(svr.is_running());
  8349. });
  8350. svr.wait_until_ready();
  8351. Client cli("localhost", PORT);
  8352. cli.set_keep_alive(true);
  8353. using namespace std::chrono;
  8354. auto start = steady_clock::now();
  8355. cli.Get("/a");
  8356. svr.stop();
  8357. listen_thread.join();
  8358. auto end = steady_clock::now();
  8359. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8360. EXPECT_LT(elapsed, 5000);
  8361. }
  8362. #ifdef CPPHTTPLIB_SSL_ENABLED
  8363. TEST(KeepAliveTest, SSLClientReconnection) {
  8364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8365. ASSERT_TRUE(svr.is_valid());
  8366. svr.set_keep_alive_timeout(1);
  8367. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8368. res.set_content("Hello World!", "text/plain");
  8369. });
  8370. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8371. auto se = detail::scope_exit([&] {
  8372. svr.stop();
  8373. listen_thread.join();
  8374. ASSERT_FALSE(svr.is_running());
  8375. });
  8376. svr.wait_until_ready();
  8377. SSLClient cli(HOST, PORT);
  8378. cli.enable_server_certificate_verification(false);
  8379. cli.set_keep_alive(true);
  8380. auto result = cli.Get("/hi");
  8381. ASSERT_TRUE(result);
  8382. EXPECT_EQ(StatusCode::OK_200, result->status);
  8383. result = cli.Get("/hi");
  8384. ASSERT_TRUE(result);
  8385. EXPECT_EQ(StatusCode::OK_200, result->status);
  8386. std::this_thread::sleep_for(std::chrono::seconds(2));
  8387. // Recoonect
  8388. result = cli.Get("/hi");
  8389. ASSERT_TRUE(result);
  8390. EXPECT_EQ(StatusCode::OK_200, result->status);
  8391. result = cli.Get("/hi");
  8392. ASSERT_TRUE(result);
  8393. EXPECT_EQ(StatusCode::OK_200, result->status);
  8394. }
  8395. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8397. ASSERT_TRUE(svr.is_valid());
  8398. svr.set_keep_alive_timeout(1);
  8399. std::string content = "reconnect";
  8400. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8401. res.set_content("Hello World!", "text/plain");
  8402. });
  8403. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8404. auto se = detail::scope_exit([&] {
  8405. svr.stop();
  8406. listen_thread.join();
  8407. ASSERT_FALSE(svr.is_running());
  8408. });
  8409. svr.wait_until_ready();
  8410. SSLClient cli(HOST, PORT);
  8411. cli.enable_server_certificate_verification(false);
  8412. cli.set_keep_alive(true);
  8413. auto result = cli.Post(
  8414. "/hi", content.size(),
  8415. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8416. sink.write(content.c_str(), content.size());
  8417. return true;
  8418. },
  8419. "text/plain");
  8420. ASSERT_TRUE(result);
  8421. EXPECT_EQ(200, result->status);
  8422. std::this_thread::sleep_for(std::chrono::seconds(2));
  8423. // Recoonect
  8424. result = cli.Post(
  8425. "/hi", content.size(),
  8426. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8427. sink.write(content.c_str(), content.size());
  8428. return true;
  8429. },
  8430. "text/plain");
  8431. ASSERT_TRUE(result);
  8432. EXPECT_EQ(200, result->status);
  8433. result = cli.Post(
  8434. "/hi", content.size(),
  8435. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8436. sink.write(content.c_str(), content.size());
  8437. return true;
  8438. },
  8439. "text/plain");
  8440. ASSERT_TRUE(result);
  8441. EXPECT_EQ(200, result->status);
  8442. }
  8443. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8444. using namespace httplib::tls;
  8445. {
  8446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8447. ASSERT_TRUE(svr.is_valid());
  8448. svr.Get("/sni", [&](const Request &req, Response &res) {
  8449. std::string expected = req.sni();
  8450. EXPECT_EQ(expected, req.get_param_value("expected"));
  8451. res.set_content("ok", "text/plain");
  8452. });
  8453. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8454. auto se = detail::scope_exit([&] {
  8455. svr.stop();
  8456. listen_thread.join();
  8457. ASSERT_FALSE(svr.is_running());
  8458. });
  8459. svr.wait_until_ready();
  8460. {
  8461. SSLClient cli("localhost", PORT);
  8462. cli.enable_server_certificate_verification(false);
  8463. auto res = cli.Get("/sni?expected=localhost");
  8464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8465. }
  8466. {
  8467. SSLClient cli("::1", PORT);
  8468. cli.enable_server_certificate_verification(false);
  8469. auto res = cli.Get("/sni?expected=");
  8470. // NOTE: This may fail if the server is listening on IPv4 only
  8471. // (e.g., when localhost resolves to 127.0.0.1 only)
  8472. if (res) {
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. } else {
  8475. EXPECT_EQ(Error::Connection, res.error());
  8476. }
  8477. }
  8478. }
  8479. }
  8480. #endif
  8481. TEST(ClientProblemDetectionTest, ContentProvider) {
  8482. Server svr;
  8483. size_t content_length = 1024 * 1024;
  8484. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8485. res.set_content_provider(
  8486. content_length, "text/plain",
  8487. [&](size_t offset, size_t length, DataSink &sink) {
  8488. auto out_len = std::min(length, static_cast<size_t>(1024));
  8489. std::string out(out_len, '@');
  8490. sink.write(out.data(), out_len);
  8491. return offset < 4096;
  8492. },
  8493. [](bool success) { ASSERT_FALSE(success); });
  8494. });
  8495. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8496. res.set_content_provider(
  8497. 0, "text/plain",
  8498. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8499. EXPECT_TRUE(false);
  8500. return true;
  8501. },
  8502. [](bool success) { ASSERT_FALSE(success); });
  8503. });
  8504. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8505. auto se = detail::scope_exit([&] {
  8506. svr.stop();
  8507. listen_thread.join();
  8508. ASSERT_FALSE(svr.is_running());
  8509. });
  8510. svr.wait_until_ready();
  8511. Client cli("localhost", PORT);
  8512. {
  8513. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8514. size_t /*data_length*/) { return false; });
  8515. ASSERT_FALSE(res);
  8516. }
  8517. {
  8518. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8519. size_t /*data_length*/) { return false; });
  8520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8521. }
  8522. }
  8523. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8524. Server svr;
  8525. svr.set_error_handler([](Request const &, Response &res) -> void {
  8526. res.set_chunked_content_provider(
  8527. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8528. sink.os << "hello";
  8529. sink.os << "world";
  8530. sink.done();
  8531. return true;
  8532. });
  8533. });
  8534. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8535. auto se = detail::scope_exit([&] {
  8536. svr.stop();
  8537. listen_thread.join();
  8538. ASSERT_FALSE(svr.is_running());
  8539. });
  8540. svr.wait_until_ready();
  8541. Client cli("localhost", PORT);
  8542. auto res = cli.Get("/");
  8543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8545. EXPECT_EQ("helloworld", res->body);
  8546. }
  8547. TEST(LongPollingTest, ClientCloseDetection) {
  8548. Server svr;
  8549. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8550. res.set_chunked_content_provider(
  8551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8552. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8553. sink.os << "hello";
  8554. auto count = 10;
  8555. while (count > 0 && sink.is_writable()) {
  8556. this_thread::sleep_for(chrono::milliseconds(10));
  8557. count--;
  8558. }
  8559. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8560. return true;
  8561. });
  8562. });
  8563. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8564. auto se = detail::scope_exit([&] {
  8565. svr.stop();
  8566. listen_thread.join();
  8567. ASSERT_FALSE(svr.is_running());
  8568. });
  8569. svr.wait_until_ready();
  8570. Client cli("localhost", PORT);
  8571. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8572. EXPECT_EQ("hello", string(data, data_length));
  8573. return false; // close the socket immediately.
  8574. });
  8575. ASSERT_FALSE(res);
  8576. }
  8577. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8578. Server svr;
  8579. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8580. res.set_chunked_content_provider(
  8581. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8582. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8583. sink.os << "hello";
  8584. EXPECT_TRUE(sink.os.good());
  8585. // Wait for the client to close the connection
  8586. auto count = 10;
  8587. while (count > 0 && sink.is_writable()) {
  8588. this_thread::sleep_for(chrono::milliseconds(10));
  8589. count--;
  8590. }
  8591. // After client disconnect, write repeatedly until the socket
  8592. // write actually fails (small writes may be absorbed by the
  8593. // kernel buffer)
  8594. std::string chunk(1024, 'x');
  8595. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8596. sink.os << chunk;
  8597. }
  8598. EXPECT_TRUE(sink.os.fail());
  8599. return true;
  8600. });
  8601. });
  8602. auto port = svr.bind_to_any_port("localhost");
  8603. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8604. auto se = detail::scope_exit([&] {
  8605. svr.stop();
  8606. listen_thread.join();
  8607. ASSERT_FALSE(svr.is_running());
  8608. });
  8609. svr.wait_until_ready();
  8610. Client cli("localhost", port);
  8611. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8612. EXPECT_EQ("hello", string(data, data_length));
  8613. return false; // close the socket immediately.
  8614. });
  8615. ASSERT_FALSE(res);
  8616. }
  8617. TEST(GetWithParametersTest, GetWithParameters) {
  8618. Server svr;
  8619. svr.Get("/", [&](const Request &req, Response &) {
  8620. EXPECT_EQ("world", req.get_param_value("hello"));
  8621. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8622. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8623. });
  8624. svr.Get("/params", [&](const Request &req, Response &) {
  8625. EXPECT_EQ("world", req.get_param_value("hello"));
  8626. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8627. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8628. });
  8629. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8630. EXPECT_EQ("resource-id", req.matches[1]);
  8631. EXPECT_EQ("foo", req.get_param_value("param1"));
  8632. EXPECT_EQ("bar", req.get_param_value("param2"));
  8633. });
  8634. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8635. EXPECT_EQ("user-id", req.path_params.at("id"));
  8636. EXPECT_EQ("foo", req.get_param_value("param1"));
  8637. EXPECT_EQ("bar", req.get_param_value("param2"));
  8638. });
  8639. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8640. auto se = detail::scope_exit([&] {
  8641. svr.stop();
  8642. listen_thread.join();
  8643. ASSERT_FALSE(svr.is_running());
  8644. });
  8645. svr.wait_until_ready();
  8646. {
  8647. Client cli(HOST, PORT);
  8648. Params params;
  8649. params.emplace("hello", "world");
  8650. params.emplace("hello2", "world2");
  8651. params.emplace("hello3", "world3");
  8652. auto res = cli.Get("/", params, Headers{});
  8653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. }
  8656. {
  8657. Client cli(HOST, PORT);
  8658. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. }
  8662. {
  8663. Client cli(HOST, PORT);
  8664. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. }
  8668. {
  8669. Client cli(HOST, PORT);
  8670. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8672. EXPECT_EQ(StatusCode::OK_200, res->status);
  8673. }
  8674. }
  8675. TEST(GetWithParametersTest, GetWithParameters2) {
  8676. Server svr;
  8677. svr.Get("/", [&](const Request &req, Response &res) {
  8678. auto text = req.get_param_value("hello");
  8679. res.set_content(text, "text/plain");
  8680. });
  8681. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8682. auto se = detail::scope_exit([&] {
  8683. svr.stop();
  8684. listen_thread.join();
  8685. ASSERT_FALSE(svr.is_running());
  8686. });
  8687. svr.wait_until_ready();
  8688. Client cli("localhost", PORT);
  8689. Params params;
  8690. params.emplace("hello", "world");
  8691. std::string body;
  8692. auto res = cli.Get("/", params, Headers{},
  8693. [&](const char *data, size_t data_length) {
  8694. body.append(data, data_length);
  8695. return true;
  8696. });
  8697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8698. EXPECT_EQ(StatusCode::OK_200, res->status);
  8699. EXPECT_EQ("world", body);
  8700. }
  8701. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8702. Server svr;
  8703. svr.Get("/search", [&](const Request &req, Response &res) {
  8704. auto q = req.get_param_value("q");
  8705. res.set_content(q, "text/plain");
  8706. });
  8707. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8708. auto se = detail::scope_exit([&] {
  8709. svr.stop();
  8710. listen_thread.join();
  8711. ASSERT_FALSE(svr.is_running());
  8712. });
  8713. svr.wait_until_ready();
  8714. Client cli("localhost", PORT);
  8715. // Verify that Get(path, params) works without requiring Headers argument
  8716. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8718. EXPECT_EQ(StatusCode::OK_200, res->status);
  8719. EXPECT_EQ("cpp-httplib", res->body);
  8720. }
  8721. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8722. auto host = "httpbingo.org";
  8723. auto path = std::string{"/range/32"};
  8724. #ifdef CPPHTTPLIB_SSL_ENABLED
  8725. SSLClient cli(host);
  8726. #else
  8727. Client cli(host);
  8728. #endif
  8729. cli.set_default_headers({make_range_header({{1, 10}})});
  8730. cli.set_connection_timeout(5);
  8731. {
  8732. auto res = cli.Get(path);
  8733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8734. EXPECT_EQ("bcdefghijk", res->body);
  8735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8736. }
  8737. {
  8738. auto res = cli.Get(path);
  8739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8740. EXPECT_EQ("bcdefghijk", res->body);
  8741. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8742. }
  8743. }
  8744. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8745. Server svr;
  8746. svr.set_default_headers({{"Hello", "World"}});
  8747. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8748. res.set_content("ok", "text/plain");
  8749. });
  8750. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. listen_thread.join();
  8754. ASSERT_FALSE(svr.is_running());
  8755. });
  8756. svr.wait_until_ready();
  8757. Client cli("localhost", PORT);
  8758. auto res = cli.Get("/");
  8759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8760. EXPECT_EQ(StatusCode::OK_200, res->status);
  8761. EXPECT_EQ("ok", res->body);
  8762. EXPECT_EQ("World", res->get_header_value("Hello"));
  8763. }
  8764. #ifdef CPPHTTPLIB_SSL_ENABLED
  8765. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8767. ASSERT_TRUE(svr.is_valid());
  8768. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8769. std::this_thread::sleep_for(std::chrono::seconds(2));
  8770. res.set_content("a", "text/plain");
  8771. });
  8772. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8773. res.set_content("b", "text/plain");
  8774. });
  8775. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8776. auto se = detail::scope_exit([&] {
  8777. svr.stop();
  8778. listen_thread.join();
  8779. ASSERT_FALSE(svr.is_running());
  8780. });
  8781. svr.wait_until_ready();
  8782. SSLClient cli("localhost", PORT);
  8783. cli.enable_server_certificate_verification(false);
  8784. cli.set_keep_alive(true);
  8785. cli.set_read_timeout(std::chrono::seconds(1));
  8786. auto resa = cli.Get("/a");
  8787. ASSERT_TRUE(!resa);
  8788. EXPECT_EQ(Error::Read, resa.error());
  8789. auto resb = cli.Get("/b");
  8790. ASSERT_TRUE(resb);
  8791. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8792. EXPECT_EQ("b", resb->body);
  8793. }
  8794. #endif
  8795. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8796. protected:
  8797. ServerTestWithAI_PASSIVE()
  8798. : cli_(HOST, PORT)
  8799. #ifdef CPPHTTPLIB_SSL_ENABLED
  8800. ,
  8801. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8802. #endif
  8803. {
  8804. #ifdef CPPHTTPLIB_SSL_ENABLED
  8805. cli_.enable_server_certificate_verification(false);
  8806. #endif
  8807. }
  8808. virtual void SetUp() {
  8809. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8810. res.set_content("Hello World!", "text/plain");
  8811. });
  8812. t_ = thread(
  8813. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8814. svr_.wait_until_ready();
  8815. }
  8816. virtual void TearDown() {
  8817. svr_.stop();
  8818. t_.join();
  8819. }
  8820. #ifdef CPPHTTPLIB_SSL_ENABLED
  8821. SSLClient cli_;
  8822. SSLServer svr_;
  8823. #else
  8824. Client cli_;
  8825. Server svr_;
  8826. #endif
  8827. thread t_;
  8828. };
  8829. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8830. auto res = cli_.Get("/hi");
  8831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8832. EXPECT_EQ(StatusCode::OK_200, res->status);
  8833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8834. EXPECT_EQ("Hello World!", res->body);
  8835. }
  8836. class ServerUpDownTest : public ::testing::Test {
  8837. protected:
  8838. ServerUpDownTest() : cli_(HOST, PORT) {}
  8839. virtual void SetUp() {
  8840. t_ = thread([&]() {
  8841. svr_.bind_to_any_port(HOST);
  8842. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8843. ASSERT_TRUE(svr_.listen_after_bind());
  8844. });
  8845. svr_.wait_until_ready();
  8846. }
  8847. virtual void TearDown() {
  8848. svr_.stop();
  8849. t_.join();
  8850. }
  8851. Client cli_;
  8852. Server svr_;
  8853. thread t_;
  8854. };
  8855. TEST_F(ServerUpDownTest, QuickStartStop) {
  8856. // Should not crash, especially when run with
  8857. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8858. }
  8859. class PayloadMaxLengthTest : public ::testing::Test {
  8860. protected:
  8861. PayloadMaxLengthTest()
  8862. : cli_(HOST, PORT)
  8863. #ifdef CPPHTTPLIB_SSL_ENABLED
  8864. ,
  8865. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8866. #endif
  8867. {
  8868. #ifdef CPPHTTPLIB_SSL_ENABLED
  8869. cli_.enable_server_certificate_verification(false);
  8870. #endif
  8871. }
  8872. virtual void SetUp() {
  8873. svr_.set_payload_max_length(8);
  8874. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8875. res.set_content("test", "text/plain");
  8876. });
  8877. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8878. svr_.wait_until_ready();
  8879. }
  8880. virtual void TearDown() {
  8881. svr_.stop();
  8882. t_.join();
  8883. }
  8884. #ifdef CPPHTTPLIB_SSL_ENABLED
  8885. SSLClient cli_;
  8886. SSLServer svr_;
  8887. #else
  8888. Client cli_;
  8889. Server svr_;
  8890. #endif
  8891. thread t_;
  8892. };
  8893. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8894. auto res = cli_.Post("/test", "123456789", "text/plain");
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8897. res = cli_.Post("/test", "12345678", "text/plain");
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8902. // Test chunked encoding with payload exceeding the 8-byte limit
  8903. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8904. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8906. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8907. }
  8908. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8909. // Test chunked encoding with payload within the 8-byte limit
  8910. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8911. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8913. EXPECT_EQ(StatusCode::OK_200, res->status);
  8914. }
  8915. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8916. // Test using send_request to send chunked data exceeding payload limit
  8917. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8918. "Host: " +
  8919. std::string(HOST) + ":" + std::to_string(PORT) +
  8920. "\r\n"
  8921. "Transfer-Encoding: chunked\r\n"
  8922. "Connection: close\r\n"
  8923. "\r\n"
  8924. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8925. "0123456789\r\n"
  8926. "0\r\n" // End chunk
  8927. "\r\n";
  8928. std::string response;
  8929. bool result = send_request(1, chunked_request, &response);
  8930. if (!result) {
  8931. // If send_request fails, it might be because the server closed the
  8932. // connection due to payload limit enforcement, which is acceptable
  8933. SUCCEED()
  8934. << "Server rejected oversized chunked request (connection closed)";
  8935. } else {
  8936. // If we got a response, check if it's an error response or connection was
  8937. // closed early Short response length indicates connection was closed due to
  8938. // payload limit
  8939. if (response.length() <= 10) {
  8940. SUCCEED() << "Server closed connection for oversized chunked request";
  8941. } else {
  8942. // Check for error status codes
  8943. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8944. response.find("Payload Too Large") != std::string::npos ||
  8945. response.find("400") != std::string::npos);
  8946. }
  8947. }
  8948. }
  8949. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8950. // Test request without Content-Length header exceeding payload limit
  8951. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8952. "Host: " +
  8953. std::string(HOST) + ":" +
  8954. std::to_string(PORT) +
  8955. "\r\n"
  8956. "Connection: close\r\n"
  8957. "\r\n";
  8958. // Add payload exceeding the 8-byte limit
  8959. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8960. request_without_content_length += large_payload;
  8961. std::string response;
  8962. bool result = send_request(1, request_without_content_length, &response);
  8963. if (!result) {
  8964. // If send_request fails, server likely closed connection due to payload
  8965. // limit
  8966. SUCCEED() << "Server rejected oversized request without Content-Length "
  8967. "(connection closed)";
  8968. } else {
  8969. // Check if server responded with error or closed connection early
  8970. if (response.length() <= 10) {
  8971. SUCCEED() << "Server closed connection for oversized request without "
  8972. "Content-Length";
  8973. } else {
  8974. // Check for error status codes
  8975. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8976. response.find("Payload Too Large") != std::string::npos ||
  8977. response.find("400") != std::string::npos);
  8978. }
  8979. }
  8980. }
  8981. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8982. // Test request without Content-Length header within payload limit
  8983. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8984. "Host: " +
  8985. std::string(HOST) + ":" +
  8986. std::to_string(PORT) +
  8987. "\r\n"
  8988. "Connection: close\r\n"
  8989. "\r\n";
  8990. // Add payload within the 8-byte limit
  8991. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8992. request_without_content_length += small_payload;
  8993. std::string response;
  8994. bool result = send_request(1, request_without_content_length, &response);
  8995. // For requests without Content-Length, the server may have different behavior
  8996. // The key is that it should not reject due to payload limit for small
  8997. // payloads
  8998. if (result) {
  8999. // Check for any HTTP response (success or error, but not connection closed)
  9000. if (response.length() > 10) {
  9001. SUCCEED()
  9002. << "Server processed request without Content-Length within limit";
  9003. } else {
  9004. // Short response might indicate connection closed, which is acceptable
  9005. SUCCEED() << "Server closed connection for request without "
  9006. "Content-Length (acceptable behavior)";
  9007. }
  9008. } else {
  9009. // Connection failure might be due to protocol requirements
  9010. SUCCEED() << "Connection issue with request without Content-Length "
  9011. "(environment-specific)";
  9012. }
  9013. }
  9014. class LargePayloadMaxLengthTest : public ::testing::Test {
  9015. protected:
  9016. LargePayloadMaxLengthTest()
  9017. : cli_(HOST, PORT)
  9018. #ifdef CPPHTTPLIB_SSL_ENABLED
  9019. ,
  9020. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  9021. #endif
  9022. {
  9023. #ifdef CPPHTTPLIB_SSL_ENABLED
  9024. cli_.enable_server_certificate_verification(false);
  9025. #endif
  9026. }
  9027. virtual void SetUp() {
  9028. // Set 10MB payload limit
  9029. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  9030. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  9031. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  9032. res.set_content("Large payload test", "text/plain");
  9033. });
  9034. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  9035. svr_.wait_until_ready();
  9036. }
  9037. virtual void TearDown() {
  9038. svr_.stop();
  9039. t_.join();
  9040. }
  9041. #ifdef CPPHTTPLIB_SSL_ENABLED
  9042. SSLClient cli_;
  9043. SSLServer svr_;
  9044. #else
  9045. Client cli_;
  9046. Server svr_;
  9047. #endif
  9048. thread t_;
  9049. };
  9050. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  9051. // Test chunked encoding with payload within 10MB limit
  9052. std::string medium_payload(5 * 1024 * 1024,
  9053. 'A'); // 5MB payload, within 10MB limit
  9054. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. }
  9058. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  9059. // Test chunked encoding with payload exceeding 10MB limit
  9060. std::string large_payload(12 * 1024 * 1024,
  9061. 'B'); // 12MB payload, exceeds 10MB limit
  9062. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  9063. // Server may either return 413 or close the connection
  9064. if (res) {
  9065. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9066. } else {
  9067. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  9068. }
  9069. }
  9070. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  9071. // Test request without Content-Length header within 10MB limit
  9072. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9073. "Host: " +
  9074. std::string(HOST) + ":" +
  9075. std::to_string(PORT) +
  9076. "\r\n"
  9077. "Connection: close\r\n"
  9078. "\r\n";
  9079. // Add 1MB payload (within 10MB limit)
  9080. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  9081. request_without_content_length += medium_payload;
  9082. std::string response;
  9083. bool result = send_request(5, request_without_content_length, &response);
  9084. if (result) {
  9085. // Should get a proper HTTP response for payloads within limit
  9086. if (response.length() > 10) {
  9087. SUCCEED() << "Server processed 1MB request without Content-Length within "
  9088. "10MB limit";
  9089. } else {
  9090. SUCCEED() << "Server closed connection (acceptable behavior for no "
  9091. "Content-Length)";
  9092. }
  9093. } else {
  9094. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  9095. }
  9096. }
  9097. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  9098. // Test request without Content-Length header exceeding 10MB limit
  9099. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  9100. "Host: " +
  9101. std::string(HOST) + ":" +
  9102. std::to_string(PORT) +
  9103. "\r\n"
  9104. "Connection: close\r\n"
  9105. "\r\n";
  9106. // Add 12MB payload (exceeds 10MB limit)
  9107. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  9108. request_without_content_length += large_payload;
  9109. std::string response;
  9110. bool result = send_request(10, request_without_content_length, &response);
  9111. if (!result) {
  9112. // Server should close connection due to payload limit
  9113. SUCCEED() << "Server rejected 12MB request without Content-Length "
  9114. "(connection closed)";
  9115. } else {
  9116. // Check for error response
  9117. if (response.length() <= 10) {
  9118. SUCCEED()
  9119. << "Server closed connection for 12MB request exceeding 10MB limit";
  9120. } else {
  9121. EXPECT_TRUE(response.find("413") != std::string::npos ||
  9122. response.find("Payload Too Large") != std::string::npos ||
  9123. response.find("400") != std::string::npos);
  9124. }
  9125. }
  9126. }
  9127. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9128. // `payload_max_length` is not enforced on decompressed body in ContentReader
  9129. // path.
  9130. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  9131. Server svr;
  9132. const size_t LIMIT = 64 * 1024; // 64KB
  9133. svr.set_payload_max_length(LIMIT);
  9134. size_t total = 0;
  9135. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  9136. const ContentReader &content_reader) {
  9137. content_reader([&](const char * /*data*/, size_t len) {
  9138. total += len;
  9139. return true;
  9140. });
  9141. res.status = 200;
  9142. res.set_content("stream_ok", "text/plain");
  9143. });
  9144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9145. auto se = detail::scope_exit([&] {
  9146. svr.stop();
  9147. thread.join();
  9148. ASSERT_FALSE(svr.is_running());
  9149. });
  9150. svr.wait_until_ready();
  9151. // Prepare 256KB raw data and gzip-compress it
  9152. std::string raw(256 * 1024, 'A');
  9153. std::string gz;
  9154. {
  9155. z_stream zs{};
  9156. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  9157. Z_DEFAULT_STRATEGY);
  9158. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  9159. zs.avail_in = static_cast<uInt>(raw.size());
  9160. char outbuf[4096];
  9161. int ret;
  9162. do {
  9163. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  9164. zs.avail_out = sizeof(outbuf);
  9165. ret = deflate(&zs, Z_FINISH);
  9166. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  9167. } while (ret != Z_STREAM_END);
  9168. deflateEnd(&zs);
  9169. }
  9170. Client cli(HOST, PORT);
  9171. cli.set_connection_timeout(std::chrono::seconds(5));
  9172. Headers headers = {{"Content-Encoding", "gzip"}};
  9173. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  9174. "application/octet-stream");
  9175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9176. // Server must reject oversized decompressed payloads with 413.
  9177. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  9178. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  9179. EXPECT_LE(total, LIMIT);
  9180. }
  9181. #endif
  9182. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  9183. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  9184. // the payload must be passed through untouched instead of being rejected.
  9185. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  9186. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  9187. Server svr;
  9188. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  9189. res.set_content(body, "image/jpeg");
  9190. res.set_header("Content-Encoding", "UTF-8");
  9191. });
  9192. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  9193. res.set_content(body, "image/jpeg");
  9194. res.set_header("Content-Encoding", "identity");
  9195. });
  9196. svr.Post("/echo", [](const Request &req, Response &res) {
  9197. res.set_content(req.body, "image/jpeg");
  9198. });
  9199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9200. auto se = detail::scope_exit([&] {
  9201. svr.stop();
  9202. t.join();
  9203. ASSERT_FALSE(svr.is_running());
  9204. });
  9205. svr.wait_until_ready();
  9206. Client cli(HOST, PORT);
  9207. {
  9208. auto res = cli.Get("/image");
  9209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9210. EXPECT_EQ(StatusCode::OK_200, res->status);
  9211. EXPECT_EQ(body, res->body);
  9212. }
  9213. {
  9214. auto res = cli.Get("/identity");
  9215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9216. EXPECT_EQ(StatusCode::OK_200, res->status);
  9217. EXPECT_EQ(body, res->body);
  9218. }
  9219. {
  9220. // The same applies to a request body reaching the server.
  9221. Headers headers = {{"Content-Encoding", "UTF-8"}};
  9222. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  9223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9224. EXPECT_EQ(StatusCode::OK_200, res->status);
  9225. EXPECT_EQ(body, res->body);
  9226. }
  9227. }
  9228. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  9229. // gzip-encoded response even when the build has no zlib support.
  9230. static const char GZIPPED_HELLO_WORLD[] = {
  9231. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  9232. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  9233. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  9234. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  9235. // A content coding cpp-httplib recognizes but was not built with must be
  9236. // reported as such. Handing the still-compressed payload back to the caller
  9237. // would silently corrupt it.
  9238. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  9239. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  9240. Server svr;
  9241. // "image/jpeg" keeps the server from applying a content coding of its own,
  9242. // so the hand-crafted Content-Encoding below survives.
  9243. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  9244. res.set_content(gzipped, "image/jpeg");
  9245. res.set_header("Content-Encoding", "gzip");
  9246. });
  9247. // Content codings are case-insensitive (RFC 9110 8.4.1).
  9248. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  9249. res.set_content(gzipped, "image/jpeg");
  9250. res.set_header("Content-Encoding", "GZIP");
  9251. });
  9252. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9253. auto se = detail::scope_exit([&] {
  9254. svr.stop();
  9255. t.join();
  9256. ASSERT_FALSE(svr.is_running());
  9257. });
  9258. svr.wait_until_ready();
  9259. Client cli(HOST, PORT);
  9260. {
  9261. auto res = cli.Get("/gzipped");
  9262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9264. EXPECT_EQ("Hello World!", res->body);
  9265. #else
  9266. ASSERT_FALSE(res);
  9267. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9268. #endif
  9269. }
  9270. {
  9271. // open_stream() must behave the same way.
  9272. auto handle = cli.open_stream("GET", "/gzipped");
  9273. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9274. ASSERT_TRUE(handle.is_valid());
  9275. std::string received;
  9276. char buf[256];
  9277. ssize_t n;
  9278. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9279. received.append(buf, static_cast<size_t>(n));
  9280. }
  9281. EXPECT_EQ("Hello World!", received);
  9282. #else
  9283. EXPECT_FALSE(handle.is_valid());
  9284. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  9285. #endif
  9286. }
  9287. {
  9288. // A differently-cased coding must not be mistaken for an unknown one, or
  9289. // the body would be handed back still compressed.
  9290. auto res = cli.Get("/gzipped-uppercase");
  9291. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9293. EXPECT_EQ("Hello World!", res->body);
  9294. #else
  9295. ASSERT_FALSE(res);
  9296. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  9297. #endif
  9298. }
  9299. }
  9300. // Regression test for DoS vulnerability: a malicious server sending a response
  9301. // without Content-Length header must not cause unbounded memory consumption on
  9302. // the client side. The client should stop reading after a reasonable limit,
  9303. // similar to the server-side set_payload_max_length protection.
  9304. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  9305. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9306. #ifndef _WIN32
  9307. signal(SIGPIPE, SIG_IGN);
  9308. #endif
  9309. auto server_thread = std::thread([] {
  9310. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  9311. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9312. default_socket_options(srv);
  9313. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9314. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9315. sockaddr_in addr{};
  9316. addr.sin_family = AF_INET;
  9317. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9318. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9319. int opt = 1;
  9320. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9321. #ifdef _WIN32
  9322. reinterpret_cast<const char *>(&opt),
  9323. #else
  9324. &opt,
  9325. #endif
  9326. sizeof(opt));
  9327. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9328. ::listen(srv, 1);
  9329. sockaddr_in cli_addr{};
  9330. socklen_t cli_len = sizeof(cli_addr);
  9331. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9332. if (cli != INVALID_SOCKET) {
  9333. char buf[4096];
  9334. ::recv(cli, buf, sizeof(buf), 0);
  9335. // Malicious response: no Content-Length, no chunked encoding
  9336. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9337. "Connection: close\r\n"
  9338. "\r\n";
  9339. ::send(cli,
  9340. #ifdef _WIN32
  9341. static_cast<const char *>(response_header.c_str()),
  9342. static_cast<int>(response_header.size()),
  9343. #else
  9344. response_header.c_str(), response_header.size(),
  9345. #endif
  9346. 0);
  9347. // Send 10MB of data
  9348. std::string chunk(64 * 1024, 'A');
  9349. size_t total_sent = 0;
  9350. while (total_sent < MALICIOUS_DATA_SIZE) {
  9351. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  9352. auto sent = ::send(cli,
  9353. #ifdef _WIN32
  9354. static_cast<const char *>(chunk.c_str()),
  9355. static_cast<int>(to_send),
  9356. #else
  9357. chunk.c_str(), to_send,
  9358. #endif
  9359. 0);
  9360. if (sent <= 0) break;
  9361. total_sent += static_cast<size_t>(sent);
  9362. }
  9363. detail::close_socket(cli);
  9364. }
  9365. detail::close_socket(srv);
  9366. });
  9367. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9368. size_t total_read = 0;
  9369. {
  9370. Client cli("127.0.0.1", PORT + 2);
  9371. cli.set_read_timeout(5, 0);
  9372. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9373. auto stream = cli.open_stream("GET", "/malicious");
  9374. ASSERT_TRUE(stream.is_valid());
  9375. char buffer[64 * 1024];
  9376. ssize_t n;
  9377. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9378. total_read += static_cast<size_t>(n);
  9379. }
  9380. } // StreamHandle and Client destroyed here, closing the socket
  9381. server_thread.join();
  9382. // With set_payload_max_length, the client must stop reading before consuming
  9383. // all 10MB. The read loop should be cut off at or near the configured limit.
  9384. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9385. << "Client read " << total_read << " bytes, exceeding the configured "
  9386. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9387. }
  9388. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9389. // the entire response body without truncation.
  9390. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9391. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9392. #ifndef _WIN32
  9393. signal(SIGPIPE, SIG_IGN);
  9394. #endif
  9395. auto server_thread = std::thread([] {
  9396. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9397. default_socket_options(srv);
  9398. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9399. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9400. sockaddr_in addr{};
  9401. addr.sin_family = AF_INET;
  9402. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9403. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9404. int opt = 1;
  9405. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9406. #ifdef _WIN32
  9407. reinterpret_cast<const char *>(&opt),
  9408. #else
  9409. &opt,
  9410. #endif
  9411. sizeof(opt));
  9412. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9413. ::listen(srv, 1);
  9414. sockaddr_in cli_addr{};
  9415. socklen_t cli_len = sizeof(cli_addr);
  9416. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9417. if (cli != INVALID_SOCKET) {
  9418. char buf[4096];
  9419. ::recv(cli, buf, sizeof(buf), 0);
  9420. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9421. "Connection: close\r\n"
  9422. "\r\n";
  9423. ::send(cli,
  9424. #ifdef _WIN32
  9425. static_cast<const char *>(response_header.c_str()),
  9426. static_cast<int>(response_header.size()),
  9427. #else
  9428. response_header.c_str(), response_header.size(),
  9429. #endif
  9430. 0);
  9431. std::string chunk(64 * 1024, 'A');
  9432. size_t total_sent = 0;
  9433. while (total_sent < DATA_SIZE) {
  9434. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9435. auto sent = ::send(cli,
  9436. #ifdef _WIN32
  9437. static_cast<const char *>(chunk.c_str()),
  9438. static_cast<int>(to_send),
  9439. #else
  9440. chunk.c_str(), to_send,
  9441. #endif
  9442. 0);
  9443. if (sent <= 0) break;
  9444. total_sent += static_cast<size_t>(sent);
  9445. }
  9446. #ifdef _WIN32
  9447. ::shutdown(cli, SD_SEND);
  9448. #else
  9449. ::shutdown(cli, SHUT_WR);
  9450. #endif
  9451. // Drain until the client closes its end, ensuring all data is delivered
  9452. char drain[1024];
  9453. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9454. detail::close_socket(cli);
  9455. }
  9456. detail::close_socket(srv);
  9457. });
  9458. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9459. size_t total_read = 0;
  9460. {
  9461. Client cli("127.0.0.1", PORT + 2);
  9462. cli.set_read_timeout(5, 0);
  9463. cli.set_payload_max_length(0); // 0 means no limit
  9464. auto stream = cli.open_stream("GET", "/data");
  9465. ASSERT_TRUE(stream.is_valid());
  9466. char buffer[64 * 1024];
  9467. ssize_t n;
  9468. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9469. total_read += static_cast<size_t>(n);
  9470. }
  9471. }
  9472. server_thread.join();
  9473. EXPECT_EQ(total_read, DATA_SIZE)
  9474. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9475. << " bytes without truncation, but only read " << total_read << " bytes.";
  9476. }
  9477. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9478. // enormous Content-Length must not cause the client to pre-allocate a huge
  9479. // response body buffer. The reservation is capped at payload_max_length_, and
  9480. // the read itself fails when the body exceeds the limit.
  9481. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9482. #ifndef _WIN32
  9483. signal(SIGPIPE, SIG_IGN);
  9484. #endif
  9485. auto server_thread = std::thread([] {
  9486. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9487. default_socket_options(srv);
  9488. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9489. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9490. sockaddr_in addr{};
  9491. addr.sin_family = AF_INET;
  9492. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9493. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9494. int opt = 1;
  9495. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9496. #ifdef _WIN32
  9497. reinterpret_cast<const char *>(&opt),
  9498. #else
  9499. &opt,
  9500. #endif
  9501. sizeof(opt));
  9502. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9503. ::listen(srv, 1);
  9504. sockaddr_in cli_addr{};
  9505. socklen_t cli_len = sizeof(cli_addr);
  9506. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9507. if (cli != INVALID_SOCKET) {
  9508. char buf[4096];
  9509. ::recv(cli, buf, sizeof(buf), 0);
  9510. // Malicious response: claim a 20GB body but send only a tiny payload.
  9511. std::string response = "HTTP/1.1 200 OK\r\n"
  9512. "Content-Length: 20000000000\r\n"
  9513. "\r\n"
  9514. "abc";
  9515. ::send(cli,
  9516. #ifdef _WIN32
  9517. static_cast<const char *>(response.c_str()),
  9518. static_cast<int>(response.size()),
  9519. #else
  9520. response.c_str(), response.size(),
  9521. #endif
  9522. 0);
  9523. detail::close_socket(cli);
  9524. }
  9525. detail::close_socket(srv);
  9526. });
  9527. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9528. {
  9529. Client cli("127.0.0.1", PORT + 2);
  9530. cli.set_read_timeout(5, 0);
  9531. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9532. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9533. // (server claims more bytes than payload_max_length permits), but it must
  9534. // not exhaust memory before getting there.
  9535. auto res = cli.Get("/malicious");
  9536. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9537. }
  9538. server_thread.join();
  9539. }
  9540. // Verify that content_receiver bypasses the default payload_max_length,
  9541. // allowing streaming downloads larger than 100MB without requiring an explicit
  9542. // set_payload_max_length call.
  9543. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9544. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9545. #ifndef _WIN32
  9546. signal(SIGPIPE, SIG_IGN);
  9547. #endif
  9548. auto server_thread = std::thread([] {
  9549. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9550. default_socket_options(srv);
  9551. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9552. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9553. sockaddr_in addr{};
  9554. addr.sin_family = AF_INET;
  9555. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9556. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9557. int opt = 1;
  9558. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9559. #ifdef _WIN32
  9560. reinterpret_cast<const char *>(&opt),
  9561. #else
  9562. &opt,
  9563. #endif
  9564. sizeof(opt));
  9565. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9566. ::listen(srv, 1);
  9567. sockaddr_in cli_addr{};
  9568. socklen_t cli_len = sizeof(cli_addr);
  9569. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9570. if (cli != INVALID_SOCKET) {
  9571. char buf[4096];
  9572. ::recv(cli, buf, sizeof(buf), 0);
  9573. // Response with Content-Length larger than default 100MB limit
  9574. auto content_length = std::to_string(DATA_SIZE);
  9575. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9576. "Content-Length: " +
  9577. content_length +
  9578. "\r\n"
  9579. "Connection: close\r\n"
  9580. "\r\n";
  9581. ::send(cli,
  9582. #ifdef _WIN32
  9583. static_cast<const char *>(response_header.c_str()),
  9584. static_cast<int>(response_header.size()),
  9585. #else
  9586. response_header.c_str(), response_header.size(),
  9587. #endif
  9588. 0);
  9589. std::string chunk(64 * 1024, 'A');
  9590. size_t total_sent = 0;
  9591. while (total_sent < DATA_SIZE) {
  9592. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9593. auto sent = ::send(cli,
  9594. #ifdef _WIN32
  9595. static_cast<const char *>(chunk.c_str()),
  9596. static_cast<int>(to_send),
  9597. #else
  9598. chunk.c_str(), to_send,
  9599. #endif
  9600. 0);
  9601. if (sent <= 0) break;
  9602. total_sent += static_cast<size_t>(sent);
  9603. }
  9604. detail::close_socket(cli);
  9605. }
  9606. detail::close_socket(srv);
  9607. });
  9608. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9609. size_t total_received = 0;
  9610. {
  9611. Client cli("127.0.0.1", PORT + 2);
  9612. cli.set_read_timeout(10, 0);
  9613. // Do NOT call set_payload_max_length — use the default 100MB limit
  9614. auto res =
  9615. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9616. total_received += data_length;
  9617. return true;
  9618. });
  9619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9620. EXPECT_EQ(StatusCode::OK_200, res->status);
  9621. }
  9622. server_thread.join();
  9623. EXPECT_EQ(total_received, DATA_SIZE)
  9624. << "With content_receiver, the client should read all " << DATA_SIZE
  9625. << " bytes despite the default 100MB payload_max_length, but only read "
  9626. << total_received << " bytes.";
  9627. }
  9628. // Verify that an explicit set_payload_max_length smaller than the response is
  9629. // enforced even when a content_receiver is used.
  9630. TEST(ClientVulnerabilityTest,
  9631. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9632. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9633. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9634. #ifndef _WIN32
  9635. signal(SIGPIPE, SIG_IGN);
  9636. #endif
  9637. auto server_thread = std::thread([] {
  9638. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9639. default_socket_options(srv);
  9640. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9641. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9642. sockaddr_in addr{};
  9643. addr.sin_family = AF_INET;
  9644. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9645. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9646. int opt = 1;
  9647. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9648. #ifdef _WIN32
  9649. reinterpret_cast<const char *>(&opt),
  9650. #else
  9651. &opt,
  9652. #endif
  9653. sizeof(opt));
  9654. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9655. ::listen(srv, 1);
  9656. sockaddr_in cli_addr{};
  9657. socklen_t cli_len = sizeof(cli_addr);
  9658. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9659. if (cli != INVALID_SOCKET) {
  9660. char buf[4096];
  9661. ::recv(cli, buf, sizeof(buf), 0);
  9662. auto content_length = std::to_string(DATA_SIZE);
  9663. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9664. "Content-Length: " +
  9665. content_length +
  9666. "\r\n"
  9667. "Connection: close\r\n"
  9668. "\r\n";
  9669. ::send(cli,
  9670. #ifdef _WIN32
  9671. static_cast<const char *>(response_header.c_str()),
  9672. static_cast<int>(response_header.size()),
  9673. #else
  9674. response_header.c_str(), response_header.size(),
  9675. #endif
  9676. 0);
  9677. std::string chunk(64 * 1024, 'A');
  9678. size_t total_sent = 0;
  9679. while (total_sent < DATA_SIZE) {
  9680. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9681. auto sent = ::send(cli,
  9682. #ifdef _WIN32
  9683. static_cast<const char *>(chunk.c_str()),
  9684. static_cast<int>(to_send),
  9685. #else
  9686. chunk.c_str(), to_send,
  9687. #endif
  9688. 0);
  9689. if (sent <= 0) break;
  9690. total_sent += static_cast<size_t>(sent);
  9691. }
  9692. detail::close_socket(cli);
  9693. }
  9694. detail::close_socket(srv);
  9695. });
  9696. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9697. size_t total_received = 0;
  9698. {
  9699. Client cli("127.0.0.1", PORT + 2);
  9700. cli.set_read_timeout(10, 0);
  9701. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9702. auto res =
  9703. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9704. total_received += data_length;
  9705. return true;
  9706. });
  9707. // Should fail because 200MB exceeds the explicit 150MB limit
  9708. EXPECT_FALSE(res);
  9709. }
  9710. server_thread.join();
  9711. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9712. << "Client with content_receiver should respect the explicit "
  9713. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9714. << total_received << " bytes.";
  9715. }
  9716. // Verify that an explicit set_payload_max_length larger than the response
  9717. // allows the content_receiver to read all data successfully.
  9718. TEST(ClientVulnerabilityTest,
  9719. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9720. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9721. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9722. #ifndef _WIN32
  9723. signal(SIGPIPE, SIG_IGN);
  9724. #endif
  9725. auto server_thread = std::thread([] {
  9726. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9727. default_socket_options(srv);
  9728. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9729. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9730. sockaddr_in addr{};
  9731. addr.sin_family = AF_INET;
  9732. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9733. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9734. int opt = 1;
  9735. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9736. #ifdef _WIN32
  9737. reinterpret_cast<const char *>(&opt),
  9738. #else
  9739. &opt,
  9740. #endif
  9741. sizeof(opt));
  9742. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9743. ::listen(srv, 1);
  9744. sockaddr_in cli_addr{};
  9745. socklen_t cli_len = sizeof(cli_addr);
  9746. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9747. if (cli != INVALID_SOCKET) {
  9748. char buf[4096];
  9749. ::recv(cli, buf, sizeof(buf), 0);
  9750. auto content_length = std::to_string(DATA_SIZE);
  9751. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9752. "Content-Length: " +
  9753. content_length +
  9754. "\r\n"
  9755. "Connection: close\r\n"
  9756. "\r\n";
  9757. ::send(cli,
  9758. #ifdef _WIN32
  9759. static_cast<const char *>(response_header.c_str()),
  9760. static_cast<int>(response_header.size()),
  9761. #else
  9762. response_header.c_str(), response_header.size(),
  9763. #endif
  9764. 0);
  9765. std::string chunk(64 * 1024, 'A');
  9766. size_t total_sent = 0;
  9767. while (total_sent < DATA_SIZE) {
  9768. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9769. auto sent = ::send(cli,
  9770. #ifdef _WIN32
  9771. static_cast<const char *>(chunk.c_str()),
  9772. static_cast<int>(to_send),
  9773. #else
  9774. chunk.c_str(), to_send,
  9775. #endif
  9776. 0);
  9777. if (sent <= 0) break;
  9778. total_sent += static_cast<size_t>(sent);
  9779. }
  9780. #ifdef _WIN32
  9781. ::shutdown(cli, SD_SEND);
  9782. #else
  9783. ::shutdown(cli, SHUT_WR);
  9784. #endif
  9785. char drain[1024];
  9786. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9787. detail::close_socket(cli);
  9788. }
  9789. detail::close_socket(srv);
  9790. });
  9791. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9792. size_t total_received = 0;
  9793. {
  9794. Client cli("127.0.0.1", PORT + 2);
  9795. cli.set_read_timeout(10, 0);
  9796. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9797. auto res =
  9798. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9799. total_received += data_length;
  9800. return true;
  9801. });
  9802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9803. EXPECT_EQ(StatusCode::OK_200, res->status);
  9804. }
  9805. server_thread.join();
  9806. EXPECT_EQ(total_received, DATA_SIZE)
  9807. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9808. << " bytes (larger than " << DATA_SIZE
  9809. << " bytes response), content_receiver should read all data, but only "
  9810. "read "
  9811. << total_received << " bytes.";
  9812. }
  9813. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9814. // Regression test for "zip bomb" attack on the client side: a malicious server
  9815. // sends a small gzip-compressed response that decompresses to a huge payload.
  9816. // The client must enforce payload_max_length on the decompressed size.
  9817. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9818. constexpr size_t DECOMPRESSED_SIZE =
  9819. 10 * 1024 * 1024; // 10MB after decompression
  9820. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9821. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9822. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9823. std::string compressed;
  9824. {
  9825. httplib::detail::gzip_compressor compressor;
  9826. bool ok =
  9827. compressor.compress(uncompressed.data(), uncompressed.size(),
  9828. /*last=*/true, [&](const char *buf, size_t len) {
  9829. compressed.append(buf, len);
  9830. return true;
  9831. });
  9832. ASSERT_TRUE(ok);
  9833. }
  9834. // Sanity: compressed data should be much smaller than the decompressed size
  9835. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9836. #ifndef _WIN32
  9837. signal(SIGPIPE, SIG_IGN);
  9838. #endif
  9839. // Set up the listening socket in the main thread so the server is guaranteed
  9840. // to be ready before the client connects (eliminates race condition).
  9841. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9842. default_socket_options(srv);
  9843. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9844. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9845. sockaddr_in addr{};
  9846. addr.sin_family = AF_INET;
  9847. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9848. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9849. int opt = 1;
  9850. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9851. #ifdef _WIN32
  9852. reinterpret_cast<const char *>(&opt),
  9853. #else
  9854. &opt,
  9855. #endif
  9856. sizeof(opt));
  9857. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9858. ASSERT_EQ(0, ::listen(srv, 1));
  9859. auto server_thread = std::thread([&compressed, srv] {
  9860. sockaddr_in cli_addr{};
  9861. socklen_t cli_len = sizeof(cli_addr);
  9862. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9863. if (cli != INVALID_SOCKET) {
  9864. // Read the full HTTP request (until \r\n\r\n)
  9865. char buf[4096];
  9866. size_t total = 0;
  9867. while (total < sizeof(buf)) {
  9868. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9869. if (n <= 0) break;
  9870. total += static_cast<size_t>(n);
  9871. // Check for end of headers
  9872. if (total >= 4) {
  9873. std::string req(buf, total);
  9874. if (req.find("\r\n\r\n") != std::string::npos) break;
  9875. }
  9876. }
  9877. // Malicious response: gzip-compressed body, no Content-Length
  9878. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9879. "Content-Encoding: gzip\r\n"
  9880. "Connection: close\r\n"
  9881. "\r\n";
  9882. ::send(cli,
  9883. #ifdef _WIN32
  9884. static_cast<const char *>(response_header.c_str()),
  9885. static_cast<int>(response_header.size()),
  9886. #else
  9887. response_header.c_str(), response_header.size(),
  9888. #endif
  9889. 0);
  9890. // Send the compressed payload (small on the wire, huge when decompressed)
  9891. size_t total_sent = 0;
  9892. while (total_sent < compressed.size()) {
  9893. auto to_send = std::min(compressed.size() - total_sent,
  9894. static_cast<size_t>(64 * 1024));
  9895. auto sent =
  9896. ::send(cli,
  9897. #ifdef _WIN32
  9898. static_cast<const char *>(compressed.c_str() + total_sent),
  9899. static_cast<int>(to_send),
  9900. #else
  9901. compressed.c_str() + total_sent, to_send,
  9902. #endif
  9903. 0);
  9904. if (sent <= 0) break;
  9905. total_sent += static_cast<size_t>(sent);
  9906. }
  9907. detail::close_socket(cli);
  9908. }
  9909. });
  9910. auto se = detail::scope_exit([&] {
  9911. detail::close_socket(srv);
  9912. server_thread.join();
  9913. });
  9914. size_t total_decompressed = 0;
  9915. {
  9916. Client cli("127.0.0.1", PORT + 3);
  9917. cli.set_read_timeout(5, 0);
  9918. cli.set_decompress(true);
  9919. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9920. auto stream = cli.open_stream("GET", "/zipbomb");
  9921. ASSERT_TRUE(stream.is_valid());
  9922. char buffer[64 * 1024];
  9923. ssize_t n;
  9924. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9925. total_decompressed += static_cast<size_t>(n);
  9926. }
  9927. }
  9928. // The decompressed size must be capped by payload_max_length. Without
  9929. // protection, the client would decompress the full 10MB from a tiny
  9930. // compressed payload, enabling a zip bomb DoS attack.
  9931. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9932. << "Client decompressed " << total_decompressed
  9933. << " bytes from a gzip response. The decompressed size should be "
  9934. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9935. }
  9936. #endif
  9937. TEST(HostAndPortPropertiesTest, NoSSL) {
  9938. httplib::Client cli("www.google.com", 1234);
  9939. ASSERT_EQ("www.google.com", cli.host());
  9940. ASSERT_EQ(1234, cli.port());
  9941. }
  9942. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9943. httplib::Client cli("www.google.com:1234");
  9944. ASSERT_EQ("www.google.com", cli.host());
  9945. ASSERT_EQ(1234, cli.port());
  9946. }
  9947. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9948. // Port number that overflows int — should not crash, client becomes invalid
  9949. httplib::Client cli("http://www.google.com:99999999999999999999");
  9950. ASSERT_FALSE(cli.is_valid());
  9951. }
  9952. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9953. // Port 99999 exceeds valid range (1-65535) — should not crash
  9954. httplib::Client cli("http://www.google.com:99999");
  9955. ASSERT_FALSE(cli.is_valid());
  9956. }
  9957. #ifdef CPPHTTPLIB_SSL_ENABLED
  9958. TEST(HostAndPortPropertiesTest, SSL) {
  9959. httplib::SSLClient cli("www.google.com");
  9960. ASSERT_EQ("www.google.com", cli.host());
  9961. ASSERT_EQ(443, cli.port());
  9962. }
  9963. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9964. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9965. std::string cert;
  9966. read_file(CA_CERT_FILE, cert);
  9967. httplib::SSLClient httplib_client("www.google.com");
  9968. // Load CA store first time
  9969. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9970. // Load CA store second time (update)
  9971. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9972. // Verify client is still valid and can make connections
  9973. httplib_client.enable_server_certificate_verification(true);
  9974. auto res = httplib_client.Get("/");
  9975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9976. // Google may return 200 or 301 depending on various factors
  9977. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9978. res->status == StatusCode::MovedPermanently_301);
  9979. }
  9980. TEST(SSLClientTest, ServerNameIndication_Online) {
  9981. auto host = "httpbingo.org";
  9982. auto path = std::string{"/get"};
  9983. SSLClient cli(host, 443);
  9984. auto res = cli.Get(path);
  9985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9986. ASSERT_EQ(StatusCode::OK_200, res->status);
  9987. }
  9988. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9989. // Use a site that will cause SSL verification failure due to self-signed cert
  9990. SSLClient cli("self-signed.badssl.com", 443);
  9991. cli.enable_server_certificate_verification(true);
  9992. auto res = cli.Get("/");
  9993. ASSERT_TRUE(!res);
  9994. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9995. // Verify backend error is captured for SSLServerVerification
  9996. // This occurs when certificate verification fails
  9997. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9998. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9999. EXPECT_NE(0UL, res.ssl_backend_error());
  10000. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10001. // For OpenSSL, ssl_error is 0 for verification errors
  10002. EXPECT_EQ(0, res.ssl_error());
  10003. #if !defined(_WIN32) || \
  10004. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10005. // On non-Windows or when Windows Schannel is disabled, the error comes
  10006. // from OpenSSL's verification
  10007. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  10008. res.ssl_backend_error());
  10009. #endif
  10010. #endif
  10011. }
  10012. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  10013. // Use a site where hostname doesn't match the certificate
  10014. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  10015. SSLClient cli("wrong.host.badssl.com", 443);
  10016. cli.enable_server_certificate_verification(true);
  10017. cli.enable_server_hostname_verification(true);
  10018. auto res = cli.Get("/");
  10019. ASSERT_TRUE(!res);
  10020. // The error type depends on when hostname verification occurs:
  10021. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  10022. // - Mbed TLS: SSLServerVerification (during handshake)
  10023. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  10024. res.error() == Error::SSLServerVerification);
  10025. // Verify backend error is captured for hostname verification failure
  10026. EXPECT_NE(0UL, res.ssl_backend_error());
  10027. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10028. // For OpenSSL, ssl_error is 0 for verification errors
  10029. EXPECT_EQ(0, res.ssl_error());
  10030. #if !defined(_WIN32) || \
  10031. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10032. // On non-Windows or when Windows Schannel is disabled, the error comes
  10033. // from OpenSSL's hostname verification
  10034. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  10035. res.ssl_backend_error());
  10036. #endif
  10037. #endif
  10038. }
  10039. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  10040. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  10041. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  10042. SSLClient cli("www.google.com", 443);
  10043. cli.enable_server_certificate_verification(true);
  10044. auto res = cli.Get("/");
  10045. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10046. }
  10047. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  10048. SSLClient cli("www.google.com", 443);
  10049. cli.enable_server_certificate_verification(true);
  10050. cli.enable_windows_certificate_verification(false);
  10051. auto res = cli.Get("/");
  10052. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  10053. }
  10054. #endif
  10055. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  10056. Client cli("https://google.com");
  10057. auto res = cli.Get("/");
  10058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10059. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10060. }
  10061. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  10062. SSLClient cli("google.com");
  10063. cli.set_ca_cert_path(CA_CERT_FILE);
  10064. auto res = cli.Get("/");
  10065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10066. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10067. }
  10068. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  10069. SSLClient cli("google.com");
  10070. cli.enable_server_certificate_verification(true);
  10071. cli.set_ca_cert_path("hello");
  10072. auto res = cli.Get("/");
  10073. ASSERT_TRUE(!res);
  10074. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  10075. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  10076. // should be set
  10077. EXPECT_EQ(0, res.ssl_error());
  10078. // Verify backend error is captured for SSLLoadingCerts
  10079. // This error occurs when loading CA certificates fails
  10080. EXPECT_NE(0UL, res.ssl_backend_error());
  10081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10082. // OpenSSL specific error codes:
  10083. // > openssl errstr 0x80000002
  10084. // error:80000002:system library::No such file or directory
  10085. // > openssl errstr 0xA000126
  10086. // error:0A000126:SSL routines::unexpected eof while reading
  10087. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  10088. res.ssl_backend_error() == 0xA000126);
  10089. #endif
  10090. }
  10091. TEST(SSLClientTest, ServerCertificateVerification4) {
  10092. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10093. ASSERT_TRUE(svr.is_valid());
  10094. svr.Get("/test", [&](const Request &, Response &res) {
  10095. res.set_content("test", "text/plain");
  10096. svr.stop();
  10097. ASSERT_TRUE(true);
  10098. });
  10099. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10100. auto se = detail::scope_exit([&] {
  10101. t.join();
  10102. ASSERT_FALSE(svr.is_running());
  10103. });
  10104. svr.wait_until_ready();
  10105. SSLClient cli("127.0.0.1", PORT);
  10106. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10107. cli.enable_server_certificate_verification(true);
  10108. cli.set_connection_timeout(30);
  10109. auto res = cli.Get("/test");
  10110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10111. ASSERT_EQ(StatusCode::OK_200, res->status);
  10112. }
  10113. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  10114. std::string cert;
  10115. read_file(CA_CERT_FILE, cert);
  10116. SSLClient cli("google.com");
  10117. cli.load_ca_cert_store(cert.data(), cert.size());
  10118. const auto res = cli.Get("/");
  10119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10120. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10121. }
  10122. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  10123. // clang-format off
  10124. static constexpr char cert[] =
  10125. "GlobalSign Root CA\n"
  10126. "==================\n"
  10127. "-----BEGIN CERTIFICATE-----\n"
  10128. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  10129. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  10130. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  10131. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  10132. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  10133. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  10134. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  10135. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  10136. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  10137. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  10138. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  10139. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  10140. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  10141. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  10142. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  10143. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  10144. "-----END CERTIFICATE-----\n";
  10145. // clang-format on
  10146. SSLClient cli("google.com");
  10147. cli.load_ca_cert_store(cert, sizeof(cert));
  10148. const auto res = cli.Get("/");
  10149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10150. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10151. }
  10152. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  10153. SSLClient cli("www.youtube.com");
  10154. cli.set_ca_cert_path(CA_CERT_FILE);
  10155. cli.enable_server_certificate_verification(true);
  10156. cli.set_follow_location(true);
  10157. auto res = cli.Get("/");
  10158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10159. ASSERT_EQ(StatusCode::OK_200, res->status);
  10160. }
  10161. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  10162. SSLClient cli("wWw.YouTube.Com");
  10163. cli.set_ca_cert_path(CA_CERT_FILE);
  10164. cli.enable_server_certificate_verification(true);
  10165. cli.enable_server_hostname_verification(true);
  10166. cli.set_follow_location(true);
  10167. auto res = cli.Get("/");
  10168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10169. ASSERT_EQ(StatusCode::OK_200, res->status);
  10170. }
  10171. TEST(SSLClientTest, HostNameMatchCase_Online) {
  10172. SSLClient cli("gOoGlE.COm");
  10173. cli.enable_server_certificate_verification(true);
  10174. cli.enable_server_hostname_verification(true);
  10175. cli.set_follow_location(true);
  10176. auto res = cli.Get("/");
  10177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10178. ASSERT_EQ(StatusCode::OK_200, res->status);
  10179. }
  10180. TEST(SSLClientTest, Issue2004_Online) {
  10181. Client client("https://google.com");
  10182. client.set_follow_location(true);
  10183. auto res = client.Get("/");
  10184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10185. ASSERT_EQ(StatusCode::OK_200, res->status);
  10186. auto body = res->body;
  10187. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  10188. }
  10189. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  10190. // Create SSLClient with invalid cert/key to make is_valid() return false
  10191. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  10192. "nonexistent_key.pem");
  10193. // is_valid() should be false due to cert loading failure
  10194. ASSERT_FALSE(cli.is_valid());
  10195. auto res = cli.Get("/");
  10196. ASSERT_FALSE(res);
  10197. EXPECT_EQ(Error::SSLConnection, res.error());
  10198. }
  10199. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  10200. // Test for Issue #2251: SSL error not properly reported when client cert
  10201. // and key paths are swapped or mismatched
  10202. // This simulates the scenario where user accidentally swaps the cert and key
  10203. // files
  10204. // Using client cert file as private key and vice versa (completely wrong)
  10205. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  10206. // Should fail validation due to cert/key mismatch
  10207. ASSERT_FALSE(cli.is_valid());
  10208. // Attempt to make a request should fail with proper error
  10209. auto res = cli.Get("/");
  10210. ASSERT_FALSE(res);
  10211. EXPECT_EQ(Error::SSLConnection, res.error());
  10212. // SSL error should be recorded in the Result object (this is the key fix for
  10213. // Issue #2251)
  10214. auto backend_error = res.ssl_backend_error();
  10215. EXPECT_NE(0u, backend_error);
  10216. }
  10217. // Tests cert/key mismatch detection at the TLS context level
  10218. TEST(TlsApiTest, ClientCertKeyMismatch) {
  10219. // Test that using mismatched cert/key causes connection failure.
  10220. // We verify this at the SSLClient level rather than through internal
  10221. // TLS API functions.
  10222. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  10223. cli.enable_server_certificate_verification(false);
  10224. cli.set_connection_timeout(2);
  10225. // The mismatch should cause a connection or handshake error
  10226. auto res = cli.Get("/test");
  10227. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  10228. // Either way, the request should fail
  10229. EXPECT_FALSE(res);
  10230. }
  10231. #endif
  10232. #if 0
  10233. TEST(SSLClientTest, SetInterfaceWithINET6) {
  10234. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  10235. ASSERT_TRUE(cli != nullptr);
  10236. cli->set_address_family(AF_INET6);
  10237. cli->set_interface("en0");
  10238. auto res = cli->Get("/get");
  10239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10240. ASSERT_EQ(StatusCode::OK_200, res->status);
  10241. }
  10242. #endif
  10243. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  10244. #ifdef CPPHTTPLIB_SSL_ENABLED
  10245. void ClientCertPresent(
  10246. const std::string &client_cert_file,
  10247. const std::string &client_private_key_file,
  10248. const std::string &client_encrypted_private_key_pass = std::string()) {
  10249. using namespace httplib::tls;
  10250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10251. CLIENT_CA_CERT_DIR);
  10252. ASSERT_TRUE(svr.is_valid());
  10253. svr.Get("/test", [&](const Request &req, Response &res) {
  10254. res.set_content("test", "text/plain");
  10255. auto cert = req.peer_cert();
  10256. ASSERT_TRUE(static_cast<bool>(cert));
  10257. std::string common_name = cert.subject_cn();
  10258. EXPECT_EQ("Common Name", common_name);
  10259. });
  10260. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10261. auto se = detail::scope_exit([&] {
  10262. svr.stop();
  10263. t.join();
  10264. ASSERT_FALSE(svr.is_running());
  10265. });
  10266. svr.wait_until_ready();
  10267. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  10268. client_encrypted_private_key_pass);
  10269. cli.enable_server_certificate_verification(false);
  10270. cli.set_connection_timeout(30);
  10271. auto res = cli.Get("/test");
  10272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10273. ASSERT_EQ(StatusCode::OK_200, res->status);
  10274. }
  10275. TEST(SSLClientServerTest, ClientCertPresent) {
  10276. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10277. }
  10278. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  10279. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10280. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10281. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10282. }
  10283. // PEM memory-based constructor tests (works with all TLS backends)
  10284. void PemMemoryClientCertPresent(
  10285. const std::string &client_cert_file,
  10286. const std::string &client_private_key_file,
  10287. const std::string &client_encrypted_private_key_pass = std::string()) {
  10288. // Read PEM files into memory
  10289. std::string server_cert_pem, server_key_pem;
  10290. std::string client_ca_pem;
  10291. std::string client_cert_pem, client_key_pem;
  10292. read_file(SERVER_CERT_FILE, server_cert_pem);
  10293. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10294. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10295. read_file(client_cert_file, client_cert_pem);
  10296. read_file(client_private_key_file, client_key_pem);
  10297. // Create server with PEM memory
  10298. SSLServer::PemMemory server_pem = {
  10299. server_cert_pem.c_str(),
  10300. server_cert_pem.size(),
  10301. server_key_pem.c_str(),
  10302. server_key_pem.size(),
  10303. client_ca_pem.c_str(),
  10304. client_ca_pem.size(),
  10305. nullptr // no password for server key
  10306. };
  10307. SSLServer svr(server_pem);
  10308. ASSERT_TRUE(svr.is_valid());
  10309. svr.Get("/test", [&](const Request &, Response &res) {
  10310. res.set_content("test", "text/plain");
  10311. });
  10312. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10313. auto se = detail::scope_exit([&] {
  10314. svr.stop();
  10315. t.join();
  10316. ASSERT_FALSE(svr.is_running());
  10317. });
  10318. svr.wait_until_ready();
  10319. // Create client with PEM memory
  10320. const char *password = client_encrypted_private_key_pass.empty()
  10321. ? nullptr
  10322. : client_encrypted_private_key_pass.c_str();
  10323. SSLClient::PemMemory client_pem = {
  10324. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  10325. client_key_pem.size(), password};
  10326. SSLClient cli(HOST, PORT, client_pem);
  10327. cli.enable_server_certificate_verification(false);
  10328. cli.set_connection_timeout(30);
  10329. auto res = cli.Get("/test");
  10330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10331. ASSERT_EQ(StatusCode::OK_200, res->status);
  10332. }
  10333. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  10334. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10335. }
  10336. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  10337. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  10338. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  10339. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  10340. }
  10341. TEST(SSLClientServerTest, ClientCertMissing) {
  10342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10343. CLIENT_CA_CERT_DIR);
  10344. ASSERT_TRUE(svr.is_valid());
  10345. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  10346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10347. auto se = detail::scope_exit([&] {
  10348. svr.stop();
  10349. t.join();
  10350. ASSERT_FALSE(svr.is_running());
  10351. });
  10352. svr.wait_until_ready();
  10353. SSLClient cli(HOST, PORT);
  10354. cli.set_connection_timeout(30);
  10355. auto res = cli.Get("/test");
  10356. ASSERT_TRUE(!res);
  10357. // When client cert is missing and server requires it, connection fails
  10358. // Error type depends on backend implementation
  10359. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10360. res.error() == Error::SSLConnection);
  10361. // Verify backend error is captured
  10362. // Note: This test may have different error codes depending on the exact
  10363. // verification failure
  10364. EXPECT_NE(0UL, res.ssl_backend_error());
  10365. }
  10366. TEST(SSLClientServerTest, TrustDirOptional) {
  10367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10368. ASSERT_TRUE(svr.is_valid());
  10369. svr.Get("/test", [&](const Request &, Response &res) {
  10370. res.set_content("test", "text/plain");
  10371. });
  10372. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10373. auto se = detail::scope_exit([&] {
  10374. svr.stop();
  10375. t.join();
  10376. ASSERT_FALSE(svr.is_running());
  10377. });
  10378. svr.wait_until_ready();
  10379. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10380. cli.enable_server_certificate_verification(false);
  10381. cli.set_connection_timeout(30);
  10382. auto res = cli.Get("/test");
  10383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10384. ASSERT_EQ(StatusCode::OK_200, res->status);
  10385. }
  10386. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10387. class NoListenSSLServer : public SSLServer {
  10388. public:
  10389. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10390. const char *client_ca_cert_file_path,
  10391. const char *client_ca_cert_dir_path = nullptr)
  10392. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10393. client_ca_cert_dir_path),
  10394. stop_(false) {}
  10395. std::atomic_bool stop_;
  10396. private:
  10397. bool process_and_close_socket(socket_t /*sock*/) override {
  10398. // Don't create SSL context
  10399. while (!stop_.load()) {
  10400. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10401. }
  10402. return true;
  10403. }
  10404. };
  10405. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10406. CLIENT_CA_CERT_FILE);
  10407. ASSERT_TRUE(svr.is_valid());
  10408. svr.Get("/test", [&](const Request &, Response &res) {
  10409. res.set_content("test", "text/plain");
  10410. });
  10411. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10412. auto se = detail::scope_exit([&] {
  10413. svr.stop_ = true;
  10414. svr.stop();
  10415. t.join();
  10416. ASSERT_FALSE(svr.is_running());
  10417. });
  10418. svr.wait_until_ready();
  10419. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10420. cli.enable_server_certificate_verification(false);
  10421. cli.set_connection_timeout(1);
  10422. auto res = cli.Get("/test");
  10423. ASSERT_TRUE(!res);
  10424. EXPECT_EQ(Error::SSLConnection, res.error());
  10425. // Timeout results in WantRead error code (maps to backend-specific value)
  10426. EXPECT_NE(0, res.ssl_error());
  10427. }
  10428. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10429. // Test SSLServer with client certificate verification using the standard
  10430. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10432. CLIENT_CA_CERT_DIR);
  10433. ASSERT_TRUE(svr.is_valid());
  10434. svr.Get("/test", [&](const Request &req, Response &res) {
  10435. res.set_content("test", "text/plain");
  10436. auto cert = req.peer_cert();
  10437. ASSERT_TRUE(static_cast<bool>(cert));
  10438. auto common_name = cert.subject_cn();
  10439. EXPECT_EQ("Common Name", common_name);
  10440. });
  10441. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10442. auto se = detail::scope_exit([&] {
  10443. svr.stop();
  10444. t.join();
  10445. ASSERT_FALSE(svr.is_running());
  10446. });
  10447. svr.wait_until_ready();
  10448. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10449. cli.enable_server_certificate_verification(false);
  10450. cli.set_connection_timeout(30);
  10451. auto res = cli.Get("/test");
  10452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10453. ASSERT_EQ(StatusCode::OK_200, res->status);
  10454. }
  10455. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10456. // Verifies that wildcard matching and exact matching work consistently
  10457. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10458. using namespace httplib::tls;
  10459. // We need a running server to test against
  10460. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10461. ASSERT_TRUE(svr.is_valid());
  10462. svr.Get("/test", [](const Request &, Response &res) {
  10463. res.set_content("ok", "text/plain");
  10464. });
  10465. thread t([&]() { svr.listen(HOST, PORT); });
  10466. auto se = detail::scope_exit([&] {
  10467. svr.stop();
  10468. t.join();
  10469. });
  10470. svr.wait_until_ready();
  10471. bool verify_callback_called = false;
  10472. bool verify_result_wrong = false;
  10473. SSLClient cli(HOST, PORT);
  10474. cli.enable_server_certificate_verification(true);
  10475. cli.set_ca_cert_path(CA_CERT_FILE);
  10476. cli.set_connection_timeout(5);
  10477. // Note: Test certificate has CN="Common Name", not "localhost"
  10478. bool verify_result_cn = false;
  10479. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10480. verify_callback_called = true;
  10481. if (!ctx.cert) return false;
  10482. // Test 1: "Common Name" should match (our test server cert CN)
  10483. verify_result_cn = ctx.check_hostname("Common Name");
  10484. // Test 2: wrong hostname should not match
  10485. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10486. return true; // Accept for the purpose of this test
  10487. });
  10488. auto res = cli.Get("/test");
  10489. // The request may succeed or fail depending on cert configuration
  10490. // but the callback should have been called
  10491. ASSERT_TRUE(verify_callback_called)
  10492. << "Verify callback should have been called";
  10493. // CN="Common Name" should match our test certificate
  10494. //
  10495. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10496. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10497. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10498. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10499. // <openssl/base.h>, which is included transitively when
  10500. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10501. #if defined(OPENSSL_IS_BORINGSSL)
  10502. EXPECT_FALSE(verify_result_cn)
  10503. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10504. #else
  10505. EXPECT_TRUE(verify_result_cn)
  10506. << "verify_hostname should match 'Common Name' (certificate CN)";
  10507. #endif
  10508. // Wrong hostname should not match
  10509. EXPECT_FALSE(verify_result_wrong)
  10510. << "verify_hostname should not match 'wronghost.example.com'";
  10511. }
  10512. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10513. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10514. // X509_check_ip behavior and must hold for every backend.
  10515. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10516. using namespace httplib::tls;
  10517. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10518. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10519. ASSERT_TRUE(svr.is_valid());
  10520. svr.Get("/test", [](const Request &, Response &res) {
  10521. res.set_content("ok", "text/plain");
  10522. });
  10523. thread t([&]() { svr.listen(HOST, PORT); });
  10524. auto se = detail::scope_exit([&] {
  10525. svr.stop();
  10526. t.join();
  10527. });
  10528. svr.wait_until_ready();
  10529. bool verify_callback_called = false;
  10530. bool ip_matched_via_cn = true;
  10531. SSLClient cli(HOST, PORT);
  10532. cli.enable_server_certificate_verification(true);
  10533. cli.set_ca_cert_path(CA_CERT_FILE);
  10534. cli.set_connection_timeout(5);
  10535. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10536. verify_callback_called = true;
  10537. if (!ctx.cert) return false;
  10538. // The IP appears only in the CN, so it must NOT be accepted.
  10539. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10540. return true; // Accept for the purpose of this test
  10541. });
  10542. cli.Get("/test");
  10543. ASSERT_TRUE(verify_callback_called)
  10544. << "Verify callback should have been called";
  10545. EXPECT_FALSE(ip_matched_via_cn)
  10546. << "An IP host must not be authenticated via the certificate CN";
  10547. }
  10548. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10549. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10550. using namespace httplib::tls;
  10551. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10552. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10553. ASSERT_TRUE(svr.is_valid());
  10554. svr.Get("/test", [](const Request &, Response &res) {
  10555. res.set_content("ok", "text/plain");
  10556. });
  10557. thread t([&]() { svr.listen(HOST, PORT); });
  10558. auto se = detail::scope_exit([&] {
  10559. svr.stop();
  10560. t.join();
  10561. });
  10562. svr.wait_until_ready();
  10563. bool verify_callback_called = false;
  10564. bool san_matched = false;
  10565. bool wrong_ipv6_matched = true;
  10566. bool cn_ipv6_matched = true;
  10567. SSLClient cli(HOST, PORT);
  10568. cli.enable_server_certificate_verification(true);
  10569. cli.set_ca_cert_path(CA_CERT_FILE);
  10570. cli.set_connection_timeout(5);
  10571. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10572. verify_callback_called = true;
  10573. if (!ctx.cert) return false;
  10574. // Matches the IPv6 iPAddress SAN.
  10575. san_matched = ctx.check_hostname("2001:db8::1");
  10576. // A different IPv6 address must not match.
  10577. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10578. // "::1" lives only in the CN, so it must not be accepted.
  10579. cn_ipv6_matched = ctx.check_hostname("::1");
  10580. return true; // Accept for the purpose of this test
  10581. });
  10582. cli.Get("/test");
  10583. ASSERT_TRUE(verify_callback_called)
  10584. << "Verify callback should have been called";
  10585. EXPECT_TRUE(san_matched)
  10586. << "verify_hostname should match an IPv6 iPAddress SAN";
  10587. EXPECT_FALSE(wrong_ipv6_matched)
  10588. << "verify_hostname should not match a non-matching IPv6 address";
  10589. EXPECT_FALSE(cn_ipv6_matched)
  10590. << "An IPv6 host must not be authenticated via the certificate CN";
  10591. }
  10592. #endif
  10593. // mbedTLS-specific callback constructor test
  10594. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10595. #ifdef CPPHTTPLIB_SSL_ENABLED
  10596. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10598. ASSERT_TRUE(svr.is_valid());
  10599. // Set up a handler to verify client certificate is present
  10600. bool client_cert_verified = false;
  10601. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10602. // Verify that client certificate was provided
  10603. client_cert_verified = true;
  10604. res.set_content("success", "text/plain");
  10605. });
  10606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10607. auto se = detail::scope_exit([&] {
  10608. svr.stop();
  10609. t.join();
  10610. ASSERT_FALSE(svr.is_running());
  10611. });
  10612. svr.wait_until_ready();
  10613. // Client with certificate
  10614. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10615. cli.enable_server_certificate_verification(false);
  10616. cli.set_connection_timeout(30);
  10617. auto res = cli.Get("/test");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. ASSERT_EQ(StatusCode::OK_200, res->status);
  10620. ASSERT_TRUE(client_cert_verified);
  10621. EXPECT_EQ("success", res->body);
  10622. }
  10623. #endif
  10624. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10625. // backends
  10626. #ifdef CPPHTTPLIB_SSL_ENABLED
  10627. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10628. using namespace httplib::tls;
  10629. // Test that when client CA cert file is provided,
  10630. // the server properly requests and validates client certificates
  10631. // Create a server with client authentication
  10632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10633. ASSERT_TRUE(svr.is_valid());
  10634. bool handler_called = false;
  10635. svr.Get("/test", [&](const Request &req, Response &res) {
  10636. handler_called = true;
  10637. // Verify that a client certificate was provided
  10638. auto cert = req.peer_cert();
  10639. ASSERT_TRUE(static_cast<bool>(cert));
  10640. // Get the issuer name
  10641. std::string issuer_str = cert.issuer_name();
  10642. ASSERT_FALSE(issuer_str.empty());
  10643. // The client certificate should be issued by our test CA
  10644. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10645. res.set_content("authenticated", "text/plain");
  10646. });
  10647. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. t.join();
  10651. ASSERT_FALSE(svr.is_running());
  10652. });
  10653. svr.wait_until_ready();
  10654. // Connect with a client certificate issued by the CA
  10655. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10656. cli.enable_server_certificate_verification(false);
  10657. cli.set_connection_timeout(30);
  10658. auto res = cli.Get("/test");
  10659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10660. ASSERT_EQ(StatusCode::OK_200, res->status);
  10661. ASSERT_TRUE(handler_called);
  10662. EXPECT_EQ("authenticated", res->body);
  10663. }
  10664. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10665. using namespace httplib::tls;
  10666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10667. ASSERT_TRUE(svr.is_valid());
  10668. svr.Get("/test", [](const Request &, Response &res) {
  10669. res.set_content("ok", "text/plain");
  10670. });
  10671. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10672. auto se = detail::scope_exit([&] {
  10673. svr.stop();
  10674. t.join();
  10675. });
  10676. svr.wait_until_ready();
  10677. SSLClient cli(HOST, PORT);
  10678. cli.enable_server_certificate_verification(false);
  10679. cli.set_connection_timeout(30);
  10680. bool cert_checked = false;
  10681. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10682. if (ctx.cert) {
  10683. auto sans = ctx.sans();
  10684. // Test certificate may or may not have SANs - just verify the API
  10685. // works If SANs exist, verify the types are valid
  10686. for (const auto &san : sans) {
  10687. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10688. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10689. san.type == SanType::OTHER);
  10690. EXPECT_FALSE(san.value.empty());
  10691. }
  10692. cert_checked = true;
  10693. }
  10694. return true;
  10695. });
  10696. auto res = cli.Get("/test");
  10697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10698. EXPECT_TRUE(cert_checked);
  10699. }
  10700. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10701. using namespace httplib::tls;
  10702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10703. ASSERT_TRUE(svr.is_valid());
  10704. svr.Get("/test", [](const Request &, Response &res) {
  10705. res.set_content("ok", "text/plain");
  10706. });
  10707. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10708. auto se = detail::scope_exit([&] {
  10709. svr.stop();
  10710. t.join();
  10711. });
  10712. svr.wait_until_ready();
  10713. SSLClient cli(HOST, PORT);
  10714. cli.enable_server_certificate_verification(false);
  10715. cli.set_connection_timeout(30);
  10716. bool validity_checked = false;
  10717. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10718. if (ctx.cert) {
  10719. time_t not_before = 0, not_after = 0;
  10720. bool result = ctx.validity(not_before, not_after);
  10721. EXPECT_TRUE(result);
  10722. // Verify that not_before < now < not_after for a valid cert
  10723. time_t now = time(nullptr);
  10724. EXPECT_LT(not_before, now);
  10725. EXPECT_GT(not_after, now);
  10726. validity_checked = true;
  10727. }
  10728. return true;
  10729. });
  10730. auto res = cli.Get("/test");
  10731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10732. EXPECT_TRUE(validity_checked);
  10733. }
  10734. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10735. using namespace httplib::tls;
  10736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10737. ASSERT_TRUE(svr.is_valid());
  10738. svr.Get("/test", [](const Request &, Response &res) {
  10739. res.set_content("ok", "text/plain");
  10740. });
  10741. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10742. auto se = detail::scope_exit([&] {
  10743. svr.stop();
  10744. t.join();
  10745. });
  10746. svr.wait_until_ready();
  10747. SSLClient cli(HOST, PORT);
  10748. cli.enable_server_certificate_verification(false);
  10749. cli.set_connection_timeout(30);
  10750. bool serial_checked = false;
  10751. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10752. if (ctx.cert) {
  10753. std::string serial = ctx.serial();
  10754. EXPECT_FALSE(serial.empty());
  10755. // Serial should be a hex string
  10756. for (char c : serial) {
  10757. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10758. (c >= 'a' && c <= 'f'));
  10759. }
  10760. serial_checked = true;
  10761. }
  10762. return true;
  10763. });
  10764. auto res = cli.Get("/test");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. EXPECT_TRUE(serial_checked);
  10767. }
  10768. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10769. // Test 1: Valid CA file - no error should be recorded
  10770. {
  10771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10772. CLIENT_CA_CERT_FILE);
  10773. ASSERT_TRUE(svr.is_valid());
  10774. // With valid setup, last_ssl_error should be 0
  10775. EXPECT_EQ(0, svr.ssl_last_error());
  10776. }
  10777. // Test 2: Invalid CA file content
  10778. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10779. {
  10780. // Create a temporary file with completely invalid content
  10781. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10782. {
  10783. std::ofstream ofs(temp_invalid_ca);
  10784. ofs << "This is not a certificate file at all\n";
  10785. ofs << "Just plain text content\n";
  10786. }
  10787. // Create server with invalid CA file
  10788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10789. // Clean up temporary file
  10790. std::remove(temp_invalid_ca);
  10791. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10792. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10793. // Note: SSL_CTX_load_verify_locations typically fails first,
  10794. // but our error handling code path is still exercised
  10795. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10796. }
  10797. }
  10798. TEST(VerifyCallbackTest, VerifyContextFields) {
  10799. using namespace httplib::tls;
  10800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10801. ASSERT_TRUE(svr.is_valid());
  10802. svr.Get("/test", [](const Request &, Response &res) {
  10803. res.set_content("ok", "text/plain");
  10804. });
  10805. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10806. auto se = detail::scope_exit([&] {
  10807. svr.stop();
  10808. t.join();
  10809. });
  10810. svr.wait_until_ready();
  10811. SSLClient cli(HOST, PORT);
  10812. cli.enable_server_certificate_verification(false);
  10813. cli.set_connection_timeout(30);
  10814. int callback_count = 0;
  10815. bool saw_leaf_cert = false;
  10816. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10817. if (ctx.cert) {
  10818. callback_count++;
  10819. // We should see at least one certificate (the leaf)
  10820. std::string cn = ctx.subject_cn();
  10821. if (!cn.empty()) { saw_leaf_cert = true; }
  10822. // Verify context fields are populated
  10823. EXPECT_NE(ctx.session, nullptr);
  10824. EXPECT_GE(ctx.depth, 0);
  10825. }
  10826. return true;
  10827. });
  10828. auto res = cli.Get("/test");
  10829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10830. EXPECT_GT(callback_count, 0);
  10831. EXPECT_TRUE(saw_leaf_cert);
  10832. }
  10833. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10834. using httplib::tls::TlsError;
  10835. // Test that verify_error_to_string returns empty for success
  10836. std::string success_str = TlsError::verify_error_to_string(0);
  10837. EXPECT_TRUE(success_str.empty());
  10838. // Test that verify_error_to_string returns non-empty for error codes
  10839. // Using a common error code (certificate expired)
  10840. std::string error_str =
  10841. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10842. EXPECT_FALSE(error_str.empty());
  10843. }
  10844. TEST(SessionVerifierTest, CertificateAccepted) {
  10845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10846. ASSERT_TRUE(svr.is_valid());
  10847. svr.Get("/test", [](const Request &, Response &res) {
  10848. res.set_content("ok", "text/plain");
  10849. });
  10850. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10851. auto se = detail::scope_exit([&] {
  10852. svr.stop();
  10853. t.join();
  10854. });
  10855. svr.wait_until_ready();
  10856. SSLClient cli(HOST, PORT);
  10857. cli.enable_server_certificate_verification(false);
  10858. cli.set_connection_timeout(30);
  10859. bool callback_called = false;
  10860. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10861. EXPECT_NE(session, nullptr);
  10862. callback_called = true;
  10863. return SSLVerifierResponse::CertificateAccepted;
  10864. });
  10865. auto res = cli.Get("/test");
  10866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10867. EXPECT_EQ(200, res->status);
  10868. EXPECT_TRUE(callback_called);
  10869. }
  10870. TEST(SessionVerifierTest, CertificateRejected) {
  10871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10872. ASSERT_TRUE(svr.is_valid());
  10873. svr.Get("/test", [](const Request &, Response &res) {
  10874. res.set_content("ok", "text/plain");
  10875. });
  10876. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10877. auto se = detail::scope_exit([&] {
  10878. svr.stop();
  10879. t.join();
  10880. });
  10881. svr.wait_until_ready();
  10882. SSLClient cli(HOST, PORT);
  10883. cli.enable_server_certificate_verification(false);
  10884. cli.set_connection_timeout(30);
  10885. bool callback_called = false;
  10886. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10887. EXPECT_NE(session, nullptr);
  10888. callback_called = true;
  10889. return SSLVerifierResponse::CertificateRejected;
  10890. });
  10891. auto res = cli.Get("/test");
  10892. EXPECT_FALSE(res);
  10893. EXPECT_TRUE(callback_called);
  10894. }
  10895. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10897. ASSERT_TRUE(svr.is_valid());
  10898. svr.Get("/test", [](const Request &, Response &res) {
  10899. res.set_content("ok", "text/plain");
  10900. });
  10901. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10902. auto se = detail::scope_exit([&] {
  10903. svr.stop();
  10904. t.join();
  10905. });
  10906. svr.wait_until_ready();
  10907. // NoDecisionMade with verification disabled should succeed (no default check)
  10908. SSLClient cli(HOST, PORT);
  10909. cli.enable_server_certificate_verification(false);
  10910. cli.set_connection_timeout(30);
  10911. bool callback_called = false;
  10912. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10913. EXPECT_NE(session, nullptr);
  10914. callback_called = true;
  10915. return SSLVerifierResponse::NoDecisionMade;
  10916. });
  10917. auto res = cli.Get("/test");
  10918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10919. EXPECT_EQ(200, res->status);
  10920. EXPECT_TRUE(callback_called);
  10921. }
  10922. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10923. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10924. ASSERT_TRUE(svr.is_valid());
  10925. svr.Get("/test", [](const Request &, Response &res) {
  10926. res.set_content("ok", "text/plain");
  10927. });
  10928. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10929. auto se = detail::scope_exit([&] {
  10930. svr.stop();
  10931. t.join();
  10932. });
  10933. svr.wait_until_ready();
  10934. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10935. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10936. // so we only check that the request fails, not whether the callback was
  10937. // called.
  10938. SSLClient cli(HOST, PORT);
  10939. cli.enable_server_certificate_verification(true);
  10940. cli.set_connection_timeout(30);
  10941. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10942. EXPECT_NE(session, nullptr);
  10943. return SSLVerifierResponse::NoDecisionMade;
  10944. });
  10945. auto res = cli.Get("/test");
  10946. EXPECT_FALSE(res);
  10947. }
  10948. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10949. // Test SSL server using PemMemory constructor with client CA certificates
  10950. // Read PEM files
  10951. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10952. read_file(SERVER_CERT_FILE, server_cert_pem);
  10953. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10954. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10955. // Create SSLServer with PemMemory constructor including client CA
  10956. SSLServer::PemMemory server_pem = {
  10957. server_cert_pem.c_str(),
  10958. server_cert_pem.size(),
  10959. server_key_pem.c_str(),
  10960. server_key_pem.size(),
  10961. client_ca_pem.c_str(),
  10962. client_ca_pem.size(),
  10963. nullptr // no password for server key
  10964. };
  10965. SSLServer svr(server_pem);
  10966. ASSERT_TRUE(svr.is_valid());
  10967. // No SSL error should be recorded for valid setup
  10968. EXPECT_EQ(0, svr.ssl_last_error());
  10969. // Set up server endpoints
  10970. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10971. res.set_content("ok", "text/plain");
  10972. });
  10973. // Start server in a thread
  10974. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10975. svr.wait_until_ready();
  10976. // Connect with client certificate (using constructor with paths)
  10977. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10978. cli.enable_server_certificate_verification(false);
  10979. auto res = cli.Get("/test-pem-ca");
  10980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10981. EXPECT_EQ(200, res->status);
  10982. EXPECT_EQ("ok", res->body);
  10983. svr.stop();
  10984. server_thread.join();
  10985. }
  10986. #endif
  10987. #ifdef _WIN32
  10988. TEST(CleanupTest, WSACleanup) {
  10989. int ret = WSACleanup();
  10990. ASSERT_EQ(0, ret);
  10991. }
  10992. #endif
  10993. #ifndef CPPHTTPLIB_SSL_ENABLED
  10994. TEST(NoSSLSupport, SimpleInterface) {
  10995. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10996. }
  10997. #endif
  10998. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10999. TEST(InvalidScheme, SimpleInterface) {
  11000. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  11001. }
  11002. #endif
  11003. TEST(NoScheme, SimpleInterface) {
  11004. Client cli("yahoo.com:80");
  11005. ASSERT_TRUE(cli.is_valid());
  11006. }
  11007. TEST(SendAPI, SimpleInterface_Online) {
  11008. Client cli("http://yahoo.com");
  11009. Request req;
  11010. req.method = "GET";
  11011. req.path = "/";
  11012. auto res = cli.send(req);
  11013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11014. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11015. }
  11016. TEST(SendAPI, WithParamsInRequest) {
  11017. Server svr;
  11018. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  11019. EXPECT_TRUE(req.has_param("test"));
  11020. EXPECT_EQ("test_value", req.get_param_value("test"));
  11021. });
  11022. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11023. auto se = detail::scope_exit([&] {
  11024. svr.stop();
  11025. t.join();
  11026. ASSERT_FALSE(svr.is_running());
  11027. });
  11028. svr.wait_until_ready();
  11029. Client cli(HOST, PORT);
  11030. {
  11031. Request req;
  11032. req.method = "GET";
  11033. req.path = "/";
  11034. req.params.emplace("test", "test_value");
  11035. auto res = cli.send(req);
  11036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11037. }
  11038. {
  11039. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  11040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11041. }
  11042. }
  11043. TEST(ClientImplMethods, GetSocketTest) {
  11044. httplib::Server svr;
  11045. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11046. res.status = StatusCode::OK_200;
  11047. });
  11048. auto port = svr.bind_to_any_port("127.0.0.1");
  11049. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11050. auto se = detail::scope_exit([&] {
  11051. svr.stop();
  11052. thread.join();
  11053. ASSERT_FALSE(svr.is_running());
  11054. });
  11055. svr.wait_until_ready();
  11056. {
  11057. httplib::Client cli("127.0.0.1", port);
  11058. cli.set_keep_alive(true);
  11059. // Use the behavior of cpp-httplib of opening the connection
  11060. // only when the first request happens. If that changes,
  11061. // this test would be obsolete.
  11062. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  11063. // This also implicitly tests the server. But other tests would fail much
  11064. // earlier than this one to be considered.
  11065. auto res = cli.Get("/");
  11066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11067. EXPECT_EQ(StatusCode::OK_200, res->status);
  11068. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  11069. }
  11070. }
  11071. #ifdef CPPHTTPLIB_SSL_ENABLED
  11072. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  11073. Client cli("http://yahoo.com");
  11074. auto res = cli.Get("/");
  11075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11076. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11077. cli.set_follow_location(true);
  11078. res = cli.Get("/");
  11079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11080. EXPECT_EQ(StatusCode::OK_200, res->status);
  11081. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11082. }
  11083. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  11084. Client cli("https://yahoo.com");
  11085. auto res = cli.Get("/");
  11086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11087. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11088. cli.set_follow_location(true);
  11089. res = cli.Get("/");
  11090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11091. EXPECT_EQ(StatusCode::OK_200, res->status);
  11092. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11093. }
  11094. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  11095. Client cli("https://yahoo.com");
  11096. auto res = cli.Get("/");
  11097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11098. ASSERT_FALSE(!res);
  11099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11100. ASSERT_FALSE(res == nullptr);
  11101. ASSERT_TRUE(res != nullptr);
  11102. EXPECT_EQ(Error::Success, res.error());
  11103. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  11104. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  11105. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11106. cli.set_follow_location(true);
  11107. res = cli.Get("/");
  11108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11109. EXPECT_EQ(Error::Success, res.error());
  11110. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  11111. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  11112. EXPECT_EQ(StatusCode::OK_200, res->status);
  11113. EXPECT_EQ("https://www.yahoo.com/", res->location);
  11114. }
  11115. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11116. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  11117. Client cli("https://cdnjs.cloudflare.com");
  11118. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  11119. Headers{{"Accept-Encoding", "br"}});
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. EXPECT_EQ(StatusCode::OK_200, res->status);
  11122. EXPECT_EQ(287630U, res->body.size());
  11123. EXPECT_EQ("application/javascript; charset=utf-8",
  11124. res->get_header_value("Content-Type"));
  11125. }
  11126. #endif
  11127. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  11128. #undef REDIR_HOST // Silence compiler warning
  11129. #define REDIR_HOST "https://httpbingo.org"
  11130. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  11131. Client cli(REDIR_HOST);
  11132. cli.set_follow_location(true);
  11133. auto res =
  11134. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  11135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11136. EXPECT_EQ(StatusCode::OK_200, res->status);
  11137. }
  11138. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  11139. Client cli(REDIR_HOST);
  11140. cli.set_follow_location(true);
  11141. Params params;
  11142. params.emplace("url", "http://example.com");
  11143. params.emplace("status_code", "302");
  11144. auto res = cli.Get(REDIR_PATH, params, Headers{});
  11145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11146. EXPECT_EQ(StatusCode::OK_200, res->status);
  11147. }
  11148. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  11149. Client cli(REDIR_HOST);
  11150. cli.set_follow_location(true);
  11151. Params params;
  11152. params.emplace("url", "http://example.com");
  11153. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  11154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11155. EXPECT_EQ(StatusCode::OK_200, res->status);
  11156. }
  11157. TEST(HttpToHttpsRedirectTest, CertFile) {
  11158. auto ssl_port = PORT + 1;
  11159. Server svr;
  11160. ASSERT_TRUE(svr.is_valid());
  11161. svr.Get("/index", [&](const Request &, Response &res) {
  11162. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11163. "/index");
  11164. svr.stop();
  11165. });
  11166. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11167. ASSERT_TRUE(ssl_svr.is_valid());
  11168. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  11169. res.set_content("test", "text/plain");
  11170. ssl_svr.stop();
  11171. });
  11172. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11173. thread t2 =
  11174. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  11175. auto se = detail::scope_exit([&] {
  11176. t2.join();
  11177. t.join();
  11178. ASSERT_FALSE(svr.is_running());
  11179. });
  11180. svr.wait_until_ready();
  11181. ssl_svr.wait_until_ready();
  11182. Client cli("127.0.0.1", PORT);
  11183. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11184. cli.enable_server_certificate_verification(true);
  11185. cli.set_follow_location(true);
  11186. cli.set_connection_timeout(30);
  11187. auto res = cli.Get("/index");
  11188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11189. ASSERT_EQ(StatusCode::OK_200, res->status);
  11190. }
  11191. TEST(SSLClientRedirectTest, CertFile) {
  11192. auto ssl_port = PORT + 1;
  11193. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11194. ASSERT_TRUE(ssl_svr1.is_valid());
  11195. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11196. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11197. "/index");
  11198. ssl_svr1.stop();
  11199. });
  11200. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11201. ASSERT_TRUE(ssl_svr2.is_valid());
  11202. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11203. res.set_content("test", "text/plain");
  11204. ssl_svr2.stop();
  11205. });
  11206. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11207. thread t2 =
  11208. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11209. auto se = detail::scope_exit([&] {
  11210. t2.join();
  11211. t.join();
  11212. ASSERT_FALSE(ssl_svr1.is_running());
  11213. });
  11214. ssl_svr1.wait_until_ready();
  11215. ssl_svr2.wait_until_ready();
  11216. SSLClient cli("127.0.0.1", PORT);
  11217. std::string cert;
  11218. read_file(SERVER_CERT2_FILE, cert);
  11219. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11220. cli.enable_server_certificate_verification(true);
  11221. cli.set_follow_location(true);
  11222. cli.set_connection_timeout(30);
  11223. auto res = cli.Get("/index");
  11224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11225. ASSERT_EQ(StatusCode::OK_200, res->status);
  11226. }
  11227. #endif
  11228. #ifdef CPPHTTPLIB_SSL_ENABLED
  11229. // Test that set_ca_cert_store() skips system certs (consistent with
  11230. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  11231. // should be trusted - system certs should NOT be loaded.
  11232. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  11233. // Load a specific cert that is NOT a system CA cert
  11234. std::string cert;
  11235. read_file(SERVER_CERT2_FILE, cert);
  11236. SSLClient cli("google.com");
  11237. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11238. cli.enable_server_certificate_verification(true);
  11239. // This should FAIL because:
  11240. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  11241. // 2. System certs should NOT be loaded when custom store is set
  11242. // If system certs WERE loaded, this would succeed
  11243. auto res = cli.Get("/");
  11244. ASSERT_FALSE(res);
  11245. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11246. }
  11247. // Same as above, but through the native store handle path. Regression test:
  11248. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  11249. // merged system certs into the user-provided store.
  11250. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  11251. std::string cert;
  11252. read_file(SERVER_CERT2_FILE, cert);
  11253. SSLClient cli("google.com");
  11254. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11255. cli.enable_server_certificate_verification(true);
  11256. auto res = cli.Get("/");
  11257. ASSERT_FALSE(res);
  11258. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11259. }
  11260. // A custom store set via the native handle must still verify a server whose
  11261. // cert it does contain.
  11262. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  11263. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11264. ASSERT_TRUE(svr.is_valid());
  11265. svr.Get("/test", [&](const Request &, Response &res) {
  11266. res.set_content("test", "text/plain");
  11267. });
  11268. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11269. auto se = detail::scope_exit([&] {
  11270. svr.stop();
  11271. t.join();
  11272. ASSERT_FALSE(svr.is_running());
  11273. });
  11274. svr.wait_until_ready();
  11275. SSLClient cli("127.0.0.1", PORT);
  11276. std::string cert;
  11277. read_file(SERVER_CERT2_FILE, cert);
  11278. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  11279. cli.enable_server_certificate_verification(true);
  11280. cli.set_connection_timeout(30);
  11281. auto res = cli.Get("/test");
  11282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11283. ASSERT_EQ(StatusCode::OK_200, res->status);
  11284. }
  11285. // CA certs loaded through the universal Client must be transferred to the
  11286. // client created internally for following an HTTPS redirect. Regression test:
  11287. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  11288. // the CA data for redirect transfer.
  11289. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  11290. auto ssl_port = PORT + 1;
  11291. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11292. ASSERT_TRUE(ssl_svr1.is_valid());
  11293. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  11294. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  11295. "/index");
  11296. });
  11297. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11298. ASSERT_TRUE(ssl_svr2.is_valid());
  11299. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  11300. res.set_content("test", "text/plain");
  11301. });
  11302. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  11303. thread t2 =
  11304. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  11305. auto se = detail::scope_exit([&] {
  11306. ssl_svr2.stop();
  11307. ssl_svr1.stop();
  11308. t2.join();
  11309. t.join();
  11310. ASSERT_FALSE(ssl_svr1.is_running());
  11311. });
  11312. ssl_svr1.wait_until_ready();
  11313. ssl_svr2.wait_until_ready();
  11314. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11315. std::string cert;
  11316. read_file(SERVER_CERT2_FILE, cert);
  11317. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11318. cli.enable_server_certificate_verification(true);
  11319. cli.set_follow_location(true);
  11320. cli.set_connection_timeout(30);
  11321. auto res = cli.Get("/index");
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. ASSERT_EQ(StatusCode::OK_200, res->status);
  11324. }
  11325. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  11326. // so a host signed by a system CA verifies even though a custom CA is set
  11327. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  11328. std::string cert;
  11329. read_file(SERVER_CERT2_FILE, cert);
  11330. SSLClient cli("google.com");
  11331. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11332. cli.enable_system_ca(true);
  11333. cli.enable_server_certificate_verification(true);
  11334. auto res = cli.Get("/");
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11337. }
  11338. // The custom CA remains effective when combined with the system CA
  11339. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  11340. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11341. ASSERT_TRUE(svr.is_valid());
  11342. svr.Get("/test", [&](const Request &, Response &res) {
  11343. res.set_content("test", "text/plain");
  11344. });
  11345. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11346. auto se = detail::scope_exit([&] {
  11347. svr.stop();
  11348. t.join();
  11349. ASSERT_FALSE(svr.is_running());
  11350. });
  11351. svr.wait_until_ready();
  11352. SSLClient cli("127.0.0.1", PORT);
  11353. std::string cert;
  11354. read_file(SERVER_CERT2_FILE, cert);
  11355. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11356. cli.enable_system_ca(true);
  11357. cli.enable_server_certificate_verification(true);
  11358. cli.set_connection_timeout(30);
  11359. auto res = cli.Get("/test");
  11360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11361. ASSERT_EQ(StatusCode::OK_200, res->status);
  11362. }
  11363. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11364. // skip chain verification entirely (only the certificate identity was
  11365. // checked), so a server presenting an untrusted certificate with a matching
  11366. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11367. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11368. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11369. ASSERT_TRUE(svr.is_valid());
  11370. svr.Get("/test", [&](const Request &, Response &res) {
  11371. res.set_content("test", "text/plain");
  11372. });
  11373. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11374. auto se = detail::scope_exit([&] {
  11375. svr.stop();
  11376. t.join();
  11377. ASSERT_FALSE(svr.is_running());
  11378. });
  11379. svr.wait_until_ready();
  11380. SSLClient cli("127.0.0.1", PORT);
  11381. std::string cert;
  11382. // A trusted CA that did not sign the server certificate. The server cert
  11383. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11384. // this connection.
  11385. read_file(CLIENT_CA_CERT_FILE, cert);
  11386. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11387. cli.enable_server_certificate_verification(true);
  11388. cli.set_connection_timeout(30);
  11389. auto res = cli.Get("/test");
  11390. ASSERT_FALSE(res);
  11391. }
  11392. // enable_system_ca(false) prevents system CA loading entirely
  11393. TEST(SSLClientTest, DisableSystemCa_Online) {
  11394. SSLClient cli("google.com");
  11395. cli.enable_system_ca(false);
  11396. cli.enable_server_certificate_verification(true);
  11397. auto res = cli.Get("/");
  11398. ASSERT_FALSE(res);
  11399. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11400. // itself when the CA chain is empty
  11401. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11402. res.error() == Error::SSLConnection);
  11403. }
  11404. // The universal Client forwards enable_system_ca()
  11405. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11406. std::string cert;
  11407. read_file(SERVER_CERT2_FILE, cert);
  11408. Client cli("https://google.com");
  11409. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11410. cli.enable_system_ca(true);
  11411. cli.enable_server_certificate_verification(true);
  11412. auto res = cli.Get("/");
  11413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11414. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11415. }
  11416. // The system CA policy must carry over to the client created internally for
  11417. // following a cross-host HTTPS redirect
  11418. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11419. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11420. ASSERT_TRUE(svr.is_valid());
  11421. svr.Get("/index", [&](const Request &, Response &res) {
  11422. res.set_redirect("https://www.google.com/");
  11423. });
  11424. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11425. auto se = detail::scope_exit([&] {
  11426. svr.stop();
  11427. t.join();
  11428. ASSERT_FALSE(svr.is_running());
  11429. });
  11430. svr.wait_until_ready();
  11431. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11432. std::string cert;
  11433. read_file(SERVER_CERT2_FILE, cert);
  11434. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11435. cli.enable_system_ca(true);
  11436. cli.enable_server_certificate_verification(true);
  11437. cli.set_follow_location(true);
  11438. cli.set_connection_timeout(30);
  11439. // Receiving any response proves the redirect client completed the TLS
  11440. // handshake with a system-CA-signed host
  11441. auto res = cli.Get("/index");
  11442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11443. }
  11444. TEST(MultipartFormDataTest, LargeData) {
  11445. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11446. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11447. const ContentReader &content_reader) {
  11448. if (req.is_multipart_form_data()) {
  11449. std::vector<FormData> items;
  11450. content_reader(
  11451. [&](const FormData &file) {
  11452. items.push_back(file);
  11453. return true;
  11454. },
  11455. [&](const char *data, size_t data_length) {
  11456. items.back().content.append(data, data_length);
  11457. return true;
  11458. });
  11459. EXPECT_TRUE(std::string(items[0].name) == "document");
  11460. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11461. EXPECT_TRUE(items[0].filename == "2MB_data");
  11462. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11463. EXPECT_TRUE(items[1].name == "hello");
  11464. EXPECT_TRUE(items[1].content == "world");
  11465. EXPECT_TRUE(items[1].filename == "");
  11466. EXPECT_TRUE(items[1].content_type == "");
  11467. } else {
  11468. std::string body;
  11469. content_reader([&](const char *data, size_t data_length) {
  11470. body.append(data, data_length);
  11471. return true;
  11472. });
  11473. }
  11474. });
  11475. auto port = svr.bind_to_any_port(HOST);
  11476. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11477. auto se = detail::scope_exit([&] {
  11478. svr.stop();
  11479. t.join();
  11480. ASSERT_FALSE(svr.is_running());
  11481. });
  11482. svr.wait_until_ready();
  11483. {
  11484. std::string data(1024 * 1024 * 2, '.');
  11485. std::stringstream buffer;
  11486. buffer << data;
  11487. SSLClient cli(HOST, port);
  11488. cli.enable_server_certificate_verification(false);
  11489. UploadFormDataItems items{
  11490. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11491. {"hello", "world", "", ""},
  11492. };
  11493. auto res = cli.Post("/post", items);
  11494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11495. ASSERT_EQ(StatusCode::OK_200, res->status);
  11496. }
  11497. }
  11498. TEST(MultipartFormDataTest, DataProviderItems) {
  11499. std::random_device seed_gen;
  11500. std::mt19937 random(seed_gen());
  11501. std::string rand1;
  11502. rand1.resize(1000);
  11503. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11504. std::string rand2;
  11505. rand2.resize(3000);
  11506. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11508. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11509. const ContentReader &content_reader) {
  11510. ASSERT_FALSE(req.is_multipart_form_data());
  11511. std::string body;
  11512. content_reader([&](const char *data, size_t data_length) {
  11513. body.append(data, data_length);
  11514. return true;
  11515. });
  11516. EXPECT_EQ(body, "");
  11517. });
  11518. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11519. const ContentReader &content_reader) {
  11520. ASSERT_TRUE(req.is_multipart_form_data());
  11521. std::vector<FormData> items;
  11522. content_reader(
  11523. [&](const FormData &file) {
  11524. items.push_back(file);
  11525. return true;
  11526. },
  11527. [&](const char *data, size_t data_length) {
  11528. items.back().content.append(data, data_length);
  11529. return true;
  11530. });
  11531. ASSERT_TRUE(items.size() == 2);
  11532. EXPECT_EQ(std::string(items[0].name), "name1");
  11533. EXPECT_EQ(items[0].content, "Testing123");
  11534. EXPECT_EQ(items[0].filename, "filename1");
  11535. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11536. EXPECT_EQ(items[1].name, "name2");
  11537. EXPECT_EQ(items[1].content, "Testing456");
  11538. EXPECT_EQ(items[1].filename, "");
  11539. EXPECT_EQ(items[1].content_type, "");
  11540. });
  11541. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11542. const ContentReader &content_reader) {
  11543. ASSERT_TRUE(req.is_multipart_form_data());
  11544. std::vector<FormData> items;
  11545. content_reader(
  11546. [&](const FormData &file) {
  11547. items.push_back(file);
  11548. return true;
  11549. },
  11550. [&](const char *data, size_t data_length) {
  11551. items.back().content.append(data, data_length);
  11552. return true;
  11553. });
  11554. ASSERT_TRUE(items.size() == 2);
  11555. EXPECT_EQ(items[0].name, "name3");
  11556. EXPECT_EQ(items[0].content, rand1);
  11557. EXPECT_EQ(items[0].filename, "filename3");
  11558. EXPECT_EQ(items[0].content_type, "");
  11559. EXPECT_EQ(items[1].name, "name4");
  11560. EXPECT_EQ(items[1].content, rand2);
  11561. EXPECT_EQ(items[1].filename, "filename4");
  11562. EXPECT_EQ(items[1].content_type, "");
  11563. });
  11564. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11565. const ContentReader &content_reader) {
  11566. ASSERT_TRUE(req.is_multipart_form_data());
  11567. std::vector<FormData> items;
  11568. content_reader(
  11569. [&](const FormData &file) {
  11570. items.push_back(file);
  11571. return true;
  11572. },
  11573. [&](const char *data, size_t data_length) {
  11574. items.back().content.append(data, data_length);
  11575. return true;
  11576. });
  11577. ASSERT_TRUE(items.size() == 4);
  11578. EXPECT_EQ(std::string(items[0].name), "name1");
  11579. EXPECT_EQ(items[0].content, "Testing123");
  11580. EXPECT_EQ(items[0].filename, "filename1");
  11581. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11582. EXPECT_EQ(items[1].name, "name2");
  11583. EXPECT_EQ(items[1].content, "Testing456");
  11584. EXPECT_EQ(items[1].filename, "");
  11585. EXPECT_EQ(items[1].content_type, "");
  11586. EXPECT_EQ(items[2].name, "name3");
  11587. EXPECT_EQ(items[2].content, rand1);
  11588. EXPECT_EQ(items[2].filename, "filename3");
  11589. EXPECT_EQ(items[2].content_type, "");
  11590. EXPECT_EQ(items[3].name, "name4");
  11591. EXPECT_EQ(items[3].content, rand2);
  11592. EXPECT_EQ(items[3].filename, "filename4");
  11593. EXPECT_EQ(items[3].content_type, "");
  11594. });
  11595. auto port = svr.bind_to_any_port("localhost");
  11596. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11597. auto se = detail::scope_exit([&] {
  11598. svr.stop();
  11599. t.join();
  11600. ASSERT_FALSE(svr.is_running());
  11601. });
  11602. svr.wait_until_ready();
  11603. {
  11604. SSLClient cli("localhost", port);
  11605. cli.enable_server_certificate_verification(false);
  11606. UploadFormDataItems items{
  11607. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11608. {"name2", "Testing456", "", ""}, // not a file
  11609. };
  11610. {
  11611. auto res = cli.Post("/post-none", {}, {}, {});
  11612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11613. ASSERT_EQ(StatusCode::OK_200, res->status);
  11614. }
  11615. FormDataProviderItems providers;
  11616. {
  11617. auto res =
  11618. cli.Post("/post-items", {}, items, providers); // empty providers
  11619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11620. ASSERT_EQ(StatusCode::OK_200, res->status);
  11621. }
  11622. providers.push_back({"name3",
  11623. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11624. // test the offset is given correctly at each step
  11625. if (!offset)
  11626. sink.os.write(rand1.data(), 30);
  11627. else if (offset == 30)
  11628. sink.os.write(rand1.data() + 30, 300);
  11629. else if (offset == 330)
  11630. sink.os.write(rand1.data() + 330, 670);
  11631. else if (offset == rand1.size())
  11632. sink.done();
  11633. return true;
  11634. },
  11635. "filename3",
  11636. {}});
  11637. providers.push_back({"name4",
  11638. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11639. // test the offset is given correctly at each step
  11640. if (!offset)
  11641. sink.os.write(rand2.data(), 2000);
  11642. else if (offset == 2000)
  11643. sink.os.write(rand2.data() + 2000, 1);
  11644. else if (offset == 2001)
  11645. sink.os.write(rand2.data() + 2001, 999);
  11646. else if (offset == rand2.size())
  11647. sink.done();
  11648. return true;
  11649. },
  11650. "filename4",
  11651. {}});
  11652. {
  11653. auto res = cli.Post("/post-providers", {}, {}, providers);
  11654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11655. ASSERT_EQ(StatusCode::OK_200, res->status);
  11656. }
  11657. {
  11658. auto res = cli.Post("/post-both", {}, items, providers);
  11659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11660. ASSERT_EQ(StatusCode::OK_200, res->status);
  11661. }
  11662. }
  11663. }
  11664. TEST(MultipartFormDataTest, BadHeader) {
  11665. Server svr;
  11666. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11667. res.set_content("ok", "text/plain");
  11668. });
  11669. thread t = thread([&] { svr.listen(HOST, PORT); });
  11670. auto se = detail::scope_exit([&] {
  11671. svr.stop();
  11672. t.join();
  11673. ASSERT_FALSE(svr.is_running());
  11674. });
  11675. svr.wait_until_ready();
  11676. const std::string body =
  11677. "This is the preamble. It is to be ignored, though it\r\n"
  11678. "is a handy place for composition agents to include an\r\n"
  11679. "explanatory note to non-MIME conformant readers.\r\n"
  11680. "\r\n"
  11681. "\r\n"
  11682. "--simple boundary\r\n"
  11683. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11684. ": BAD...\r\n"
  11685. "\r\n"
  11686. "value1\r\n"
  11687. "--simple boundary\r\n"
  11688. "Content-Disposition: form-data; name=\"field2\"; "
  11689. "filename=\"example.txt\"\r\n"
  11690. "\r\n"
  11691. "value2\r\n"
  11692. "--simple boundary--\r\n"
  11693. "This is the epilogue. It is also to be ignored.\r\n";
  11694. std::string content_type =
  11695. R"(multipart/form-data; boundary="simple boundary")";
  11696. Client cli(HOST, PORT);
  11697. auto res = cli.Post("/post", body, content_type.c_str());
  11698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11699. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11700. }
  11701. TEST(MultipartFormDataTest, WithPreamble) {
  11702. Server svr;
  11703. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11704. res.set_content("ok", "text/plain");
  11705. });
  11706. thread t = thread([&] { svr.listen(HOST, PORT); });
  11707. auto se = detail::scope_exit([&] {
  11708. svr.stop();
  11709. t.join();
  11710. ASSERT_FALSE(svr.is_running());
  11711. });
  11712. svr.wait_until_ready();
  11713. const std::string body =
  11714. "This is the preamble. It is to be ignored, though it\r\n"
  11715. "is a handy place for composition agents to include an\r\n"
  11716. "explanatory note to non-MIME conformant readers.\r\n"
  11717. "\r\n"
  11718. "\r\n"
  11719. "--simple boundary\r\n"
  11720. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11721. "\r\n"
  11722. "value1\r\n"
  11723. "--simple boundary\r\n"
  11724. "Content-Disposition: form-data; name=\"field2\"; "
  11725. "filename=\"example.txt\"\r\n"
  11726. "\r\n"
  11727. "value2\r\n"
  11728. "--simple boundary--\r\n"
  11729. "This is the epilogue. It is also to be ignored.\r\n";
  11730. std::string content_type =
  11731. R"(multipart/form-data; boundary="simple boundary")";
  11732. Client cli(HOST, PORT);
  11733. auto res = cli.Post("/post", body, content_type.c_str());
  11734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11735. EXPECT_EQ(StatusCode::OK_200, res->status);
  11736. }
  11737. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11739. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11740. const ContentReader &content_reader) {
  11741. if (req.is_multipart_form_data()) {
  11742. std::vector<FormData> items;
  11743. content_reader(
  11744. [&](const FormData &file) {
  11745. items.push_back(file);
  11746. return true;
  11747. },
  11748. [&](const char *data, size_t data_length) {
  11749. items.back().content.append(data, data_length);
  11750. return true;
  11751. });
  11752. EXPECT_TRUE(std::string(items[0].name) == "document");
  11753. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11754. EXPECT_TRUE(items[0].filename == "2MB_data");
  11755. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11756. EXPECT_TRUE(items[1].name == "hello");
  11757. EXPECT_TRUE(items[1].content == "world");
  11758. EXPECT_TRUE(items[1].filename == "");
  11759. EXPECT_TRUE(items[1].content_type == "");
  11760. } else {
  11761. std::string body;
  11762. content_reader([&](const char *data, size_t data_length) {
  11763. body.append(data, data_length);
  11764. return true;
  11765. });
  11766. }
  11767. });
  11768. auto port = svr.bind_to_any_port("localhost");
  11769. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11770. auto se = detail::scope_exit([&] {
  11771. svr.stop();
  11772. t.join();
  11773. ASSERT_FALSE(svr.is_running());
  11774. });
  11775. svr.wait_until_ready();
  11776. {
  11777. std::string data(1024 * 1024 * 2, '.');
  11778. std::stringstream buffer;
  11779. buffer << data;
  11780. SSLClient cli("localhost", port);
  11781. cli.enable_server_certificate_verification(false);
  11782. UploadFormDataItems items{
  11783. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11784. {"hello", "world", "", ""},
  11785. };
  11786. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11788. ASSERT_EQ(StatusCode::OK_200, res->status);
  11789. }
  11790. }
  11791. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11792. std::string data(1024 * 1024 * 2, '&');
  11793. std::stringstream buffer;
  11794. buffer << data;
  11795. Client cli("https://localhost:8080");
  11796. UploadFormDataItems items{
  11797. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11798. {"hello", "world", "", ""},
  11799. };
  11800. for (const char &c : " \t\r\n") {
  11801. auto res =
  11802. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11803. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11804. ASSERT_FALSE(res);
  11805. }
  11806. }
  11807. TEST(MultipartFormDataTest, PutFormData) {
  11808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11809. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11810. const ContentReader &content_reader) {
  11811. if (req.is_multipart_form_data()) {
  11812. std::vector<FormData> items;
  11813. content_reader(
  11814. [&](const FormData &file) {
  11815. items.push_back(file);
  11816. return true;
  11817. },
  11818. [&](const char *data, size_t data_length) {
  11819. items.back().content.append(data, data_length);
  11820. return true;
  11821. });
  11822. EXPECT_TRUE(std::string(items[0].name) == "document");
  11823. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11824. EXPECT_TRUE(items[0].filename == "2MB_data");
  11825. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11826. EXPECT_TRUE(items[1].name == "hello");
  11827. EXPECT_TRUE(items[1].content == "world");
  11828. EXPECT_TRUE(items[1].filename == "");
  11829. EXPECT_TRUE(items[1].content_type == "");
  11830. } else {
  11831. std::string body;
  11832. content_reader([&](const char *data, size_t data_length) {
  11833. body.append(data, data_length);
  11834. return true;
  11835. });
  11836. }
  11837. });
  11838. auto port = svr.bind_to_any_port("localhost");
  11839. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11840. auto se = detail::scope_exit([&] {
  11841. svr.stop();
  11842. t.join();
  11843. ASSERT_FALSE(svr.is_running());
  11844. });
  11845. svr.wait_until_ready();
  11846. {
  11847. std::string data(1024 * 1024 * 2, '&');
  11848. std::stringstream buffer;
  11849. buffer << data;
  11850. SSLClient cli("localhost", port);
  11851. cli.enable_server_certificate_verification(false);
  11852. UploadFormDataItems items{
  11853. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11854. {"hello", "world", "", ""},
  11855. };
  11856. auto res = cli.Put("/put", items);
  11857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11858. ASSERT_EQ(StatusCode::OK_200, res->status);
  11859. }
  11860. }
  11861. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11863. svr.Put("/put_customboundary",
  11864. [&](const Request &req, const Response & /*res*/,
  11865. const ContentReader &content_reader) {
  11866. if (req.is_multipart_form_data()) {
  11867. std::vector<FormData> items;
  11868. content_reader(
  11869. [&](const FormData &file) {
  11870. items.push_back(file);
  11871. return true;
  11872. },
  11873. [&](const char *data, size_t data_length) {
  11874. items.back().content.append(data, data_length);
  11875. return true;
  11876. });
  11877. EXPECT_TRUE(std::string(items[0].name) == "document");
  11878. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11879. EXPECT_TRUE(items[0].filename == "2MB_data");
  11880. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11881. EXPECT_TRUE(items[1].name == "hello");
  11882. EXPECT_TRUE(items[1].content == "world");
  11883. EXPECT_TRUE(items[1].filename == "");
  11884. EXPECT_TRUE(items[1].content_type == "");
  11885. } else {
  11886. std::string body;
  11887. content_reader([&](const char *data, size_t data_length) {
  11888. body.append(data, data_length);
  11889. return true;
  11890. });
  11891. }
  11892. });
  11893. auto port = svr.bind_to_any_port("localhost");
  11894. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11895. auto se = detail::scope_exit([&] {
  11896. svr.stop();
  11897. t.join();
  11898. ASSERT_FALSE(svr.is_running());
  11899. });
  11900. svr.wait_until_ready();
  11901. {
  11902. std::string data(1024 * 1024 * 2, '&');
  11903. std::stringstream buffer;
  11904. buffer << data;
  11905. SSLClient cli("localhost", port);
  11906. cli.enable_server_certificate_verification(false);
  11907. UploadFormDataItems items{
  11908. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11909. {"hello", "world", "", ""},
  11910. };
  11911. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11913. ASSERT_EQ(StatusCode::OK_200, res->status);
  11914. }
  11915. }
  11916. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11917. std::string data(1024 * 1024 * 2, '&');
  11918. std::stringstream buffer;
  11919. buffer << data;
  11920. Client cli("https://localhost:8080");
  11921. cli.enable_server_certificate_verification(false);
  11922. UploadFormDataItems items{
  11923. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11924. {"hello", "world", "", ""},
  11925. };
  11926. for (const char &c : " \t\r\n") {
  11927. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11928. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11929. ASSERT_FALSE(res);
  11930. }
  11931. }
  11932. TEST(MultipartFormDataTest, AlternateFilename) {
  11933. auto handled = false;
  11934. Server svr;
  11935. svr.Post("/test", [&](const Request &req, Response &res) {
  11936. ASSERT_EQ(2u, req.form.files.size());
  11937. ASSERT_EQ(1u, req.form.fields.size());
  11938. // Test files
  11939. const auto &file1 = req.form.get_file("file1");
  11940. ASSERT_EQ("file1", file1.name);
  11941. ASSERT_EQ("A.txt", file1.filename);
  11942. ASSERT_EQ("text/plain", file1.content_type);
  11943. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11944. const auto &file2 = req.form.get_file("file2");
  11945. ASSERT_EQ("file2", file2.name);
  11946. ASSERT_EQ("a.html", file2.filename);
  11947. ASSERT_EQ("text/html", file2.content_type);
  11948. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11949. file2.content);
  11950. // Test text field
  11951. const auto &text = req.form.get_field("text");
  11952. ASSERT_EQ("text default", text);
  11953. res.set_content("ok", "text/plain");
  11954. handled = true;
  11955. });
  11956. thread t = thread([&] { svr.listen(HOST, PORT); });
  11957. auto se = detail::scope_exit([&] {
  11958. svr.stop();
  11959. t.join();
  11960. ASSERT_FALSE(svr.is_running());
  11961. ASSERT_TRUE(handled);
  11962. });
  11963. svr.wait_until_ready();
  11964. auto req = "POST /test HTTP/1.1\r\n"
  11965. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11966. "Content-Length: 399\r\n"
  11967. "\r\n"
  11968. "----------\r\n"
  11969. "Content-Disposition: form-data; name=\"text\"\r\n"
  11970. "\r\n"
  11971. "text default\r\n"
  11972. "----------\r\n"
  11973. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11974. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11975. "Content-Type: text/plain\r\n"
  11976. "\r\n"
  11977. "Content of a.txt.\r\n"
  11978. "\r\n"
  11979. "----------\r\n"
  11980. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11981. "\"a.html\"\r\n"
  11982. "Content-Type: text/html\r\n"
  11983. "\r\n"
  11984. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11985. "\r\n"
  11986. "------------\r\n";
  11987. ASSERT_TRUE(send_request(1, req));
  11988. }
  11989. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11990. auto handled = false;
  11991. Server svr;
  11992. svr.Post("/test", [&](const Request &req, Response &res) {
  11993. // Case-insensitive "utf-8''" prefix with a long value
  11994. const auto &file = req.form.get_file("file1");
  11995. ASSERT_EQ("file1", file.name);
  11996. // 8000 chars exercises both the Content-Disposition parser and the
  11997. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11998. // Prior to the fix, std::regex_match on this header would cause O(N)
  11999. // stack recursion in libstdc++, leading to SIGSEGV.
  12000. std::string expected_filename(8000, 'A');
  12001. ASSERT_EQ(expected_filename, file.filename);
  12002. res.set_content("ok", "text/plain");
  12003. handled = true;
  12004. });
  12005. thread t = thread([&] { svr.listen(HOST, PORT); });
  12006. auto se = detail::scope_exit([&] {
  12007. svr.stop();
  12008. t.join();
  12009. ASSERT_FALSE(svr.is_running());
  12010. ASSERT_TRUE(handled);
  12011. });
  12012. svr.wait_until_ready();
  12013. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  12014. // Regression test for GHSA-qq6v-r583-3h69
  12015. std::string long_filename(8000, 'A');
  12016. std::string body = "----------\r\n"
  12017. "Content-Disposition: form-data; name=\"file1\"; "
  12018. "filename*=\"Utf-8''" +
  12019. long_filename +
  12020. "\"\r\n"
  12021. "\r\n"
  12022. "hello\r\n"
  12023. "------------\r\n";
  12024. auto req = "POST /test HTTP/1.1\r\n"
  12025. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12026. "Content-Length: " +
  12027. std::to_string(body.size()) + "\r\n\r\n" + body;
  12028. ASSERT_TRUE(send_request(1, req));
  12029. }
  12030. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  12031. auto handled = false;
  12032. Server svr;
  12033. svr.Post("/test", [&](const Request &req, Response &) {
  12034. ASSERT_EQ(2u, req.form.fields.size());
  12035. const auto &text1 = req.form.get_field("text1");
  12036. ASSERT_EQ("text1", text1);
  12037. const auto &text2 = req.form.get_field("text2");
  12038. ASSERT_EQ("text2", text2);
  12039. handled = true;
  12040. });
  12041. thread t = thread([&] { svr.listen(HOST, PORT); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. t.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. ASSERT_TRUE(handled);
  12047. });
  12048. svr.wait_until_ready();
  12049. auto req = "POST /test HTTP/1.1\r\n"
  12050. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12051. "Content-Length: 146\r\n"
  12052. "\r\n----------\r\n"
  12053. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12054. "\r\n"
  12055. "text1"
  12056. "\r\n----------\r\n"
  12057. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12058. "\r\n"
  12059. "text2"
  12060. "\r\n------------";
  12061. std::string response;
  12062. ASSERT_TRUE(send_request(1, req, &response));
  12063. ASSERT_EQ("200", response.substr(9, 3));
  12064. }
  12065. TEST(MultipartFormDataTest, ContentLength) {
  12066. auto handled = false;
  12067. Server svr;
  12068. svr.Post("/test", [&](const Request &req, Response &) {
  12069. ASSERT_EQ(2u, req.form.fields.size());
  12070. const auto &text1 = req.form.get_field("text1");
  12071. ASSERT_EQ("text1", text1);
  12072. const auto &text2 = req.form.get_field("text2");
  12073. ASSERT_EQ("text2", text2);
  12074. handled = true;
  12075. });
  12076. thread t = thread([&] { svr.listen(HOST, PORT); });
  12077. auto se = detail::scope_exit([&] {
  12078. svr.stop();
  12079. t.join();
  12080. ASSERT_FALSE(svr.is_running());
  12081. ASSERT_TRUE(handled);
  12082. });
  12083. svr.wait_until_ready();
  12084. auto req = "POST /test HTTP/1.1\r\n"
  12085. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12086. "Content-Length: 167\r\n"
  12087. "\r\n----------\r\n"
  12088. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12089. "Content-Length: 5\r\n"
  12090. "\r\n"
  12091. "text1"
  12092. "\r\n----------\r\n"
  12093. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12094. "\r\n"
  12095. "text2"
  12096. "\r\n------------\r\n";
  12097. std::string response;
  12098. ASSERT_TRUE(send_request(1, req, &response));
  12099. ASSERT_EQ("200", response.substr(9, 3));
  12100. }
  12101. TEST(MultipartFormDataTest, AccessPartHeaders) {
  12102. auto handled = false;
  12103. Server svr;
  12104. svr.Post("/test", [&](const Request &req, Response &) {
  12105. ASSERT_EQ(2u, req.form.fields.size());
  12106. const auto &text1 = req.form.get_field("text1");
  12107. ASSERT_EQ("text1", text1);
  12108. // TODO: Add header access for text fields if needed
  12109. const auto &text2 = req.form.get_field("text2");
  12110. ASSERT_EQ("text2", text2);
  12111. // TODO: Header access for text fields needs to be implemented
  12112. // auto &headers = it->second.headers;
  12113. // ASSERT_EQ(3U, headers.size());
  12114. // auto custom_header = headers.find("x-whatever");
  12115. // ASSERT_TRUE(custom_header != headers.end());
  12116. // ASSERT_NE("customvalue", custom_header->second);
  12117. // ASSERT_EQ("CustomValue", custom_header->second);
  12118. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  12119. handled = true;
  12120. });
  12121. thread t = thread([&] { svr.listen(HOST, PORT); });
  12122. auto se = detail::scope_exit([&] {
  12123. svr.stop();
  12124. t.join();
  12125. ASSERT_FALSE(svr.is_running());
  12126. ASSERT_TRUE(handled);
  12127. });
  12128. svr.wait_until_ready();
  12129. auto req = "POST /test HTTP/1.1\r\n"
  12130. "Content-Type: multipart/form-data;boundary=--------\r\n"
  12131. "Content-Length: 232\r\n"
  12132. "\r\n----------\r\n"
  12133. "Content-Disposition: form-data; name=\"text1\"\r\n"
  12134. "Content-Length: 5\r\n"
  12135. "X-Test: 1\r\n"
  12136. "\r\n"
  12137. "text1"
  12138. "\r\n----------\r\n"
  12139. "Content-Disposition: form-data; name=\"text2\"\r\n"
  12140. "Content-Type: text/plain\r\n"
  12141. "X-Whatever: CustomValue\r\n"
  12142. "\r\n"
  12143. "text2"
  12144. "\r\n------------\r\n"
  12145. "That should be disregarded. Not even read";
  12146. std::string response;
  12147. ASSERT_TRUE(send_request(1, req, &response));
  12148. ASSERT_EQ("200", response.substr(9, 3));
  12149. }
  12150. TEST(MultipartFormDataTest, LargeHeader) {
  12151. auto handled = false;
  12152. Server svr;
  12153. svr.Post("/test", [&](const Request &req, Response &) {
  12154. ASSERT_EQ(1u, req.form.fields.size());
  12155. const auto &text = req.form.get_field("name1");
  12156. ASSERT_EQ("text1", text);
  12157. handled = true;
  12158. });
  12159. thread t = thread([&] { svr.listen(HOST, PORT); });
  12160. auto se = detail::scope_exit([&] {
  12161. svr.stop();
  12162. t.join();
  12163. ASSERT_FALSE(svr.is_running());
  12164. ASSERT_TRUE(handled);
  12165. });
  12166. svr.wait_until_ready();
  12167. auto boundary = std::string("cpp-httplib-multipart-data");
  12168. std::string content = "--" + boundary +
  12169. "\r\n"
  12170. "Content-Disposition: form-data; name=\"name1\"\r\n"
  12171. "\r\n"
  12172. "text1\r\n"
  12173. "--" +
  12174. boundary + "--\r\n";
  12175. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  12176. "Content-Type: multipart/form-data;boundary=" +
  12177. boundary +
  12178. "\r\n"
  12179. "Content-Length: " +
  12180. std::to_string(content.size()) +
  12181. "\r\n"
  12182. "Dummy-Header: ";
  12183. std::string header_suffix = "\r\n"
  12184. "\r\n";
  12185. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  12186. size_t header_dummy_size =
  12187. read_buff_size -
  12188. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  12189. auto header_dummy = std::string(header_dummy_size, '@');
  12190. auto req = header_prefix + header_dummy + header_suffix + content;
  12191. std::string response;
  12192. ASSERT_TRUE(send_request(1, req, &response));
  12193. ASSERT_EQ("200", response.substr(9, 3));
  12194. }
  12195. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  12196. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  12197. // (not chunked Transfer-Encoding) after the streaming refactor.
  12198. auto handled = false;
  12199. Server svr;
  12200. svr.Post("/upload", [&](const Request &req, Response &res) {
  12201. auto cl_it = req.headers.find("Content-Length");
  12202. EXPECT_TRUE(cl_it != req.headers.end());
  12203. auto te_it = req.headers.find("Transfer-Encoding");
  12204. EXPECT_TRUE(te_it == req.headers.end());
  12205. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  12206. res.set_content("ok", "text/plain");
  12207. handled = true;
  12208. });
  12209. auto port = svr.bind_to_any_port(HOST);
  12210. auto t = thread([&] { svr.listen_after_bind(); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. t.join();
  12214. ASSERT_FALSE(svr.is_running());
  12215. ASSERT_TRUE(handled);
  12216. });
  12217. svr.wait_until_ready();
  12218. UploadFormDataItems items = {
  12219. {"field1", "hello", "", "text/plain"},
  12220. {"file1", "world", "test.txt", "application/octet-stream"},
  12221. };
  12222. Client cli(HOST, port);
  12223. auto res = cli.Post("/upload", {}, items);
  12224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12225. EXPECT_EQ(StatusCode::OK_200, res->status);
  12226. }
  12227. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  12228. // Verify that make_multipart_content_provider coalesces many small segments
  12229. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  12230. constexpr size_t kItemCount = 1000;
  12231. UploadFormDataItems items;
  12232. items.reserve(kItemCount);
  12233. for (size_t i = 0; i < kItemCount; i++) {
  12234. items.push_back(
  12235. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12236. }
  12237. const std::string boundary = "----test-boundary";
  12238. auto content_length = detail::get_multipart_content_length(items, boundary);
  12239. auto provider = detail::make_multipart_content_provider(items, boundary);
  12240. // Drive the provider the same way write_content_with_progress does
  12241. size_t write_count = 0;
  12242. size_t total_bytes = 0;
  12243. DataSink sink;
  12244. size_t offset = 0;
  12245. sink.write = [&](const char *d, size_t l) -> bool {
  12246. (void)d;
  12247. write_count++;
  12248. total_bytes += l;
  12249. offset += l;
  12250. return true;
  12251. };
  12252. sink.is_writable = []() -> bool { return true; };
  12253. while (offset < content_length) {
  12254. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  12255. }
  12256. EXPECT_EQ(content_length, total_bytes);
  12257. // The total number of segments is 3 * kItemCount + 1 = 3001.
  12258. // With buffering into 64KB blocks, write_count should be much smaller.
  12259. auto segment_count = 3 * kItemCount + 1;
  12260. EXPECT_LT(write_count, segment_count / 10);
  12261. }
  12262. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  12263. // Integration test: send many UploadFormDataItems and verify the server
  12264. // receives all of them correctly (#2410).
  12265. constexpr size_t kItemCount = 500;
  12266. auto handled = false;
  12267. Server svr;
  12268. svr.Post("/upload", [&](const Request &req, Response &res) {
  12269. EXPECT_EQ(kItemCount, req.form.fields.size());
  12270. for (size_t i = 0; i < kItemCount; i++) {
  12271. auto key = "field" + std::to_string(i);
  12272. auto val = "value" + std::to_string(i);
  12273. auto it = req.form.fields.find(key);
  12274. if (it != req.form.fields.end()) {
  12275. EXPECT_EQ(val, it->second.content);
  12276. } else {
  12277. ADD_FAILURE() << "Missing field: " << key;
  12278. }
  12279. }
  12280. res.set_content("ok", "text/plain");
  12281. handled = true;
  12282. });
  12283. auto port = svr.bind_to_any_port(HOST);
  12284. auto t = thread([&] { svr.listen_after_bind(); });
  12285. auto se = detail::scope_exit([&] {
  12286. svr.stop();
  12287. t.join();
  12288. ASSERT_FALSE(svr.is_running());
  12289. ASSERT_TRUE(handled);
  12290. });
  12291. svr.wait_until_ready();
  12292. UploadFormDataItems items;
  12293. items.reserve(kItemCount);
  12294. for (size_t i = 0; i < kItemCount; i++) {
  12295. items.push_back(
  12296. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  12297. }
  12298. Client cli(HOST, port);
  12299. auto res = cli.Post("/upload", items);
  12300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12301. EXPECT_EQ(StatusCode::OK_200, res->status);
  12302. }
  12303. TEST(MultipartFormDataTest, MakeFileProvider) {
  12304. // Verify make_file_provider sends a file's contents correctly.
  12305. const std::string file_content(4096, 'Z');
  12306. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  12307. {
  12308. std::ofstream ofs(tmp_path, std::ios::binary);
  12309. ofs.write(file_content.data(),
  12310. static_cast<std::streamsize>(file_content.size()));
  12311. }
  12312. auto handled = false;
  12313. Server svr;
  12314. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  12315. const ContentReader &content_reader) {
  12316. ASSERT_TRUE(req.is_multipart_form_data());
  12317. std::vector<FormData> items;
  12318. content_reader(
  12319. [&](const FormData &file) {
  12320. items.push_back(file);
  12321. return true;
  12322. },
  12323. [&](const char *data, size_t data_length) {
  12324. items.back().content.append(data, data_length);
  12325. return true;
  12326. });
  12327. ASSERT_EQ(1u, items.size());
  12328. EXPECT_EQ("myfile", items[0].name);
  12329. EXPECT_EQ("data.bin", items[0].filename);
  12330. EXPECT_EQ("application/octet-stream", items[0].content_type);
  12331. EXPECT_EQ(file_content, items[0].content);
  12332. handled = true;
  12333. });
  12334. auto port = svr.bind_to_any_port(HOST);
  12335. auto t = thread([&] { svr.listen_after_bind(); });
  12336. auto se = detail::scope_exit([&] {
  12337. svr.stop();
  12338. t.join();
  12339. ASSERT_FALSE(svr.is_running());
  12340. ASSERT_TRUE(handled);
  12341. std::remove(tmp_path.c_str());
  12342. });
  12343. svr.wait_until_ready();
  12344. FormDataProviderItems providers;
  12345. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  12346. "application/octet-stream"));
  12347. Client cli(HOST, port);
  12348. auto res = cli.Post("/upload", {}, {}, providers);
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. EXPECT_EQ(StatusCode::OK_200, res->status);
  12351. }
  12352. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  12353. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  12354. // (100) headers is rejected with a 400 Bad Request response.
  12355. Server svr;
  12356. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  12357. res.set_content("ok", "text/plain");
  12358. });
  12359. thread t = thread([&] { svr.listen(HOST, PORT); });
  12360. auto se = detail::scope_exit([&] {
  12361. svr.stop();
  12362. t.join();
  12363. ASSERT_FALSE(svr.is_running());
  12364. });
  12365. svr.wait_until_ready();
  12366. // Build a multipart part with 101 custom headers (exceeding
  12367. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12368. std::stringstream body;
  12369. body << "--simpleboundary\r\n"
  12370. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12371. for (int i = 0; i < 101; i++) {
  12372. body << "X-Custom-Header-" << i << ": value\r\n";
  12373. }
  12374. body << "\r\n"
  12375. << "value1\r\n"
  12376. << "--simpleboundary--\r\n";
  12377. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12378. Client cli(HOST, PORT);
  12379. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12381. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12382. }
  12383. TEST(MakeFileBodyTest, Basic) {
  12384. const std::string file_content(4096, 'Z');
  12385. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12386. {
  12387. std::ofstream ofs(tmp_path, std::ios::binary);
  12388. ofs.write(file_content.data(),
  12389. static_cast<std::streamsize>(file_content.size()));
  12390. }
  12391. auto handled = false;
  12392. Server svr;
  12393. svr.Post("/upload", [&](const Request &req, Response &res) {
  12394. EXPECT_EQ(file_content, req.body);
  12395. handled = true;
  12396. res.status = StatusCode::OK_200;
  12397. });
  12398. auto port = svr.bind_to_any_port(HOST);
  12399. auto t = thread([&] { svr.listen_after_bind(); });
  12400. auto se = detail::scope_exit([&] {
  12401. svr.stop();
  12402. t.join();
  12403. ASSERT_FALSE(svr.is_running());
  12404. ASSERT_TRUE(handled);
  12405. std::remove(tmp_path.c_str());
  12406. });
  12407. svr.wait_until_ready();
  12408. auto fb = make_file_body(tmp_path);
  12409. ASSERT_GT(fb.first, 0u);
  12410. Client cli(HOST, port);
  12411. auto res =
  12412. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12414. EXPECT_EQ(StatusCode::OK_200, res->status);
  12415. }
  12416. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12417. static constexpr unsigned int number_of_tasks{1000000};
  12418. std::atomic_uint count{0};
  12419. std::unique_ptr<TaskQueue> task_queue{
  12420. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12421. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12422. auto queued = task_queue->enqueue(
  12423. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12424. EXPECT_TRUE(queued);
  12425. }
  12426. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12427. task_queue->shutdown();
  12428. #else
  12429. EXPECT_NO_THROW(task_queue->shutdown());
  12430. #endif
  12431. EXPECT_EQ(number_of_tasks, count.load());
  12432. }
  12433. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12434. static constexpr unsigned int number_of_tasks{1000000};
  12435. static constexpr unsigned int qlimit{2};
  12436. unsigned int queued_count{0};
  12437. std::atomic_uint count{0};
  12438. std::unique_ptr<TaskQueue> task_queue{
  12439. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12440. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12441. if (task_queue->enqueue(
  12442. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12443. queued_count++;
  12444. }
  12445. }
  12446. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12447. task_queue->shutdown();
  12448. #else
  12449. EXPECT_NO_THROW(task_queue->shutdown());
  12450. #endif
  12451. EXPECT_EQ(queued_count, count.load());
  12452. EXPECT_TRUE(queued_count <= number_of_tasks);
  12453. EXPECT_TRUE(queued_count >= qlimit);
  12454. }
  12455. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12456. // Use a short idle timeout so a dynamic thread spawns, times out and
  12457. // exits during the test, and the pool keeps working afterwards.
  12458. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12459. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12460. /*idle_timeout_sec=*/1}};
  12461. std::atomic_uint count{0};
  12462. std::condition_variable cv;
  12463. std::mutex mtx;
  12464. bool release = false;
  12465. // Block the base thread so the second task spawns a dynamic thread.
  12466. EXPECT_TRUE(task_queue->enqueue([&] {
  12467. std::unique_lock<std::mutex> lock(mtx);
  12468. while (!release) {
  12469. cv.wait(lock);
  12470. }
  12471. count++;
  12472. }));
  12473. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12474. // Let the dynamic thread finish its task and exceed the idle timeout.
  12475. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12476. {
  12477. std::unique_lock<std::mutex> lock(mtx);
  12478. release = true;
  12479. }
  12480. cv.notify_all();
  12481. // The pool must still accept and run tasks after the dynamic thread exited.
  12482. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12483. task_queue->shutdown();
  12484. EXPECT_EQ(3u, count.load());
  12485. }
  12486. TEST(TaskQueueTest, MaxQueuedRequests) {
  12487. static constexpr unsigned int qlimit{3};
  12488. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12489. std::condition_variable sem_cv;
  12490. std::mutex sem_mtx;
  12491. int credits = 0;
  12492. bool queued;
  12493. /* Fill up the queue with tasks that will block until we give them credits to
  12494. * complete. */
  12495. for (unsigned int n = 0; n <= qlimit;) {
  12496. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12497. std::unique_lock<std::mutex> lock(sem_mtx);
  12498. while (credits <= 0) {
  12499. sem_cv.wait(lock);
  12500. }
  12501. /* Consume the credit and signal the test code if they are all gone. */
  12502. if (--credits == 0) { sem_cv.notify_one(); }
  12503. });
  12504. if (n < qlimit) {
  12505. /* The first qlimit enqueues must succeed. */
  12506. EXPECT_TRUE(queued);
  12507. } else {
  12508. /* The last one will succeed only when the worker thread
  12509. * starts and dequeues the first blocking task. Although
  12510. * not necessary for the correctness of this test, we sleep for
  12511. * a short while to avoid busy waiting. */
  12512. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12513. }
  12514. if (queued) { n++; }
  12515. }
  12516. /* Further enqueues must fail since the queue is full. */
  12517. for (auto i = 0; i < 4; i++) {
  12518. queued = task_queue->enqueue([] {});
  12519. EXPECT_FALSE(queued);
  12520. }
  12521. /* Give the credits to allow the previous tasks to complete. */
  12522. {
  12523. std::unique_lock<std::mutex> lock(sem_mtx);
  12524. credits += qlimit + 1;
  12525. }
  12526. sem_cv.notify_all();
  12527. /* Wait for all the credits to be consumed. */
  12528. {
  12529. std::unique_lock<std::mutex> lock(sem_mtx);
  12530. while (credits > 0) {
  12531. sem_cv.wait(lock);
  12532. }
  12533. }
  12534. /* Check that we are able again to enqueue at least qlimit tasks. */
  12535. for (unsigned int i = 0; i < qlimit; i++) {
  12536. queued = task_queue->enqueue([] {});
  12537. EXPECT_TRUE(queued);
  12538. }
  12539. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12540. task_queue->shutdown();
  12541. #else
  12542. EXPECT_NO_THROW(task_queue->shutdown());
  12543. #endif
  12544. }
  12545. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12546. Server svr;
  12547. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12548. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12549. });
  12550. svr.Get("/hello", [](const Request &req, Response &res) {
  12551. res.set_content(req.get_param_value("key"), "text/plain");
  12552. });
  12553. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12554. auto se = detail::scope_exit([&] {
  12555. svr.stop();
  12556. thread.join();
  12557. ASSERT_FALSE(svr.is_running());
  12558. });
  12559. svr.wait_until_ready();
  12560. {
  12561. Client cli(HOST, PORT);
  12562. cli.set_follow_location(true);
  12563. auto res = cli.Get("/");
  12564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12565. EXPECT_EQ(StatusCode::OK_200, res->status);
  12566. EXPECT_EQ("val&key2=val2", res->body);
  12567. }
  12568. }
  12569. #endif
  12570. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12571. Server svr;
  12572. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12573. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12574. });
  12575. svr.Get("/hello", [](const Request &req, Response &res) {
  12576. res.set_content(req.get_param_value("key"), "text/plain");
  12577. });
  12578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12579. auto se = detail::scope_exit([&] {
  12580. svr.stop();
  12581. thread.join();
  12582. ASSERT_FALSE(svr.is_running());
  12583. });
  12584. svr.wait_until_ready();
  12585. {
  12586. Client cli(HOST, PORT);
  12587. cli.set_follow_location(true);
  12588. auto res = cli.Get("/");
  12589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12590. EXPECT_EQ(StatusCode::OK_200, res->status);
  12591. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12592. }
  12593. }
  12594. TEST(RedirectTest, RedirectWithPlusInPath) {
  12595. Server svr;
  12596. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12597. res.set_redirect("/a+b");
  12598. });
  12599. // Route pattern uses regex; escape + as \\+
  12600. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12601. res.set_content(req.path, "text/plain");
  12602. });
  12603. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12604. auto se = detail::scope_exit([&] {
  12605. svr.stop();
  12606. thread.join();
  12607. ASSERT_FALSE(svr.is_running());
  12608. });
  12609. svr.wait_until_ready();
  12610. {
  12611. Client cli(HOST, PORT);
  12612. cli.set_follow_location(true);
  12613. auto res = cli.Get("/");
  12614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12615. EXPECT_EQ(StatusCode::OK_200, res->status);
  12616. EXPECT_EQ("/a+b", res->body);
  12617. }
  12618. }
  12619. #ifdef CPPHTTPLIB_SSL_ENABLED
  12620. TEST(RedirectTest, Issue2185_Online) {
  12621. SSLClient client("github.com");
  12622. client.set_follow_location(true);
  12623. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12624. "Coollab-Windows.zip");
  12625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12626. EXPECT_EQ(StatusCode::OK_200, res->status);
  12627. EXPECT_EQ(9920427U, res->body.size());
  12628. }
  12629. #endif
  12630. TEST(VulnerabilityTest, CRLFInjection) {
  12631. Server svr;
  12632. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12633. res.set_content("Hello 1", "text/plain");
  12634. });
  12635. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12636. res.set_content("Hello 2", "text/plain");
  12637. });
  12638. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12639. res.set_content("Hello 3", "text/plain");
  12640. });
  12641. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12642. res.set_content("Hello 4", "text/plain");
  12643. });
  12644. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12645. for (const auto &x : req.headers) {
  12646. auto key = x.first;
  12647. EXPECT_STRNE("evil", key.c_str());
  12648. }
  12649. });
  12650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12651. auto se = detail::scope_exit([&] {
  12652. svr.stop();
  12653. thread.join();
  12654. ASSERT_FALSE(svr.is_running());
  12655. });
  12656. svr.wait_until_ready();
  12657. {
  12658. Client cli(HOST, PORT);
  12659. cli.Post("/test1", "A=B",
  12660. "application/x-www-form-urlencoded\r\nevil: hello1");
  12661. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12662. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12663. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12664. }
  12665. }
  12666. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12667. auto server_thread = std::thread([] {
  12668. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12669. default_socket_options(srv);
  12670. sockaddr_in addr{};
  12671. addr.sin_family = AF_INET;
  12672. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12673. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12674. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12675. ::listen(srv, 1);
  12676. sockaddr_in cli_addr{};
  12677. socklen_t cli_len = sizeof(cli_addr);
  12678. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12679. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12680. std::string buf_all;
  12681. char buf[2048];
  12682. ssize_t n;
  12683. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12684. buf_all.append(buf, static_cast<size_t>(n));
  12685. size_t pos;
  12686. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12687. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12688. auto e = request_block.find("\r\n");
  12689. if (e != std::string::npos) {
  12690. auto request_line = request_block.substr(0, e);
  12691. std::string msg =
  12692. "CRLF injection detected in request line: '" + request_line + "'";
  12693. EXPECT_FALSE(true) << msg;
  12694. }
  12695. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12696. ::send(cli,
  12697. #ifdef _WIN32
  12698. static_cast<const char *>(resp.c_str()),
  12699. static_cast<int>(resp.size()),
  12700. #else
  12701. resp.c_str(), resp.size(),
  12702. #endif
  12703. 0);
  12704. buf_all.erase(0, pos + 4);
  12705. }
  12706. }
  12707. detail::close_socket(cli);
  12708. detail::close_socket(srv);
  12709. });
  12710. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12711. auto cli = Client("127.0.0.1", PORT + 1);
  12712. auto headers = Headers{
  12713. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12714. {"Connection", "keep-alive"}};
  12715. auto res = cli.Get("/hi", headers);
  12716. EXPECT_FALSE(res);
  12717. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12718. server_thread.join();
  12719. }
  12720. TEST(PathParamsTest, StaticMatch) {
  12721. const auto pattern = "/users/all";
  12722. detail::PathParamsMatcher matcher(pattern);
  12723. Request request;
  12724. request.path = "/users/all";
  12725. ASSERT_TRUE(matcher.match(request));
  12726. std::unordered_map<std::string, std::string> expected_params = {};
  12727. EXPECT_EQ(request.path_params, expected_params);
  12728. }
  12729. TEST(PathParamsTest, StaticMismatch) {
  12730. const auto pattern = "/users/all";
  12731. detail::PathParamsMatcher matcher(pattern);
  12732. Request request;
  12733. request.path = "/users/1";
  12734. ASSERT_FALSE(matcher.match(request));
  12735. }
  12736. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12737. const auto pattern = "/users/:id/subscriptions";
  12738. detail::PathParamsMatcher matcher(pattern);
  12739. Request request;
  12740. request.path = "/users/42/subscriptions";
  12741. ASSERT_TRUE(matcher.match(request));
  12742. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12743. EXPECT_EQ(request.path_params, expected_params);
  12744. }
  12745. TEST(PathParamsTest, SingleParamInTheEnd) {
  12746. const auto pattern = "/users/:id";
  12747. detail::PathParamsMatcher matcher(pattern);
  12748. Request request;
  12749. request.path = "/users/24";
  12750. ASSERT_TRUE(matcher.match(request));
  12751. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12752. EXPECT_EQ(request.path_params, expected_params);
  12753. }
  12754. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12755. const auto pattern = "/users/:id/";
  12756. detail::PathParamsMatcher matcher(pattern);
  12757. Request request;
  12758. request.path = "/users/42/";
  12759. ASSERT_TRUE(matcher.match(request));
  12760. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12761. EXPECT_EQ(request.path_params, expected_params);
  12762. }
  12763. TEST(PathParamsTest, EmptyParam) {
  12764. const auto pattern = "/users/:id/";
  12765. detail::PathParamsMatcher matcher(pattern);
  12766. Request request;
  12767. request.path = "/users//";
  12768. ASSERT_TRUE(matcher.match(request));
  12769. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12770. EXPECT_EQ(request.path_params, expected_params);
  12771. }
  12772. TEST(PathParamsTest, FragmentMismatch) {
  12773. const auto pattern = "/users/:id/";
  12774. detail::PathParamsMatcher matcher(pattern);
  12775. Request request;
  12776. request.path = "/admins/24/";
  12777. ASSERT_FALSE(matcher.match(request));
  12778. }
  12779. TEST(PathParamsTest, ExtraFragments) {
  12780. const auto pattern = "/users/:id";
  12781. detail::PathParamsMatcher matcher(pattern);
  12782. Request request;
  12783. request.path = "/users/42/subscriptions";
  12784. ASSERT_FALSE(matcher.match(request));
  12785. }
  12786. TEST(PathParamsTest, MissingTrailingParam) {
  12787. const auto pattern = "/users/:id";
  12788. detail::PathParamsMatcher matcher(pattern);
  12789. Request request;
  12790. request.path = "/users";
  12791. ASSERT_FALSE(matcher.match(request));
  12792. }
  12793. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12794. const auto pattern = "/users/:id/subscriptions";
  12795. detail::PathParamsMatcher matcher(pattern);
  12796. Request request;
  12797. request.path = "/users/subscriptions";
  12798. ASSERT_FALSE(matcher.match(request));
  12799. }
  12800. TEST(PathParamsTest, MultipleParams) {
  12801. const auto pattern = "/users/:userid/subscriptions/:subid";
  12802. detail::PathParamsMatcher matcher(pattern);
  12803. Request request;
  12804. request.path = "/users/42/subscriptions/2";
  12805. ASSERT_TRUE(matcher.match(request));
  12806. std::unordered_map<std::string, std::string> expected_params = {
  12807. {"userid", "42"}, {"subid", "2"}};
  12808. EXPECT_EQ(request.path_params, expected_params);
  12809. }
  12810. TEST(PathParamsTest, SequenceOfParams) {
  12811. const auto pattern = "/values/:x/:y/:z";
  12812. detail::PathParamsMatcher matcher(pattern);
  12813. Request request;
  12814. request.path = "/values/1/2/3";
  12815. ASSERT_TRUE(matcher.match(request));
  12816. std::unordered_map<std::string, std::string> expected_params = {
  12817. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12818. EXPECT_EQ(request.path_params, expected_params);
  12819. }
  12820. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12821. const auto pattern = "/prefix:suffix";
  12822. detail::PathParamsMatcher matcher(pattern);
  12823. Request request;
  12824. request.path = "/prefix:suffix";
  12825. ASSERT_TRUE(matcher.match(request));
  12826. const std::unordered_map<std::string, std::string> expected_params = {};
  12827. EXPECT_EQ(request.path_params, expected_params);
  12828. }
  12829. TEST(ParseUrlTest, VariousPatterns) {
  12830. {
  12831. detail::UrlComponents uc;
  12832. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12833. EXPECT_EQ("http", uc.scheme);
  12834. EXPECT_EQ("example.com", uc.host);
  12835. EXPECT_EQ("8080", uc.port);
  12836. EXPECT_EQ("/path", uc.path);
  12837. EXPECT_EQ("?q=1", uc.query);
  12838. }
  12839. {
  12840. detail::UrlComponents uc;
  12841. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12842. EXPECT_EQ("https", uc.scheme);
  12843. EXPECT_EQ("example.com", uc.host);
  12844. EXPECT_TRUE(uc.port.empty());
  12845. EXPECT_EQ("/path", uc.path);
  12846. }
  12847. {
  12848. detail::UrlComponents uc;
  12849. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12850. EXPECT_EQ("::1", uc.host);
  12851. EXPECT_EQ("8080", uc.port);
  12852. EXPECT_EQ("/path", uc.path);
  12853. }
  12854. {
  12855. detail::UrlComponents uc;
  12856. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12857. }
  12858. {
  12859. detail::UrlComponents uc;
  12860. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12861. EXPECT_TRUE(uc.scheme.empty());
  12862. EXPECT_EQ("example.com", uc.host);
  12863. EXPECT_EQ("/path", uc.path);
  12864. EXPECT_EQ("?q=1", uc.query);
  12865. }
  12866. {
  12867. detail::UrlComponents uc;
  12868. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12869. EXPECT_TRUE(uc.host.empty());
  12870. EXPECT_EQ("/path", uc.path);
  12871. EXPECT_EQ("?q=1", uc.query);
  12872. }
  12873. {
  12874. detail::UrlComponents uc;
  12875. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12876. EXPECT_EQ("example.com", uc.host);
  12877. EXPECT_EQ("8080", uc.port);
  12878. }
  12879. {
  12880. // Unix socket path — must not be parsed as host
  12881. detail::UrlComponents uc;
  12882. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12883. EXPECT_TRUE(uc.host.empty());
  12884. }
  12885. {
  12886. detail::UrlComponents uc;
  12887. ASSERT_TRUE(detail::parse_url("", uc));
  12888. EXPECT_TRUE(uc.host.empty());
  12889. EXPECT_TRUE(uc.path.empty());
  12890. }
  12891. {
  12892. detail::UrlComponents uc;
  12893. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12894. }
  12895. {
  12896. detail::UrlComponents uc;
  12897. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12898. }
  12899. {
  12900. // Accepted by parse_url; callers restrict to http/https
  12901. detail::UrlComponents uc;
  12902. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12903. EXPECT_EQ("ftp", uc.scheme);
  12904. }
  12905. {
  12906. detail::UrlComponents uc;
  12907. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12908. }
  12909. {
  12910. detail::UrlComponents uc;
  12911. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12912. }
  12913. }
  12914. TEST(ParseUrlTest, FragmentHandling) {
  12915. {
  12916. detail::UrlComponents uc;
  12917. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12918. EXPECT_EQ("/path", uc.path);
  12919. EXPECT_TRUE(uc.query.empty());
  12920. }
  12921. {
  12922. detail::UrlComponents uc;
  12923. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12924. EXPECT_TRUE(uc.path.empty());
  12925. EXPECT_TRUE(uc.query.empty());
  12926. }
  12927. }
  12928. TEST(ParseUrlTest, UserinfoHandling) {
  12929. // Userinfo with @ but no colon — host includes @
  12930. detail::UrlComponents uc;
  12931. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12932. EXPECT_EQ("user@host.com", uc.host);
  12933. EXPECT_EQ("/path", uc.path);
  12934. }
  12935. TEST(ParseUrlTest, IPv6EdgeCases) {
  12936. {
  12937. detail::UrlComponents uc;
  12938. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12939. EXPECT_TRUE(uc.scheme.empty());
  12940. EXPECT_EQ("::1", uc.host);
  12941. EXPECT_EQ("8080", uc.port);
  12942. }
  12943. {
  12944. // Zone ID '%25' is not in [a-fA-F0-9:]
  12945. detail::UrlComponents uc;
  12946. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12947. }
  12948. }
  12949. TEST(ParseUrlTest, SchemeEdgeCases) {
  12950. {
  12951. detail::UrlComponents uc;
  12952. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12953. }
  12954. {
  12955. detail::UrlComponents uc;
  12956. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12957. }
  12958. {
  12959. detail::UrlComponents uc;
  12960. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12961. }
  12962. }
  12963. TEST(ParseUrlTest, PortEdgeCases) {
  12964. {
  12965. detail::UrlComponents uc;
  12966. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12967. EXPECT_TRUE(uc.port.empty());
  12968. EXPECT_EQ("/path", uc.path);
  12969. }
  12970. {
  12971. // parse_url accepts any port string; validation is done by parse_port
  12972. detail::UrlComponents uc;
  12973. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12974. EXPECT_EQ("abc", uc.port);
  12975. }
  12976. }
  12977. TEST(ParseUrlTest, WebSocketPatterns) {
  12978. {
  12979. detail::UrlComponents uc;
  12980. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12981. EXPECT_EQ("ws", uc.scheme);
  12982. EXPECT_EQ("echo.example.com", uc.host);
  12983. EXPECT_EQ("8080", uc.port);
  12984. EXPECT_EQ("/ws", uc.path);
  12985. }
  12986. {
  12987. detail::UrlComponents uc;
  12988. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12989. EXPECT_EQ("wss", uc.scheme);
  12990. EXPECT_EQ("echo.example.com", uc.host);
  12991. EXPECT_TRUE(uc.port.empty());
  12992. EXPECT_EQ("/ws", uc.path);
  12993. }
  12994. }
  12995. TEST(ParseUrlTest, QueryOnly) {
  12996. detail::UrlComponents uc;
  12997. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12998. EXPECT_TRUE(uc.host.empty());
  12999. EXPECT_TRUE(uc.path.empty());
  13000. EXPECT_EQ("?q=1&r=2", uc.query);
  13001. }
  13002. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  13003. detail::UrlComponents uc;
  13004. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  13005. EXPECT_TRUE(uc.scheme.empty());
  13006. EXPECT_EQ("example.com", uc.host);
  13007. EXPECT_EQ("443", uc.port);
  13008. EXPECT_EQ("/path", uc.path);
  13009. }
  13010. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  13011. // If ipv6 regex working, regex match codepath is taken.
  13012. // else port will default to 80 in Client impl
  13013. int clientImplMagicPort = 80;
  13014. int port = 4321;
  13015. // above ports must be different to avoid false negative
  13016. EXPECT_NE(clientImplMagicPort, port);
  13017. std::string ipV6TestURL = "http://[ff06::c3]";
  13018. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  13019. CLIENT_PRIVATE_KEY_FILE);
  13020. EXPECT_EQ(cli.port(), port);
  13021. }
  13022. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  13023. auto file_path = "./www/dir/index.html";
  13024. auto dir_path = "./www/dir";
  13025. detail::FileStat stat_file(file_path);
  13026. EXPECT_TRUE(stat_file.is_file());
  13027. EXPECT_FALSE(stat_file.is_dir());
  13028. detail::FileStat stat_dir(dir_path);
  13029. EXPECT_FALSE(stat_dir.is_file());
  13030. EXPECT_TRUE(stat_dir.is_dir());
  13031. }
  13032. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  13033. // IPv4 with default HTTP port (80)
  13034. EXPECT_EQ("example.com",
  13035. detail::make_host_and_port_string("example.com", 80, false));
  13036. // IPv4 with default HTTPS port (443)
  13037. EXPECT_EQ("example.com",
  13038. detail::make_host_and_port_string("example.com", 443, true));
  13039. // IPv4 with non-default HTTP port
  13040. EXPECT_EQ("example.com:8080",
  13041. detail::make_host_and_port_string("example.com", 8080, false));
  13042. // IPv4 with non-default HTTPS port
  13043. EXPECT_EQ("example.com:8443",
  13044. detail::make_host_and_port_string("example.com", 8443, true));
  13045. // IPv6 with default HTTP port (80)
  13046. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  13047. // IPv6 with default HTTPS port (443)
  13048. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  13049. // IPv6 with non-default HTTP port
  13050. EXPECT_EQ("[::1]:8080",
  13051. detail::make_host_and_port_string("::1", 8080, false));
  13052. // IPv6 with non-default HTTPS port
  13053. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  13054. // IPv6 full address with default port
  13055. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  13056. detail::make_host_and_port_string(
  13057. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  13058. // IPv6 full address with non-default port
  13059. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  13060. detail::make_host_and_port_string(
  13061. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  13062. // IPv6 localhost with non-default port
  13063. EXPECT_EQ("[::1]:3000",
  13064. detail::make_host_and_port_string("::1", 3000, false));
  13065. // IPv6 with zone ID (link-local address) with default port
  13066. EXPECT_EQ("[fe80::1%eth0]",
  13067. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  13068. // IPv6 with zone ID (link-local address) with non-default port
  13069. EXPECT_EQ("[fe80::1%eth0]:8080",
  13070. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  13071. // Edge case: Port 443 with is_ssl=false (should add port)
  13072. EXPECT_EQ("example.com:443",
  13073. detail::make_host_and_port_string("example.com", 443, false));
  13074. // Edge case: Port 80 with is_ssl=true (should add port)
  13075. EXPECT_EQ("example.com:80",
  13076. detail::make_host_and_port_string("example.com", 80, true));
  13077. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  13078. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  13079. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  13080. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  13081. // Security fix: Already bracketed IPv6 should not get double brackets
  13082. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  13083. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  13084. EXPECT_EQ("[::1]:8080",
  13085. detail::make_host_and_port_string("[::1]", 8080, false));
  13086. EXPECT_EQ("[2001:db8::1]:8080",
  13087. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  13088. EXPECT_EQ("[fe80::1%eth0]",
  13089. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  13090. EXPECT_EQ("[fe80::1%eth0]:8080",
  13091. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  13092. // Edge case: Empty host (should return as-is)
  13093. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  13094. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  13095. // This is a known limitation but shouldn't crash
  13096. EXPECT_EQ("[host:name]",
  13097. detail::make_host_and_port_string("host:name", 80, false));
  13098. // Port number edge cases (no validation, but should not crash)
  13099. EXPECT_EQ("example.com:0",
  13100. detail::make_host_and_port_string("example.com", 0, false));
  13101. EXPECT_EQ("example.com:-1",
  13102. detail::make_host_and_port_string("example.com", -1, false));
  13103. EXPECT_EQ("example.com:65535",
  13104. detail::make_host_and_port_string("example.com", 65535, false));
  13105. EXPECT_EQ("example.com:65536",
  13106. detail::make_host_and_port_string("example.com", 65536, false));
  13107. }
  13108. #ifdef CPPHTTPLIB_SSL_ENABLED
  13109. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  13110. httplib::SSLClient cli("roblox.com", 443);
  13111. cli.set_follow_location(true);
  13112. auto res = cli.Get("/");
  13113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13114. EXPECT_EQ(StatusCode::OK_200, res->status);
  13115. }
  13116. #endif
  13117. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  13118. Server svr;
  13119. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13120. EXPECT_EQ(res.status, 400);
  13121. });
  13122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13123. auto se = detail::scope_exit([&] {
  13124. svr.stop();
  13125. thread.join();
  13126. ASSERT_FALSE(svr.is_running());
  13127. });
  13128. svr.wait_until_ready();
  13129. Client cli(HOST, PORT);
  13130. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  13131. }
  13132. TEST(InvalidHeaderCharsTest, is_field_name) {
  13133. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  13134. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  13135. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  13136. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  13137. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  13138. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  13139. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  13140. EXPECT_FALSE(detail::fields::is_field_name(""));
  13141. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  13142. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  13143. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  13144. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  13145. }
  13146. TEST(InvalidHeaderCharsTest, is_field_value) {
  13147. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  13148. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  13149. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  13150. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  13151. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  13152. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  13153. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  13154. EXPECT_TRUE(detail::fields::is_field_value(""));
  13155. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  13156. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  13157. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  13158. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  13159. EXPECT_TRUE(detail::fields::is_field_value("0"));
  13160. }
  13161. TEST(InvalidHeaderCharsTest, OnServer) {
  13162. Server svr;
  13163. svr.Get("/test_name", [&](const Request &req, Response &res) {
  13164. std::string header = "Not Set";
  13165. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13166. res.set_header(header, "value");
  13167. res.set_content("Page Content Page Content", "text/plain");
  13168. });
  13169. svr.Get("/test_value", [&](const Request &req, Response &res) {
  13170. std::string header = "Not Set";
  13171. if (req.has_param("header")) { header = req.get_param_value("header"); }
  13172. res.set_header("X-Test", header);
  13173. res.set_content("Page Content Page Content", "text/plain");
  13174. });
  13175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13176. auto se = detail::scope_exit([&] {
  13177. svr.stop();
  13178. thread.join();
  13179. ASSERT_FALSE(svr.is_running());
  13180. });
  13181. svr.wait_until_ready();
  13182. Client cli(HOST, PORT);
  13183. {
  13184. auto res = cli.Get(
  13185. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13187. EXPECT_EQ("Page Content Page Content", res->body);
  13188. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13189. }
  13190. {
  13191. auto res = cli.Get(
  13192. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  13193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13194. EXPECT_EQ("Page Content Page Content", res->body);
  13195. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  13196. }
  13197. }
  13198. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  13199. auto handled = false;
  13200. Server svr;
  13201. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13202. thread t = thread([&] { svr.listen(HOST, PORT); });
  13203. auto se = detail::scope_exit([&] {
  13204. svr.stop();
  13205. t.join();
  13206. ASSERT_FALSE(svr.is_running());
  13207. ASSERT_FALSE(handled);
  13208. });
  13209. svr.wait_until_ready();
  13210. auto req = "POST /test HTTP/1.1\r\n"
  13211. "Content-Length: x\r\n"
  13212. "\r\n";
  13213. std::string response;
  13214. ASSERT_TRUE(send_request(1, req, &response));
  13215. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13216. response.substr(0, response.find("\r\n")));
  13217. }
  13218. #ifndef _WIN32
  13219. TEST(Expect100ContinueTest, ServerClosesConnection) {
  13220. static constexpr char reject[] = "Unauthorized";
  13221. static constexpr char accept[] = "Upload accepted";
  13222. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  13223. Server svr;
  13224. svr.set_expect_100_continue_handler(
  13225. [](const Request & /*req*/, Response &res) {
  13226. res.status = StatusCode::Unauthorized_401;
  13227. res.set_content(reject, "text/plain");
  13228. return res.status;
  13229. });
  13230. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  13231. res.set_content(accept, "text/plain");
  13232. });
  13233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13234. auto se = detail::scope_exit([&] {
  13235. svr.stop();
  13236. thread.join();
  13237. ASSERT_FALSE(svr.is_running());
  13238. });
  13239. svr.wait_until_ready();
  13240. {
  13241. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  13242. curl_easy_init(), &curl_easy_cleanup};
  13243. ASSERT_NE(curl, nullptr);
  13244. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  13245. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  13246. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  13247. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  13248. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  13249. &curl_slist_free_all};
  13250. ASSERT_NE(list, nullptr);
  13251. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  13252. struct read_data {
  13253. size_t read_size;
  13254. size_t total_size;
  13255. } data = {0, total_size};
  13256. using read_callback_t =
  13257. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13258. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  13259. void *userdata) -> size_t {
  13260. read_data *d = (read_data *)userdata;
  13261. if (!userdata || d->read_size >= d->total_size) { return 0; }
  13262. std::fill_n(ptr, size * nmemb, 'A');
  13263. d->read_size += size * nmemb;
  13264. return size * nmemb;
  13265. };
  13266. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  13267. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  13268. std::vector<char> buffer;
  13269. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  13270. using write_callback_t =
  13271. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  13272. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  13273. void *userdata) -> size_t {
  13274. std::vector<char> *buf = (std::vector<char> *)userdata;
  13275. buf->reserve(buf->size() + size * nmemb + 1);
  13276. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  13277. return size * nmemb;
  13278. };
  13279. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  13280. {
  13281. const auto res = curl_easy_perform(curl.get());
  13282. ASSERT_EQ(res, CURLE_OK);
  13283. }
  13284. {
  13285. auto response_code = long{};
  13286. const auto res =
  13287. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  13288. ASSERT_EQ(res, CURLE_OK);
  13289. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  13290. }
  13291. {
  13292. auto dl = curl_off_t{};
  13293. const auto res =
  13294. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  13295. ASSERT_EQ(res, CURLE_OK);
  13296. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  13297. }
  13298. {
  13299. buffer.push_back('\0');
  13300. ASSERT_STRCASEEQ(buffer.data(), reject);
  13301. }
  13302. }
  13303. }
  13304. #endif
  13305. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  13306. // Regression test for #2458.
  13307. //
  13308. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  13309. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  13310. // ticket can make the client socket spuriously readable during the
  13311. // 100-continue wait. If the readiness is mistaken for an incoming response,
  13312. // the client withholds the body and then blocks reading a response that never
  13313. // comes, failing with `Failed to read connection`.
  13314. //
  13315. // A correct client (like curl) sends the body once no `100 Continue` arrives
  13316. // within the timeout. This raw OpenSSL server deliberately never sends
  13317. // `100 Continue`; the client must still deliver the body and receive 200.
  13318. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  13319. signal(SIGPIPE, SIG_IGN);
  13320. const auto port = PORT + 4;
  13321. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13322. ASSERT_NE(srv, INVALID_SOCKET);
  13323. int opt = 1;
  13324. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  13325. sockaddr_in addr{};
  13326. addr.sin_family = AF_INET;
  13327. addr.sin_port = htons(static_cast<uint16_t>(port));
  13328. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13329. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13330. ASSERT_EQ(0, ::listen(srv, 1));
  13331. std::atomic<size_t> server_body_bytes{0};
  13332. auto server_thread = std::thread([&] {
  13333. sockaddr_in cli_addr{};
  13334. socklen_t cli_len = sizeof(cli_addr);
  13335. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13336. if (cli == INVALID_SOCKET) { return; }
  13337. // Bound the lifetime of the server side so a buggy client (which never
  13338. // sends the body) cannot make this thread block forever on join.
  13339. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  13340. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  13341. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  13342. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  13343. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  13344. SSL *ssl = SSL_new(ctx);
  13345. SSL_set_fd(ssl, static_cast<int>(cli));
  13346. if (SSL_accept(ssl) > 0) {
  13347. // Read the request headers. Reading here also flushes the TLS 1.3
  13348. // session tickets to the client. Deliberately do NOT send
  13349. // `100 Continue`.
  13350. std::string buf;
  13351. char tmp[1024];
  13352. while (buf.find("\r\n\r\n") == std::string::npos) {
  13353. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13354. if (n <= 0) { break; }
  13355. buf.append(tmp, static_cast<size_t>(n));
  13356. }
  13357. // A correct client sends the body now; count what arrives.
  13358. auto pos = buf.find("\r\n\r\n");
  13359. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13360. while (body < 4096) {
  13361. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13362. if (n <= 0) { break; }
  13363. body += static_cast<size_t>(n);
  13364. }
  13365. server_body_bytes = body;
  13366. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13367. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13368. SSL_shutdown(ssl);
  13369. }
  13370. SSL_free(ssl);
  13371. detail::close_socket(cli);
  13372. SSL_CTX_free(ctx);
  13373. });
  13374. auto se = detail::scope_exit([&] {
  13375. server_thread.join();
  13376. detail::close_socket(srv);
  13377. });
  13378. SSLClient cli("127.0.0.1", port);
  13379. cli.enable_server_certificate_verification(false);
  13380. cli.set_connection_timeout(5, 0);
  13381. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13382. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13383. std::string body(4096, 'A');
  13384. auto res = cli.Put("/api/test", body, "application/json");
  13385. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13386. EXPECT_EQ(StatusCode::OK_200, res->status);
  13387. EXPECT_EQ(body.size(), server_body_bytes.load());
  13388. }
  13389. #endif
  13390. template <typename S, typename C>
  13391. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13392. svr.Get("/stream", [&](const Request &, Response &res) {
  13393. auto data = new std::string("01234567890123456789");
  13394. res.set_content_provider(
  13395. data->size(), "text/plain",
  13396. [&, data](size_t offset, size_t length, DataSink &sink) {
  13397. const size_t DATA_CHUNK_SIZE = 4;
  13398. const auto &d = *data;
  13399. std::this_thread::sleep_for(std::chrono::seconds(1));
  13400. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13401. return true;
  13402. },
  13403. [data](bool success) {
  13404. EXPECT_FALSE(success);
  13405. delete data;
  13406. });
  13407. });
  13408. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13409. auto i = new size_t(0);
  13410. res.set_content_provider(
  13411. "text/plain",
  13412. [i](size_t, DataSink &sink) {
  13413. if (*i < 5) {
  13414. std::this_thread::sleep_for(std::chrono::seconds(1));
  13415. sink.write("abcd", 4);
  13416. (*i)++;
  13417. } else {
  13418. sink.done();
  13419. }
  13420. return true;
  13421. },
  13422. [i](bool success) {
  13423. EXPECT_FALSE(success);
  13424. delete i;
  13425. });
  13426. });
  13427. svr.Get("/chunked", [&](const Request &, Response &res) {
  13428. auto i = new size_t(0);
  13429. res.set_chunked_content_provider(
  13430. "text/plain",
  13431. [i](size_t, DataSink &sink) {
  13432. if (*i < 5) {
  13433. std::this_thread::sleep_for(std::chrono::seconds(1));
  13434. sink.os << "abcd";
  13435. (*i)++;
  13436. } else {
  13437. sink.done();
  13438. }
  13439. return true;
  13440. },
  13441. [i](bool success) {
  13442. EXPECT_FALSE(success);
  13443. delete i;
  13444. });
  13445. });
  13446. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13447. auto se = detail::scope_exit([&] {
  13448. svr.stop();
  13449. listen_thread.join();
  13450. ASSERT_FALSE(svr.is_running());
  13451. });
  13452. svr.wait_until_ready();
  13453. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13454. {
  13455. auto start = std::chrono::steady_clock::now();
  13456. auto res = cli.Get("/stream");
  13457. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13458. std::chrono::steady_clock::now() - start)
  13459. .count();
  13460. ASSERT_FALSE(res);
  13461. EXPECT_EQ(Error::Read, res.error());
  13462. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13463. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13464. }
  13465. {
  13466. auto start = std::chrono::steady_clock::now();
  13467. auto res = cli.Get("/stream_without_length");
  13468. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13469. std::chrono::steady_clock::now() - start)
  13470. .count();
  13471. ASSERT_FALSE(res);
  13472. EXPECT_EQ(Error::Read, res.error());
  13473. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13474. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13475. }
  13476. {
  13477. auto start = std::chrono::steady_clock::now();
  13478. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13479. EXPECT_EQ("abcd", string(data, data_length));
  13480. return true;
  13481. });
  13482. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13483. std::chrono::steady_clock::now() - start)
  13484. .count();
  13485. ASSERT_FALSE(res);
  13486. EXPECT_EQ(Error::Read, res.error());
  13487. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13488. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13489. }
  13490. }
  13491. TEST(MaxTimeoutTest, ContentStream) {
  13492. time_t timeout = 2000;
  13493. time_t threshold = 200;
  13494. Server svr;
  13495. Client cli("localhost", PORT);
  13496. max_timeout_test(svr, cli, timeout, threshold);
  13497. }
  13498. #ifdef CPPHTTPLIB_SSL_ENABLED
  13499. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13500. time_t timeout = 2000;
  13501. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13503. SSLClient cli("localhost", PORT);
  13504. cli.enable_server_certificate_verification(false);
  13505. max_timeout_test(svr, cli, timeout, threshold);
  13506. }
  13507. #endif
  13508. class EventDispatcher {
  13509. public:
  13510. EventDispatcher() {}
  13511. bool wait_event(DataSink *sink) {
  13512. unique_lock<mutex> lk(m_);
  13513. int id = id_;
  13514. // Wait with timeout to prevent hanging if client disconnects
  13515. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13516. [&] { return cid_ == id; })) {
  13517. return false; // Timeout occurred
  13518. }
  13519. sink->write(message_.data(), message_.size());
  13520. return true;
  13521. }
  13522. void send_event(const string &message) {
  13523. lock_guard<mutex> lk(m_);
  13524. cid_ = id_++;
  13525. message_ = message;
  13526. cv_.notify_all();
  13527. }
  13528. private:
  13529. mutex m_;
  13530. condition_variable cv_;
  13531. atomic_int id_{0};
  13532. atomic_int cid_{-1};
  13533. string message_;
  13534. };
  13535. TEST(ClientInThreadTest, Issue2068) {
  13536. EventDispatcher ed;
  13537. Server svr;
  13538. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13539. res.set_chunked_content_provider("text/event-stream",
  13540. [&](size_t /*offset*/, DataSink &sink) {
  13541. return ed.wait_event(&sink);
  13542. });
  13543. });
  13544. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13545. svr.wait_until_ready();
  13546. thread event_thread([&] {
  13547. int id = 0;
  13548. while (svr.is_running()) {
  13549. this_thread::sleep_for(chrono::milliseconds(500));
  13550. std::stringstream ss;
  13551. ss << "data: " << id << "\n\n";
  13552. ed.send_event(ss.str());
  13553. id++;
  13554. }
  13555. });
  13556. auto se = detail::scope_exit([&] {
  13557. svr.stop();
  13558. listen_thread.join();
  13559. event_thread.join();
  13560. ASSERT_FALSE(svr.is_running());
  13561. });
  13562. {
  13563. auto client = detail::make_unique<Client>(HOST, PORT);
  13564. client->set_read_timeout(std::chrono::minutes(10));
  13565. std::atomic<bool> stop{false};
  13566. std::thread t([&] {
  13567. client->Get("/event1",
  13568. [&](const char *, size_t) -> bool { return !stop; });
  13569. });
  13570. std::this_thread::sleep_for(std::chrono::seconds(2));
  13571. stop = true;
  13572. client->stop();
  13573. t.join();
  13574. // Reset client after thread has finished
  13575. client.reset();
  13576. }
  13577. }
  13578. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13579. auto handled = false;
  13580. Server svr;
  13581. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13583. auto se = detail::scope_exit([&] {
  13584. svr.stop();
  13585. t.join();
  13586. ASSERT_FALSE(svr.is_running());
  13587. ASSERT_FALSE(handled);
  13588. });
  13589. svr.wait_until_ready();
  13590. // Two Content-Length headers with different values — must be rejected
  13591. auto req = "POST /test HTTP/1.1\r\n"
  13592. "Content-Length: 5\r\n"
  13593. "Content-Length: 10\r\n"
  13594. "\r\n"
  13595. "hello";
  13596. std::string response;
  13597. ASSERT_TRUE(send_request(1, req, &response));
  13598. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13599. response.substr(0, response.find("\r\n")));
  13600. }
  13601. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13602. auto handled = false;
  13603. Server svr;
  13604. svr.Post("/test", [&](const Request &, Response &res) {
  13605. handled = true;
  13606. res.set_content("ok", "text/plain");
  13607. });
  13608. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13609. auto se = detail::scope_exit([&] {
  13610. svr.stop();
  13611. t.join();
  13612. ASSERT_FALSE(svr.is_running());
  13613. ASSERT_TRUE(handled);
  13614. });
  13615. svr.wait_until_ready();
  13616. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13617. auto req = "POST /test HTTP/1.1\r\n"
  13618. "Content-Length: 5\r\n"
  13619. "Content-Length: 5\r\n"
  13620. "\r\n"
  13621. "hello";
  13622. std::string response;
  13623. ASSERT_TRUE(send_request(1, req, &response));
  13624. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13625. }
  13626. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13627. Server svr;
  13628. svr.Get("/", [](const Request &req, Response &res) {
  13629. EXPECT_EQ(2U, req.trailers.size());
  13630. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13631. // Denied
  13632. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13633. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13634. // Accepted
  13635. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13636. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13637. EXPECT_TRUE(req.has_trailer("X-World"));
  13638. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13639. res.set_content("ok", "text/plain");
  13640. });
  13641. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13642. auto se = detail::scope_exit([&] {
  13643. svr.stop();
  13644. t.join();
  13645. ASSERT_FALSE(svr.is_running());
  13646. });
  13647. svr.wait_until_ready();
  13648. const std::string req = "GET / HTTP/1.1\r\n"
  13649. "Transfer-Encoding: chunked\r\n"
  13650. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13651. "\r\n"
  13652. "0\r\n"
  13653. "Content-Length: 10\r\n"
  13654. "Host: internal.local\r\n"
  13655. "Content-Type: malicious/content\r\n"
  13656. "Cookie: any\r\n"
  13657. "Set-Cookie: any\r\n"
  13658. "X-Forwarded-For: attacker.com\r\n"
  13659. "X-Real-Ip: 1.1.1.1\r\n"
  13660. "X-Hello: hello\r\n"
  13661. "X-World: world\r\n"
  13662. "\r\n";
  13663. std::string res;
  13664. ASSERT_TRUE(send_request(1, req, &res));
  13665. }
  13666. // A direct client that is not listed in trusted_proxies must not be able to
  13667. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13668. // the peer address on the actual TCP connection determines whether the
  13669. // header is honored.
  13670. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13671. Server svr;
  13672. // Deliberately does NOT include the loopback address the test client
  13673. // actually connects from, so the direct connection is not a trusted proxy.
  13674. svr.set_trusted_proxies({"203.0.113.66"});
  13675. std::string observed_remote_addr;
  13676. svr.Get("/ip", [&](const Request &req, Response &res) {
  13677. observed_remote_addr = req.remote_addr;
  13678. res.set_content("ok", "text/plain");
  13679. });
  13680. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13681. auto se = detail::scope_exit([&] {
  13682. svr.stop();
  13683. t.join();
  13684. ASSERT_FALSE(svr.is_running());
  13685. });
  13686. svr.wait_until_ready();
  13687. Client cli(HOST, PORT);
  13688. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13690. EXPECT_EQ(StatusCode::OK_200, res->status);
  13691. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13692. // ignored entirely and the real connection-level address retained.
  13693. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13694. observed_remote_addr == "127.0.0.1");
  13695. }
  13696. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13697. Server svr;
  13698. std::string observed_remote_addr;
  13699. std::string observed_xff;
  13700. svr.Get("/ip", [&](const Request &req, Response &res) {
  13701. observed_remote_addr = req.remote_addr;
  13702. observed_xff = req.get_header_value("X-Forwarded-For");
  13703. res.set_content("ok", "text/plain");
  13704. });
  13705. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13706. auto se = detail::scope_exit([&] {
  13707. svr.stop();
  13708. t.join();
  13709. ASSERT_FALSE(svr.is_running());
  13710. });
  13711. svr.wait_until_ready();
  13712. Client cli(HOST, PORT);
  13713. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13715. EXPECT_EQ(StatusCode::OK_200, res->status);
  13716. EXPECT_EQ(observed_xff, "203.0.113.66");
  13717. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13718. observed_remote_addr == "127.0.0.1");
  13719. }
  13720. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13721. Server svr;
  13722. svr.set_trusted_proxies({"203.0.113.66"});
  13723. std::string observed_remote_addr;
  13724. std::string observed_xff;
  13725. svr.Get("/ip", [&](const Request &req, Response &res) {
  13726. observed_remote_addr = req.remote_addr;
  13727. observed_xff = req.get_header_value("X-Forwarded-For");
  13728. res.set_content("ok", "text/plain");
  13729. });
  13730. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13731. auto se = detail::scope_exit([&] {
  13732. svr.stop();
  13733. t.join();
  13734. ASSERT_FALSE(svr.is_running());
  13735. });
  13736. svr.wait_until_ready();
  13737. Client cli(HOST, PORT);
  13738. auto res = cli.Get("/ip");
  13739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13740. EXPECT_EQ(StatusCode::OK_200, res->status);
  13741. EXPECT_EQ(observed_xff, "");
  13742. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13743. observed_remote_addr == "127.0.0.1");
  13744. }
  13745. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13746. Server svr;
  13747. // Include the loopback address the test client actually connects from, so
  13748. // the direct connection itself is recognized as the trusted proxy hop.
  13749. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13750. std::string observed_remote_addr;
  13751. std::string observed_xff;
  13752. svr.Get("/ip", [&](const Request &req, Response &res) {
  13753. observed_remote_addr = req.remote_addr;
  13754. observed_xff = req.get_header_value("X-Forwarded-For");
  13755. res.set_content("ok", "text/plain");
  13756. });
  13757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13758. auto se = detail::scope_exit([&] {
  13759. svr.stop();
  13760. t.join();
  13761. ASSERT_FALSE(svr.is_running());
  13762. });
  13763. svr.wait_until_ready();
  13764. Client cli(HOST, PORT);
  13765. auto res = cli.Get(
  13766. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13768. EXPECT_EQ(StatusCode::OK_200, res->status);
  13769. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13770. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13771. }
  13772. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13773. Server svr;
  13774. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13775. std::string observed_remote_addr;
  13776. std::string observed_xff;
  13777. svr.Get("/ip", [&](const Request &req, Response &res) {
  13778. observed_remote_addr = req.remote_addr;
  13779. observed_xff = req.get_header_value("X-Forwarded-For");
  13780. res.set_content("ok", "text/plain");
  13781. });
  13782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13783. auto se = detail::scope_exit([&] {
  13784. svr.stop();
  13785. t.join();
  13786. ASSERT_FALSE(svr.is_running());
  13787. });
  13788. svr.wait_until_ready();
  13789. Client cli(HOST, PORT);
  13790. auto res = cli.Get(
  13791. "/ip",
  13792. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13794. EXPECT_EQ(StatusCode::OK_200, res->status);
  13795. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13796. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13797. }
  13798. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13799. Server svr;
  13800. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13801. std::string observed_remote_addr;
  13802. std::string observed_xff;
  13803. svr.Get("/ip", [&](const Request &req, Response &res) {
  13804. observed_remote_addr = req.remote_addr;
  13805. observed_xff = req.get_header_value("X-Forwarded-For");
  13806. res.set_content("ok", "text/plain");
  13807. });
  13808. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13809. auto se = detail::scope_exit([&] {
  13810. svr.stop();
  13811. t.join();
  13812. ASSERT_FALSE(svr.is_running());
  13813. });
  13814. svr.wait_until_ready();
  13815. Client cli(HOST, PORT);
  13816. auto res = cli.Get(
  13817. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13819. EXPECT_EQ(StatusCode::OK_200, res->status);
  13820. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13821. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13822. // and must not be selected.
  13823. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13824. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13825. }
  13826. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13827. Server svr;
  13828. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13829. std::string observed_remote_addr;
  13830. svr.Get("/ip", [&](const Request &req, Response &res) {
  13831. observed_remote_addr = req.remote_addr;
  13832. res.set_content("ok", "text/plain");
  13833. });
  13834. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13835. auto se = detail::scope_exit([&] {
  13836. svr.stop();
  13837. t.join();
  13838. ASSERT_FALSE(svr.is_running());
  13839. });
  13840. svr.wait_until_ready();
  13841. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13842. // a forged address and the trusted proxy's own address; the forged value must
  13843. // not win over the address the trusted proxy actually recorded.
  13844. Client cli(HOST, PORT);
  13845. auto res = cli.Get(
  13846. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13848. EXPECT_EQ(StatusCode::OK_200, res->status);
  13849. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13850. }
  13851. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13852. Server svr;
  13853. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13854. std::string observed_remote_addr;
  13855. std::string observed_xff;
  13856. svr.Get("/ip", [&](const Request &req, Response &res) {
  13857. observed_remote_addr = req.remote_addr;
  13858. observed_xff = req.get_header_value("X-Forwarded-For");
  13859. res.set_content("ok", "text/plain");
  13860. });
  13861. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13862. auto se = detail::scope_exit([&] {
  13863. svr.stop();
  13864. t.join();
  13865. ASSERT_FALSE(svr.is_running());
  13866. });
  13867. svr.wait_until_ready();
  13868. Client cli(HOST, PORT);
  13869. auto res = cli.Get(
  13870. "/ip",
  13871. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13873. EXPECT_EQ(StatusCode::OK_200, res->status);
  13874. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13875. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13876. }
  13877. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13878. Server svr;
  13879. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13880. std::string observed_remote_addr;
  13881. std::string observed_xff;
  13882. svr.Get("/ip", [&](const Request &req, Response &res) {
  13883. observed_remote_addr = req.remote_addr;
  13884. observed_xff = req.get_header_value("X-Forwarded-For");
  13885. res.set_content("ok", "text/plain");
  13886. });
  13887. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13888. auto se = detail::scope_exit([&] {
  13889. svr.stop();
  13890. t.join();
  13891. ASSERT_FALSE(svr.is_running());
  13892. });
  13893. svr.wait_until_ready();
  13894. std::string raw_req =
  13895. "GET /ip HTTP/1.1\r\n"
  13896. "Host: localhost\r\n"
  13897. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13898. "Connection: close\r\n"
  13899. "\r\n";
  13900. std::string out;
  13901. ASSERT_TRUE(send_request(5, raw_req, &out));
  13902. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13903. // Header parser trims surrounding whitespace of the header value
  13904. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13905. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13906. }
  13907. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13908. // crash the server (it used to call front() on an empty vector inside
  13909. // get_client_ip). The connection-level remote address must be retained instead.
  13910. static void run_malformed_xff_test(const std::string &xff_value) {
  13911. Server svr;
  13912. svr.set_trusted_proxies({"192.0.2.45"});
  13913. std::string observed_remote_addr;
  13914. svr.Get("/ip", [&](const Request &req, Response &res) {
  13915. observed_remote_addr = req.remote_addr;
  13916. res.set_content("ok", "text/plain");
  13917. });
  13918. int port = 0;
  13919. thread t = thread([&]() {
  13920. port = svr.bind_to_any_port(HOST);
  13921. svr.listen_after_bind();
  13922. });
  13923. auto se = detail::scope_exit([&] {
  13924. svr.stop();
  13925. t.join();
  13926. ASSERT_FALSE(svr.is_running());
  13927. });
  13928. svr.wait_until_ready();
  13929. Client cli(HOST, port);
  13930. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13932. EXPECT_EQ(StatusCode::OK_200, res->status);
  13933. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13934. observed_remote_addr == "127.0.0.1");
  13935. }
  13936. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13937. run_malformed_xff_test("");
  13938. }
  13939. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13940. run_malformed_xff_test(",");
  13941. }
  13942. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13943. run_malformed_xff_test(", , ,");
  13944. }
  13945. #ifndef _WIN32
  13946. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13947. Server svr;
  13948. svr.Post("/post", [&](const Request &req, Response &res) {
  13949. res.set_content(req.body, "text/plain");
  13950. });
  13951. svr.Put("/put", [&](const Request &req, Response &res) {
  13952. res.set_content(req.body, "text/plain");
  13953. });
  13954. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13955. res.set_content(req.body, "text/plain");
  13956. });
  13957. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13958. res.set_content(req.body, "text/plain");
  13959. });
  13960. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13961. auto se = detail::scope_exit([&] {
  13962. svr.stop();
  13963. t.join();
  13964. ASSERT_FALSE(svr.is_running());
  13965. });
  13966. svr.wait_until_ready();
  13967. std::string resp;
  13968. // POST without Content-Length
  13969. ASSERT_TRUE(send_request(5,
  13970. "POST /post HTTP/1.1\r\n"
  13971. "Host: localhost\r\n"
  13972. "Connection: close\r\n"
  13973. "\r\n",
  13974. &resp));
  13975. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13976. // PUT without Content-Length
  13977. resp.clear();
  13978. ASSERT_TRUE(send_request(5,
  13979. "PUT /put HTTP/1.1\r\n"
  13980. "Host: localhost\r\n"
  13981. "Connection: close\r\n"
  13982. "\r\n",
  13983. &resp));
  13984. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13985. // PATCH without Content-Length
  13986. resp.clear();
  13987. ASSERT_TRUE(send_request(5,
  13988. "PATCH /patch HTTP/1.1\r\n"
  13989. "Host: localhost\r\n"
  13990. "Connection: close\r\n"
  13991. "\r\n",
  13992. &resp));
  13993. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13994. // DELETE without Content-Length
  13995. resp.clear();
  13996. ASSERT_TRUE(send_request(5,
  13997. "DELETE /delete HTTP/1.1\r\n"
  13998. "Host: localhost\r\n"
  13999. "Connection: close\r\n"
  14000. "\r\n",
  14001. &resp));
  14002. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  14003. }
  14004. #endif
  14005. //==============================================================================
  14006. // open_stream() Tests
  14007. //==============================================================================
  14008. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  14009. std::string result;
  14010. char buf[8192];
  14011. ssize_t n;
  14012. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14013. result.append(buf, static_cast<size_t>(n));
  14014. }
  14015. return result;
  14016. }
  14017. // Mock stream for unit tests
  14018. class MockStream : public Stream {
  14019. public:
  14020. std::string data;
  14021. size_t pos = 0;
  14022. ssize_t error_after = -1; // -1 = no error
  14023. explicit MockStream(const std::string &d, ssize_t err = -1)
  14024. : data(d), error_after(err) {}
  14025. bool is_readable() const override { return true; }
  14026. bool wait_readable() const override { return true; }
  14027. bool wait_writable() const override { return true; }
  14028. ssize_t read(char *ptr, size_t size) override {
  14029. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  14030. if (pos >= data.size()) return 0;
  14031. size_t limit =
  14032. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  14033. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  14034. std::memcpy(ptr, data.data() + pos, to_read);
  14035. pos += to_read;
  14036. return static_cast<ssize_t>(to_read);
  14037. }
  14038. ssize_t write(const char *, size_t) override { return -1; }
  14039. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  14040. ip = "127.0.0.1";
  14041. port = 0;
  14042. }
  14043. void get_local_ip_and_port(std::string &ip, int &port) const override {
  14044. ip = "127.0.0.1";
  14045. port = 0;
  14046. }
  14047. socket_t socket() const override { return INVALID_SOCKET; }
  14048. time_t duration() const override { return 0; }
  14049. };
  14050. TEST(StreamHandleTest, Basic) {
  14051. ClientImpl::StreamHandle handle;
  14052. EXPECT_FALSE(handle.is_valid());
  14053. handle.response = detail::make_unique<Response>();
  14054. handle.error = Error::Connection;
  14055. EXPECT_FALSE(handle.is_valid());
  14056. handle.error = Error::Success;
  14057. EXPECT_TRUE(handle.is_valid());
  14058. }
  14059. TEST(BodyReaderTest, Basic) {
  14060. MockStream stream("Hello, World!");
  14061. detail::BodyReader reader;
  14062. reader.stream = &stream;
  14063. reader.content_length = 13;
  14064. char buf[32];
  14065. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  14066. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  14067. EXPECT_TRUE(reader.eof);
  14068. }
  14069. TEST(BodyReaderTest, NoStream) {
  14070. detail::BodyReader reader;
  14071. char buf[32];
  14072. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14073. EXPECT_EQ(Error::Connection, reader.last_error);
  14074. }
  14075. TEST(BodyReaderTest, Error) {
  14076. MockStream stream("Hello, World!", 5);
  14077. detail::BodyReader reader;
  14078. reader.stream = &stream;
  14079. reader.content_length = 13;
  14080. char buf[32];
  14081. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  14082. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  14083. EXPECT_EQ(Error::Read, reader.last_error);
  14084. }
  14085. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  14086. // Mock-based StreamHandle tests relying on private internals are removed.
  14087. class OpenStreamTest : public ::testing::Test {
  14088. protected:
  14089. void SetUp() override {
  14090. svr_.Get("/hello", [](const Request &, Response &res) {
  14091. res.set_content("Hello World!", "text/plain");
  14092. });
  14093. svr_.Get("/large", [](const Request &, Response &res) {
  14094. res.set_content(std::string(10000, 'X'), "text/plain");
  14095. });
  14096. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  14097. res.set_content("Hello World!", "image/jpeg");
  14098. res.set_header("Content-Encoding", "UTF-8");
  14099. });
  14100. svr_.Get("/chunked", [](const Request &, Response &res) {
  14101. res.set_chunked_content_provider("text/plain",
  14102. [](size_t offset, DataSink &sink) {
  14103. if (offset < 15) {
  14104. sink.write("chunk", 5);
  14105. return true;
  14106. }
  14107. sink.done();
  14108. return true;
  14109. });
  14110. });
  14111. svr_.Get("/compressible", [](const Request &, Response &res) {
  14112. res.set_chunked_content_provider("text/plain", [](size_t offset,
  14113. DataSink &sink) {
  14114. if (offset < 100 * 1024) {
  14115. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  14116. sink.write(chunk.data(), chunk.size());
  14117. return true;
  14118. }
  14119. sink.done();
  14120. return true;
  14121. });
  14122. });
  14123. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  14124. [](const Request & /*req*/, Response &res) {
  14125. auto i = new int(0);
  14126. res.set_header("Trailer", "Content-Length, X-Allowed");
  14127. res.set_chunked_content_provider(
  14128. "text/plain",
  14129. [i](size_t /*offset*/, DataSink &sink) {
  14130. switch (*i) {
  14131. case 0: sink.os << "123"; break;
  14132. case 1: sink.os << "456"; break;
  14133. case 2: sink.os << "789"; break;
  14134. case 3: {
  14135. sink.done_with_trailer(
  14136. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  14137. } break;
  14138. }
  14139. (*i)++;
  14140. return true;
  14141. },
  14142. [i](bool success) {
  14143. EXPECT_TRUE(success);
  14144. delete i;
  14145. });
  14146. });
  14147. // Echo headers endpoint for header-related tests
  14148. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  14149. std::string body;
  14150. for (const auto &h : req.headers) {
  14151. body.append(h.first);
  14152. body.push_back(':');
  14153. body.append(h.second);
  14154. body.push_back('\n');
  14155. }
  14156. res.set_content(body, "text/plain");
  14157. });
  14158. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  14159. std::string body;
  14160. for (const auto &h : req.headers) {
  14161. body.append(h.first);
  14162. body.push_back(':');
  14163. body.append(h.second);
  14164. body.push_back('\n');
  14165. }
  14166. res.set_content(body, "text/plain");
  14167. });
  14168. port_ = svr_.bind_to_any_port("127.0.0.1");
  14169. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14170. svr_.wait_until_ready();
  14171. }
  14172. void TearDown() override {
  14173. svr_.stop();
  14174. if (thread_.joinable()) thread_.join();
  14175. }
  14176. Server svr_;
  14177. std::thread thread_;
  14178. int port_ = 0;
  14179. };
  14180. TEST_F(OpenStreamTest, Basic) {
  14181. Client cli("127.0.0.1", port_);
  14182. auto handle = cli.open_stream("GET", "/hello");
  14183. EXPECT_TRUE(handle.is_valid());
  14184. EXPECT_EQ("Hello World!", read_all(handle));
  14185. }
  14186. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  14187. Client cli("127.0.0.1", port_);
  14188. auto handle = cli.open_stream("GET", "/unknown-encoding");
  14189. ASSERT_TRUE(handle.is_valid());
  14190. EXPECT_EQ("Hello World!", read_all(handle));
  14191. }
  14192. TEST_F(OpenStreamTest, SmallBuffer) {
  14193. Client cli("127.0.0.1", port_);
  14194. auto handle = cli.open_stream("GET", "/hello");
  14195. std::string result;
  14196. char buf[4];
  14197. ssize_t n;
  14198. while ((n = handle.read(buf, sizeof(buf))) > 0)
  14199. result.append(buf, static_cast<size_t>(n));
  14200. EXPECT_EQ("Hello World!", result);
  14201. }
  14202. TEST_F(OpenStreamTest, DefaultHeaders) {
  14203. Client cli("127.0.0.1", port_);
  14204. // open_stream GET should include Host, User-Agent and Accept-Encoding
  14205. {
  14206. auto handle = cli.open_stream("GET", "/echo-headers");
  14207. ASSERT_TRUE(handle.is_valid());
  14208. auto body = read_all(handle);
  14209. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  14210. std::string::npos);
  14211. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  14212. std::string::npos);
  14213. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  14214. }
  14215. // open_stream POST with body and no explicit content_type should NOT add
  14216. // text/plain Content-Type (behavior differs from non-streaming path), but
  14217. // should include Content-Length
  14218. {
  14219. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  14220. ASSERT_TRUE(handle.is_valid());
  14221. auto body = read_all(handle);
  14222. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  14223. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  14224. }
  14225. // open_stream POST with explicit Content-Type should preserve it
  14226. {
  14227. auto handle = cli.open_stream("POST", "/echo-headers", {},
  14228. {{"Content-Type", "application/custom"}},
  14229. "{}", "application/custom");
  14230. ASSERT_TRUE(handle.is_valid());
  14231. auto body = read_all(handle);
  14232. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  14233. }
  14234. // User-specified User-Agent must not be overwritten for stream API
  14235. {
  14236. auto handle = cli.open_stream("GET", "/echo-headers", {},
  14237. {{"User-Agent", "MyAgent/1.2"}});
  14238. ASSERT_TRUE(handle.is_valid());
  14239. auto body = read_all(handle);
  14240. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  14241. }
  14242. }
  14243. TEST_F(OpenStreamTest, Large) {
  14244. Client cli("127.0.0.1", port_);
  14245. auto handle = cli.open_stream("GET", "/large");
  14246. EXPECT_EQ(10000u, read_all(handle).size());
  14247. }
  14248. TEST_F(OpenStreamTest, ConnectionError) {
  14249. Client cli("127.0.0.1", 9999);
  14250. auto handle = cli.open_stream("GET", "/hello");
  14251. EXPECT_FALSE(handle.is_valid());
  14252. }
  14253. TEST_F(OpenStreamTest, Chunked) {
  14254. Client cli("127.0.0.1", port_);
  14255. auto handle = cli.open_stream("GET", "/chunked");
  14256. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14257. "Transfer-Encoding") == "chunked");
  14258. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  14259. }
  14260. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  14261. Client cli("127.0.0.1", port_);
  14262. auto handle =
  14263. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  14264. ASSERT_TRUE(handle.is_valid());
  14265. // Consume body to allow trailers to be received/parsed
  14266. auto body = read_all(handle);
  14267. // Explicitly parse trailers (ensure trailers are available for assertion)
  14268. handle.parse_trailers_if_needed();
  14269. EXPECT_EQ(std::string("123456789"), body);
  14270. // The response should include a Trailer header declaring both names
  14271. ASSERT_TRUE(handle.response);
  14272. EXPECT_TRUE(handle.response->has_header("Trailer"));
  14273. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  14274. handle.response->get_header_value("Trailer"));
  14275. // Prohibited trailer must not be present
  14276. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  14277. // Allowed trailer should be present
  14278. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  14279. EXPECT_EQ(std::string("yes"),
  14280. handle.response->get_trailer_value("X-Allowed"));
  14281. // Verify trailers are NOT present as regular headers
  14282. EXPECT_EQ(std::string(""),
  14283. handle.response->get_header_value("Content-Length"));
  14284. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  14285. }
  14286. static std::thread serve_single_response(std::promise<int> &port_promise,
  14287. const std::string &response) {
  14288. return std::thread([&port_promise, response] {
  14289. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14290. default_socket_options(srv);
  14291. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14292. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14293. sockaddr_in addr{};
  14294. addr.sin_family = AF_INET;
  14295. addr.sin_port = htons(0); // Let OS assign a free port
  14296. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14297. int opt = 1;
  14298. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14299. #ifdef _WIN32
  14300. reinterpret_cast<const char *>(&opt),
  14301. #else
  14302. &opt,
  14303. #endif
  14304. sizeof(opt));
  14305. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  14306. ::listen(srv, 1) != 0) {
  14307. port_promise.set_value(-1);
  14308. detail::close_socket(srv);
  14309. return;
  14310. }
  14311. socklen_t addr_len = sizeof(addr);
  14312. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  14313. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  14314. sockaddr_in cli_addr{};
  14315. socklen_t cli_len = sizeof(cli_addr);
  14316. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14317. if (cli != INVALID_SOCKET) {
  14318. // Read the complete HTTP request (until the blank line that terminates
  14319. // headers) before sending the response. If the server closes the socket
  14320. // while the client's request data is still unread in the kernel receive
  14321. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  14322. // connection on both sides: it discards the client's receive buffer
  14323. // (which already holds our response) and causes any in-progress write on
  14324. // the client to fail with ECONNRESET. Reading all request data first
  14325. // ensures close() emits a graceful FIN.
  14326. {
  14327. char rbuf[256];
  14328. std::string req;
  14329. while (req.find("\r\n\r\n") == std::string::npos) {
  14330. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  14331. if (n <= 0) { break; }
  14332. req.append(rbuf, static_cast<size_t>(n));
  14333. }
  14334. }
  14335. ::send(cli,
  14336. #ifdef _WIN32
  14337. static_cast<const char *>(response.c_str()),
  14338. static_cast<int>(response.size()),
  14339. #else
  14340. response.c_str(), response.size(),
  14341. #endif
  14342. 0);
  14343. detail::close_socket(cli);
  14344. }
  14345. detail::close_socket(srv);
  14346. });
  14347. }
  14348. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  14349. #ifndef _WIN32
  14350. signal(SIGPIPE, SIG_IGN);
  14351. #endif
  14352. std::promise<int> port_promise;
  14353. auto port_future = port_promise.get_future();
  14354. auto server_thread =
  14355. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  14356. "Content-Type: text/plain\r\n"
  14357. "Content-Length: not-a-number\r\n"
  14358. "Connection: close\r\n"
  14359. "\r\n"
  14360. "hello");
  14361. auto port = port_future.get();
  14362. ASSERT_GT(port, 0);
  14363. Client cli("127.0.0.1", port);
  14364. auto handle = cli.open_stream("GET", "/");
  14365. EXPECT_FALSE(handle.is_valid());
  14366. server_thread.join();
  14367. }
  14368. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14369. #ifndef _WIN32
  14370. signal(SIGPIPE, SIG_IGN);
  14371. #endif
  14372. std::promise<int> port_promise;
  14373. auto port_future = port_promise.get_future();
  14374. auto server_thread = serve_single_response(
  14375. port_promise, "HTTP/1.1 200 OK\r\n"
  14376. "Content-Type: text/plain\r\n"
  14377. "Content-Length: 99999999999999999999999999\r\n"
  14378. "Connection: close\r\n"
  14379. "\r\n"
  14380. "hello");
  14381. auto port = port_future.get();
  14382. ASSERT_GT(port, 0);
  14383. // Historically std::stoull would throw std::out_of_range here and crash
  14384. // the process, then parsing silently clamped to a bogus framing length and
  14385. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14386. // so the stream fails to open, matching the not-a-number case above. The
  14387. // process still must NOT terminate.
  14388. Client cli("127.0.0.1", port);
  14389. auto handle = cli.open_stream("GET", "/");
  14390. EXPECT_FALSE(handle.is_valid());
  14391. server_thread.join();
  14392. }
  14393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14394. TEST_F(OpenStreamTest, Gzip) {
  14395. Client cli("127.0.0.1", port_);
  14396. auto handle = cli.open_stream("GET", "/compressible", {},
  14397. {{"Accept-Encoding", "gzip"}});
  14398. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14399. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14400. }
  14401. #endif
  14402. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14403. TEST_F(OpenStreamTest, Brotli) {
  14404. Client cli("127.0.0.1", port_);
  14405. auto handle =
  14406. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14407. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14408. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14409. }
  14410. #endif
  14411. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14412. TEST_F(OpenStreamTest, Zstd) {
  14413. Client cli("127.0.0.1", port_);
  14414. auto handle = cli.open_stream("GET", "/compressible", {},
  14415. {{"Accept-Encoding", "zstd"}});
  14416. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14417. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14418. }
  14419. #endif
  14420. #ifdef CPPHTTPLIB_SSL_ENABLED
  14421. class SSLOpenStreamTest : public ::testing::Test {
  14422. protected:
  14423. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14424. void SetUp() override {
  14425. svr_.Get("/hello", [](const Request &, Response &res) {
  14426. res.set_content("Hello SSL World!", "text/plain");
  14427. });
  14428. svr_.Get("/chunked", [](const Request &, Response &res) {
  14429. res.set_chunked_content_provider("text/plain",
  14430. [](size_t offset, DataSink &sink) {
  14431. if (offset < 15) {
  14432. sink.write("chunk", 5);
  14433. return true;
  14434. }
  14435. sink.done();
  14436. return true;
  14437. });
  14438. });
  14439. svr_.Post("/echo", [](const Request &req, Response &res) {
  14440. res.set_content(req.body, req.get_header_value("Content-Type"));
  14441. });
  14442. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14443. std::string body = req.body;
  14444. res.set_chunked_content_provider(
  14445. "text/plain", [body](size_t offset, DataSink &sink) {
  14446. if (offset < body.size()) {
  14447. sink.write(body.data() + offset, body.size() - offset);
  14448. }
  14449. sink.done();
  14450. return true;
  14451. });
  14452. });
  14453. port_ = svr_.bind_to_any_port("127.0.0.1");
  14454. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14455. svr_.wait_until_ready();
  14456. }
  14457. void TearDown() override {
  14458. svr_.stop();
  14459. if (thread_.joinable()) thread_.join();
  14460. }
  14461. SSLServer svr_;
  14462. std::thread thread_;
  14463. int port_ = 0;
  14464. };
  14465. TEST_F(SSLOpenStreamTest, Basic) {
  14466. SSLClient cli("127.0.0.1", port_);
  14467. cli.enable_server_certificate_verification(false);
  14468. auto handle = cli.open_stream("GET", "/hello");
  14469. ASSERT_TRUE(handle.is_valid());
  14470. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14471. }
  14472. TEST_F(SSLOpenStreamTest, Chunked) {
  14473. SSLClient cli("127.0.0.1", port_);
  14474. cli.enable_server_certificate_verification(false);
  14475. auto handle = cli.open_stream("GET", "/chunked");
  14476. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14477. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14478. "Transfer-Encoding") == "chunked");
  14479. auto body = read_all(handle);
  14480. EXPECT_EQ("chunkchunkchunk", body);
  14481. }
  14482. TEST_F(SSLOpenStreamTest, Post) {
  14483. SSLClient cli("127.0.0.1", port_);
  14484. cli.enable_server_certificate_verification(false);
  14485. auto handle =
  14486. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14487. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14488. EXPECT_EQ(200, handle.response->status);
  14489. auto body = read_all(handle);
  14490. EXPECT_EQ("Hello SSL POST", body);
  14491. }
  14492. TEST_F(SSLOpenStreamTest, PostChunked) {
  14493. SSLClient cli("127.0.0.1", port_);
  14494. cli.enable_server_certificate_verification(false);
  14495. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14496. "Chunked SSL Data", "text/plain");
  14497. ASSERT_TRUE(handle.is_valid());
  14498. EXPECT_EQ(200, handle.response->status);
  14499. auto body = read_all(handle);
  14500. EXPECT_EQ("Chunked SSL Data", body);
  14501. }
  14502. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14503. // Content-Length is terminated by the server closing the connection. When the
  14504. // SSL peer sends a close_notify after the body, the client must treat it as a
  14505. // clean EOF and return a successful response rather than an error.
  14506. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14508. ASSERT_TRUE(svr.is_valid());
  14509. svr.set_keep_alive_max_count(1);
  14510. const std::string expected_body = "Hello from connection-close response!";
  14511. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14512. res.set_content_provider("text/plain",
  14513. [&](size_t offset, DataSink &sink) -> bool {
  14514. if (offset < expected_body.size()) {
  14515. sink.write(expected_body.data() + offset,
  14516. expected_body.size() - offset);
  14517. }
  14518. sink.done();
  14519. return true;
  14520. });
  14521. });
  14522. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14523. auto se = detail::scope_exit([&] {
  14524. svr.stop();
  14525. listen_thread.join();
  14526. ASSERT_FALSE(svr.is_running());
  14527. });
  14528. svr.wait_until_ready();
  14529. SSLClient cli(HOST, PORT);
  14530. cli.enable_server_certificate_verification(false);
  14531. auto res = cli.Get("/no-content-length");
  14532. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14533. EXPECT_EQ(StatusCode::OK_200, res->status);
  14534. EXPECT_EQ(expected_body, res->body);
  14535. }
  14536. #endif // CPPHTTPLIB_SSL_ENABLED
  14537. //==============================================================================
  14538. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14539. // results for various scenarios.
  14540. //==============================================================================
  14541. TEST(ParityTest, GetVsOpenStream) {
  14542. Server svr;
  14543. const std::string path = "/parity";
  14544. const std::string content = "Parity test content: hello world";
  14545. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14546. res.set_content(content, "text/plain");
  14547. });
  14548. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14549. auto se = detail::scope_exit([&] {
  14550. svr.stop();
  14551. t.join();
  14552. ASSERT_FALSE(svr.is_running());
  14553. });
  14554. svr.wait_until_ready();
  14555. Client cli(HOST, PORT);
  14556. // Non-stream path
  14557. auto r1 = cli.Get(path);
  14558. ASSERT_TRUE(r1);
  14559. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14560. // Stream path
  14561. auto h = cli.open_stream("GET", path);
  14562. ASSERT_TRUE(h.is_valid());
  14563. EXPECT_EQ(r1->body, read_all(h));
  14564. }
  14565. // Helper to compress data with provided compressor type T
  14566. template <typename Compressor>
  14567. static std::string compress_payload_for_parity(const std::string &in) {
  14568. std::string out;
  14569. Compressor compressor;
  14570. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14571. [&](const char *data, size_t n) {
  14572. out.append(data, n);
  14573. return true;
  14574. });
  14575. EXPECT_TRUE(ok);
  14576. return out;
  14577. }
  14578. // Helper function for compression parity tests
  14579. template <typename Compressor>
  14580. static void test_compression_parity(const std::string &original,
  14581. const std::string &path,
  14582. const std::string &encoding) {
  14583. const std::string compressed =
  14584. compress_payload_for_parity<Compressor>(original);
  14585. Server svr;
  14586. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14587. res.set_content(compressed, "application/octet-stream");
  14588. res.set_header("Content-Encoding", encoding);
  14589. });
  14590. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14591. auto se = detail::scope_exit([&] {
  14592. svr.stop();
  14593. t.join();
  14594. ASSERT_FALSE(svr.is_running());
  14595. });
  14596. svr.wait_until_ready();
  14597. Client cli(HOST, PORT);
  14598. // Non-streaming
  14599. {
  14600. auto res = cli.Get(path);
  14601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14602. EXPECT_EQ(StatusCode::OK_200, res->status);
  14603. EXPECT_EQ(original, res->body);
  14604. }
  14605. // Streaming
  14606. {
  14607. auto h = cli.open_stream("GET", path);
  14608. ASSERT_TRUE(h.is_valid());
  14609. EXPECT_EQ(original, read_all(h));
  14610. }
  14611. }
  14612. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14613. TEST(ParityTest, Gzip) {
  14614. test_compression_parity<detail::gzip_compressor>(
  14615. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14616. }
  14617. #endif
  14618. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14619. TEST(ParityTest, Brotli) {
  14620. test_compression_parity<detail::brotli_compressor>(
  14621. "Hello, brotli parity test payload", "/parity-br", "br");
  14622. }
  14623. #endif
  14624. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14625. TEST(ParityTest, Zstd) {
  14626. test_compression_parity<detail::zstd_compressor>(
  14627. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14628. }
  14629. #endif
  14630. //==============================================================================
  14631. // New Stream API Tests
  14632. //==============================================================================
  14633. inline std::string read_body(httplib::stream::Result &result) {
  14634. std::string body;
  14635. while (result.next()) {
  14636. body.append(result.data(), result.size());
  14637. }
  14638. return body;
  14639. }
  14640. TEST(ClientConnectionTest, Basic) {
  14641. httplib::ClientConnection conn;
  14642. EXPECT_FALSE(conn.is_open());
  14643. conn.sock = 1;
  14644. EXPECT_TRUE(conn.is_open());
  14645. httplib::ClientConnection conn2(std::move(conn));
  14646. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14647. conn2.sock = INVALID_SOCKET;
  14648. }
  14649. // Unified test server for all stream::* tests
  14650. class StreamApiTest : public ::testing::Test {
  14651. protected:
  14652. void SetUp() override {
  14653. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14654. res.set_content("Hello World!", "text/plain");
  14655. });
  14656. svr_.Get("/echo-params",
  14657. [](const httplib::Request &req, httplib::Response &res) {
  14658. std::string r;
  14659. for (const auto &p : req.params) {
  14660. if (!r.empty()) r += "&";
  14661. r += p.first + "=" + p.second;
  14662. }
  14663. res.set_content(r, "text/plain");
  14664. });
  14665. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14666. res.set_content(req.body, req.get_header_value("Content-Type"));
  14667. });
  14668. svr_.Post("/echo-headers",
  14669. [](const httplib::Request &req, httplib::Response &res) {
  14670. std::string r;
  14671. for (const auto &h : req.headers)
  14672. r += h.first + ": " + h.second + "\n";
  14673. res.set_content(r, "text/plain");
  14674. });
  14675. svr_.Post("/echo-params",
  14676. [](const httplib::Request &req, httplib::Response &res) {
  14677. std::string r = "params:";
  14678. for (const auto &p : req.params)
  14679. r += p.first + "=" + p.second + ";";
  14680. res.set_content(r + " body:" + req.body, "text/plain");
  14681. });
  14682. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14683. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14684. });
  14685. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14686. res.set_content("PUT:" + req.body, "text/plain");
  14687. });
  14688. svr_.Patch("/echo",
  14689. [](const httplib::Request &req, httplib::Response &res) {
  14690. res.set_content("PATCH:" + req.body, "text/plain");
  14691. });
  14692. svr_.Delete(
  14693. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14694. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14695. "text/plain");
  14696. });
  14697. svr_.Get("/head-test",
  14698. [](const httplib::Request &, httplib::Response &res) {
  14699. res.set_content("body for HEAD", "text/plain");
  14700. });
  14701. svr_.Options("/options",
  14702. [](const httplib::Request &, httplib::Response &res) {
  14703. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14704. });
  14705. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14706. svr_.wait_until_ready();
  14707. }
  14708. void TearDown() override {
  14709. svr_.stop();
  14710. if (thread_.joinable()) thread_.join();
  14711. }
  14712. httplib::Server svr_;
  14713. std::thread thread_;
  14714. };
  14715. // stream::Get tests
  14716. TEST_F(StreamApiTest, GetBasic) {
  14717. httplib::Client cli(HOST, PORT);
  14718. auto result = httplib::stream::Get(cli, "/hello");
  14719. ASSERT_TRUE(result.is_valid());
  14720. EXPECT_EQ(200, result.status());
  14721. EXPECT_EQ("Hello World!", read_body(result));
  14722. }
  14723. TEST_F(StreamApiTest, GetWithParams) {
  14724. httplib::Client cli(HOST, PORT);
  14725. httplib::Params params{{"foo", "bar"}};
  14726. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14727. ASSERT_TRUE(result.is_valid());
  14728. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14729. }
  14730. TEST_F(StreamApiTest, GetConnectionError) {
  14731. httplib::Client cli(HOST, 9999);
  14732. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14733. }
  14734. TEST_F(StreamApiTest, Get404) {
  14735. httplib::Client cli(HOST, PORT);
  14736. auto result = httplib::stream::Get(cli, "/nonexistent");
  14737. EXPECT_TRUE(result.is_valid());
  14738. EXPECT_EQ(404, result.status());
  14739. }
  14740. // stream::Post tests
  14741. TEST_F(StreamApiTest, PostBasic) {
  14742. httplib::Client cli(HOST, PORT);
  14743. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14744. "application/json");
  14745. ASSERT_TRUE(result.is_valid());
  14746. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14747. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14748. }
  14749. TEST_F(StreamApiTest, PostWithHeaders) {
  14750. httplib::Client cli(HOST, PORT);
  14751. httplib::Headers headers{{"X-Custom", "value"}};
  14752. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14753. "text/plain");
  14754. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14755. }
  14756. TEST_F(StreamApiTest, PostWithParams) {
  14757. httplib::Client cli(HOST, PORT);
  14758. httplib::Params params{{"k", "v"}};
  14759. auto result =
  14760. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14761. auto body = read_body(result);
  14762. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14763. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14764. }
  14765. TEST_F(StreamApiTest, PostLarge) {
  14766. httplib::Client cli(HOST, PORT);
  14767. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14768. size_t total = 0;
  14769. while (result.next()) {
  14770. total += result.size();
  14771. }
  14772. EXPECT_EQ(100u * 1024u, total);
  14773. }
  14774. // stream::Put/Patch tests
  14775. TEST_F(StreamApiTest, PutAndPatch) {
  14776. httplib::Client cli(HOST, PORT);
  14777. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14778. EXPECT_EQ("PUT:test", read_body(put));
  14779. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14780. EXPECT_EQ("PATCH:test", read_body(patch));
  14781. }
  14782. // stream::Delete tests
  14783. TEST_F(StreamApiTest, Delete) {
  14784. httplib::Client cli(HOST, PORT);
  14785. auto del1 = httplib::stream::Delete(cli, "/resource");
  14786. EXPECT_EQ("Deleted", read_body(del1));
  14787. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14788. EXPECT_EQ("Deleted:data", read_body(del2));
  14789. }
  14790. // stream::Head/Options tests
  14791. TEST_F(StreamApiTest, HeadAndOptions) {
  14792. httplib::Client cli(HOST, PORT);
  14793. auto head = httplib::stream::Head(cli, "/head-test");
  14794. EXPECT_TRUE(head.is_valid());
  14795. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14796. auto opts = httplib::stream::Options(cli, "/options");
  14797. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14798. }
  14799. // SSL stream::* tests
  14800. #ifdef CPPHTTPLIB_SSL_ENABLED
  14801. class SSLStreamApiTest : public ::testing::Test {
  14802. protected:
  14803. void SetUp() override {
  14804. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14805. res.set_content("Hello SSL!", "text/plain");
  14806. });
  14807. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14808. res.set_content(req.body, "text/plain");
  14809. });
  14810. port_ = svr_.bind_to_any_port("127.0.0.1");
  14811. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14812. svr_.wait_until_ready();
  14813. }
  14814. void TearDown() override {
  14815. svr_.stop();
  14816. if (thread_.joinable()) thread_.join();
  14817. }
  14818. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14819. std::thread thread_;
  14820. int port_ = 0;
  14821. };
  14822. TEST_F(SSLStreamApiTest, GetAndPost) {
  14823. httplib::SSLClient cli("127.0.0.1", port_);
  14824. cli.enable_server_certificate_verification(false);
  14825. auto get = httplib::stream::Get(cli, "/hello");
  14826. EXPECT_EQ("Hello SSL!", read_body(get));
  14827. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14828. EXPECT_EQ("test", read_body(post));
  14829. }
  14830. #endif
  14831. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14832. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14833. // BodyReader
  14834. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14835. // Test that read timeout during streaming is detected
  14836. // Use a large content-length response where server delays mid-stream
  14837. Server svr;
  14838. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14839. // Send a large response with delay in the middle
  14840. res.set_content_provider(
  14841. 1000, // content_length
  14842. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14843. if (offset < 100) {
  14844. // Send first 100 bytes immediately
  14845. std::string data(100, 'A');
  14846. sink.write(data.c_str(), data.size());
  14847. return true;
  14848. }
  14849. // Then delay longer than client timeout
  14850. std::this_thread::sleep_for(std::chrono::seconds(3));
  14851. std::string data(900, 'B');
  14852. sink.write(data.c_str(), data.size());
  14853. return true;
  14854. });
  14855. });
  14856. auto port = 8091;
  14857. std::thread t([&]() { svr.listen("localhost", port); });
  14858. svr.wait_until_ready();
  14859. Client cli("localhost", port);
  14860. cli.set_read_timeout(1, 0); // 1 second timeout
  14861. auto handle = cli.open_stream("GET", "/slow-stream");
  14862. ASSERT_TRUE(handle.is_valid());
  14863. char buf[256];
  14864. ssize_t total = 0;
  14865. ssize_t n;
  14866. bool got_error = false;
  14867. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14868. total += n;
  14869. }
  14870. if (n < 0) {
  14871. got_error = true;
  14872. // Should be timeout or read error
  14873. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14874. handle.get_read_error() == Error::Read)
  14875. << "Actual error: " << to_string(handle.get_read_error());
  14876. }
  14877. // Either we got an error, or we got less data than expected
  14878. EXPECT_TRUE(got_error || total < 1000)
  14879. << "Expected timeout but got all " << total << " bytes";
  14880. svr.stop();
  14881. t.join();
  14882. }
  14883. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14884. // Test connection closed detection via BodyReader
  14885. Server svr;
  14886. std::atomic<bool> close_now{false};
  14887. svr.Get("/will-close", [&](const Request &, Response &res) {
  14888. res.set_content_provider(
  14889. 10000, // Large content_length that we won't fully send
  14890. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14891. if (offset < 100) {
  14892. std::string data(100, 'X');
  14893. sink.write(data.c_str(), data.size());
  14894. return true;
  14895. }
  14896. // Wait for signal then abort
  14897. while (!close_now) {
  14898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14899. }
  14900. return false; // Abort - server will close connection
  14901. });
  14902. });
  14903. auto port = 8092;
  14904. std::thread t([&]() { svr.listen("localhost", port); });
  14905. svr.wait_until_ready();
  14906. Client cli("localhost", port);
  14907. auto handle = cli.open_stream("GET", "/will-close");
  14908. ASSERT_TRUE(handle.is_valid());
  14909. char buf[256];
  14910. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14911. EXPECT_GT(n, 0) << "First read should succeed";
  14912. // Signal server to close
  14913. close_now = true;
  14914. // Keep reading until error or EOF
  14915. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14916. // Keep reading
  14917. }
  14918. // Should get an error since content_length wasn't satisfied
  14919. if (n < 0) {
  14920. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14921. handle.get_read_error() == Error::Read)
  14922. << "Actual error: " << to_string(handle.get_read_error());
  14923. }
  14924. svr.stop();
  14925. t.join();
  14926. }
  14927. #ifdef CPPHTTPLIB_SSL_ENABLED
  14928. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14929. // Test that read timeout during SSL streaming is detected
  14930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14931. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14932. res.set_content_provider(
  14933. 1000, "text/plain",
  14934. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14935. if (offset < 100) {
  14936. std::string data(100, 'A');
  14937. sink.write(data.c_str(), data.size());
  14938. return true;
  14939. }
  14940. std::this_thread::sleep_for(std::chrono::seconds(3));
  14941. std::string data(900, 'B');
  14942. sink.write(data.c_str(), data.size());
  14943. return true;
  14944. });
  14945. });
  14946. auto port = 8093;
  14947. std::thread t([&]() { svr.listen("localhost", port); });
  14948. svr.wait_until_ready();
  14949. SSLClient cli("localhost", port);
  14950. cli.enable_server_certificate_verification(false);
  14951. cli.set_read_timeout(1, 0); // 1 second timeout
  14952. auto handle = cli.open_stream("GET", "/slow-stream");
  14953. ASSERT_TRUE(handle.is_valid());
  14954. char buf[256];
  14955. ssize_t total = 0;
  14956. ssize_t n;
  14957. bool got_error = false;
  14958. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14959. total += n;
  14960. }
  14961. if (n < 0) {
  14962. got_error = true;
  14963. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14964. handle.get_read_error() == Error::Read)
  14965. << "Actual error: " << to_string(handle.get_read_error());
  14966. }
  14967. EXPECT_TRUE(got_error || total < 1000)
  14968. << "Expected timeout but got all " << total << " bytes";
  14969. svr.stop();
  14970. t.join();
  14971. }
  14972. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14973. // Test SSL connection closed detection
  14974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14975. std::atomic<bool> close_now{false};
  14976. svr.Get("/will-close", [&](const Request &, Response &res) {
  14977. res.set_content_provider(
  14978. 10000, "text/plain",
  14979. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14980. if (offset < 100) {
  14981. std::string data(100, 'X');
  14982. sink.write(data.c_str(), data.size());
  14983. return true;
  14984. }
  14985. while (!close_now) {
  14986. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14987. }
  14988. return false;
  14989. });
  14990. });
  14991. auto port = 8094;
  14992. std::thread t([&]() { svr.listen("localhost", port); });
  14993. svr.wait_until_ready();
  14994. SSLClient cli("localhost", port);
  14995. cli.enable_server_certificate_verification(false);
  14996. auto handle = cli.open_stream("GET", "/will-close");
  14997. ASSERT_TRUE(handle.is_valid());
  14998. char buf[256];
  14999. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  15000. EXPECT_GT(n, 0);
  15001. // Signal server to close
  15002. close_now = true;
  15003. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  15004. // Keep reading
  15005. }
  15006. if (n < 0) {
  15007. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  15008. handle.get_read_error() == Error::Read)
  15009. << "Actual error: " << to_string(handle.get_read_error());
  15010. }
  15011. svr.stop();
  15012. t.join();
  15013. }
  15014. #endif
  15015. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  15016. using namespace httplib;
  15017. // Create a test file
  15018. const char *fname = "etag_testfile.txt";
  15019. const char *content = "etag-content";
  15020. {
  15021. std::ofstream ofs(fname);
  15022. ofs << content;
  15023. ASSERT_TRUE(ofs.good());
  15024. }
  15025. Server svr;
  15026. svr.set_mount_point("/static", ".");
  15027. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15028. svr.wait_until_ready();
  15029. Client cli(HOST, PORT);
  15030. // First request: should get 200 with ETag header
  15031. auto res1 = cli.Get("/static/etag_testfile.txt");
  15032. ASSERT_TRUE(res1);
  15033. ASSERT_EQ(200, res1->status);
  15034. ASSERT_TRUE(res1->has_header("ETag"));
  15035. std::string etag = res1->get_header_value("ETag");
  15036. EXPECT_FALSE(etag.empty());
  15037. // Verify ETag format: W/"hex-hex"
  15038. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  15039. EXPECT_EQ('W', etag[0]);
  15040. EXPECT_EQ('/', etag[1]);
  15041. EXPECT_EQ('"', etag[2]);
  15042. EXPECT_EQ('"', etag.back());
  15043. // Exact match: expect 304 Not Modified
  15044. Headers h2 = {{"If-None-Match", etag}};
  15045. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  15046. ASSERT_TRUE(res2);
  15047. EXPECT_EQ(304, res2->status);
  15048. // Wildcard match: expect 304 Not Modified
  15049. Headers h3 = {{"If-None-Match", "*"}};
  15050. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  15051. ASSERT_TRUE(res3);
  15052. EXPECT_EQ(304, res3->status);
  15053. // Non-matching ETag: expect 200
  15054. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  15055. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  15056. ASSERT_TRUE(res4);
  15057. EXPECT_EQ(200, res4->status);
  15058. // Multiple ETags with one matching: expect 304
  15059. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  15060. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  15061. ASSERT_TRUE(res5);
  15062. EXPECT_EQ(304, res5->status);
  15063. svr.stop();
  15064. t.join();
  15065. std::remove(fname);
  15066. }
  15067. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  15068. using namespace httplib;
  15069. Server svr;
  15070. svr.set_mount_point("/static", ".");
  15071. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15072. svr.wait_until_ready();
  15073. Client cli(HOST, PORT);
  15074. // Send If-None-Match: * to a non-existent file
  15075. Headers h = {{"If-None-Match", "*"}};
  15076. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  15077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15078. EXPECT_EQ(404, res->status);
  15079. svr.stop();
  15080. t.join();
  15081. }
  15082. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  15083. using namespace httplib;
  15084. // Create a test file
  15085. const char *fname = "etag_boundary_testfile.txt";
  15086. const char *content = "boundary-test";
  15087. {
  15088. std::ofstream ofs(fname);
  15089. ofs << content;
  15090. ASSERT_TRUE(ofs.good());
  15091. }
  15092. Server svr;
  15093. svr.set_mount_point("/static", ".");
  15094. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  15095. svr.wait_until_ready();
  15096. Client cli(HOST, PORT);
  15097. // Get the actual ETag
  15098. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  15099. ASSERT_TRUE(res1);
  15100. ASSERT_EQ(200, res1->status);
  15101. ASSERT_TRUE(res1->has_header("ETag"));
  15102. std::string etag = res1->get_header_value("ETag");
  15103. // Test 1: Very long ETag value (longer than actual ETag)
  15104. // Should NOT match and return 200 (not trigger out-of-bounds read)
  15105. Headers h1 = {{"If-None-Match", "W/"
  15106. "\"very-long-etag-value-that-is-much-longer-"
  15107. "than-the-actual-etag-value\""}};
  15108. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  15109. ASSERT_TRUE(res2);
  15110. EXPECT_EQ(200, res2->status); // Should not match
  15111. // Test 2: Long string followed by wildcard
  15112. // Should match on "*" and return 304 (without out-of-bounds read on the long
  15113. // string)
  15114. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  15115. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  15116. ASSERT_TRUE(res3);
  15117. EXPECT_EQ(304, res3->status); // Should match on "*"
  15118. // Test 3: Wildcard followed by long string
  15119. // Should match on "*" immediately and return 304
  15120. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  15121. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  15122. ASSERT_TRUE(res4);
  15123. EXPECT_EQ(304, res4->status); // Should match on "*"
  15124. // Test 4: Multiple long non-matching values
  15125. // Should NOT match and return 200 (test that all comparisons are safe)
  15126. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  15127. "W/\"second-long-non-matching-value\", "
  15128. "W/\"third-long-non-matching-value\""}};
  15129. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  15130. ASSERT_TRUE(res5);
  15131. EXPECT_EQ(200, res5->status); // Should not match
  15132. // Test 5: Single character that is not "*" (edge case)
  15133. Headers h5 = {{"If-None-Match", "X"}};
  15134. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  15135. ASSERT_TRUE(res6);
  15136. EXPECT_EQ(200, res6->status); // Should not match
  15137. svr.stop();
  15138. t.join();
  15139. std::remove(fname);
  15140. }
  15141. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  15142. using namespace httplib;
  15143. // Create a test file
  15144. const char *fname = "ims_testfile.txt";
  15145. const char *content = "if-modified-since-test";
  15146. {
  15147. std::ofstream ofs(fname);
  15148. ofs << content;
  15149. ASSERT_TRUE(ofs.good());
  15150. }
  15151. Server svr;
  15152. svr.set_mount_point("/static", ".");
  15153. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15154. svr.wait_until_ready();
  15155. Client cli(HOST, PORT);
  15156. // First request: should get 200 with Last-Modified header
  15157. auto res1 = cli.Get("/static/ims_testfile.txt");
  15158. ASSERT_TRUE(res1);
  15159. ASSERT_EQ(200, res1->status);
  15160. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15161. std::string last_modified = res1->get_header_value("Last-Modified");
  15162. EXPECT_FALSE(last_modified.empty());
  15163. // If-Modified-Since with same time: expect 304
  15164. Headers h2 = {{"If-Modified-Since", last_modified}};
  15165. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  15166. ASSERT_TRUE(res2);
  15167. EXPECT_EQ(304, res2->status);
  15168. // If-Modified-Since with future time: expect 304
  15169. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15170. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  15171. ASSERT_TRUE(res3);
  15172. EXPECT_EQ(304, res3->status);
  15173. // If-Modified-Since with past time: expect 200
  15174. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15175. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  15176. ASSERT_TRUE(res4);
  15177. EXPECT_EQ(200, res4->status);
  15178. // If-None-Match takes precedence over If-Modified-Since
  15179. // (send matching ETag with old If-Modified-Since -> should still be 304)
  15180. ASSERT_TRUE(res1->has_header("ETag"));
  15181. std::string etag = res1->get_header_value("ETag");
  15182. Headers h5 = {{"If-None-Match", etag},
  15183. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15184. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  15185. ASSERT_TRUE(res5);
  15186. EXPECT_EQ(304, res5->status);
  15187. svr.stop();
  15188. t.join();
  15189. std::remove(fname);
  15190. }
  15191. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  15192. using namespace httplib;
  15193. Server svr;
  15194. // Endpoint that returns compressible content
  15195. svr.Get("/compressible", [](const Request &, Response &res) {
  15196. // Return a large enough body to trigger compression
  15197. std::string body(1000, 'a');
  15198. res.set_content(body, "text/plain");
  15199. });
  15200. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15201. svr.wait_until_ready();
  15202. Client cli(HOST, PORT);
  15203. // Request with gzip support: should get Vary header when compressed
  15204. cli.set_compress(true);
  15205. auto res1 = cli.Get("/compressible");
  15206. ASSERT_TRUE(res1);
  15207. EXPECT_EQ(200, res1->status);
  15208. // If Content-Encoding is set, Vary should also be set
  15209. if (res1->has_header("Content-Encoding")) {
  15210. EXPECT_TRUE(res1->has_header("Vary"));
  15211. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  15212. }
  15213. // Request without Accept-Encoding header: should not have compression
  15214. Headers h_no_compress;
  15215. auto res2 = cli.Get("/compressible", h_no_compress);
  15216. ASSERT_TRUE(res2);
  15217. EXPECT_EQ(200, res2->status);
  15218. // Verify Vary header is present when compression is applied
  15219. // (the exact behavior depends on server configuration)
  15220. svr.stop();
  15221. t.join();
  15222. }
  15223. TEST(ETagTest, IfRangeWithETag) {
  15224. using namespace httplib;
  15225. // Create a test file with known content
  15226. const char *fname = "if_range_testfile.txt";
  15227. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  15228. {
  15229. std::ofstream ofs(fname);
  15230. ofs << content;
  15231. ASSERT_TRUE(ofs.good());
  15232. }
  15233. Server svr;
  15234. svr.set_mount_point("/static", ".");
  15235. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15236. svr.wait_until_ready();
  15237. Client cli(HOST, PORT);
  15238. // First request: get ETag
  15239. auto res1 = cli.Get("/static/if_range_testfile.txt");
  15240. ASSERT_TRUE(res1);
  15241. ASSERT_EQ(200, res1->status);
  15242. ASSERT_TRUE(res1->has_header("ETag"));
  15243. std::string etag = res1->get_header_value("ETag");
  15244. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  15245. // Since our server generates weak ETags (W/"..."), If-Range with our
  15246. // ETag should NOT result in partial content - it should return full content.
  15247. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  15248. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  15249. ASSERT_TRUE(res2);
  15250. // Weak ETag in If-Range -> full content (200), not partial (206)
  15251. EXPECT_EQ(200, res2->status);
  15252. EXPECT_EQ(content, res2->body);
  15253. EXPECT_FALSE(res2->has_header("Content-Range"));
  15254. // Range request with non-matching If-Range (ETag): should get 200 (full
  15255. // content)
  15256. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  15257. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  15258. ASSERT_TRUE(res3);
  15259. EXPECT_EQ(200, res3->status);
  15260. EXPECT_EQ(content, res3->body);
  15261. EXPECT_FALSE(res3->has_header("Content-Range"));
  15262. // Range request with strong ETag (hypothetical - our server doesn't generate
  15263. // strong ETags, but if client sends a strong ETag that doesn't match, it
  15264. // should return full content)
  15265. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  15266. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  15267. ASSERT_TRUE(res4);
  15268. EXPECT_EQ(200, res4->status);
  15269. EXPECT_EQ(content, res4->body);
  15270. EXPECT_FALSE(res4->has_header("Content-Range"));
  15271. svr.stop();
  15272. t.join();
  15273. std::remove(fname);
  15274. }
  15275. TEST(ETagTest, IfRangeWithDate) {
  15276. using namespace httplib;
  15277. // Create a test file
  15278. const char *fname = "if_range_date_testfile.txt";
  15279. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  15280. {
  15281. std::ofstream ofs(fname);
  15282. ofs << content;
  15283. ASSERT_TRUE(ofs.good());
  15284. }
  15285. Server svr;
  15286. svr.set_mount_point("/static", ".");
  15287. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15288. svr.wait_until_ready();
  15289. Client cli(HOST, PORT);
  15290. // First request: get Last-Modified
  15291. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  15292. ASSERT_TRUE(res1);
  15293. ASSERT_EQ(200, res1->status);
  15294. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15295. std::string last_modified = res1->get_header_value("Last-Modified");
  15296. // Range request with matching If-Range (date): should get 206
  15297. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  15298. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  15299. ASSERT_TRUE(res2);
  15300. EXPECT_EQ(206, res2->status);
  15301. EXPECT_EQ("FGHIJ", res2->body);
  15302. // Range request with old If-Range date: should get 200 (full content)
  15303. Headers h3 = {{"Range", "bytes=5-9"},
  15304. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  15305. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  15306. ASSERT_TRUE(res3);
  15307. EXPECT_EQ(200, res3->status);
  15308. EXPECT_EQ(content, res3->body);
  15309. // Range request with future If-Range date: should get 206
  15310. Headers h4 = {{"Range", "bytes=0-4"},
  15311. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  15312. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  15313. ASSERT_TRUE(res4);
  15314. EXPECT_EQ(206, res4->status);
  15315. EXPECT_EQ("ABCDE", res4->body);
  15316. svr.stop();
  15317. t.join();
  15318. std::remove(fname);
  15319. }
  15320. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  15321. using namespace httplib;
  15322. const char *fname = "etag_malformed.txt";
  15323. const char *content = "malformed-etag";
  15324. {
  15325. std::ofstream ofs(fname);
  15326. ofs << content;
  15327. ASSERT_TRUE(ofs.good());
  15328. }
  15329. Server svr;
  15330. svr.set_mount_point("/static", ".");
  15331. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15332. svr.wait_until_ready();
  15333. Client cli(HOST, PORT);
  15334. // baseline: should get 200 and an ETag
  15335. auto res1 = cli.Get("/static/etag_malformed.txt");
  15336. ASSERT_TRUE(res1);
  15337. ASSERT_EQ(200, res1->status);
  15338. ASSERT_TRUE(res1->has_header("ETag"));
  15339. // Malformed ETag value (missing quotes) should be treated as non-matching
  15340. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  15341. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  15342. ASSERT_TRUE(res_bad);
  15343. EXPECT_EQ(200, res_bad->status);
  15344. // Whitespace-only header value should be considered invalid / non-matching
  15345. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  15346. "Host: localhost\r\n"
  15347. "If-None-Match: \r\n"
  15348. "Connection: close\r\n"
  15349. "\r\n";
  15350. std::string out;
  15351. ASSERT_TRUE(send_request(5, raw_req, &out));
  15352. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  15353. svr.stop();
  15354. t.join();
  15355. std::remove(fname);
  15356. }
  15357. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15358. using namespace httplib;
  15359. const char *fname = "ims_invalid_format.txt";
  15360. const char *content = "ims-bad-format";
  15361. {
  15362. std::ofstream ofs(fname);
  15363. ofs << content;
  15364. ASSERT_TRUE(ofs.good());
  15365. }
  15366. Server svr;
  15367. svr.set_mount_point("/static", ".");
  15368. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15369. svr.wait_until_ready();
  15370. Client cli(HOST, PORT);
  15371. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15372. ASSERT_TRUE(res1);
  15373. ASSERT_EQ(200, res1->status);
  15374. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15375. // If-Modified-Since with invalid format should not result in 304
  15376. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15377. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15378. ASSERT_TRUE(res_bad);
  15379. EXPECT_EQ(200, res_bad->status);
  15380. // If-Range with invalid date format should be treated as mismatch -> full
  15381. // content (200)
  15382. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15383. {"If-Range", "invalid-date"}};
  15384. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15385. ASSERT_TRUE(res_ifrange);
  15386. EXPECT_EQ(200, res_ifrange->status);
  15387. svr.stop();
  15388. t.join();
  15389. std::remove(fname);
  15390. }
  15391. TEST(ETagTest, IfRangeWithMalformedETag) {
  15392. using namespace httplib;
  15393. const char *fname = "ifrange_malformed.txt";
  15394. const std::string content = "0123456789";
  15395. {
  15396. std::ofstream ofs(fname);
  15397. ofs << content;
  15398. ASSERT_TRUE(ofs.good());
  15399. }
  15400. Server svr;
  15401. svr.set_mount_point("/static", ".");
  15402. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15403. svr.wait_until_ready();
  15404. Client cli(HOST, PORT);
  15405. // First request: get ETag
  15406. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15407. ASSERT_TRUE(res1);
  15408. ASSERT_EQ(200, res1->status);
  15409. ASSERT_TRUE(res1->has_header("ETag"));
  15410. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15411. // full content (200)
  15412. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15413. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15414. ASSERT_TRUE(res2);
  15415. EXPECT_EQ(200, res2->status);
  15416. EXPECT_EQ(content, res2->body);
  15417. svr.stop();
  15418. t.join();
  15419. std::remove(fname);
  15420. }
  15421. TEST(ETagTest, ExtremeLargeDateValues) {
  15422. using namespace httplib;
  15423. const char *fname = "ims_extreme_date.txt";
  15424. const char *content = "ims-extreme-date";
  15425. {
  15426. std::ofstream ofs(fname);
  15427. ofs << content;
  15428. ASSERT_TRUE(ofs.good());
  15429. }
  15430. Server svr;
  15431. svr.set_mount_point("/static", ".");
  15432. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15433. svr.wait_until_ready();
  15434. Client cli(HOST, PORT);
  15435. auto res1 = cli.Get(std::string("/static/") + fname);
  15436. ASSERT_TRUE(res1);
  15437. ASSERT_EQ(200, res1->status);
  15438. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15439. // Extremely large year that may overflow date parsing routines.
  15440. Headers h_large_date = {
  15441. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15442. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15443. ASSERT_TRUE(res_bad);
  15444. // Expect server to treat this as invalid/mismatch and return full content
  15445. EXPECT_EQ(200, res_bad->status);
  15446. // If-Range with extremely large date should be treated as mismatch -> full
  15447. // content (200)
  15448. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15449. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15450. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15451. ASSERT_TRUE(res_ifrange);
  15452. EXPECT_EQ(200, res_ifrange->status);
  15453. svr.stop();
  15454. t.join();
  15455. std::remove(fname);
  15456. }
  15457. TEST(ETagTest, NegativeFileModificationTime) {
  15458. using namespace httplib;
  15459. const char *fname = "ims_negative_mtime.txt";
  15460. const std::string content = "negative-mtime";
  15461. {
  15462. std::ofstream ofs(fname);
  15463. ofs << content;
  15464. ASSERT_TRUE(ofs.good());
  15465. }
  15466. // Try to set file mtime to a negative value. This may fail on some
  15467. // platforms/filesystems; if it fails, the test will still verify server
  15468. // behaves safely by performing a regular conditional request.
  15469. #if defined(__APPLE__) || defined(__linux__)
  15470. bool set_negative = false;
  15471. do {
  15472. struct timeval times[2];
  15473. // access time: now
  15474. times[0].tv_sec = time(nullptr);
  15475. times[0].tv_usec = 0;
  15476. // modification time: negative (e.g., -1)
  15477. times[1].tv_sec = -1;
  15478. times[1].tv_usec = 0;
  15479. if (utimes(fname, times) == 0) { set_negative = true; }
  15480. } while (0);
  15481. #else
  15482. bool set_negative = false;
  15483. #endif
  15484. Server svr;
  15485. svr.set_mount_point("/static", ".");
  15486. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15487. svr.wait_until_ready();
  15488. Client cli(HOST, PORT);
  15489. auto res1 = cli.Get(std::string("/static/") + fname);
  15490. ASSERT_TRUE(res1);
  15491. ASSERT_EQ(200, res1->status);
  15492. bool has_last_modified = res1->has_header("Last-Modified");
  15493. std::string last_modified;
  15494. if (has_last_modified) {
  15495. last_modified = res1->get_header_value("Last-Modified");
  15496. }
  15497. if (set_negative) {
  15498. // If we successfully set a negative mtime, ensure server returns a
  15499. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15500. // with an old date and ensure server handles it without crash.
  15501. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15502. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15503. ASSERT_TRUE(res2);
  15504. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15505. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15506. } else {
  15507. // Could not set negative mtime on this platform; fall back to verifying
  15508. // that normal invalid/malformed dates are treated safely (non-304).
  15509. Headers h_bad_date = {
  15510. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15511. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15512. ASSERT_TRUE(res_bad);
  15513. EXPECT_EQ(200, res_bad->status);
  15514. }
  15515. svr.stop();
  15516. t.join();
  15517. std::remove(fname);
  15518. }
  15519. //==============================================================================
  15520. // SSE Parsing Tests
  15521. //==============================================================================
  15522. class SSEParsingTest : public ::testing::Test {
  15523. protected:
  15524. // Test helper that mimics SSE parsing behavior
  15525. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15526. int &retry_ms) {
  15527. // Blank line signals end of event
  15528. if (line.empty() || line == "\r") { return true; }
  15529. // Lines starting with ':' are comments (ignored)
  15530. if (!line.empty() && line[0] == ':') { return false; }
  15531. // Find the colon separator
  15532. auto colon_pos = line.find(':');
  15533. if (colon_pos == std::string::npos) {
  15534. // Line with no colon is treated as field name with empty value
  15535. return false;
  15536. }
  15537. std::string field = line.substr(0, colon_pos);
  15538. std::string value;
  15539. // Value starts after colon, skip optional single space
  15540. if (colon_pos + 1 < line.size()) {
  15541. size_t value_start = colon_pos + 1;
  15542. if (line[value_start] == ' ') { value_start++; }
  15543. value = line.substr(value_start);
  15544. // Remove trailing \r if present
  15545. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15546. }
  15547. // Handle known fields
  15548. if (field == "event") {
  15549. msg.event = value;
  15550. } else if (field == "data") {
  15551. // Multiple data lines are concatenated with newlines
  15552. if (!msg.data.empty()) { msg.data += "\n"; }
  15553. msg.data += value;
  15554. } else if (field == "id") {
  15555. // Empty id is valid (clears the last event ID)
  15556. msg.id = value;
  15557. } else if (field == "retry") {
  15558. // Parse retry interval in milliseconds
  15559. {
  15560. int v = 0;
  15561. auto res =
  15562. detail::from_chars(value.data(), value.data() + value.size(), v);
  15563. if (res.ec == std::errc{}) { retry_ms = v; }
  15564. }
  15565. }
  15566. // Unknown fields are ignored per SSE spec
  15567. return false;
  15568. }
  15569. };
  15570. // Test: Single-line data
  15571. TEST_F(SSEParsingTest, SingleLineData) {
  15572. sse::SSEMessage msg;
  15573. int retry_ms = 3000;
  15574. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15575. EXPECT_EQ(msg.data, "hello");
  15576. EXPECT_EQ(msg.event, "message");
  15577. // Blank line ends event
  15578. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15579. }
  15580. // Test: Multi-line data
  15581. TEST_F(SSEParsingTest, MultiLineData) {
  15582. sse::SSEMessage msg;
  15583. int retry_ms = 3000;
  15584. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15585. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15586. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15587. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15588. }
  15589. // Test: Custom event types
  15590. TEST_F(SSEParsingTest, CustomEventType) {
  15591. sse::SSEMessage msg;
  15592. int retry_ms = 3000;
  15593. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15594. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15595. EXPECT_EQ(msg.event, "update");
  15596. EXPECT_EQ(msg.data, "payload");
  15597. }
  15598. // Test: Event ID handling
  15599. TEST_F(SSEParsingTest, EventIdHandling) {
  15600. sse::SSEMessage msg;
  15601. int retry_ms = 3000;
  15602. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15603. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15604. EXPECT_EQ(msg.id, "12345");
  15605. }
  15606. // Test: Empty event ID (clears last event ID)
  15607. TEST_F(SSEParsingTest, EmptyEventId) {
  15608. sse::SSEMessage msg;
  15609. msg.id = "previous";
  15610. int retry_ms = 3000;
  15611. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15612. EXPECT_EQ(msg.id, "");
  15613. }
  15614. // Test: Retry field parsing
  15615. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15616. sse::SSEMessage msg;
  15617. int retry_ms = 3000;
  15618. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15619. EXPECT_EQ(retry_ms, 5000);
  15620. }
  15621. // Test: Invalid retry value
  15622. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15623. sse::SSEMessage msg;
  15624. int retry_ms = 3000;
  15625. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15626. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15627. }
  15628. // Test: Comments (lines starting with :)
  15629. TEST_F(SSEParsingTest, CommentsIgnored) {
  15630. sse::SSEMessage msg;
  15631. int retry_ms = 3000;
  15632. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15633. EXPECT_EQ(msg.data, "");
  15634. EXPECT_EQ(msg.event, "message");
  15635. }
  15636. // Test: Colon in value
  15637. TEST_F(SSEParsingTest, ColonInValue) {
  15638. sse::SSEMessage msg;
  15639. int retry_ms = 3000;
  15640. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15641. EXPECT_EQ(msg.data, "hello:world:test");
  15642. }
  15643. // Test: Line with no colon (field name only)
  15644. TEST_F(SSEParsingTest, FieldNameOnly) {
  15645. sse::SSEMessage msg;
  15646. int retry_ms = 3000;
  15647. // According to SSE spec, this is treated as field name with empty value
  15648. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15649. // Since we don't recognize "data" without colon, data should be empty
  15650. EXPECT_EQ(msg.data, "");
  15651. }
  15652. // Test: Trailing \r handling
  15653. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15654. sse::SSEMessage msg;
  15655. int retry_ms = 3000;
  15656. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15657. EXPECT_EQ(msg.data, "hello");
  15658. }
  15659. // Test: Unknown fields ignored
  15660. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15661. sse::SSEMessage msg;
  15662. int retry_ms = 3000;
  15663. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15664. EXPECT_EQ(msg.data, "");
  15665. EXPECT_EQ(msg.event, "message");
  15666. }
  15667. // Test: Space after colon is optional
  15668. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15669. sse::SSEMessage msg1, msg2;
  15670. int retry_ms = 3000;
  15671. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15672. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15673. EXPECT_EQ(msg1.data, "hello");
  15674. EXPECT_EQ(msg2.data, "hello");
  15675. }
  15676. // Test: SSEMessage clear
  15677. TEST_F(SSEParsingTest, MessageClear) {
  15678. sse::SSEMessage msg;
  15679. msg.event = "custom";
  15680. msg.data = "some data";
  15681. msg.id = "123";
  15682. msg.clear();
  15683. EXPECT_EQ(msg.event, "message");
  15684. EXPECT_EQ(msg.data, "");
  15685. EXPECT_EQ(msg.id, "");
  15686. }
  15687. // Test: Complete event parsing
  15688. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15689. sse::SSEMessage msg;
  15690. int retry_ms = 3000;
  15691. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15692. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15693. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15694. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15695. // Blank line ends event
  15696. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15697. EXPECT_EQ(msg.event, "notification");
  15698. EXPECT_EQ(msg.id, "evt-42");
  15699. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15700. EXPECT_EQ(retry_ms, 1000);
  15701. }
  15702. //==============================================================================
  15703. // Integration Tests with Server
  15704. //==============================================================================
  15705. class SSEIntegrationTest : public ::testing::Test {
  15706. protected:
  15707. void SetUp() override {
  15708. stop_server_.store(false);
  15709. events_.clear();
  15710. server_ = httplib::detail::make_unique<Server>();
  15711. setup_server();
  15712. start_server();
  15713. }
  15714. void TearDown() override {
  15715. stop_server_.store(true);
  15716. event_cv_.notify_all();
  15717. server_->stop();
  15718. if (server_thread_.joinable()) { server_thread_.join(); }
  15719. }
  15720. void setup_server() {
  15721. // Simple SSE endpoint
  15722. server_->Get("/events", [this](const Request &req, Response &res) {
  15723. auto last_id = req.get_header_value("Last-Event-ID");
  15724. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15725. res.set_chunked_content_provider(
  15726. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15727. std::unique_lock<std::mutex> lock(event_mutex_);
  15728. if (event_cv_.wait_for(
  15729. lock, std::chrono::milliseconds(200), [this] {
  15730. return !events_.empty() || stop_server_.load();
  15731. })) {
  15732. if (stop_server_.load()) { return false; }
  15733. if (!events_.empty()) {
  15734. std::string event = events_.front();
  15735. events_.erase(events_.begin());
  15736. sink.write(event.data(), event.size());
  15737. return true;
  15738. }
  15739. }
  15740. return !stop_server_.load();
  15741. });
  15742. });
  15743. // Endpoint that returns error
  15744. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15745. res.status = 500;
  15746. res.set_content("Internal Server Error", "text/plain");
  15747. });
  15748. // Endpoint for custom event types
  15749. server_->Get("/custom-events", [](const Request &, Response &res) {
  15750. res.set_chunked_content_provider(
  15751. "text/event-stream", [](size_t offset, DataSink &sink) {
  15752. if (offset == 0) {
  15753. std::string event = "event: update\ndata: updated\n\n"
  15754. "event: delete\ndata: deleted\n\n";
  15755. sink.write(event.data(), event.size());
  15756. }
  15757. return false; // End stream after sending
  15758. });
  15759. });
  15760. }
  15761. void start_server() {
  15762. port_ = server_->bind_to_any_port(HOST);
  15763. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15764. // Wait for server to start
  15765. while (!server_->is_running()) {
  15766. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15767. }
  15768. }
  15769. int get_port() const { return port_; }
  15770. void send_event(const std::string &event) {
  15771. std::lock_guard<std::mutex> lock(event_mutex_);
  15772. events_.push_back(event);
  15773. event_cv_.notify_all();
  15774. }
  15775. std::unique_ptr<Server> server_;
  15776. std::thread server_thread_;
  15777. std::mutex event_mutex_;
  15778. std::condition_variable event_cv_;
  15779. std::vector<std::string> events_;
  15780. std::atomic<bool> stop_server_{false};
  15781. std::string last_received_event_id_;
  15782. int port_ = 0;
  15783. };
  15784. // Test: Successful connection and on_open callback
  15785. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15786. // Add a simple endpoint that sends one event and closes
  15787. server_->Get("/simple-event", [](const Request &, Response &res) {
  15788. res.set_chunked_content_provider(
  15789. "text/event-stream", [](size_t offset, DataSink &sink) {
  15790. if (offset == 0) {
  15791. std::string event = "data: hello\n\n";
  15792. sink.write(event.data(), event.size());
  15793. }
  15794. return false; // Close stream after sending
  15795. });
  15796. });
  15797. Client client("localhost", get_port());
  15798. sse::SSEClient sse(client, "/simple-event");
  15799. std::atomic<bool> open_called{false};
  15800. std::atomic<bool> message_received{false};
  15801. sse.on_open([&open_called]() { open_called.store(true); });
  15802. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15803. if (msg.data == "hello") { message_received.store(true); }
  15804. });
  15805. sse.set_reconnect_interval(100);
  15806. sse.set_max_reconnect_attempts(1);
  15807. // Start async
  15808. sse.start_async();
  15809. // Wait for message to be processed
  15810. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15811. sse.stop();
  15812. EXPECT_TRUE(open_called.load());
  15813. EXPECT_TRUE(message_received.load());
  15814. }
  15815. // Test: on_message callback
  15816. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15817. // Endpoint that sends multiple events then closes
  15818. server_->Get("/multi-event", [](const Request &, Response &res) {
  15819. res.set_chunked_content_provider(
  15820. "text/event-stream", [](size_t offset, DataSink &sink) {
  15821. if (offset == 0) {
  15822. std::string events = "data: message1\n\ndata: message2\n\n";
  15823. sink.write(events.data(), events.size());
  15824. }
  15825. return false;
  15826. });
  15827. });
  15828. Client client("localhost", get_port());
  15829. sse::SSEClient sse(client, "/multi-event");
  15830. std::vector<std::string> received_messages;
  15831. std::mutex messages_mutex;
  15832. sse.on_message([&](const sse::SSEMessage &msg) {
  15833. std::lock_guard<std::mutex> lock(messages_mutex);
  15834. received_messages.push_back(msg.data);
  15835. });
  15836. sse.set_reconnect_interval(100);
  15837. sse.set_max_reconnect_attempts(1);
  15838. sse.start_async();
  15839. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15840. sse.stop();
  15841. std::lock_guard<std::mutex> lock(messages_mutex);
  15842. EXPECT_GE(received_messages.size(), 2u);
  15843. if (received_messages.size() >= 2) {
  15844. EXPECT_EQ(received_messages[0], "message1");
  15845. EXPECT_EQ(received_messages[1], "message2");
  15846. }
  15847. }
  15848. // Test: on_event for specific types
  15849. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15850. Client client("localhost", get_port());
  15851. sse::SSEClient sse(client, "/custom-events");
  15852. std::atomic<bool> update_received{false};
  15853. std::atomic<bool> delete_received{false};
  15854. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15855. if (msg.data == "updated") { update_received.store(true); }
  15856. });
  15857. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15858. if (msg.data == "deleted") { delete_received.store(true); }
  15859. });
  15860. sse.set_max_reconnect_attempts(1);
  15861. sse.start_async();
  15862. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15863. sse.stop();
  15864. EXPECT_TRUE(update_received.load());
  15865. EXPECT_TRUE(delete_received.load());
  15866. }
  15867. // Test: on_error callback on connection failure
  15868. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15869. // Connect to a non-existent port
  15870. Client client("localhost", 59999);
  15871. sse::SSEClient sse(client, "/events");
  15872. std::atomic<bool> error_called{false};
  15873. Error received_error = Error::Success;
  15874. sse.on_error([&](Error err) {
  15875. error_called.store(true);
  15876. received_error = err;
  15877. });
  15878. sse.set_reconnect_interval(50);
  15879. sse.set_max_reconnect_attempts(1);
  15880. sse.start_async();
  15881. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15882. sse.stop();
  15883. EXPECT_TRUE(error_called.load());
  15884. EXPECT_NE(received_error, Error::Success);
  15885. }
  15886. // Test: Last-Event-ID header sent on reconnect
  15887. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15888. // Endpoint that sends event with ID
  15889. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15890. res.set_chunked_content_provider(
  15891. "text/event-stream", [](size_t offset, DataSink &sink) {
  15892. if (offset == 0) {
  15893. std::string event = "id: evt-123\ndata: test\n\n";
  15894. sink.write(event.data(), event.size());
  15895. }
  15896. return false;
  15897. });
  15898. });
  15899. Client client("localhost", get_port());
  15900. sse::SSEClient sse(client, "/event-with-id");
  15901. std::atomic<bool> id_received{false};
  15902. sse.on_message([&](const sse::SSEMessage &msg) {
  15903. if (!msg.id.empty()) { id_received.store(true); }
  15904. });
  15905. sse.set_reconnect_interval(100);
  15906. sse.set_max_reconnect_attempts(1);
  15907. sse.start_async();
  15908. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15909. sse.stop();
  15910. EXPECT_TRUE(id_received.load());
  15911. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15912. }
  15913. // Test: Manual stop
  15914. TEST_F(SSEIntegrationTest, ManualStop) {
  15915. // Endpoint that sends one event and stays open briefly
  15916. std::atomic<bool> handler_running{true};
  15917. server_->Get("/stay-open", [&handler_running](const Request &,
  15918. Response &res) {
  15919. res.set_chunked_content_provider(
  15920. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15921. if (offset == 0) {
  15922. std::string event = "data: connected\n\n";
  15923. sink.write(event.data(), event.size());
  15924. }
  15925. // Keep connection open while handler_running is true
  15926. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15927. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15928. }
  15929. return false;
  15930. });
  15931. });
  15932. Client client("localhost", get_port());
  15933. sse::SSEClient sse(client, "/stay-open");
  15934. std::atomic<bool> connected{false};
  15935. sse.on_open([&connected]() { connected.store(true); });
  15936. sse.set_reconnect_interval(100);
  15937. sse.set_max_reconnect_attempts(1);
  15938. sse.start_async();
  15939. // Wait for connection to establish
  15940. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15941. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15942. }
  15943. EXPECT_TRUE(connected.load());
  15944. EXPECT_TRUE(sse.is_connected());
  15945. // Signal handler to stop
  15946. handler_running.store(false);
  15947. // Stop SSE client
  15948. sse.stop();
  15949. EXPECT_FALSE(sse.is_connected());
  15950. }
  15951. // Test: SSEClient with custom headers
  15952. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15953. // Setup a server endpoint that checks for custom header
  15954. std::atomic<bool> header_received{false};
  15955. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15956. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15957. header_received.store(true);
  15958. }
  15959. res.set_chunked_content_provider("text/event-stream",
  15960. [](size_t, DataSink &) { return false; });
  15961. });
  15962. Client client("localhost", get_port());
  15963. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15964. sse::SSEClient sse(client, "/header-check", headers);
  15965. sse.set_max_reconnect_attempts(1);
  15966. sse.start_async();
  15967. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15968. sse.stop();
  15969. EXPECT_TRUE(header_received.load());
  15970. }
  15971. // Test: Reconnect interval configuration
  15972. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15973. Client client("localhost", get_port());
  15974. sse::SSEClient sse(client, "/events");
  15975. auto &result = sse.set_reconnect_interval(500);
  15976. // Builder pattern should return reference to self
  15977. EXPECT_EQ(&result, &sse);
  15978. }
  15979. // Test: Max reconnect attempts
  15980. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15981. // Connect to non-existent port to force reconnects
  15982. Client client("localhost", 59998);
  15983. sse::SSEClient sse(client, "/events");
  15984. std::atomic<int> error_count{0};
  15985. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15986. sse.set_reconnect_interval(50);
  15987. sse.set_max_reconnect_attempts(2);
  15988. auto start = std::chrono::steady_clock::now();
  15989. sse.start(); // Blocking call
  15990. auto end = std::chrono::steady_clock::now();
  15991. // Should have stopped after 2 failed attempts
  15992. EXPECT_GE(error_count.load(), 2);
  15993. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15994. auto duration =
  15995. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15996. #ifdef _WIN32
  15997. // Windows is much slower for socket connection failures
  15998. EXPECT_LT(duration.count(), 7000);
  15999. #else
  16000. EXPECT_LT(duration.count(), 1000);
  16001. #endif
  16002. }
  16003. // Test: Multi-line data in integration
  16004. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  16005. // Endpoint with multi-line data
  16006. server_->Get("/multiline-data", [](const Request &, Response &res) {
  16007. res.set_chunked_content_provider(
  16008. "text/event-stream", [](size_t offset, DataSink &sink) {
  16009. if (offset == 0) {
  16010. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  16011. sink.write(event.data(), event.size());
  16012. }
  16013. return false;
  16014. });
  16015. });
  16016. Client client("localhost", get_port());
  16017. sse::SSEClient sse(client, "/multiline-data");
  16018. std::string received_data;
  16019. std::mutex data_mutex;
  16020. sse.on_message([&](const sse::SSEMessage &msg) {
  16021. std::lock_guard<std::mutex> lock(data_mutex);
  16022. received_data = msg.data;
  16023. });
  16024. sse.set_reconnect_interval(100);
  16025. sse.set_max_reconnect_attempts(1);
  16026. sse.start_async();
  16027. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16028. sse.stop();
  16029. std::lock_guard<std::mutex> lock(data_mutex);
  16030. EXPECT_EQ(received_data, "line1\nline2\nline3");
  16031. }
  16032. // Test: Auto-reconnect after server disconnection
  16033. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  16034. std::atomic<int> connection_count{0};
  16035. std::atomic<int> message_count{0};
  16036. // Endpoint that sends one event and closes, forcing reconnect
  16037. server_->Get("/reconnect-test",
  16038. [&connection_count](const Request &, Response &res) {
  16039. connection_count.fetch_add(1);
  16040. res.set_chunked_content_provider(
  16041. "text/event-stream", [](size_t offset, DataSink &sink) {
  16042. if (offset == 0) {
  16043. std::string event = "data: hello\n\n";
  16044. sink.write(event.data(), event.size());
  16045. }
  16046. return false; // Close connection after sending
  16047. });
  16048. });
  16049. Client client("localhost", get_port());
  16050. sse::SSEClient sse(client, "/reconnect-test");
  16051. sse.on_message([&message_count](const sse::SSEMessage &) {
  16052. message_count.fetch_add(1);
  16053. });
  16054. sse.set_reconnect_interval(100);
  16055. sse.set_max_reconnect_attempts(3);
  16056. sse.start_async();
  16057. // Wait long enough for multiple reconnects
  16058. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16059. sse.stop();
  16060. // Should have connected multiple times (initial + reconnects)
  16061. EXPECT_GE(connection_count.load(), 2);
  16062. // Should have received messages from multiple connections
  16063. EXPECT_GE(message_count.load(), 2);
  16064. }
  16065. // Test: Last-Event-ID sent on reconnect
  16066. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  16067. std::atomic<int> connection_count{0};
  16068. std::vector<std::string> received_last_event_ids;
  16069. std::mutex id_mutex;
  16070. // Endpoint that checks Last-Event-ID header and sends event with ID
  16071. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  16072. int conn = connection_count.fetch_add(1);
  16073. // Capture the Last-Event-ID header from each connection
  16074. {
  16075. std::lock_guard<std::mutex> lock(id_mutex);
  16076. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  16077. }
  16078. res.set_chunked_content_provider(
  16079. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  16080. if (offset == 0) {
  16081. std::string event =
  16082. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  16083. sink.write(event.data(), event.size());
  16084. }
  16085. return false;
  16086. });
  16087. });
  16088. Client client("localhost", get_port());
  16089. sse::SSEClient sse(client, "/reconnect-with-id");
  16090. sse.set_reconnect_interval(100);
  16091. sse.set_max_reconnect_attempts(3);
  16092. sse.start_async();
  16093. // Wait for at least 2 connections
  16094. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  16095. sse.stop();
  16096. // Verify behavior
  16097. std::lock_guard<std::mutex> lock(id_mutex);
  16098. EXPECT_GE(received_last_event_ids.size(), 2u);
  16099. // First connection should have no Last-Event-ID
  16100. if (!received_last_event_ids.empty()) {
  16101. EXPECT_EQ(received_last_event_ids[0], "");
  16102. }
  16103. // Second connection should have Last-Event-ID from first connection
  16104. if (received_last_event_ids.size() >= 2) {
  16105. EXPECT_EQ(received_last_event_ids[1], "event-0");
  16106. }
  16107. }
  16108. // Test: set_headers updates headers used on reconnect
  16109. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  16110. std::vector<std::string> received_tokens;
  16111. std::mutex token_mutex;
  16112. // Endpoint that captures Authorization header
  16113. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  16114. {
  16115. std::lock_guard<std::mutex> lock(token_mutex);
  16116. received_tokens.push_back(req.get_header_value("Authorization"));
  16117. }
  16118. res.set_chunked_content_provider(
  16119. "text/event-stream", [](size_t offset, DataSink &sink) {
  16120. if (offset == 0) {
  16121. std::string event = "data: hello\n\n";
  16122. sink.write(event.data(), event.size());
  16123. }
  16124. return false; // Close connection to trigger reconnect
  16125. });
  16126. });
  16127. Client client("localhost", get_port());
  16128. Headers headers = {{"Authorization", "Bearer old-token"}};
  16129. sse::SSEClient sse(client, "/auth-check", headers);
  16130. // Update headers on each successful connection
  16131. sse.on_open(
  16132. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  16133. sse.set_reconnect_interval(100);
  16134. sse.set_max_reconnect_attempts(3);
  16135. sse.start_async();
  16136. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16137. sse.stop();
  16138. std::lock_guard<std::mutex> lock(token_mutex);
  16139. ASSERT_GE(received_tokens.size(), 2u);
  16140. // First connection uses original header
  16141. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  16142. // Second connection uses updated header from set_headers
  16143. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  16144. }
  16145. // Test: 401 allows reconnection (so on_error can refresh headers)
  16146. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  16147. std::atomic<int> connection_count{0};
  16148. // Endpoint: returns 401 on first attempt, 200 on second
  16149. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  16150. int conn = connection_count.fetch_add(1);
  16151. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  16152. res.status = StatusCode::Unauthorized_401;
  16153. res.set_content("Unauthorized", "text/plain");
  16154. return;
  16155. }
  16156. res.set_chunked_content_provider(
  16157. "text/event-stream", [](size_t offset, DataSink &sink) {
  16158. if (offset == 0) {
  16159. std::string event = "data: authenticated\n\n";
  16160. sink.write(event.data(), event.size());
  16161. }
  16162. return false;
  16163. });
  16164. });
  16165. Client client("localhost", get_port());
  16166. Headers headers = {{"Authorization", "Bearer expired"}};
  16167. sse::SSEClient sse(client, "/auth-retry", headers);
  16168. std::atomic<bool> message_received{false};
  16169. // Refresh token on error
  16170. sse.on_error(
  16171. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  16172. sse.on_message([&](const sse::SSEMessage &msg) {
  16173. if (msg.data == "authenticated") { message_received.store(true); }
  16174. });
  16175. sse.set_reconnect_interval(100);
  16176. sse.set_max_reconnect_attempts(3);
  16177. sse.start_async();
  16178. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  16179. sse.stop();
  16180. // Should have reconnected after 401 and succeeded with new token
  16181. EXPECT_GE(connection_count.load(), 2);
  16182. EXPECT_TRUE(message_received.load());
  16183. }
  16184. TEST(Issue2318Test, EmptyHostString) {
  16185. {
  16186. httplib::Client cli_empty("", PORT);
  16187. auto res = cli_empty.Get("/");
  16188. ASSERT_FALSE(res);
  16189. EXPECT_EQ(httplib::Error::Connection, res.error());
  16190. }
  16191. {
  16192. httplib::Client cli(" ", PORT);
  16193. auto res = cli.Get("/");
  16194. ASSERT_FALSE(res);
  16195. EXPECT_EQ(httplib::Error::Connection, res.error());
  16196. }
  16197. }
  16198. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16199. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  16200. Server svr;
  16201. // Set a small payload limit (1KB)
  16202. svr.set_payload_max_length(1024);
  16203. svr.Post("/test", [&](const Request &req, Response &res) {
  16204. res.set_content("Body size: " + std::to_string(req.body.size()),
  16205. "text/plain");
  16206. });
  16207. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16208. auto se = detail::scope_exit([&] {
  16209. svr.stop();
  16210. listen_thread.join();
  16211. });
  16212. svr.wait_until_ready();
  16213. // Create data that compresses well but exceeds limit when decompressed
  16214. // 8KB of repeated null bytes compresses to a very small size
  16215. std::string original_data(8 * 1024, '\0');
  16216. // Compress the data using gzip
  16217. std::string compressed_data;
  16218. detail::gzip_compressor compressor;
  16219. compressor.compress(original_data.data(), original_data.size(), true,
  16220. [&](const char *data, size_t size) {
  16221. compressed_data.append(data, size);
  16222. return true;
  16223. });
  16224. // Verify compression worked (compressed should be much smaller)
  16225. ASSERT_LT(compressed_data.size(), original_data.size());
  16226. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  16227. // Send compressed data with Content-Encoding: gzip
  16228. Client cli(HOST, PORT);
  16229. Headers headers = {{"Content-Encoding", "gzip"}};
  16230. auto res =
  16231. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  16232. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  16233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16234. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  16235. }
  16236. #endif
  16237. // ============================================================================
  16238. // OpenSSL-Specific Tests
  16239. // ============================================================================
  16240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16241. X509 *readCertificate(const std::string &strFileName) {
  16242. std::ifstream inStream(strFileName);
  16243. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  16244. std::istreambuf_iterator<char>());
  16245. if (strCertPEM.empty()) return (nullptr);
  16246. BIO *pbCert = BIO_new(BIO_s_mem());
  16247. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  16248. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  16249. BIO_free(pbCert);
  16250. return (pCert);
  16251. }
  16252. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  16253. std::ifstream inStream(strFileName);
  16254. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  16255. std::istreambuf_iterator<char>());
  16256. if (strPrivateKeyPEM.empty()) return (nullptr);
  16257. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  16258. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  16259. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  16260. BIO_free(pbPrivKey);
  16261. return (pPrivateKey);
  16262. }
  16263. TEST(BindServerTest, UpdateCerts) {
  16264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16265. int port = svr.bind_to_any_port("0.0.0.0");
  16266. ASSERT_TRUE(svr.is_valid());
  16267. ASSERT_TRUE(port > 0);
  16268. X509 *cert = readCertificate(SERVER_CERT_FILE);
  16269. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  16270. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  16271. ASSERT_TRUE(cert != nullptr);
  16272. ASSERT_TRUE(ca_cert != nullptr);
  16273. ASSERT_TRUE(key != nullptr);
  16274. X509_STORE *cert_store = X509_STORE_new();
  16275. X509_STORE_add_cert(cert_store, ca_cert);
  16276. // svr.update_certs(cert, key, cert_store); // deprecated
  16277. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  16278. CLIENT_CA_CERT_FILE);
  16279. ASSERT_TRUE(svr.is_valid());
  16280. svr.stop();
  16281. X509_STORE_free(cert_store);
  16282. X509_free(cert);
  16283. X509_free(ca_cert);
  16284. EVP_PKEY_free(key);
  16285. }
  16286. // Test that update_certs() updates client CA list correctly
  16287. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  16288. // Start with file-based constructor
  16289. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16290. ASSERT_TRUE(svr.is_valid());
  16291. // Initially no client CA list should be set
  16292. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16293. ASSERT_TRUE(ssl_ctx != nullptr);
  16294. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  16295. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  16296. EXPECT_EQ(0, count_before);
  16297. // Now update with client CA (PEM string)
  16298. std::string cert_pem, key_pem, ca_pem;
  16299. read_file(SERVER_CERT_FILE, cert_pem);
  16300. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  16301. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  16302. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  16303. ASSERT_TRUE(svr.is_valid());
  16304. // Now client CA list should be set
  16305. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  16306. ASSERT_TRUE(ca_list_after != nullptr);
  16307. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  16308. }
  16309. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  16310. // Test that the file-path SSLServer constructor properly sets the client CA
  16311. // list that is sent to clients during the TLS handshake (CertificateRequest)
  16312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  16313. ASSERT_TRUE(svr.is_valid());
  16314. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  16315. ASSERT_TRUE(ssl_ctx != nullptr);
  16316. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  16317. ASSERT_TRUE(ca_list != nullptr);
  16318. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  16319. }
  16320. #endif
  16321. // ============================================================================
  16322. // MbedTLS-Specific Tests
  16323. // ============================================================================
  16324. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  16325. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  16326. using namespace httplib::tls;
  16327. // Track if callback was invoked
  16328. bool callback_invoked = false;
  16329. // The callback receives void* ctx which is actually MbedTlsContext*
  16330. // We can access the mbedtls_ssl_config via the context
  16331. auto setup_callback = [&callback_invoked](void *ctx) {
  16332. callback_invoked = true;
  16333. // Cast to MbedTlsContext* to access the ssl config
  16334. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  16335. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  16336. // Use static variables to hold certificate data (simplified for test)
  16337. static mbedtls_x509_crt own_cert;
  16338. static mbedtls_pk_context own_key;
  16339. static mbedtls_x509_crt ca_chain;
  16340. static bool initialized = false;
  16341. if (!initialized) {
  16342. mbedtls_x509_crt_init(&own_cert);
  16343. mbedtls_pk_init(&own_key);
  16344. mbedtls_x509_crt_init(&ca_chain);
  16345. // Load server certificate
  16346. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  16347. return false;
  16348. }
  16349. // Load server private key.
  16350. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  16351. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  16352. #if MBEDTLS_VERSION_MAJOR == 3
  16353. ,
  16354. mbedtls_ctr_drbg_random, nullptr
  16355. #endif
  16356. ) != 0) {
  16357. return false;
  16358. }
  16359. // Load CA chain for client verification
  16360. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16361. return false;
  16362. }
  16363. initialized = true;
  16364. }
  16365. // Configure the SSL config
  16366. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16367. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16368. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16369. // Set minimum TLS version using mbedTLS native API
  16370. #if MBEDTLS_VERSION_MAJOR >= 3
  16371. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16372. #else
  16373. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16374. MBEDTLS_SSL_MINOR_VERSION_3);
  16375. #endif
  16376. return true;
  16377. };
  16378. SSLServer svr(setup_callback);
  16379. ASSERT_TRUE(svr.is_valid());
  16380. ASSERT_TRUE(callback_invoked);
  16381. svr.Get("/test", [&](const Request &req, Response &res) {
  16382. res.set_content("test", "text/plain");
  16383. auto cert = req.peer_cert();
  16384. ASSERT_TRUE(static_cast<bool>(cert));
  16385. auto common_name = cert.subject_cn();
  16386. EXPECT_EQ("Common Name", common_name);
  16387. });
  16388. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16389. auto se = detail::scope_exit([&] {
  16390. svr.stop();
  16391. t.join();
  16392. ASSERT_FALSE(svr.is_running());
  16393. });
  16394. svr.wait_until_ready();
  16395. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16396. cli.enable_server_certificate_verification(false);
  16397. cli.set_connection_timeout(30);
  16398. auto res = cli.Get("/test");
  16399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16400. ASSERT_EQ(StatusCode::OK_200, res->status);
  16401. }
  16402. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16403. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16404. // keep-alive SSL session, which reads through that config in
  16405. // mbedtls_ssl_close_notify.
  16406. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16408. ASSERT_TRUE(svr.is_valid());
  16409. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16410. res.set_content("test", "text/plain");
  16411. });
  16412. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16413. auto se = detail::scope_exit([&] {
  16414. svr.stop();
  16415. t.join();
  16416. ASSERT_FALSE(svr.is_running());
  16417. });
  16418. svr.wait_until_ready();
  16419. {
  16420. SSLClient cli(HOST, PORT);
  16421. cli.enable_server_certificate_verification(false);
  16422. cli.set_keep_alive(true);
  16423. auto res = cli.Get("/test");
  16424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16425. ASSERT_EQ(StatusCode::OK_200, res->status);
  16426. // cli is destructed here with the keep-alive SSL session still open.
  16427. }
  16428. }
  16429. #endif
  16430. // WebSocket Tests
  16431. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16432. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16433. // defining the meaning of these bits has been negotiated.
  16434. auto make_frame = [](uint8_t first_byte) {
  16435. std::string frame;
  16436. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16437. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16438. frame += "Hello";
  16439. return frame;
  16440. };
  16441. // RSV1 set (0x40)
  16442. {
  16443. detail::BufferStream strm;
  16444. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16445. ws::Opcode opcode;
  16446. std::string payload;
  16447. bool fin;
  16448. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16449. false, 1024));
  16450. }
  16451. // RSV2 set (0x20)
  16452. {
  16453. detail::BufferStream strm;
  16454. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16455. ws::Opcode opcode;
  16456. std::string payload;
  16457. bool fin;
  16458. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16459. false, 1024));
  16460. }
  16461. // RSV3 set (0x10)
  16462. {
  16463. detail::BufferStream strm;
  16464. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16465. ws::Opcode opcode;
  16466. std::string payload;
  16467. bool fin;
  16468. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16469. false, 1024));
  16470. }
  16471. // No RSV bits set - should succeed
  16472. {
  16473. detail::BufferStream strm;
  16474. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16475. ws::Opcode opcode;
  16476. std::string payload;
  16477. bool fin;
  16478. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16479. false, 1024));
  16480. EXPECT_EQ(ws::Opcode::Text, opcode);
  16481. EXPECT_EQ("Hello", payload);
  16482. EXPECT_TRUE(fin);
  16483. }
  16484. }
  16485. TEST(WebSocketTest, ControlFrameValidation) {
  16486. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16487. // payload length <= 125.
  16488. // Ping with FIN=0 - must be rejected
  16489. {
  16490. detail::BufferStream strm;
  16491. std::string frame;
  16492. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16493. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16494. strm.write(frame.data(), frame.size());
  16495. ws::Opcode opcode;
  16496. std::string payload;
  16497. bool fin;
  16498. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16499. false, 1024));
  16500. }
  16501. // Close with FIN=0 - must be rejected
  16502. {
  16503. detail::BufferStream strm;
  16504. std::string frame;
  16505. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16506. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16507. strm.write(frame.data(), frame.size());
  16508. ws::Opcode opcode;
  16509. std::string payload;
  16510. bool fin;
  16511. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16512. false, 1024));
  16513. }
  16514. // Ping with payload_len=126 (extended length) - must be rejected
  16515. {
  16516. detail::BufferStream strm;
  16517. std::string frame;
  16518. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16519. frame += static_cast<char>(126); // payload_len=126 (>125)
  16520. frame += static_cast<char>(0x00); // extended length high byte
  16521. frame += static_cast<char>(126); // extended length low byte
  16522. frame += std::string(126, 'x');
  16523. strm.write(frame.data(), frame.size());
  16524. ws::Opcode opcode;
  16525. std::string payload;
  16526. bool fin;
  16527. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16528. false, 1024));
  16529. }
  16530. // Ping with FIN=1 and payload_len=125 - should succeed
  16531. {
  16532. detail::BufferStream strm;
  16533. std::string frame;
  16534. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16535. frame += static_cast<char>(125); // payload_len=125
  16536. frame += std::string(125, 'x');
  16537. strm.write(frame.data(), frame.size());
  16538. ws::Opcode opcode;
  16539. std::string payload;
  16540. bool fin;
  16541. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16542. false, 1024));
  16543. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16544. EXPECT_EQ(125u, payload.size());
  16545. EXPECT_TRUE(fin);
  16546. }
  16547. }
  16548. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16549. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16550. // length MUST be 0.
  16551. // MSB set - must be rejected
  16552. {
  16553. detail::BufferStream strm;
  16554. std::string frame;
  16555. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16556. frame += static_cast<char>(127); // 64-bit extended length
  16557. frame += static_cast<char>(0x80); // MSB set (invalid)
  16558. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16559. strm.write(frame.data(), frame.size());
  16560. ws::Opcode opcode;
  16561. std::string payload;
  16562. bool fin;
  16563. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16564. false, 1024));
  16565. }
  16566. // MSB clear - should pass length parsing (will be rejected by max_len,
  16567. // but that's a different check; use a small length to verify)
  16568. {
  16569. detail::BufferStream strm;
  16570. std::string frame;
  16571. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16572. frame += static_cast<char>(127); // 64-bit extended length
  16573. frame += std::string(7, '\0'); // high bytes = 0
  16574. frame += static_cast<char>(0x03); // length = 3
  16575. frame += "abc";
  16576. strm.write(frame.data(), frame.size());
  16577. ws::Opcode opcode;
  16578. std::string payload;
  16579. bool fin;
  16580. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16581. false, 1024));
  16582. EXPECT_EQ(ws::Opcode::Text, opcode);
  16583. EXPECT_EQ("abc", payload);
  16584. }
  16585. }
  16586. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16587. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16588. // Valid UTF-8
  16589. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16590. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16591. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16592. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16593. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16594. // Invalid UTF-8
  16595. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16596. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16597. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16598. EXPECT_FALSE(
  16599. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16600. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16601. }
  16602. TEST(WebSocketTest, ConnectAndDisconnect) {
  16603. Server svr;
  16604. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16605. std::string msg;
  16606. while (ws.read(msg)) {}
  16607. });
  16608. auto port = svr.bind_to_any_port(HOST);
  16609. std::thread t([&]() { svr.listen_after_bind(); });
  16610. svr.wait_until_ready();
  16611. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16612. ASSERT_TRUE(client.connect());
  16613. EXPECT_TRUE(client.is_open());
  16614. client.close();
  16615. EXPECT_FALSE(client.is_open());
  16616. svr.stop();
  16617. t.join();
  16618. }
  16619. TEST(WebSocketTest, ValidURL) {
  16620. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16621. EXPECT_TRUE(ws1.is_valid());
  16622. ws::WebSocketClient ws2("ws://example.com/path");
  16623. EXPECT_TRUE(ws2.is_valid());
  16624. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16625. EXPECT_TRUE(ws3.is_valid());
  16626. #ifdef CPPHTTPLIB_SSL_ENABLED
  16627. ws::WebSocketClient wss1("wss://example.com/path");
  16628. EXPECT_TRUE(wss1.is_valid());
  16629. ws::WebSocketClient wss2("wss://example.com:443/path");
  16630. EXPECT_TRUE(wss2.is_valid());
  16631. #endif
  16632. }
  16633. TEST(WebSocketTest, InvalidURL) {
  16634. // No scheme
  16635. ws::WebSocketClient ws1("localhost:8080/path");
  16636. EXPECT_FALSE(ws1.is_valid());
  16637. // No path
  16638. ws::WebSocketClient ws2("ws://localhost:8080");
  16639. EXPECT_FALSE(ws2.is_valid());
  16640. // Empty string
  16641. ws::WebSocketClient ws3("");
  16642. EXPECT_FALSE(ws3.is_valid());
  16643. // Missing host
  16644. ws::WebSocketClient ws4("ws://:8080/path");
  16645. EXPECT_FALSE(ws4.is_valid());
  16646. // Port number overflow — should not crash
  16647. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16648. EXPECT_FALSE(ws5.is_valid());
  16649. // Port out of range
  16650. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16651. EXPECT_FALSE(ws6.is_valid());
  16652. }
  16653. TEST(WebSocketTest, UnsupportedScheme) {
  16654. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16655. ws::WebSocketClient ws1("http://localhost:8080/path");
  16656. EXPECT_FALSE(ws1.is_valid());
  16657. ws::WebSocketClient ws2("https://localhost:8080/path");
  16658. EXPECT_FALSE(ws2.is_valid());
  16659. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16660. EXPECT_FALSE(ws3.is_valid());
  16661. #else
  16662. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16663. std::invalid_argument);
  16664. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16665. std::invalid_argument);
  16666. #endif
  16667. }
  16668. TEST(WebSocketTest, ConnectWhenInvalid) {
  16669. ws::WebSocketClient ws("not a valid url");
  16670. EXPECT_FALSE(ws.is_valid());
  16671. EXPECT_FALSE(ws.connect());
  16672. }
  16673. TEST(WebSocketTest, DefaultPort) {
  16674. ws::WebSocketClient ws1("ws://example.com/path");
  16675. EXPECT_TRUE(ws1.is_valid());
  16676. // ws:// defaults to port 80 (verified by successful parse)
  16677. #ifdef CPPHTTPLIB_SSL_ENABLED
  16678. ws::WebSocketClient ws2("wss://example.com/path");
  16679. EXPECT_TRUE(ws2.is_valid());
  16680. // wss:// defaults to port 443 (verified by successful parse)
  16681. #endif
  16682. }
  16683. TEST(WebSocketTest, IPv6LiteralAddress) {
  16684. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16685. EXPECT_TRUE(ws1.is_valid());
  16686. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16687. EXPECT_TRUE(ws2.is_valid());
  16688. }
  16689. TEST(WebSocketTest, ComplexPath) {
  16690. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16691. EXPECT_TRUE(ws1.is_valid());
  16692. ws::WebSocketClient ws2("ws://localhost:8080/");
  16693. EXPECT_TRUE(ws2.is_valid());
  16694. }
  16695. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16696. Server svr;
  16697. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16698. std::string msg;
  16699. while (ws.read(msg)) {}
  16700. });
  16701. auto port = svr.bind_to_any_port(HOST);
  16702. std::thread t([&]() { svr.listen_after_bind(); });
  16703. svr.wait_until_ready();
  16704. auto another_host = "example.com";
  16705. auto wrong_ip = "192.0.2.1";
  16706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16707. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16708. ASSERT_TRUE(client.connect());
  16709. EXPECT_TRUE(client.is_open());
  16710. client.close();
  16711. svr.stop();
  16712. t.join();
  16713. }
  16714. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16715. Server svr;
  16716. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16717. std::string msg;
  16718. while (ws.read(msg)) {}
  16719. });
  16720. auto port = svr.bind_to_any_port(HOST);
  16721. std::thread t([&]() { svr.listen_after_bind(); });
  16722. svr.wait_until_ready();
  16723. auto wrong_ip = "192.0.2.1";
  16724. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16725. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16726. client.set_connection_timeout(1);
  16727. client.set_read_timeout(1);
  16728. client.set_write_timeout(1);
  16729. EXPECT_FALSE(client.connect());
  16730. EXPECT_FALSE(client.is_open());
  16731. svr.stop();
  16732. t.join();
  16733. }
  16734. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16735. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16736. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16737. // (RFC 6761) is only a map key and the Host header value.
  16738. auto host = "target.invalid";
  16739. Server svr;
  16740. std::string received_host;
  16741. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16742. received_host = req.get_header_value("Host");
  16743. std::string msg;
  16744. while (ws.read(msg)) {}
  16745. });
  16746. auto port = svr.bind_to_any_port(HOST);
  16747. std::thread t([&]() { svr.listen_after_bind(); });
  16748. // ASSERT_* below returns from the test body, which would leave t joinable
  16749. // and make ~thread call std::terminate.
  16750. auto se = detail::scope_exit([&] {
  16751. svr.stop();
  16752. if (t.joinable()) { t.join(); }
  16753. });
  16754. svr.wait_until_ready();
  16755. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16756. std::to_string(port) + "/ws");
  16757. client.set_hostname_addr_map({{host, HOST}});
  16758. ASSERT_TRUE(client.connect());
  16759. EXPECT_TRUE(client.is_open());
  16760. client.close();
  16761. svr.stop();
  16762. t.join();
  16763. // The mapping only redirects the connection; the identity stays host_.
  16764. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16765. }
  16766. class WebSocketIntegrationTest : public ::testing::Test {
  16767. protected:
  16768. void SetUp() override {
  16769. server_ = httplib::detail::make_unique<Server>();
  16770. setup_server();
  16771. start_server();
  16772. }
  16773. void TearDown() override {
  16774. server_->stop();
  16775. if (server_thread_.joinable()) { server_thread_.join(); }
  16776. }
  16777. void setup_server() {
  16778. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16779. std::string msg;
  16780. ws::ReadResult ret;
  16781. while ((ret = ws.read(msg))) {
  16782. if (ret == ws::Binary) {
  16783. ws.send(msg.data(), msg.size());
  16784. } else {
  16785. ws.send(msg);
  16786. }
  16787. }
  16788. });
  16789. server_->WebSocket("/ws-echo-string",
  16790. [](const Request &, ws::WebSocket &ws) {
  16791. std::string msg;
  16792. while (ws.read(msg)) {
  16793. ws.send("echo: " + msg);
  16794. }
  16795. });
  16796. server_->WebSocket(
  16797. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16798. // Echo back request metadata
  16799. ws.send("path:" + req.path);
  16800. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16801. std::string msg;
  16802. while (ws.read(msg)) {}
  16803. });
  16804. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16805. std::string msg;
  16806. ws.read(msg); // wait for a message
  16807. ws.close();
  16808. });
  16809. server_->WebSocket("/ws-close-status",
  16810. [](const Request &, ws::WebSocket &ws) {
  16811. std::string msg;
  16812. ws.read(msg); // wait for a message
  16813. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16814. });
  16815. server_->WebSocket(
  16816. "/ws-subprotocol",
  16817. [](const Request &, ws::WebSocket &ws) {
  16818. std::string msg;
  16819. while (ws.read(msg)) {
  16820. ws.send(msg);
  16821. }
  16822. },
  16823. [](const std::vector<std::string> &protocols) -> std::string {
  16824. for (const auto &p : protocols) {
  16825. if (p == "graphql-ws") { return p; }
  16826. }
  16827. return "";
  16828. });
  16829. }
  16830. void start_server() {
  16831. port_ = server_->bind_to_any_port(HOST);
  16832. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16833. server_->wait_until_ready();
  16834. }
  16835. std::unique_ptr<Server> server_;
  16836. std::thread server_thread_;
  16837. int port_ = 0;
  16838. };
  16839. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16841. "/ws-echo");
  16842. ASSERT_TRUE(client.connect());
  16843. ASSERT_TRUE(client.is_open());
  16844. ASSERT_TRUE(client.send("Hello WebSocket"));
  16845. std::string msg;
  16846. EXPECT_EQ(ws::Text, client.read(msg));
  16847. EXPECT_EQ("Hello WebSocket", msg);
  16848. client.close();
  16849. }
  16850. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16851. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16852. "/ws-echo");
  16853. ASSERT_TRUE(client.connect());
  16854. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16855. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16856. std::string msg;
  16857. EXPECT_EQ(ws::Binary, client.read(msg));
  16858. EXPECT_EQ(binary_data, msg);
  16859. client.close();
  16860. }
  16861. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16862. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16863. "/ws-echo");
  16864. ASSERT_TRUE(client.connect());
  16865. for (int i = 0; i < 10; i++) {
  16866. auto text = "message " + std::to_string(i);
  16867. ASSERT_TRUE(client.send(text));
  16868. std::string msg;
  16869. ASSERT_TRUE(client.read(msg));
  16870. EXPECT_EQ(text, msg);
  16871. }
  16872. client.close();
  16873. }
  16874. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16875. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16876. "/ws-close");
  16877. ASSERT_TRUE(client.connect());
  16878. // Send a message to trigger the server to close
  16879. ASSERT_TRUE(client.send("trigger close"));
  16880. // The server will close, so read should return false
  16881. std::string msg;
  16882. EXPECT_FALSE(client.read(msg));
  16883. EXPECT_FALSE(client.is_open());
  16884. }
  16885. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16886. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16887. "/ws-echo");
  16888. ASSERT_TRUE(client.connect());
  16889. // 128KB message
  16890. std::string large_data(128 * 1024, 'X');
  16891. ASSERT_TRUE(client.send(large_data));
  16892. std::string msg;
  16893. ASSERT_TRUE(client.read(msg));
  16894. EXPECT_EQ(large_data, msg);
  16895. client.close();
  16896. }
  16897. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16898. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16899. "/ws-echo");
  16900. ASSERT_TRUE(client.connect());
  16901. const int num_threads = 4;
  16902. std::vector<std::thread> threads;
  16903. std::atomic<int> send_count{0};
  16904. for (int t = 0; t < num_threads; t++) {
  16905. threads.emplace_back([&client, &send_count, t]() {
  16906. for (int i = 0; i < 5; i++) {
  16907. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16908. if (client.send(text)) { send_count++; }
  16909. }
  16910. });
  16911. }
  16912. for (auto &th : threads) {
  16913. th.join();
  16914. }
  16915. int received = 0;
  16916. std::string msg;
  16917. while (received < send_count.load()) {
  16918. if (!client.read(msg)) { break; }
  16919. received++;
  16920. }
  16921. EXPECT_EQ(send_count.load(), received);
  16922. client.close();
  16923. }
  16924. TEST_F(WebSocketIntegrationTest, ReadString) {
  16925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16926. "/ws-echo-string");
  16927. ASSERT_TRUE(client.connect());
  16928. ASSERT_TRUE(client.send("hello"));
  16929. std::string msg;
  16930. ASSERT_TRUE(client.read(msg));
  16931. EXPECT_EQ("echo: hello", msg);
  16932. ASSERT_TRUE(client.send("world"));
  16933. ASSERT_TRUE(client.read(msg));
  16934. EXPECT_EQ("echo: world", msg);
  16935. client.close();
  16936. }
  16937. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16938. Headers headers = {{"X-Test-Header", "test-value"}};
  16939. ws::WebSocketClient client(
  16940. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16941. ASSERT_TRUE(client.connect());
  16942. std::string msg;
  16943. ASSERT_TRUE(client.read(msg));
  16944. EXPECT_EQ("path:/ws-request-info", msg);
  16945. ASSERT_TRUE(client.read(msg));
  16946. EXPECT_EQ("header:test-value", msg);
  16947. client.close();
  16948. }
  16949. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16951. "/ws-echo");
  16952. client.set_read_timeout(1, 0); // 1 second
  16953. ASSERT_TRUE(client.connect());
  16954. // Don't send anything — server echo handler waits for a message,
  16955. // so read() should time out and return false.
  16956. std::string msg;
  16957. EXPECT_FALSE(client.read(msg));
  16958. }
  16959. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16960. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16961. "/ws-echo");
  16962. client.set_read_timeout(5, 0);
  16963. ASSERT_TRUE(client.connect());
  16964. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16965. // The server should reject it and close the connection.
  16966. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16967. client.send(oversized);
  16968. // The server's read() should have failed due to payload limit,
  16969. // so our read() should return false (connection closed).
  16970. std::string msg;
  16971. EXPECT_FALSE(client.read(msg));
  16972. }
  16973. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16974. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16975. "/ws-echo");
  16976. client.set_read_timeout(10, 0);
  16977. ASSERT_TRUE(client.connect());
  16978. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16979. // This should succeed.
  16980. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16981. ASSERT_TRUE(client.send(at_limit));
  16982. std::string msg;
  16983. ASSERT_TRUE(client.read(msg));
  16984. EXPECT_EQ(at_limit.size(), msg.size());
  16985. client.close();
  16986. }
  16987. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16989. "/nonexistent");
  16990. EXPECT_FALSE(client.connect());
  16991. EXPECT_FALSE(client.is_open());
  16992. }
  16993. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16994. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16995. "/ws-echo");
  16996. ASSERT_TRUE(client.connect());
  16997. ASSERT_TRUE(client.send(""));
  16998. std::string msg;
  16999. EXPECT_EQ(ws::Text, client.read(msg));
  17000. EXPECT_EQ("", msg);
  17001. client.close();
  17002. }
  17003. TEST_F(WebSocketIntegrationTest, Reconnect) {
  17004. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17005. "/ws-echo");
  17006. // First connection
  17007. ASSERT_TRUE(client.connect());
  17008. ASSERT_TRUE(client.send("first"));
  17009. std::string msg;
  17010. ASSERT_TRUE(client.read(msg));
  17011. EXPECT_EQ("first", msg);
  17012. client.close();
  17013. EXPECT_FALSE(client.is_open());
  17014. // Reconnect using the same client object
  17015. ASSERT_TRUE(client.connect());
  17016. ASSERT_TRUE(client.is_open());
  17017. ASSERT_TRUE(client.send("second"));
  17018. ASSERT_TRUE(client.read(msg));
  17019. EXPECT_EQ("second", msg);
  17020. client.close();
  17021. }
  17022. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  17023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17024. "/ws-close-status");
  17025. ASSERT_TRUE(client.connect());
  17026. // Trigger the server to close with GoingAway status
  17027. ASSERT_TRUE(client.send("trigger"));
  17028. // read() should return false after receiving the close frame
  17029. std::string msg;
  17030. EXPECT_FALSE(client.read(msg));
  17031. EXPECT_FALSE(client.is_open());
  17032. }
  17033. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  17034. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17035. "/ws-echo");
  17036. ASSERT_TRUE(client.connect());
  17037. client.close(ws::CloseStatus::GoingAway, "client leaving");
  17038. EXPECT_FALSE(client.is_open());
  17039. }
  17040. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  17041. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  17042. ws::WebSocketClient client(
  17043. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17044. ASSERT_TRUE(client.connect());
  17045. // Server should have selected graphql-ws
  17046. EXPECT_EQ("graphql-ws", client.subprotocol());
  17047. client.close();
  17048. }
  17049. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  17050. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  17051. ws::WebSocketClient client(
  17052. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  17053. ASSERT_TRUE(client.connect());
  17054. // Server should not have selected any subprotocol
  17055. EXPECT_TRUE(client.subprotocol().empty());
  17056. client.close();
  17057. }
  17058. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  17059. // Connect without requesting any subprotocol
  17060. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17061. "/ws-subprotocol");
  17062. ASSERT_TRUE(client.connect());
  17063. EXPECT_TRUE(client.subprotocol().empty());
  17064. client.close();
  17065. }
  17066. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  17067. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17068. "/ws-echo");
  17069. client.set_tcp_nodelay(true);
  17070. client.set_connection_timeout(3, 0);
  17071. bool socket_options_called = false;
  17072. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  17073. ASSERT_TRUE(client.connect());
  17074. ASSERT_TRUE(client.is_open());
  17075. EXPECT_TRUE(socket_options_called);
  17076. ASSERT_TRUE(client.send("hello"));
  17077. std::string msg;
  17078. auto result = client.read(msg);
  17079. EXPECT_EQ(result, ws::ReadResult::Text);
  17080. EXPECT_EQ(msg, "hello");
  17081. client.close();
  17082. }
  17083. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  17084. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  17085. "/ws-echo");
  17086. client.set_connection_timeout(std::chrono::seconds(3));
  17087. client.set_write_timeout(std::chrono::seconds(3));
  17088. // A sub-second remainder exercises the seconds/microseconds split.
  17089. client.set_read_timeout(std::chrono::milliseconds(1500));
  17090. ASSERT_TRUE(client.connect());
  17091. auto start = std::chrono::steady_clock::now();
  17092. std::string msg;
  17093. EXPECT_EQ(client.read(msg), ws::ReadResult::Fail);
  17094. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17095. std::chrono::steady_clock::now() - start)
  17096. .count();
  17097. // Above 1s so that dropping the microseconds half of the split fails here,
  17098. // and well under the 300s default so that ignoring the setter fails too.
  17099. EXPECT_GE(elapsed, 1400);
  17100. EXPECT_LT(elapsed, 30000);
  17101. }
  17102. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  17103. Server svr;
  17104. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  17105. if (!req.has_header("Authorization")) {
  17106. res.status = StatusCode::Unauthorized_401;
  17107. res.set_content("Unauthorized", "text/plain");
  17108. return Server::HandlerResponse::Handled;
  17109. }
  17110. return Server::HandlerResponse::Unhandled;
  17111. });
  17112. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  17113. std::string msg;
  17114. while (ws.read(msg)) {
  17115. ws.send(msg);
  17116. }
  17117. });
  17118. auto port = svr.bind_to_any_port("localhost");
  17119. std::thread t([&]() { svr.listen_after_bind(); });
  17120. svr.wait_until_ready();
  17121. // Without Authorization header - should be rejected before upgrade
  17122. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  17123. EXPECT_FALSE(client1.connect());
  17124. // With Authorization header - should succeed
  17125. Headers headers = {{"Authorization", "Bearer token123"}};
  17126. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  17127. headers);
  17128. ASSERT_TRUE(client2.connect());
  17129. ASSERT_TRUE(client2.send("hello"));
  17130. std::string msg;
  17131. ASSERT_TRUE(client2.read(msg));
  17132. EXPECT_EQ("hello", msg);
  17133. client2.close();
  17134. svr.stop();
  17135. t.join();
  17136. }
  17137. TEST(WebSocketTest, QueryStringInHandshake) {
  17138. Server svr;
  17139. std::mutex mtx;
  17140. std::string received_target;
  17141. std::string received_token;
  17142. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17143. {
  17144. std::lock_guard<std::mutex> lock(mtx);
  17145. received_target = req.target;
  17146. if (req.has_param("token")) {
  17147. received_token = req.get_param_value("token");
  17148. }
  17149. }
  17150. std::string msg;
  17151. while (ws.read(msg)) {
  17152. ws.send(msg);
  17153. }
  17154. });
  17155. auto port = svr.bind_to_any_port("localhost");
  17156. std::thread t([&]() { svr.listen_after_bind(); });
  17157. svr.wait_until_ready();
  17158. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  17159. "/ws?token=ABC&session=123");
  17160. ASSERT_TRUE(client.connect());
  17161. // Round-trip ensures the handler has run and captured the request.
  17162. ASSERT_TRUE(client.send("hello"));
  17163. std::string msg;
  17164. ASSERT_TRUE(client.read(msg));
  17165. EXPECT_EQ("hello", msg);
  17166. client.close();
  17167. {
  17168. std::lock_guard<std::mutex> lock(mtx);
  17169. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  17170. EXPECT_EQ("ABC", received_token);
  17171. }
  17172. svr.stop();
  17173. t.join();
  17174. }
  17175. // Run a handshake against a throwaway server and hand the request the server
  17176. // received back to the caller, so tests can assert on the headers the client
  17177. // actually put on the wire.
  17178. static void capture_websocket_handshake_request(
  17179. const Headers &client_headers,
  17180. std::function<void(const Request &, int port)> verify) {
  17181. Server svr;
  17182. std::mutex mtx;
  17183. Request received;
  17184. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17185. {
  17186. std::lock_guard<std::mutex> lock(mtx);
  17187. received = req;
  17188. }
  17189. std::string msg;
  17190. while (ws.read(msg)) {
  17191. ws.send(msg);
  17192. }
  17193. });
  17194. auto port = svr.bind_to_any_port("localhost");
  17195. std::thread t([&]() { svr.listen_after_bind(); });
  17196. auto se = detail::scope_exit([&] {
  17197. svr.stop();
  17198. t.join();
  17199. });
  17200. svr.wait_until_ready();
  17201. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  17202. client_headers);
  17203. ASSERT_TRUE(client.connect());
  17204. ASSERT_TRUE(client.send("hello"));
  17205. std::string msg;
  17206. ASSERT_TRUE(client.read(msg));
  17207. client.close();
  17208. {
  17209. std::lock_guard<std::mutex> lock(mtx);
  17210. verify(received, port);
  17211. }
  17212. }
  17213. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  17214. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  17215. // Non-default port must be present in the Host header. Default ports
  17216. // (80/443) are omitted; that logic is covered by
  17217. // MakeHostAndPortStringTest.
  17218. EXPECT_EQ("localhost:" + std::to_string(port),
  17219. req.get_header_value("Host"));
  17220. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  17221. req.get_header_value("User-Agent"));
  17222. EXPECT_FALSE(req.has_header("Accept"));
  17223. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  17224. EXPECT_FALSE(req.has_header("Content-Length"));
  17225. });
  17226. }
  17227. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  17228. capture_websocket_handshake_request(
  17229. {{"Host", "example.com"},
  17230. {"User-Agent", "custom-agent"},
  17231. {"X-Custom", "value"}},
  17232. [](const Request &req, int) {
  17233. EXPECT_EQ("example.com", req.get_header_value("Host"));
  17234. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  17235. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  17236. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  17237. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  17238. });
  17239. }
  17240. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  17241. capture_websocket_handshake_request(
  17242. {{"Upgrade", "bogus"},
  17243. {"Connection", "close"},
  17244. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  17245. {"Sec-WebSocket-Version", "8"}},
  17246. [](const Request &req, int) {
  17247. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  17248. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  17249. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  17250. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  17251. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  17252. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  17253. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  17254. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  17255. req.get_header_value("Sec-WebSocket-Key"));
  17256. });
  17257. }
  17258. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  17259. // A header the client refuses to send must abort the handshake before any
  17260. // part of it reaches the wire; a lone request line would otherwise sit in
  17261. // the peer's buffer as a truncated request.
  17262. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17263. ASSERT_NE(INVALID_SOCKET, srv);
  17264. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  17265. sockaddr_in addr{};
  17266. addr.sin_family = AF_INET;
  17267. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  17268. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17269. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17270. ASSERT_EQ(0, ::listen(srv, 1));
  17271. sockaddr_in bound{};
  17272. socklen_t bound_len = sizeof(bound);
  17273. ASSERT_EQ(
  17274. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  17275. auto port = ntohs(bound.sin_port);
  17276. ssize_t received = -1;
  17277. std::thread t([&] {
  17278. // Bound every blocking call so a regression fails the test with a bad
  17279. // value instead of hanging the suite.
  17280. fd_set rfds;
  17281. FD_ZERO(&rfds);
  17282. FD_SET(srv, &rfds);
  17283. timeval tv{5, 0};
  17284. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  17285. 0) {
  17286. return;
  17287. }
  17288. sockaddr_in cli_addr{};
  17289. socklen_t cli_len = sizeof(cli_addr);
  17290. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17291. if (cli == INVALID_SOCKET) { return; }
  17292. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  17293. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17294. char buf[4096];
  17295. received = ::recv(cli, buf, sizeof(buf), 0);
  17296. });
  17297. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  17298. // connect() has already shut the socket down by the time it returns false,
  17299. // so the peer sees EOF without waiting for the client to be destroyed.
  17300. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  17301. {{"X-Bad", "a\r\nInjected: 1"}});
  17302. EXPECT_FALSE(client.connect());
  17303. t.join();
  17304. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  17305. EXPECT_EQ(0, received);
  17306. }
  17307. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  17308. // The socket path doubles as the URL host, so it must not contain '/'.
  17309. const char *shard = getenv("GTEST_SHARD_INDEX");
  17310. const std::string sock_path =
  17311. shard ? std::string("httplib-ws-") + shard + ".sock"
  17312. : std::string("httplib-ws.sock");
  17313. std::remove(sock_path.c_str());
  17314. Server svr;
  17315. std::mutex mtx;
  17316. std::string received_host;
  17317. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  17318. {
  17319. std::lock_guard<std::mutex> lock(mtx);
  17320. received_host = req.get_header_value("Host");
  17321. }
  17322. std::string msg;
  17323. while (ws.read(msg)) {
  17324. ws.send(msg);
  17325. }
  17326. });
  17327. svr.set_address_family(AF_UNIX);
  17328. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  17329. auto se = detail::scope_exit([&] {
  17330. svr.stop();
  17331. t.join();
  17332. std::remove(sock_path.c_str());
  17333. });
  17334. svr.wait_until_ready();
  17335. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  17336. client.set_address_family(AF_UNIX);
  17337. ASSERT_TRUE(client.connect());
  17338. ASSERT_TRUE(client.send("hello"));
  17339. std::string msg;
  17340. ASSERT_TRUE(client.read(msg));
  17341. client.close();
  17342. {
  17343. std::lock_guard<std::mutex> lock(mtx);
  17344. // There is no host:port for a Unix socket, so the same "localhost"
  17345. // placeholder the HTTP client uses is expected.
  17346. EXPECT_EQ("localhost", received_host);
  17347. }
  17348. }
  17349. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  17350. class WebSocketSSLIntegrationTest : public ::testing::Test {
  17351. protected:
  17352. void SetUp() override {
  17353. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  17354. SERVER_PRIVATE_KEY_FILE);
  17355. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17356. std::string msg;
  17357. ws::ReadResult ret;
  17358. while ((ret = ws.read(msg))) {
  17359. if (ret == ws::Binary) {
  17360. ws.send(msg.data(), msg.size());
  17361. } else {
  17362. ws.send(msg);
  17363. }
  17364. }
  17365. });
  17366. port_ = server_->bind_to_any_port(HOST);
  17367. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17368. server_->wait_until_ready();
  17369. }
  17370. void TearDown() override {
  17371. server_->stop();
  17372. if (server_thread_.joinable()) { server_thread_.join(); }
  17373. }
  17374. std::unique_ptr<SSLServer> server_;
  17375. std::thread server_thread_;
  17376. int port_ = 0;
  17377. };
  17378. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17379. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17380. "/ws-echo");
  17381. client.enable_server_certificate_verification(false);
  17382. ASSERT_TRUE(client.connect());
  17383. ASSERT_TRUE(client.is_open());
  17384. ASSERT_TRUE(client.send("Hello WSS"));
  17385. std::string msg;
  17386. EXPECT_EQ(ws::Text, client.read(msg));
  17387. EXPECT_EQ("Hello WSS", msg);
  17388. client.close();
  17389. }
  17390. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17391. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17392. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17393. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17394. // client (without calling close() first) is the only path that runs
  17395. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17396. // bug exactly.
  17397. //
  17398. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17399. // when linked against an instrumented libssl; run under Valgrind to catch it
  17400. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17401. // suite (the freed session otherwise stalls on the close handshake) — this test
  17402. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17403. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17404. {
  17405. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17406. "/ws-echo");
  17407. client.enable_server_certificate_verification(false);
  17408. client.set_read_timeout(2, 0);
  17409. client.set_write_timeout(2, 0);
  17410. ASSERT_TRUE(client.connect());
  17411. ASSERT_TRUE(client.is_open());
  17412. ASSERT_TRUE(client.send("still open"));
  17413. // Intentionally do NOT call client.close(): leaving scope runs
  17414. // shutdown_and_close() with the WebSocket still open, which must send the
  17415. // close frame while the TLS session is still alive.
  17416. }
  17417. }
  17418. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17419. // shutdown_and_close() at the start of connect(), reproducing the same
  17420. // use-after-free within the test body rather than at scope exit. The second
  17421. // connect must succeed and echo, proving the close handshake ran over a live
  17422. // session. See the note above about memory-tool requirements.
  17423. TEST_F(WebSocketSSLIntegrationTest,
  17424. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17425. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17426. "/ws-echo");
  17427. client.enable_server_certificate_verification(false);
  17428. client.set_read_timeout(2, 0);
  17429. client.set_write_timeout(2, 0);
  17430. ASSERT_TRUE(client.connect());
  17431. ASSERT_TRUE(client.is_open());
  17432. ASSERT_TRUE(client.send("still open"));
  17433. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17434. // the still-open connection, which must not touch a freed TLS session.
  17435. ASSERT_TRUE(client.connect());
  17436. ASSERT_TRUE(client.is_open());
  17437. ASSERT_TRUE(client.send("after reconnect"));
  17438. std::string msg;
  17439. EXPECT_EQ(ws::Text, client.read(msg));
  17440. EXPECT_EQ("after reconnect", msg);
  17441. client.close();
  17442. }
  17443. #endif
  17444. #ifdef CPPHTTPLIB_SSL_ENABLED
  17445. class WebSocketSSLCATest : public ::testing::Test {
  17446. protected:
  17447. void SetUp() override {
  17448. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17449. SERVER_PRIVATE_KEY_FILE);
  17450. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17451. std::string msg;
  17452. while (ws.read(msg)) {
  17453. ws.send(msg);
  17454. }
  17455. });
  17456. port_ = server_->bind_to_any_port("127.0.0.1");
  17457. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17458. server_->wait_until_ready();
  17459. }
  17460. void TearDown() override {
  17461. server_->stop();
  17462. if (server_thread_.joinable()) { server_thread_.join(); }
  17463. }
  17464. std::string url() const {
  17465. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17466. }
  17467. std::unique_ptr<SSLServer> server_;
  17468. std::thread server_thread_;
  17469. int port_ = 0;
  17470. };
  17471. // A custom CA loaded as PEM verifies the server with full certificate
  17472. // verification enabled
  17473. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17474. ws::WebSocketClient client(url());
  17475. std::string cert;
  17476. read_file(SERVER_CERT2_FILE, cert);
  17477. client.load_ca_cert_store(cert.c_str(), cert.size());
  17478. ASSERT_TRUE(client.connect());
  17479. ASSERT_TRUE(client.send("hello"));
  17480. std::string msg;
  17481. EXPECT_EQ(ws::Text, client.read(msg));
  17482. EXPECT_EQ("hello", msg);
  17483. client.close();
  17484. }
  17485. // A custom CA that does not cover the server must fail verification (the
  17486. // custom CA is exclusive; system certs are not loaded alongside it)
  17487. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17488. ws::WebSocketClient client(url());
  17489. std::string cert;
  17490. read_file(CLIENT_CA_CERT_FILE, cert);
  17491. client.load_ca_cert_store(cert.c_str(), cert.size());
  17492. ASSERT_FALSE(client.connect());
  17493. }
  17494. // The same CA as a file path rather than PEM in memory
  17495. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  17496. ws::WebSocketClient client(url());
  17497. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17498. ASSERT_TRUE(client.connect());
  17499. ASSERT_TRUE(client.send("hello"));
  17500. std::string msg;
  17501. EXPECT_EQ(ws::Text, client.read(msg));
  17502. EXPECT_EQ("hello", msg);
  17503. client.close();
  17504. }
  17505. // ...and a CA file that does not cover the server still fails, so it is the
  17506. // path above that decides the outcome
  17507. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  17508. ws::WebSocketClient client(url());
  17509. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17510. ASSERT_FALSE(client.connect());
  17511. }
  17512. // Regression test: reconnecting with a native custom CA store used to reuse
  17513. // a store handle the previous TLS context had already freed (use-after-free
  17514. // under the OpenSSL backend). The context now lives as long as the client.
  17515. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17516. ws::WebSocketClient client(url());
  17517. std::string cert;
  17518. read_file(SERVER_CERT2_FILE, cert);
  17519. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17520. ASSERT_TRUE(client.connect());
  17521. client.close();
  17522. ASSERT_TRUE(client.connect());
  17523. ASSERT_TRUE(client.send("again"));
  17524. std::string msg;
  17525. EXPECT_EQ(ws::Text, client.read(msg));
  17526. EXPECT_EQ("again", msg);
  17527. client.close();
  17528. }
  17529. // Regression test: a certificate with a trusted chain but no identity match
  17530. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17531. // verification entirely for IP hosts, so this connection succeeded there.
  17532. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17533. // chain verification while the identity check must still fail.
  17534. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17536. ASSERT_TRUE(svr.is_valid());
  17537. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17538. std::string msg;
  17539. while (ws.read(msg)) {
  17540. ws.send(msg);
  17541. }
  17542. });
  17543. auto port = svr.bind_to_any_port("127.0.0.1");
  17544. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17545. auto se = detail::scope_exit([&] {
  17546. svr.stop();
  17547. t.join();
  17548. });
  17549. svr.wait_until_ready();
  17550. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17551. "/echo");
  17552. std::string cert;
  17553. read_file(SERVER_CERT_FILE, cert);
  17554. client.load_ca_cert_store(cert.c_str(), cert.size());
  17555. ASSERT_FALSE(client.connect());
  17556. }
  17557. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  17558. // SNI, so nothing binds the host name to the TLS session. These bind the
  17559. // server to "localhost" instead, the only shape that exercises the SNI and
  17560. // hostname-verification path with certificate verification left enabled.
  17561. class WebSocketSSLDnsHostTest : public ::testing::Test {
  17562. protected:
  17563. void Start(const char *cert_file) {
  17564. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  17565. SERVER_PRIVATE_KEY_FILE);
  17566. ASSERT_TRUE(server_->is_valid());
  17567. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17568. std::string msg;
  17569. while (ws.read(msg)) {
  17570. ws.send(msg);
  17571. }
  17572. });
  17573. port_ = server_->bind_to_any_port("localhost");
  17574. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17575. server_->wait_until_ready();
  17576. }
  17577. void TearDown() override {
  17578. if (server_) { server_->stop(); }
  17579. if (server_thread_.joinable()) { server_thread_.join(); }
  17580. }
  17581. std::string url() const {
  17582. return "wss://localhost:" + std::to_string(port_) + "/echo";
  17583. }
  17584. std::unique_ptr<SSLServer> server_;
  17585. std::thread server_thread_;
  17586. int port_ = 0;
  17587. };
  17588. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  17589. // out and the connection is usable
  17590. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  17591. Start(SERVER_CERT2_FILE);
  17592. ws::WebSocketClient client(url());
  17593. client.set_ca_cert_path(SERVER_CERT2_FILE);
  17594. ASSERT_TRUE(client.connect());
  17595. ASSERT_TRUE(client.send("hello"));
  17596. std::string msg;
  17597. EXPECT_EQ(ws::Text, client.read(msg));
  17598. EXPECT_EQ("hello", msg);
  17599. client.close();
  17600. }
  17601. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  17602. // while the identity check must still reject "localhost"
  17603. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  17604. Start(SERVER_CERT_FILE);
  17605. ws::WebSocketClient client(url());
  17606. client.set_ca_cert_path(SERVER_CERT_FILE);
  17607. ASSERT_FALSE(client.connect());
  17608. }
  17609. // A CA that did not sign the server certificate fails the chain, even though
  17610. // the name would match
  17611. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  17612. Start(SERVER_CERT2_FILE);
  17613. ws::WebSocketClient client(url());
  17614. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  17615. ASSERT_FALSE(client.connect());
  17616. }
  17617. // With verification disabled, neither the chain nor the name is checked
  17618. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  17619. Start(SERVER_CERT_FILE);
  17620. ws::WebSocketClient client(url());
  17621. client.enable_server_certificate_verification(false);
  17622. ASSERT_TRUE(client.connect());
  17623. ASSERT_TRUE(client.send("hello"));
  17624. std::string msg;
  17625. EXPECT_EQ(ws::Text, client.read(msg));
  17626. EXPECT_EQ("hello", msg);
  17627. client.close();
  17628. }
  17629. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  17630. protected:
  17631. void SetUp() override {
  17632. server_ = httplib::detail::make_unique<SSLServer>(
  17633. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  17634. ASSERT_TRUE(server_->is_valid());
  17635. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  17636. std::string msg;
  17637. while (ws.read(msg)) {
  17638. ws.send(msg);
  17639. }
  17640. });
  17641. port_ = server_->bind_to_any_port("localhost");
  17642. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17643. server_->wait_until_ready();
  17644. }
  17645. void TearDown() override {
  17646. server_->stop();
  17647. if (server_thread_.joinable()) { server_thread_.join(); }
  17648. }
  17649. std::string url() const {
  17650. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  17651. }
  17652. void ConnectWithClientCert(const std::string &client_cert_file,
  17653. const std::string &client_private_key_file,
  17654. const char *private_key_password) {
  17655. std::string cert_pem, key_pem;
  17656. read_file(client_cert_file, cert_pem);
  17657. read_file(client_private_key_file, key_pem);
  17658. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  17659. key_pem.c_str(), key_pem.size(),
  17660. private_key_password};
  17661. ws::WebSocketClient client(url(), pem);
  17662. ASSERT_TRUE(client.is_valid());
  17663. client.enable_server_certificate_verification(false);
  17664. ASSERT_TRUE(client.connect());
  17665. ASSERT_TRUE(client.send("hello"));
  17666. std::string msg;
  17667. EXPECT_EQ(ws::Text, client.read(msg));
  17668. EXPECT_EQ("hello", msg);
  17669. client.close();
  17670. }
  17671. std::unique_ptr<SSLServer> server_;
  17672. std::thread server_thread_;
  17673. int port_ = 0;
  17674. };
  17675. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  17676. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  17677. }
  17678. // Control for the tests above: the fixture's server really does require a
  17679. // client certificate, so it is the PEM the constructor installed that decides
  17680. // the outcome.
  17681. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  17682. ws::WebSocketClient client(url());
  17683. ASSERT_TRUE(client.is_valid());
  17684. client.enable_server_certificate_verification(false);
  17685. EXPECT_FALSE(client.connect());
  17686. }
  17687. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  17688. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  17689. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  17690. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  17691. }
  17692. #endif
  17693. #if !defined(_WIN32)
  17694. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17695. auto secret_dir = std::string("./symlink_test_secret");
  17696. auto served_dir = std::string("./symlink_test_served");
  17697. auto secret_file = secret_dir + "/secret.txt";
  17698. auto symlink_path = served_dir + "/escape";
  17699. // Setup: create directories and files
  17700. mkdir(secret_dir.c_str(), 0755);
  17701. mkdir(served_dir.c_str(), 0755);
  17702. {
  17703. std::ofstream ofs(secret_file);
  17704. ofs << "SECRET_DATA";
  17705. }
  17706. // Create symlink using absolute path so it resolves correctly
  17707. #ifdef PATH_MAX
  17708. char abs_secret[PATH_MAX];
  17709. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17710. #else
  17711. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17712. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17713. ASSERT_NE(nullptr, abs_secret);
  17714. #endif
  17715. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17716. auto se = detail::scope_exit([&] {
  17717. unlink(symlink_path.c_str());
  17718. unlink(secret_file.c_str());
  17719. rmdir(served_dir.c_str());
  17720. rmdir(secret_dir.c_str());
  17721. });
  17722. Server svr;
  17723. svr.set_mount_point("/", served_dir);
  17724. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17725. auto se2 = detail::scope_exit([&] {
  17726. svr.stop();
  17727. listen_thread.join();
  17728. });
  17729. svr.wait_until_ready();
  17730. Client cli("localhost", PORT);
  17731. // Symlink pointing outside base dir should be blocked
  17732. auto res = cli.Get("/escape/secret.txt");
  17733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17734. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17735. }
  17736. #endif
  17737. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17738. // A GET request with Content-Length to a static file handler must have its
  17739. // body drained before the keep-alive connection is reused. Otherwise the
  17740. // unread body bytes are interpreted as the next HTTP request.
  17741. //
  17742. // The body is sent AFTER receiving the first response (as in the original
  17743. // PoC) so that the stream_line_reader cannot buffer it together with the
  17744. // headers of the first request.
  17745. Server svr;
  17746. svr.set_mount_point("/", "./www");
  17747. std::atomic<int> smuggled_count(0);
  17748. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17749. smuggled_count++;
  17750. res.set_content("oops", "text/plain");
  17751. });
  17752. auto port = svr.bind_to_any_port("localhost");
  17753. thread t = thread([&] { svr.listen_after_bind(); });
  17754. auto se = detail::scope_exit([&] {
  17755. svr.stop();
  17756. t.join();
  17757. });
  17758. svr.wait_until_ready();
  17759. auto error = Error::Success;
  17760. auto sock = detail::create_client_socket(
  17761. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17762. /*connection_timeout_sec=*/2, 0,
  17763. /*read_timeout_sec=*/2, 0,
  17764. /*write_timeout_sec=*/2, 0, std::string(), error);
  17765. ASSERT_NE(INVALID_SOCKET, sock);
  17766. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17767. // The "smuggled" request will be sent as the body of the outer GET
  17768. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17769. "Host: localhost\r\n"
  17770. "Connection: close\r\n"
  17771. "\r\n";
  17772. // Step 1: Send only the outer request headers (no body yet)
  17773. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17774. "Host: localhost\r\n"
  17775. "Content-Length: " +
  17776. std::to_string(smuggled.size()) +
  17777. "\r\n"
  17778. "\r\n";
  17779. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17780. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17781. // Step 2: Read the first response (server serves file without reading body)
  17782. std::string first_response;
  17783. char buf[4096];
  17784. for (;;) {
  17785. auto n = recv(sock, buf, sizeof(buf), 0);
  17786. if (n <= 0) break;
  17787. first_response.append(buf, static_cast<size_t>(n));
  17788. // Stop once we have a complete response (headers + body)
  17789. auto hdr_end = first_response.find("\r\n\r\n");
  17790. if (hdr_end != std::string::npos) {
  17791. // Check for Content-Length to know when the body is complete
  17792. auto cl_pos = first_response.find("Content-Length:");
  17793. if (cl_pos != std::string::npos) {
  17794. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17795. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17796. auto cl = std::stoul(
  17797. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17798. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17799. } else {
  17800. break; // No Content-Length, assume headers-only response
  17801. }
  17802. }
  17803. }
  17804. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17805. // Step 3: Now send the body, which looks like a new HTTP request.
  17806. // On a vulnerable server the keep-alive loop reads this as a second request.
  17807. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17808. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17809. // Step 4: Try to read a second response (should NOT exist after fix)
  17810. std::string second_response;
  17811. for (;;) {
  17812. auto n = recv(sock, buf, sizeof(buf), 0);
  17813. if (n <= 0) break;
  17814. second_response.append(buf, static_cast<size_t>(n));
  17815. }
  17816. // The smuggled request must NOT have been processed
  17817. EXPECT_EQ(0, smuggled_count.load());
  17818. }
  17819. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17820. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17821. // must be rejected with 400 Bad Request.
  17822. Server svr;
  17823. svr.Post("/test", [&](const Request &, Response &res) {
  17824. res.set_content("ok", "text/plain");
  17825. });
  17826. thread t = thread([&] { svr.listen(HOST, PORT); });
  17827. auto se = detail::scope_exit([&] {
  17828. svr.stop();
  17829. t.join();
  17830. ASSERT_FALSE(svr.is_running());
  17831. });
  17832. svr.wait_until_ready();
  17833. // Exact "chunked"
  17834. {
  17835. auto req = "POST /test HTTP/1.1\r\n"
  17836. "Host: localhost\r\n"
  17837. "Content-Length: 5\r\n"
  17838. "Transfer-Encoding: chunked\r\n"
  17839. "Connection: close\r\n"
  17840. "\r\n"
  17841. "hello";
  17842. std::string response;
  17843. ASSERT_TRUE(send_request(1, req, &response));
  17844. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17845. response.substr(0, response.find("\r\n")));
  17846. }
  17847. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17848. {
  17849. auto req = "POST /test HTTP/1.1\r\n"
  17850. "Host: localhost\r\n"
  17851. "Content-Length: 5\r\n"
  17852. "Transfer-Encoding: gzip, chunked\r\n"
  17853. "Connection: close\r\n"
  17854. "\r\n"
  17855. "hello";
  17856. std::string response;
  17857. ASSERT_TRUE(send_request(1, req, &response));
  17858. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17859. response.substr(0, response.find("\r\n")));
  17860. }
  17861. }
  17862. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  17863. Server svr;
  17864. svr.Post("/test", [&](const Request &, Response &res) {
  17865. res.set_content("ok", "text/plain");
  17866. });
  17867. thread t = thread([&] { svr.listen(HOST, PORT); });
  17868. auto se = detail::scope_exit([&] {
  17869. svr.stop();
  17870. t.join();
  17871. ASSERT_FALSE(svr.is_running());
  17872. });
  17873. svr.wait_until_ready();
  17874. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  17875. // length cannot be determined, so the server must answer 400 and close
  17876. // rather than treat the request as bodyless and leave the body in the
  17877. // socket for the next request to pick up.
  17878. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  17879. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  17880. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  17881. std::string response;
  17882. ASSERT_TRUE(send_request(1, req, &response));
  17883. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17884. response.substr(0, response.find("\r\n")))
  17885. << transfer_encoding;
  17886. }
  17887. // RFC 9110 5.3: the codings may also be split across several
  17888. // Transfer-Encoding lines, which combine in the order they were received.
  17889. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  17890. // just like the single-line "chunked, gzip" above.
  17891. {
  17892. auto req = "POST /test HTTP/1.1\r\n"
  17893. "Host: localhost\r\n"
  17894. "Transfer-Encoding: chunked\r\n"
  17895. "Transfer-Encoding: gzip\r\n"
  17896. "\r\n"
  17897. "0\r\n\r\n";
  17898. std::string response;
  17899. ASSERT_TRUE(send_request(1, req, &response));
  17900. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17901. response.substr(0, response.find("\r\n")));
  17902. }
  17903. // A sequence ending in chunked stays valid.
  17904. auto req = "POST /test HTTP/1.1\r\n"
  17905. "Host: localhost\r\n"
  17906. "Transfer-Encoding: gzip, chunked\r\n"
  17907. "Connection: close\r\n"
  17908. "\r\n"
  17909. "0\r\n\r\n";
  17910. std::string response;
  17911. ASSERT_TRUE(send_request(1, req, &response));
  17912. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17913. // ...including when it is spread over several lines.
  17914. auto split_req = "POST /test HTTP/1.1\r\n"
  17915. "Host: localhost\r\n"
  17916. "Transfer-Encoding: gzip\r\n"
  17917. "Transfer-Encoding: chunked\r\n"
  17918. "Connection: close\r\n"
  17919. "\r\n"
  17920. "0\r\n\r\n";
  17921. std::string split_response;
  17922. ASSERT_TRUE(send_request(1, split_req, &split_response));
  17923. EXPECT_EQ("HTTP/1.1 200 OK",
  17924. split_response.substr(0, split_response.find("\r\n")));
  17925. }
  17926. // Regression for issue #2450: a DELETE without Content-Length on a
  17927. // keep-alive connection must not let the post-response drain consume the
  17928. // next request's bytes.
  17929. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17930. Server svr;
  17931. std::atomic<int> delete_count(0);
  17932. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17933. delete_count++;
  17934. res.status = StatusCode::NoContent_204;
  17935. });
  17936. auto port = svr.bind_to_any_port(HOST);
  17937. thread t = thread([&] { svr.listen_after_bind(); });
  17938. auto se = detail::scope_exit([&] {
  17939. svr.stop();
  17940. t.join();
  17941. });
  17942. svr.wait_until_ready();
  17943. auto error = Error::Success;
  17944. auto sock = detail::create_client_socket(
  17945. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17946. /*connection_timeout_sec=*/2, 0,
  17947. /*read_timeout_sec=*/2, 0,
  17948. /*write_timeout_sec=*/2, 0, std::string(), error);
  17949. ASSERT_NE(INVALID_SOCKET, sock);
  17950. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17951. auto send_request_and_read_response = [&](const std::string &req,
  17952. std::string &out) -> bool {
  17953. auto sent = send(sock, req.data(), req.size(), 0);
  17954. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17955. char buf[4096];
  17956. for (;;) {
  17957. auto n = recv(sock, buf, sizeof(buf), 0);
  17958. if (n <= 0) { return !out.empty(); }
  17959. out.append(buf, static_cast<size_t>(n));
  17960. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17961. }
  17962. };
  17963. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17964. "Host: localhost\r\n"
  17965. "\r\n";
  17966. std::string resp1;
  17967. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17968. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17969. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17970. "Host: localhost\r\n"
  17971. "Connection: close\r\n"
  17972. "\r\n";
  17973. std::string resp2;
  17974. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17975. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17976. EXPECT_EQ(2, delete_count.load());
  17977. }
  17978. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17979. Server svr;
  17980. svr.Post("/ingest", [&](const Request &, Response &res,
  17981. const ContentReader &content_reader) {
  17982. auto consumed = content_reader([](const char *, size_t) { return false; });
  17983. EXPECT_FALSE(consumed);
  17984. res.status = StatusCode::Conflict_409;
  17985. res.set_header("Connection", "close");
  17986. });
  17987. auto port = svr.bind_to_any_port(HOST);
  17988. thread t = thread([&] { svr.listen_after_bind(); });
  17989. auto se = detail::scope_exit([&] {
  17990. svr.stop();
  17991. t.join();
  17992. });
  17993. svr.wait_until_ready();
  17994. auto error = Error::Success;
  17995. auto sock = detail::create_client_socket(
  17996. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17997. /*connection_timeout_sec=*/2, 0,
  17998. /*read_timeout_sec=*/1, 0,
  17999. /*write_timeout_sec=*/2, 0, std::string(), error);
  18000. ASSERT_NE(INVALID_SOCKET, sock);
  18001. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  18002. std::string request = "POST /ingest HTTP/1.1\r\n"
  18003. "Host: localhost\r\n"
  18004. "Transfer-Encoding: chunked\r\n"
  18005. "\r\n"
  18006. "4\r\n"
  18007. "data\r\n";
  18008. auto sent = send(sock, request.data(), request.size(), 0);
  18009. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  18010. std::string response;
  18011. ssize_t received = 0;
  18012. do {
  18013. char buf[4096];
  18014. received = recv(sock, buf, sizeof(buf), 0);
  18015. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  18016. } while (received > 0);
  18017. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  18018. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  18019. EXPECT_EQ(0, received);
  18020. }
  18021. namespace no_proxy_test {
  18022. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  18023. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  18024. // calling listen().
  18025. class ScopedServer {
  18026. public:
  18027. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  18028. ~ScopedServer() {
  18029. svr_.stop();
  18030. if (th_.joinable()) { th_.join(); }
  18031. }
  18032. Server &svr() { return svr_; }
  18033. int port() const { return port_; }
  18034. void listen() {
  18035. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18036. svr_.wait_until_ready();
  18037. }
  18038. private:
  18039. Server svr_;
  18040. std::thread th_;
  18041. int port_ = 0;
  18042. };
  18043. class ProxyAndTargetServers {
  18044. public:
  18045. ProxyAndTargetServers() {
  18046. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  18047. proxy_hits_++;
  18048. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18049. res.set_content("via-proxy", "text/plain");
  18050. });
  18051. target_.Get(".*", [this](const Request &req, Response &res) {
  18052. target_hits_++;
  18053. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  18054. res.set_content("direct", "text/plain");
  18055. });
  18056. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  18057. target_port_ = target_.bind_to_any_port("127.0.0.1");
  18058. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  18059. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  18060. proxy_mock_.wait_until_ready();
  18061. target_.wait_until_ready();
  18062. }
  18063. ~ProxyAndTargetServers() {
  18064. proxy_mock_.stop();
  18065. target_.stop();
  18066. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  18067. if (target_thread_.joinable()) { target_thread_.join(); }
  18068. }
  18069. Server &proxy_mock() { return proxy_mock_; }
  18070. Server &target() { return target_; }
  18071. int proxy_port() const { return proxy_port_; }
  18072. int target_port() const { return target_port_; }
  18073. int proxy_hits() const { return proxy_hits_.load(); }
  18074. int target_hits() const { return target_hits_.load(); }
  18075. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  18076. void reset_counters() {
  18077. proxy_hits_ = 0;
  18078. target_hits_ = 0;
  18079. last_had_proxy_authz_ = false;
  18080. }
  18081. private:
  18082. Server proxy_mock_;
  18083. Server target_;
  18084. std::thread proxy_thread_;
  18085. std::thread target_thread_;
  18086. int proxy_port_ = 0;
  18087. int target_port_ = 0;
  18088. std::atomic<int> proxy_hits_{0};
  18089. std::atomic<int> target_hits_{0};
  18090. std::atomic<bool> last_had_proxy_authz_{false};
  18091. };
  18092. inline std::unique_ptr<Client> make_client(const std::string &host,
  18093. ProxyAndTargetServers &s) {
  18094. auto cli = detail::make_unique<Client>(host, s.target_port());
  18095. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  18096. cli->set_proxy("127.0.0.1", s.proxy_port());
  18097. return cli;
  18098. }
  18099. } // namespace no_proxy_test
  18100. using no_proxy_test::make_client;
  18101. using no_proxy_test::ProxyAndTargetServers;
  18102. TEST(NoProxyTest, ExactHostnameBypasses) {
  18103. ProxyAndTargetServers s;
  18104. auto cli = make_client("example.com", s);
  18105. cli->set_no_proxy({"example.com"});
  18106. auto res = cli->Get("/");
  18107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18108. EXPECT_EQ(0, s.proxy_hits());
  18109. EXPECT_EQ(1, s.target_hits());
  18110. }
  18111. TEST(NoProxyTest, SubdomainBypasses) {
  18112. ProxyAndTargetServers s;
  18113. auto cli = make_client("foo.example.com", s);
  18114. cli->set_no_proxy({"example.com"});
  18115. auto res = cli->Get("/");
  18116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18117. EXPECT_EQ(0, s.proxy_hits());
  18118. EXPECT_EQ(1, s.target_hits());
  18119. }
  18120. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  18121. // Regression guard: "evilexample.com" must not be considered a subdomain
  18122. // of "example.com". Without the dot-boundary rule, a naive endsWith
  18123. // check would let traffic bypass the proxy and leak credentials direct
  18124. // to the attacker host.
  18125. ProxyAndTargetServers s;
  18126. auto cli = make_client("evilexample.com", s);
  18127. cli->set_no_proxy({"example.com"});
  18128. auto res = cli->Get("/");
  18129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18130. EXPECT_GE(s.proxy_hits(), 1);
  18131. EXPECT_EQ(0, s.target_hits());
  18132. }
  18133. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  18134. ProxyAndTargetServers s;
  18135. auto cli = make_client("example.com.evil.com", s);
  18136. cli->set_no_proxy({"example.com"});
  18137. auto res = cli->Get("/");
  18138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18139. EXPECT_GE(s.proxy_hits(), 1);
  18140. EXPECT_EQ(0, s.target_hits());
  18141. }
  18142. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  18143. ProxyAndTargetServers s;
  18144. auto cli = make_client("example.com", s);
  18145. cli->set_no_proxy({".example.com"});
  18146. auto res = cli->Get("/");
  18147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18148. EXPECT_EQ(0, s.proxy_hits());
  18149. EXPECT_EQ(1, s.target_hits());
  18150. }
  18151. TEST(NoProxyTest, CaseInsensitiveHostname) {
  18152. ProxyAndTargetServers s;
  18153. auto cli = make_client("Example.COM", s);
  18154. cli->set_no_proxy({"EXAMPLE.com"});
  18155. auto res = cli->Get("/");
  18156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18157. EXPECT_EQ(0, s.proxy_hits());
  18158. EXPECT_EQ(1, s.target_hits());
  18159. }
  18160. TEST(NoProxyTest, TrailingDotIsNormalized) {
  18161. ProxyAndTargetServers s;
  18162. auto cli = make_client("example.com.", s);
  18163. cli->set_no_proxy({"example.com"});
  18164. auto res = cli->Get("/");
  18165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18166. EXPECT_EQ(0, s.proxy_hits());
  18167. EXPECT_EQ(1, s.target_hits());
  18168. }
  18169. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  18170. // Trailing dots must be normalized on BOTH sides — host and entry.
  18171. // An implementation that only strips the host-side trailing dot would
  18172. // fail to match host "example.com" against entry "example.com." because
  18173. // a literal substring search would compare 11 chars against 12.
  18174. ProxyAndTargetServers s;
  18175. auto cli = make_client("example.com", s);
  18176. cli->set_no_proxy({"example.com."});
  18177. auto res = cli->Get("/");
  18178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18179. EXPECT_EQ(0, s.proxy_hits());
  18180. EXPECT_EQ(1, s.target_hits());
  18181. }
  18182. TEST(NoProxyTest, WildcardBypassesEverything) {
  18183. ProxyAndTargetServers s;
  18184. auto cli = make_client("anything.invalid.test", s);
  18185. cli->set_no_proxy({"*"});
  18186. auto res = cli->Get("/");
  18187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18188. EXPECT_EQ(0, s.proxy_hits());
  18189. EXPECT_EQ(1, s.target_hits());
  18190. }
  18191. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  18192. ProxyAndTargetServers s;
  18193. Client cli("127.0.0.1", s.target_port());
  18194. cli.set_proxy("127.0.0.1", s.proxy_port());
  18195. cli.set_no_proxy({"127.0.0.1"});
  18196. auto res = cli.Get("/");
  18197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18198. EXPECT_EQ(0, s.proxy_hits());
  18199. EXPECT_EQ(1, s.target_hits());
  18200. }
  18201. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  18202. ProxyAndTargetServers s;
  18203. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  18204. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  18205. cli.set_proxy("127.0.0.1", s.proxy_port());
  18206. cli.set_no_proxy({"::1"});
  18207. auto res = cli.Get("/");
  18208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18209. EXPECT_EQ(0, s.proxy_hits());
  18210. EXPECT_EQ(1, s.target_hits());
  18211. }
  18212. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  18213. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  18214. // must still be recognized as IPv6 for CIDR matching. Implementations
  18215. // that detect IPv6 only when the host begins with '[' would parse the
  18216. // host as a hostname and miss the match.
  18217. ProxyAndTargetServers s;
  18218. Client cli("fe80::1", s.target_port());
  18219. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18220. cli.set_proxy("127.0.0.1", s.proxy_port());
  18221. cli.set_no_proxy({"fe80::/10"});
  18222. auto res = cli.Get("/");
  18223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18224. EXPECT_EQ(0, s.proxy_hits());
  18225. EXPECT_EQ(1, s.target_hits());
  18226. }
  18227. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  18228. ProxyAndTargetServers s;
  18229. Client cli("::1", s.target_port());
  18230. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  18231. cli.set_proxy("127.0.0.1", s.proxy_port());
  18232. cli.set_no_proxy({"[::1]"});
  18233. auto res = cli.Get("/");
  18234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18235. EXPECT_EQ(0, s.proxy_hits());
  18236. EXPECT_EQ(1, s.target_hits());
  18237. }
  18238. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  18239. ProxyAndTargetServers s;
  18240. Client cli("fe80::1", s.target_port());
  18241. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  18242. cli.set_proxy("127.0.0.1", s.proxy_port());
  18243. cli.set_no_proxy({"[fe80::]/10"});
  18244. auto res = cli.Get("/");
  18245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18246. EXPECT_EQ(0, s.proxy_hits());
  18247. EXPECT_EQ(1, s.target_hits());
  18248. }
  18249. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  18250. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  18251. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  18252. // tricks via address-family conversion.
  18253. ProxyAndTargetServers s;
  18254. Client cli("::ffff:127.0.0.1", s.target_port());
  18255. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  18256. cli.set_proxy("127.0.0.1", s.proxy_port());
  18257. cli.set_no_proxy({"127.0.0.1"});
  18258. auto res = cli.Get("/");
  18259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18260. EXPECT_GE(s.proxy_hits(), 1);
  18261. EXPECT_EQ(0, s.target_hits());
  18262. }
  18263. TEST(NoProxyTest, IPv4CidrMatch) {
  18264. ProxyAndTargetServers s;
  18265. Client cli("127.0.0.1", s.target_port());
  18266. cli.set_proxy("127.0.0.1", s.proxy_port());
  18267. cli.set_no_proxy({"127.0.0.0/8"});
  18268. auto res = cli.Get("/");
  18269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18270. EXPECT_EQ(0, s.proxy_hits());
  18271. EXPECT_EQ(1, s.target_hits());
  18272. }
  18273. TEST(NoProxyTest, IPv4CidrNonMatch) {
  18274. ProxyAndTargetServers s;
  18275. Client cli("127.0.0.1", s.target_port());
  18276. cli.set_proxy("127.0.0.1", s.proxy_port());
  18277. cli.set_no_proxy({"10.0.0.0/8"});
  18278. auto res = cli.Get("/");
  18279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18280. EXPECT_GE(s.proxy_hits(), 1);
  18281. EXPECT_EQ(0, s.target_hits());
  18282. }
  18283. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  18284. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  18285. // IPv4 target matches.
  18286. ProxyAndTargetServers s;
  18287. Client cli("127.0.0.1", s.target_port());
  18288. cli.set_proxy("127.0.0.1", s.proxy_port());
  18289. cli.set_no_proxy({"0.0.0.0/0"});
  18290. auto res = cli.Get("/");
  18291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18292. EXPECT_EQ(0, s.proxy_hits());
  18293. EXPECT_EQ(1, s.target_hits());
  18294. }
  18295. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  18296. ProxyAndTargetServers s;
  18297. Client cli("127.0.0.1", s.target_port());
  18298. cli.set_proxy("127.0.0.1", s.proxy_port());
  18299. cli.set_no_proxy({"127.0.0.1"});
  18300. auto res = cli.Get("/");
  18301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18302. EXPECT_EQ(0, s.proxy_hits());
  18303. EXPECT_EQ(1, s.target_hits());
  18304. }
  18305. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  18306. ProxyAndTargetServers s;
  18307. Client cli("127.0.0.1", s.target_port());
  18308. cli.set_proxy("127.0.0.1", s.proxy_port());
  18309. cli.set_no_proxy({"127.0.0.0/33"});
  18310. auto res = cli.Get("/");
  18311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18312. EXPECT_GE(s.proxy_hits(), 1);
  18313. EXPECT_EQ(0, s.target_hits());
  18314. }
  18315. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  18316. // Empty prefix after the slash must be rejected, not silently treated as /32.
  18317. ProxyAndTargetServers s;
  18318. Client cli("127.0.0.1", s.target_port());
  18319. cli.set_proxy("127.0.0.1", s.proxy_port());
  18320. cli.set_no_proxy({"127.0.0.1/"});
  18321. auto res = cli.Get("/");
  18322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18323. EXPECT_GE(s.proxy_hits(), 1);
  18324. EXPECT_EQ(0, s.target_hits());
  18325. }
  18326. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  18327. ProxyAndTargetServers s;
  18328. auto cli = make_client("internal.corp", s);
  18329. cli->set_proxy_basic_auth("u", "p");
  18330. cli->set_no_proxy({"internal.corp"});
  18331. auto res = cli->Get("/");
  18332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18333. EXPECT_EQ(1, s.target_hits());
  18334. EXPECT_EQ(0, s.proxy_hits());
  18335. EXPECT_FALSE(s.last_had_proxy_authz())
  18336. << "Proxy-Authorization must not be sent direct to the target";
  18337. }
  18338. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  18339. ProxyAndTargetServers s;
  18340. auto cli = make_client("public.example", s);
  18341. cli->set_proxy_basic_auth("u", "p");
  18342. cli->set_no_proxy({"internal.corp"}); // does not match
  18343. auto res = cli->Get("/");
  18344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18345. EXPECT_GE(s.proxy_hits(), 1);
  18346. EXPECT_TRUE(s.last_had_proxy_authz());
  18347. }
  18348. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  18349. ProxyAndTargetServers s;
  18350. auto cli = make_client("anything.test", s);
  18351. auto res = cli->Get("/");
  18352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18353. EXPECT_GE(s.proxy_hits(), 1);
  18354. EXPECT_EQ(0, s.target_hits());
  18355. }
  18356. TEST(NoProxyTest, PortSpecificEntryRejected) {
  18357. ProxyAndTargetServers s;
  18358. auto cli = make_client("example.com", s);
  18359. cli->set_no_proxy({"example.com:8080"});
  18360. auto res = cli->Get("/");
  18361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18362. EXPECT_GE(s.proxy_hits(), 1);
  18363. EXPECT_EQ(0, s.target_hits());
  18364. }
  18365. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  18366. ProxyAndTargetServers s;
  18367. auto cli = make_client("anything.test", s);
  18368. cli->set_no_proxy({"", " ", "\t"});
  18369. auto res = cli->Get("/");
  18370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18371. EXPECT_GE(s.proxy_hits(), 1);
  18372. EXPECT_EQ(0, s.target_hits());
  18373. }
  18374. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  18375. // An entry with leading/trailing whitespace must still match — env-style
  18376. // values are commonly pasted with stray spaces and an implementation
  18377. // that feeds the raw token directly to inet_pton would fail to match
  18378. // valid CIDRs because of the spaces.
  18379. ProxyAndTargetServers s;
  18380. Client cli("127.0.0.1", s.target_port());
  18381. cli.set_proxy("127.0.0.1", s.proxy_port());
  18382. cli.set_no_proxy({" 127.0.0.0/8 "});
  18383. auto res = cli.Get("/");
  18384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18385. EXPECT_EQ(0, s.proxy_hits());
  18386. EXPECT_EQ(1, s.target_hits());
  18387. }
  18388. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  18389. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  18390. // go direct and must NOT carry Proxy-Authorization.
  18391. std::atomic<int> proxy_hits{0};
  18392. std::atomic<int> target_hits{0};
  18393. std::atomic<bool> target_saw_authz{false};
  18394. no_proxy_test::ScopedServer proxy_mock, target;
  18395. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18396. proxy_hits++;
  18397. res.status = 302;
  18398. res.set_header("Location", "http://127.0.0.1:" +
  18399. std::to_string(target.port()) + "/landed");
  18400. });
  18401. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18402. target_hits++;
  18403. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  18404. res.set_content("direct", "text/plain");
  18405. });
  18406. proxy_mock.listen();
  18407. target.listen();
  18408. Client cli("public.example", target.port());
  18409. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18410. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18411. cli.set_proxy_basic_auth("u", "p");
  18412. cli.set_no_proxy({"127.0.0.1"});
  18413. cli.set_follow_location(true);
  18414. auto res = cli.Get("/redir");
  18415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18416. EXPECT_GE(proxy_hits.load(), 1);
  18417. EXPECT_GE(target_hits.load(), 1);
  18418. EXPECT_FALSE(target_saw_authz.load());
  18419. }
  18420. #ifdef CPPHTTPLIB_SSL_ENABLED
  18421. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  18422. // Direct origin replying 407 must not trigger the digest retry; otherwise
  18423. // proxy creds would be sent to the (possibly hostile) origin.
  18424. std::atomic<int> target_hits{0};
  18425. std::atomic<bool> target_saw_proxy_authz{false};
  18426. no_proxy_test::ScopedServer target;
  18427. target.svr().Get(".*", [&](const Request &req, Response &res) {
  18428. target_hits++;
  18429. if (req.has_header("Proxy-Authorization")) {
  18430. target_saw_proxy_authz = true;
  18431. }
  18432. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18433. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  18434. "nonce=\"abc\", algorithm=MD5");
  18435. });
  18436. target.listen();
  18437. // The proxy address is set to the target's port: the bypass MUST kick in;
  18438. // if it doesn't, the test still routes "via proxy" to the same server and
  18439. // the Proxy-Authorization assertion below catches the leak.
  18440. Client cli("evil.example", target.port());
  18441. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  18442. cli.set_proxy("127.0.0.1", target.port());
  18443. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18444. cli.set_no_proxy({"evil.example"});
  18445. auto res = cli.Get("/x");
  18446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18447. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18448. EXPECT_EQ(1, target_hits.load());
  18449. EXPECT_FALSE(target_saw_proxy_authz.load());
  18450. }
  18451. #endif
  18452. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  18453. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  18454. std::atomic<int> proxy_hits{0};
  18455. std::atomic<int> bypass_hits{0};
  18456. std::atomic<bool> proxy_saw_c_url{false};
  18457. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  18458. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  18459. proxy_hits++;
  18460. if (req.path.find("/start") != std::string::npos) {
  18461. res.status = 302;
  18462. res.set_header("Location", "http://127.0.0.1:" +
  18463. std::to_string(bypass_server.port()) +
  18464. "/middle");
  18465. return;
  18466. }
  18467. if (req.path.find("/end") != std::string::npos) {
  18468. proxy_saw_c_url = true;
  18469. res.set_content("c-via-proxy", "text/plain");
  18470. return;
  18471. }
  18472. res.set_content("unexpected", "text/plain");
  18473. });
  18474. // public.example's "advertised" port is arbitrary (the request never lands
  18475. // there — it goes through the proxy), but use a dynamic value to stay
  18476. // friendly with sharded parallel runs.
  18477. int public_port = bypass_server.port();
  18478. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  18479. bypass_hits++;
  18480. res.status = 302;
  18481. res.set_header("Location", "http://public.example:" +
  18482. std::to_string(public_port) + "/end");
  18483. });
  18484. proxy_mock.listen();
  18485. bypass_server.listen();
  18486. Client cli("public.example", public_port);
  18487. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18488. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18489. cli.set_no_proxy({"127.0.0.1"});
  18490. cli.set_follow_location(true);
  18491. auto res = cli.Get("/start");
  18492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18493. EXPECT_EQ(StatusCode::OK_200, res->status);
  18494. EXPECT_EQ("c-via-proxy", res->body);
  18495. EXPECT_GE(proxy_hits.load(), 2);
  18496. EXPECT_GE(bypass_hits.load(), 1);
  18497. EXPECT_TRUE(proxy_saw_c_url.load());
  18498. }
  18499. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  18500. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  18501. // request reconnects to the correct endpoint.
  18502. std::atomic<int> proxy_hits{0};
  18503. std::atomic<int> target_hits{0};
  18504. no_proxy_test::ScopedServer proxy_mock, target;
  18505. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  18506. proxy_hits++;
  18507. res.set_content("via-proxy", "text/plain");
  18508. });
  18509. target.svr().Get(".*", [&](const Request &, Response &res) {
  18510. target_hits++;
  18511. res.set_content("direct", "text/plain");
  18512. });
  18513. proxy_mock.listen();
  18514. target.listen();
  18515. Client cli("public.example", target.port());
  18516. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  18517. cli.set_proxy("127.0.0.1", proxy_mock.port());
  18518. cli.set_keep_alive(true);
  18519. auto res1 = cli.Get("/a");
  18520. ASSERT_TRUE(res1);
  18521. EXPECT_EQ("via-proxy", res1->body);
  18522. EXPECT_EQ(1, proxy_hits.load());
  18523. EXPECT_EQ(0, target_hits.load());
  18524. cli.set_no_proxy({"public.example"});
  18525. auto res2 = cli.Get("/b");
  18526. ASSERT_TRUE(res2);
  18527. EXPECT_EQ("direct", res2->body);
  18528. EXPECT_EQ(1, proxy_hits.load());
  18529. EXPECT_EQ(1, target_hits.load());
  18530. }
  18531. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  18532. namespace proxy_tunnel_test {
  18533. // SSLServer counterpart to no_proxy_test::ScopedServer.
  18534. class ScopedSSLServer {
  18535. public:
  18536. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  18537. port_ = svr_.bind_to_any_port("127.0.0.1");
  18538. }
  18539. ~ScopedSSLServer() {
  18540. svr_.stop();
  18541. if (th_.joinable()) { th_.join(); }
  18542. }
  18543. SSLServer &svr() { return svr_; }
  18544. int port() const { return port_; }
  18545. void listen() {
  18546. th_ = std::thread([this] { svr_.listen_after_bind(); });
  18547. svr_.wait_until_ready();
  18548. }
  18549. private:
  18550. SSLServer svr_;
  18551. std::thread th_;
  18552. int port_ = 0;
  18553. };
  18554. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  18555. class ScopedConnectProxy {
  18556. public:
  18557. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  18558. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  18559. if (listen_fd_ < 0) { return; }
  18560. int yes = 1;
  18561. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  18562. sockaddr_in a{};
  18563. a.sin_family = AF_INET;
  18564. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18565. a.sin_port = 0;
  18566. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  18567. return;
  18568. }
  18569. socklen_t alen = sizeof(a);
  18570. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  18571. 0) {
  18572. return;
  18573. }
  18574. port_ = ntohs(a.sin_port);
  18575. if (::listen(listen_fd_, 1) != 0) { return; }
  18576. th_ = std::thread([this] { run(); });
  18577. }
  18578. ~ScopedConnectProxy() {
  18579. stop_ = true;
  18580. if (listen_fd_ >= 0) {
  18581. ::shutdown(listen_fd_, SHUT_RDWR);
  18582. ::close(listen_fd_);
  18583. }
  18584. if (th_.joinable()) { th_.join(); }
  18585. }
  18586. int port() const { return port_; }
  18587. int connect_hits() const { return connect_hits_.load(); }
  18588. private:
  18589. void run() {
  18590. while (!stop_.load()) {
  18591. fd_set rfds;
  18592. FD_ZERO(&rfds);
  18593. FD_SET(listen_fd_, &rfds);
  18594. timeval tv{0, 100 * 1000};
  18595. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18596. if (sel <= 0) { continue; }
  18597. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18598. if (client_fd < 0) { continue; }
  18599. std::string req;
  18600. char buf[2048];
  18601. while (req.find("\r\n\r\n") == std::string::npos) {
  18602. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18603. if (n <= 0) { break; }
  18604. req.append(buf, static_cast<size_t>(n));
  18605. }
  18606. if (req.compare(0, 7, "CONNECT") != 0) {
  18607. ::close(client_fd);
  18608. continue;
  18609. }
  18610. connect_hits_++;
  18611. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18612. ::send(client_fd, ok, std::strlen(ok), 0);
  18613. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18614. sockaddr_in o{};
  18615. o.sin_family = AF_INET;
  18616. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18617. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18618. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18619. 0) {
  18620. ::close(client_fd);
  18621. ::close(origin_fd);
  18622. continue;
  18623. }
  18624. auto forward = [](int from, int to) {
  18625. char b[8192];
  18626. for (;;) {
  18627. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18628. if (n <= 0) { break; }
  18629. ssize_t off = 0;
  18630. while (off < n) {
  18631. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18632. if (s <= 0) {
  18633. off = n;
  18634. break;
  18635. }
  18636. off += s;
  18637. }
  18638. }
  18639. ::shutdown(to, SHUT_WR);
  18640. };
  18641. std::thread t1([&] { forward(client_fd, origin_fd); });
  18642. std::thread t2([&] { forward(origin_fd, client_fd); });
  18643. t1.join();
  18644. t2.join();
  18645. ::close(client_fd);
  18646. ::close(origin_fd);
  18647. }
  18648. }
  18649. int forward_port_ = -1;
  18650. int listen_fd_ = -1;
  18651. int port_ = 0;
  18652. std::thread th_;
  18653. std::atomic<bool> stop_{false};
  18654. std::atomic<int> connect_hits_{0};
  18655. };
  18656. } // namespace proxy_tunnel_test
  18657. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18658. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18659. // retry; otherwise proxy creds would be sent to the origin.
  18660. std::atomic<int> origin_hits{0};
  18661. std::atomic<bool> origin_saw_proxy_authz{false};
  18662. proxy_tunnel_test::ScopedSSLServer origin;
  18663. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18664. origin_hits++;
  18665. if (req.has_header("Proxy-Authorization")) {
  18666. origin_saw_proxy_authz = true;
  18667. }
  18668. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18669. res.set_header("Proxy-Authenticate",
  18670. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18671. "algorithm=MD5");
  18672. });
  18673. origin.listen();
  18674. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18675. ASSERT_NE(0, proxy.port());
  18676. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18677. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18678. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18679. // and answer with its own status, making this test flaky.
  18680. SSLClient cli("127.0.0.1", origin.port());
  18681. cli.enable_server_certificate_verification(false);
  18682. cli.set_proxy("127.0.0.1", proxy.port());
  18683. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18684. auto res = cli.Get("/x");
  18685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18686. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18687. EXPECT_EQ(1, origin_hits.load());
  18688. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18689. EXPECT_EQ(1, proxy.connect_hits());
  18690. }
  18691. #endif