test.cc 689 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649
  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. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  258. ASSERT_EQ(0, listen(s, 1));
  259. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  260. ASSERT_EQ(0, close(s));
  261. }};
  262. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  263. std::thread cli{[&] {
  264. const int s = socket(AF_INET, SOCK_STREAM, 0);
  265. ASSERT_LE(0, s);
  266. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, close(s));
  268. }};
  269. cli.join();
  270. svr.join();
  271. ASSERT_NE(disconnected_svr_sock, -1);
  272. const auto asSocketStream = [&](socket_t fd,
  273. std::function<bool(Stream &)> func) {
  274. return detail::process_client_socket(
  275. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  276. };
  277. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  278. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  279. // wait_writable() returns true because select_write() only checks if the
  280. // send buffer has space. Peer disconnection is detected later by send().
  281. EXPECT_TRUE(ss.wait_writable());
  282. return true;
  283. });
  284. ASSERT_EQ(0, close(disconnected_svr_sock));
  285. }
  286. #endif // #ifndef _WIN32
  287. TEST(SetSocketOptTest, TcpNoDelay) {
  288. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  289. ASSERT_NE(sock, INVALID_SOCKET);
  290. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  291. int val = 0;
  292. socklen_t len = sizeof(val);
  293. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  294. reinterpret_cast<char *>(&val), &len));
  295. EXPECT_NE(val, 0);
  296. detail::close_socket(sock);
  297. }
  298. TEST(ClientTest, MoveConstructible) {
  299. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  300. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  301. }
  302. TEST(ClientTest, MoveAssignable) {
  303. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  304. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  305. }
  306. #ifdef _WIN32
  307. TEST(StartupTest, WSAStartup) {
  308. WSADATA wsaData;
  309. int ret = WSAStartup(0x0002, &wsaData);
  310. ASSERT_EQ(0, ret);
  311. }
  312. #endif
  313. TEST(DecodePathTest, PercentCharacter) {
  314. EXPECT_EQ(
  315. decode_path_component(
  316. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  317. U8("descrip=Gastos áéíóúñÑ 6"));
  318. }
  319. TEST(DecodePathTest, PercentCharacterNUL) {
  320. string expected;
  321. expected.push_back('x');
  322. expected.push_back('\0');
  323. expected.push_back('x');
  324. EXPECT_EQ(decode_path_component("x%00x"), expected);
  325. }
  326. TEST(DecodePathTest, UnicodeEncoding) {
  327. // %u0041 = 'A' (1-byte UTF-8)
  328. EXPECT_EQ("A", decode_path_component("%u0041"));
  329. // %u00E9 = 'é' (2-byte UTF-8)
  330. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  331. // %u3042 = 'あ' (3-byte UTF-8)
  332. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  333. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  334. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  335. // %uD800 = surrogate (invalid, silently dropped)
  336. EXPECT_EQ("", decode_path_component("%uD800"));
  337. }
  338. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  339. // A sign or whitespace inside the two-character escape window must not be
  340. // accepted as a valid percent-encoding; the sequence is passed through
  341. // literally, matching decode_uri_component / decode_path_component.
  342. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  343. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  344. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  345. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  346. // Well-formed escapes still decode.
  347. EXPECT_EQ("-", decode_query_component("%2D", false));
  348. EXPECT_EQ("A", decode_query_component("%41", false));
  349. }
  350. TEST(SanitizeFilenameTest, VariousPatterns) {
  351. // Path traversal
  352. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  353. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  354. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  355. // Normal and edge cases
  356. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  357. EXPECT_EQ("filename.txt",
  358. httplib::sanitize_filename("/path/to/filename.txt"));
  359. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  360. EXPECT_EQ("", httplib::sanitize_filename(".."));
  361. EXPECT_EQ("", httplib::sanitize_filename(""));
  362. // Null bytes stripped
  363. EXPECT_EQ("safe.txt",
  364. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  365. // Whitespace-only rejected
  366. EXPECT_EQ("", httplib::sanitize_filename(" "));
  367. }
  368. // Forward declaration (see the base64_encode note below): split builds move the
  369. // definition into httplib.cc, so re-declaring it here lets the test link.
  370. namespace httplib {
  371. namespace detail {
  372. bool is_chunked_transfer_encoding(const Headers &headers);
  373. } // namespace detail
  374. } // namespace httplib
  375. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  376. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  377. auto make = [](std::initializer_list<const char *> lines) {
  378. Headers h;
  379. for (auto te : lines) {
  380. if (te) { h.emplace("Transfer-Encoding", te); }
  381. }
  382. return h;
  383. };
  384. // Sole coding, matched case-insensitively.
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  386. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  388. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  390. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  392. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  395. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  396. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  397. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  398. // portable, so any line naming chunked is treated as chunked (fail safe).
  399. // The result must not depend on the order the lines were added.
  400. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  401. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  403. }
  404. // Forward declaration: in split builds split.py strips `inline` and moves the
  405. // definition into httplib.cc, so detail::base64_encode is not visible from the
  406. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  407. // in both header-only and split builds.
  408. namespace httplib {
  409. namespace detail {
  410. std::string base64_encode(const std::string &in);
  411. } // namespace detail
  412. } // namespace httplib
  413. TEST(Base64EncodeTest, KnownAnswers) {
  414. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  415. // where the accumulator's top bit is already set before the next shift.
  416. EXPECT_EQ("", detail::base64_encode(""));
  417. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  418. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  419. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  420. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  421. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  422. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  423. // High bytes keep the top bit set across several rounds.
  424. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  425. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  426. }
  427. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  428. string unescapedCharacters = "-_.!~*'()";
  429. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  430. }
  431. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  432. string reservedCharacters = ";,/?:@&=+$";
  433. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  434. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  435. }
  436. TEST(ClientQueryOrder, PreserveOrder) {
  437. // This test reproduces Issue #2259: client may reorder query parameters
  438. // when sending a GET request. The expected behavior is that the client
  439. // preserves the original query string order when the caller supplied it
  440. // as part of the path.
  441. Server svr;
  442. svr.Get("/", [&](const Request &req, Response &res) {
  443. // Echo back the raw target so the test can assert ordering
  444. res.set_content(req.target, "text/plain");
  445. });
  446. std::thread t{[&] { svr.listen(HOST, PORT); }};
  447. auto se = detail::scope_exit([&] {
  448. svr.stop();
  449. t.join();
  450. ASSERT_FALSE(svr.is_running());
  451. });
  452. svr.wait_until_ready();
  453. Client cli(HOST, PORT);
  454. ASSERT_TRUE(cli.is_valid());
  455. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  456. auto res = cli.Get(original);
  457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  458. // Expect the echoed target to exactly match the original path (order
  459. // preserved)
  460. EXPECT_EQ(res->body, original);
  461. }
  462. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  463. string chineseCharacters = U8("中国語");
  464. string russianCharacters = U8("дом");
  465. string brazilianCharacters = U8("óculos");
  466. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  467. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  468. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  469. "%D0%B4%D0%BE%D0%BC");
  470. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  471. }
  472. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  473. string unescapedCharacters = "-_.!~*'()";
  474. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  475. }
  476. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  477. string reservedCharacters = ";,/?:@&=+$";
  478. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  479. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  480. }
  481. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  482. string chineseCharacters = U8("中国語");
  483. string russianCharacters = U8("дом");
  484. string brazilianCharacters = U8("óculos");
  485. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  486. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  487. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  488. "%D0%B4%D0%BE%D0%BC");
  489. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  490. }
  491. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  492. // Issue #2082 use case: encoding path component with ampersand
  493. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  494. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  495. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  496. }
  497. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  498. string unescapedCharacters = "-_.!~*'()";
  499. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  500. }
  501. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  502. string reservedCharacters = ";,/?:@&=+$#";
  503. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  504. }
  505. TEST(EncodeUriTest, TestUTF8Characters) {
  506. string chineseCharacters = U8("中国語");
  507. string russianCharacters = U8("дом");
  508. string brazilianCharacters = U8("óculos");
  509. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  510. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  511. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  512. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  513. }
  514. TEST(EncodeUriTest, TestCompleteUri) {
  515. string uri =
  516. "https://example.com/path/to/resource?query=value&param=test#fragment";
  517. EXPECT_EQ(
  518. httplib::encode_uri(uri),
  519. "https://example.com/path/to/resource?query=value&param=test#fragment");
  520. }
  521. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  522. string uri =
  523. "https://example.com/path with spaces/file name.html?q=hello world";
  524. EXPECT_EQ(httplib::encode_uri(uri),
  525. "https://example.com/path%20with%20spaces/"
  526. "file%20name.html?q=hello%20world");
  527. }
  528. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  529. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  530. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  531. }
  532. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  533. string unescapedCharacters = "-_.!~*'()";
  534. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  535. }
  536. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  537. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  538. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  539. string encodedBrazilian = "%C3%B3culos";
  540. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  541. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  542. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  543. }
  544. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  545. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  546. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  547. "Piri Tommy Villiers - on & on");
  548. }
  549. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  550. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  551. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  552. }
  553. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  554. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  555. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  556. }
  557. TEST(DecodeUriTest, TestUTF8Characters) {
  558. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  559. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  560. string encodedBrazilian = "%C3%B3culos";
  561. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  562. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  563. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  564. }
  565. TEST(DecodeUriTest, TestCompleteUri) {
  566. string encodedUri = "https://example.com/path%20with%20spaces/"
  567. "file%20name.html?q=hello%20world";
  568. EXPECT_EQ(
  569. httplib::decode_uri(encodedUri),
  570. "https://example.com/path with spaces/file name.html?q=hello world");
  571. }
  572. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  573. string original =
  574. "https://example.com/path with spaces/file name.html?q=hello world";
  575. string encoded = httplib::encode_uri(original);
  576. string decoded = httplib::decode_uri(encoded);
  577. EXPECT_EQ(decoded, original);
  578. }
  579. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  580. string original = "Piri Tommy Villiers - on & on";
  581. string encoded = httplib::encode_uri_component(original);
  582. string decoded = httplib::decode_uri_component(encoded);
  583. EXPECT_EQ(decoded, original);
  584. }
  585. TEST(TrimTests, TrimStringTests) {
  586. EXPECT_EQ("abc", detail::trim_copy("abc"));
  587. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  588. EXPECT_TRUE(detail::trim_copy("").empty());
  589. }
  590. TEST(AsciiTest, LocaleIndependentClassification) {
  591. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  592. // which consult the global C locale: std::isalnum(0xC5) can return true
  593. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  594. // helpers must classify every byte by the ASCII grammar alone.
  595. for (int i = 0; i < 256; i++) {
  596. auto c = static_cast<char>(i);
  597. auto is_digit = i >= '0' && i <= '9';
  598. auto is_upper = i >= 'A' && i <= 'Z';
  599. auto is_lower = i >= 'a' && i <= 'z';
  600. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  601. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  602. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  603. << "byte " << i;
  604. }
  605. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  606. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  607. // Non-ASCII bytes must be percent-encoded, never passed through as
  608. // alphanumeric.
  609. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  610. }
  611. TEST(FromCharsTest, Double) {
  612. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  613. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  614. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  615. auto parse = [](const std::string &s, double &v) {
  616. return detail::from_chars(s.data(), s.data() + s.size(), v);
  617. };
  618. double v = -1.0;
  619. // Representative quality values.
  620. EXPECT_EQ(parse("0", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 0.0);
  622. EXPECT_EQ(parse("1", v).ec, std::errc{});
  623. EXPECT_DOUBLE_EQ(v, 1.0);
  624. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  625. EXPECT_DOUBLE_EQ(v, 0.8);
  626. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  627. EXPECT_DOUBLE_EQ(v, 0.001);
  628. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  629. EXPECT_DOUBLE_EQ(v, 1.0);
  630. // A missing integer or fractional part is tolerated.
  631. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 0.5);
  633. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 5.0);
  635. // Values outside [0, 1] still parse; the caller range-checks them.
  636. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  637. EXPECT_DOUBLE_EQ(v, 123.456);
  638. // Stops at the first byte that is not part of the number and reports where.
  639. std::string trailing = "0.9, text/html";
  640. auto r = parse(trailing, v);
  641. EXPECT_EQ(r.ec, std::errc{});
  642. EXPECT_DOUBLE_EQ(v, 0.9);
  643. EXPECT_EQ(*r.ptr, ',');
  644. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  645. // outright, and an 'e'/'E' simply ends the number.
  646. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  647. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  648. std::string exp_input = "1.5e3";
  649. r = parse(exp_input, v);
  650. EXPECT_EQ(r.ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 1.5);
  652. EXPECT_EQ(*r.ptr, 'e');
  653. // Invalid inputs.
  654. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  655. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  657. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  658. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  659. // Pathological but well-formed inputs must stay bounded (no overflow, no
  660. // out-of-bounds table access) and stay within [0, 1] for the caller.
  661. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  662. std::errc{});
  663. EXPECT_DOUBLE_EQ(v, 0.0);
  664. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  665. std::errc{});
  666. EXPECT_GE(v, 0.0);
  667. EXPECT_LE(v, 1.0);
  668. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  669. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  670. }
  671. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  672. // Simple case without quality values
  673. std::vector<std::string> result1;
  674. EXPECT_TRUE(detail::parse_accept_header(
  675. "text/html,application/json,text/plain", result1));
  676. EXPECT_EQ(result1.size(), 3U);
  677. EXPECT_EQ(result1[0], "text/html");
  678. EXPECT_EQ(result1[1], "application/json");
  679. EXPECT_EQ(result1[2], "text/plain");
  680. // With quality values
  681. std::vector<std::string> result2;
  682. EXPECT_TRUE(detail::parse_accept_header(
  683. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  684. EXPECT_EQ(result2.size(), 3U);
  685. EXPECT_EQ(result2[0], "application/json"); // highest q value
  686. EXPECT_EQ(result2[1], "text/html");
  687. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  688. }
  689. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  690. // Mixed with and without quality values
  691. std::vector<std::string> result;
  692. EXPECT_TRUE(detail::parse_accept_header(
  693. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  694. EXPECT_EQ(result.size(), 3U);
  695. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  696. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  697. EXPECT_EQ(result[2], "application/json"); // q=0.5
  698. }
  699. TEST(ParseAcceptHeaderTest, EdgeCases) {
  700. // Empty header
  701. std::vector<std::string> empty_result;
  702. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  703. EXPECT_TRUE(empty_result.empty());
  704. // Single type
  705. std::vector<std::string> single_result;
  706. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  707. EXPECT_EQ(single_result.size(), 1U);
  708. EXPECT_EQ(single_result[0], "application/json");
  709. // Wildcard types
  710. std::vector<std::string> wildcard_result;
  711. EXPECT_TRUE(detail::parse_accept_header(
  712. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  713. EXPECT_EQ(wildcard_result.size(), 3U);
  714. EXPECT_EQ(wildcard_result[0], "application/json");
  715. EXPECT_EQ(wildcard_result[1], "text/*");
  716. EXPECT_EQ(wildcard_result[2], "*/*");
  717. }
  718. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  719. // Common browser Accept header
  720. std::vector<std::string> browser_result;
  721. EXPECT_TRUE(
  722. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  723. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  724. browser_result));
  725. EXPECT_EQ(browser_result.size(), 6U);
  726. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  727. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  728. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  729. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  730. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  731. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  732. // API client header
  733. std::vector<std::string> api_result;
  734. EXPECT_TRUE(detail::parse_accept_header(
  735. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  736. api_result));
  737. EXPECT_EQ(api_result.size(), 3U);
  738. EXPECT_EQ(api_result[0], "application/json");
  739. EXPECT_EQ(api_result[1], "application/xml");
  740. EXPECT_EQ(api_result[2], "text/plain");
  741. }
  742. TEST(ParseAcceptHeaderTest, SpecialCases) {
  743. // Quality value with 3 decimal places
  744. std::vector<std::string> decimal_result;
  745. EXPECT_TRUE(detail::parse_accept_header(
  746. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  747. EXPECT_EQ(decimal_result.size(), 2U);
  748. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  749. EXPECT_EQ(decimal_result[1], "text/html");
  750. // Zero quality (should still be included but with lowest priority)
  751. std::vector<std::string> zero_q_result;
  752. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  753. zero_q_result));
  754. EXPECT_EQ(zero_q_result.size(), 2U);
  755. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  756. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  757. // No spaces around commas
  758. std::vector<std::string> no_space_result;
  759. EXPECT_TRUE(detail::parse_accept_header(
  760. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  761. no_space_result));
  762. EXPECT_EQ(no_space_result.size(), 3U);
  763. EXPECT_EQ(no_space_result[0], "text/html");
  764. EXPECT_EQ(no_space_result[1], "application/json");
  765. EXPECT_EQ(no_space_result[2], "text/plain");
  766. }
  767. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  768. // Quality values always use '.' as the decimal separator, so parsing must
  769. // not depend on the process locale. An embedding application may have
  770. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  771. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  772. std::string saved = cur ? cur : "C";
  773. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  774. "fr_FR.UTF-8"};
  775. bool switched = false;
  776. for (const auto loc : comma_locales) {
  777. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  778. std::localeconv()->decimal_point[0] == ',') {
  779. switched = true;
  780. break;
  781. }
  782. }
  783. if (!switched) {
  784. std::setlocale(LC_NUMERIC, saved.c_str());
  785. GTEST_SKIP() << "no comma-decimal locale available on this host";
  786. }
  787. // The higher-weighted type appears later in the list, so a correct parse
  788. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  789. // sensitive parse reads both weights as 0 and leaves the original order.
  790. std::vector<std::string> result;
  791. EXPECT_TRUE(detail::parse_accept_header(
  792. "application/json;q=0.1,text/html;q=0.9", result));
  793. ASSERT_EQ(result.size(), 2U);
  794. EXPECT_EQ(result[0], "text/html");
  795. EXPECT_EQ(result[1], "application/json");
  796. std::setlocale(LC_NUMERIC, saved.c_str());
  797. }
  798. TEST(ParseAcceptHeaderTest, InvalidCases) {
  799. std::vector<std::string> result;
  800. // Invalid quality value (> 1.0)
  801. EXPECT_FALSE(
  802. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  803. // Invalid quality value (< 0.0)
  804. EXPECT_FALSE(
  805. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  806. // Invalid quality value (not a number)
  807. EXPECT_FALSE(detail::parse_accept_header(
  808. "text/html;q=invalid,application/json", result));
  809. // Empty quality value
  810. EXPECT_FALSE(
  811. detail::parse_accept_header("text/html;q=,application/json", result));
  812. // Invalid media type format (no slash and not wildcard)
  813. EXPECT_FALSE(
  814. detail::parse_accept_header("invalidtype,application/json", result));
  815. // Empty media type
  816. result.clear();
  817. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  818. // Only commas
  819. result.clear();
  820. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  821. // Valid cases should still work
  822. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  823. EXPECT_EQ(result.size(), 1U);
  824. EXPECT_EQ(result[0], "*/*");
  825. EXPECT_TRUE(detail::parse_accept_header("*", result));
  826. EXPECT_EQ(result.size(), 1U);
  827. EXPECT_EQ(result[0], "*");
  828. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  829. EXPECT_EQ(result.size(), 1U);
  830. EXPECT_EQ(result[0], "text/*");
  831. }
  832. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  833. Server svr;
  834. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  835. EXPECT_EQ(req.accept_content_types.size(), 3U);
  836. EXPECT_EQ(req.accept_content_types[0], "application/json");
  837. EXPECT_EQ(req.accept_content_types[1], "text/html");
  838. EXPECT_EQ(req.accept_content_types[2], "*/*");
  839. res.set_content("ok", "text/plain");
  840. });
  841. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  842. EXPECT_TRUE(false);
  843. res.set_content("bad request", "text/plain");
  844. });
  845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  846. auto se = detail::scope_exit([&] {
  847. svr.stop();
  848. listen_thread.join();
  849. ASSERT_FALSE(svr.is_running());
  850. });
  851. svr.wait_until_ready();
  852. Client cli("localhost", PORT);
  853. {
  854. auto res = cli.Get(
  855. "/accept_ok",
  856. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  858. EXPECT_EQ(StatusCode::OK_200, res->status);
  859. }
  860. {
  861. auto res = cli.Get("/accept_bad_request",
  862. Headers{{"Accept", "text/html;q=abc,application/json"}});
  863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  864. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  865. }
  866. }
  867. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  868. Server svr;
  869. svr.Get("/", [](const Request & /*req*/, Response &res) {
  870. res.set_content("ok", "text/plain");
  871. });
  872. std::atomic<int> start_count{0};
  873. std::atomic<bool> running_when_called{false};
  874. svr.set_start_handler([&]() {
  875. running_when_called = svr.is_running();
  876. start_count++;
  877. });
  878. auto port = svr.bind_to_any_port(HOST);
  879. std::thread t([&]() { svr.listen_after_bind(); });
  880. auto se = detail::scope_exit([&] {
  881. svr.stop();
  882. t.join();
  883. ASSERT_FALSE(svr.is_running());
  884. });
  885. svr.wait_until_ready();
  886. // A successful request proves the accept loop is running, which the start
  887. // handler precedes; so by now the handler must have run exactly once.
  888. Client cli(HOST, port);
  889. cli.set_connection_timeout(std::chrono::seconds(5));
  890. auto res = cli.Get("/");
  891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  892. EXPECT_EQ(StatusCode::OK_200, res->status);
  893. EXPECT_EQ(1, start_count.load());
  894. EXPECT_TRUE(running_when_called.load());
  895. }
  896. TEST(DivideTest, DivideStringTests) {
  897. auto divide = [](const std::string &str, char d) {
  898. std::string lhs;
  899. std::string rhs;
  900. detail::divide(str, d,
  901. [&](const char *lhs_data, std::size_t lhs_size,
  902. const char *rhs_data, std::size_t rhs_size) {
  903. lhs.assign(lhs_data, lhs_size);
  904. rhs.assign(rhs_data, rhs_size);
  905. });
  906. return std::make_pair(std::move(lhs), std::move(rhs));
  907. };
  908. {
  909. const auto res = divide("", '=');
  910. EXPECT_EQ(res.first, "");
  911. EXPECT_EQ(res.second, "");
  912. }
  913. {
  914. const auto res = divide("=", '=');
  915. EXPECT_EQ(res.first, "");
  916. EXPECT_EQ(res.second, "");
  917. }
  918. {
  919. const auto res = divide(" ", '=');
  920. EXPECT_EQ(res.first, " ");
  921. EXPECT_EQ(res.second, "");
  922. }
  923. {
  924. const auto res = divide("a", '=');
  925. EXPECT_EQ(res.first, "a");
  926. EXPECT_EQ(res.second, "");
  927. }
  928. {
  929. const auto res = divide("a=", '=');
  930. EXPECT_EQ(res.first, "a");
  931. EXPECT_EQ(res.second, "");
  932. }
  933. {
  934. const auto res = divide("=b", '=');
  935. EXPECT_EQ(res.first, "");
  936. EXPECT_EQ(res.second, "b");
  937. }
  938. {
  939. const auto res = divide("a=b", '=');
  940. EXPECT_EQ(res.first, "a");
  941. EXPECT_EQ(res.second, "b");
  942. }
  943. {
  944. const auto res = divide("a=b=", '=');
  945. EXPECT_EQ(res.first, "a");
  946. EXPECT_EQ(res.second, "b=");
  947. }
  948. {
  949. const auto res = divide("a=b=c", '=');
  950. EXPECT_EQ(res.first, "a");
  951. EXPECT_EQ(res.second, "b=c");
  952. }
  953. }
  954. TEST(SplitTest, ParseQueryString) {
  955. string s = "key1=val1&key2=val2&key3=val3";
  956. Params dic;
  957. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  958. [&](const char *b, const char *e) {
  959. string key, val;
  960. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  961. if (key.empty()) {
  962. key.assign(b2, e2);
  963. } else {
  964. val.assign(b2, e2);
  965. }
  966. });
  967. dic.emplace(key, val);
  968. });
  969. EXPECT_EQ("val1", dic.find("key1")->second);
  970. EXPECT_EQ("val2", dic.find("key2")->second);
  971. EXPECT_EQ("val3", dic.find("key3")->second);
  972. }
  973. TEST(SplitTest, ParseInvalidQueryTests) {
  974. {
  975. string s = " ";
  976. Params dict;
  977. detail::parse_query_text(s, dict);
  978. EXPECT_TRUE(dict.empty());
  979. }
  980. {
  981. string s = " = =";
  982. Params dict;
  983. detail::parse_query_text(s, dict);
  984. EXPECT_TRUE(dict.empty());
  985. }
  986. }
  987. TEST(ParseQueryTest, ParseQueryString) {
  988. {
  989. std::string s = "key1=val1&key2=val2&key3=val3";
  990. Params dic;
  991. detail::parse_query_text(s, dic);
  992. EXPECT_EQ("val1", dic.find("key1")->second);
  993. EXPECT_EQ("val2", dic.find("key2")->second);
  994. EXPECT_EQ("val3", dic.find("key3")->second);
  995. }
  996. {
  997. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  998. Params dic;
  999. detail::parse_query_text(s, dic);
  1000. EXPECT_EQ("", dic.find("key1")->second);
  1001. EXPECT_EQ("val1", dic.find("key2")->second);
  1002. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1003. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1004. }
  1005. }
  1006. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1007. Params dic;
  1008. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1009. dic.emplace("key1", "val1");
  1010. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1011. dic.emplace("key2", "val2");
  1012. dic.emplace("key3", "val3");
  1013. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1014. }
  1015. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1016. string content_type = "multipart/form-data; boundary=something";
  1017. string boundary;
  1018. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1019. EXPECT_TRUE(ret);
  1020. EXPECT_EQ(boundary, "something");
  1021. }
  1022. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1023. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1024. string boundary;
  1025. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1026. EXPECT_TRUE(ret);
  1027. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1028. }
  1029. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1030. string content_type =
  1031. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1032. string boundary;
  1033. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1034. EXPECT_TRUE(ret);
  1035. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1036. }
  1037. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1038. string content_type =
  1039. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1040. string boundary;
  1041. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1042. EXPECT_TRUE(ret);
  1043. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1044. }
  1045. TEST(GetHeaderValueTest, DefaultValue) {
  1046. Headers headers = {{"Dummy", "Dummy"}};
  1047. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1048. EXPECT_STREQ("text/plain", val);
  1049. }
  1050. TEST(GetHeaderValueTest, DefaultValueInt) {
  1051. Headers headers = {{"Dummy", "Dummy"}};
  1052. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1053. EXPECT_EQ(100ull, val);
  1054. }
  1055. TEST(GetHeaderValueTest, RegularValue) {
  1056. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1057. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1058. EXPECT_STREQ("text/html", val);
  1059. }
  1060. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1061. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1062. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1063. EXPECT_STREQ("text/html", val);
  1064. }
  1065. TEST(GetHeaderValueTest, SetContent) {
  1066. Response res;
  1067. res.set_content("html", "text/html");
  1068. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1069. res.set_content("text", "text/plain");
  1070. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1071. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1072. }
  1073. TEST(GetHeaderValueTest, RegularValueInt) {
  1074. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1075. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1076. EXPECT_EQ(100ull, val);
  1077. }
  1078. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1079. Headers headers = {{"Content-Length", "x"}};
  1080. auto is_invalid_value = false;
  1081. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1082. is_invalid_value);
  1083. EXPECT_EQ(0ull, val);
  1084. EXPECT_TRUE(is_invalid_value);
  1085. }
  1086. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1087. // An all-digit value that overflows size_t must be reported as invalid, not
  1088. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1089. // a large length to a small one on 32-bit builds, leaving the framing length
  1090. // wrong while is_invalid_value stayed false.
  1091. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1092. auto is_invalid_value = false;
  1093. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1094. is_invalid_value);
  1095. EXPECT_TRUE(is_invalid_value);
  1096. // A well-formed length is unaffected.
  1097. Headers ok = {{"Content-Length", "1234"}};
  1098. is_invalid_value = false;
  1099. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1100. is_invalid_value);
  1101. EXPECT_EQ(1234ull, val);
  1102. EXPECT_FALSE(is_invalid_value);
  1103. }
  1104. TEST(GetHeaderValueTest, Range) {
  1105. {
  1106. Headers headers = {make_range_header({{1, -1}})};
  1107. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1108. EXPECT_STREQ("bytes=1-", val);
  1109. }
  1110. {
  1111. Headers headers = {make_range_header({{-1, 1}})};
  1112. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1113. EXPECT_STREQ("bytes=-1", val);
  1114. }
  1115. {
  1116. Headers headers = {make_range_header({{1, 10}})};
  1117. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1118. EXPECT_STREQ("bytes=1-10", val);
  1119. }
  1120. {
  1121. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1122. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1123. EXPECT_STREQ("bytes=1-10, 100-", val);
  1124. }
  1125. {
  1126. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1127. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1128. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1129. }
  1130. {
  1131. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1132. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1133. EXPECT_STREQ("bytes=0-0, -1", val);
  1134. }
  1135. }
  1136. TEST(ParseHeaderValueTest, Range) {
  1137. {
  1138. Ranges ranges;
  1139. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1140. EXPECT_TRUE(ret);
  1141. EXPECT_EQ(1u, ranges.size());
  1142. EXPECT_EQ(1u, ranges[0].first);
  1143. EXPECT_EQ(-1, ranges[0].second);
  1144. }
  1145. {
  1146. Ranges ranges;
  1147. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1148. EXPECT_TRUE(ret);
  1149. EXPECT_EQ(1u, ranges.size());
  1150. EXPECT_EQ(-1, ranges[0].first);
  1151. EXPECT_EQ(1u, ranges[0].second);
  1152. }
  1153. {
  1154. Ranges ranges;
  1155. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1156. EXPECT_TRUE(ret);
  1157. EXPECT_EQ(1u, ranges.size());
  1158. EXPECT_EQ(1u, ranges[0].first);
  1159. EXPECT_EQ(10u, ranges[0].second);
  1160. }
  1161. {
  1162. Ranges ranges;
  1163. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1164. EXPECT_FALSE(ret);
  1165. }
  1166. {
  1167. Ranges ranges;
  1168. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1169. EXPECT_TRUE(ret);
  1170. EXPECT_EQ(2u, ranges.size());
  1171. EXPECT_EQ(1u, ranges[0].first);
  1172. EXPECT_EQ(10u, ranges[0].second);
  1173. EXPECT_EQ(100u, ranges[1].first);
  1174. EXPECT_EQ(-1, ranges[1].second);
  1175. }
  1176. {
  1177. Ranges ranges;
  1178. auto ret =
  1179. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1180. EXPECT_TRUE(ret);
  1181. EXPECT_EQ(3u, ranges.size());
  1182. EXPECT_EQ(1u, ranges[0].first);
  1183. EXPECT_EQ(10u, ranges[0].second);
  1184. EXPECT_EQ(100u, ranges[1].first);
  1185. EXPECT_EQ(200u, ranges[1].second);
  1186. EXPECT_EQ(300u, ranges[2].first);
  1187. EXPECT_EQ(400u, ranges[2].second);
  1188. }
  1189. {
  1190. Ranges ranges;
  1191. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1192. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1193. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1194. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1195. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1196. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1197. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1198. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1199. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1200. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1201. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1202. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1203. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1204. EXPECT_TRUE(ranges.empty());
  1205. }
  1206. }
  1207. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1208. Request req;
  1209. req.set_header("Accept-Encoding", "gzip");
  1210. Response res;
  1211. res.set_header("Content-Type", "text/plain");
  1212. auto ret = detail::encoding_type(req, res);
  1213. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1214. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1215. #else
  1216. EXPECT_TRUE(ret == detail::EncodingType::None);
  1217. #endif
  1218. }
  1219. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1220. Request req;
  1221. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1222. Response res;
  1223. res.set_header("Content-Type", "text/plain");
  1224. auto ret = detail::encoding_type(req, res);
  1225. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1226. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1227. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1228. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1229. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1230. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1231. #else
  1232. EXPECT_TRUE(ret == detail::EncodingType::None);
  1233. #endif
  1234. }
  1235. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1236. Request req;
  1237. req.set_header("Accept-Encoding",
  1238. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1239. Response res;
  1240. res.set_header("Content-Type", "text/plain");
  1241. auto ret = detail::encoding_type(req, res);
  1242. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1243. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1244. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1245. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1246. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1247. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1248. #else
  1249. EXPECT_TRUE(ret == detail::EncodingType::None);
  1250. #endif
  1251. }
  1252. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1253. // All supported encodings rejected with q=0 should return None
  1254. Request req;
  1255. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1256. Response res;
  1257. res.set_header("Content-Type", "text/plain");
  1258. auto ret = detail::encoding_type(req, res);
  1259. EXPECT_TRUE(ret == detail::EncodingType::None);
  1260. }
  1261. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1262. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1263. Request req;
  1264. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1265. Response res;
  1266. res.set_header("Content-Type", "text/plain");
  1267. auto ret = detail::encoding_type(req, res);
  1268. EXPECT_TRUE(ret == detail::EncodingType::None);
  1269. }
  1270. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1271. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1272. Request req;
  1273. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1274. Response res;
  1275. res.set_header("Content-Type", "text/plain");
  1276. auto ret = detail::encoding_type(req, res);
  1277. EXPECT_TRUE(ret == detail::EncodingType::None);
  1278. }
  1279. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1280. // RFC 7231: Accept-Encoding values are case-insensitive
  1281. Request req;
  1282. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1283. Response res;
  1284. res.set_header("Content-Type", "text/plain");
  1285. auto ret = detail::encoding_type(req, res);
  1286. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1287. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1288. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1289. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1290. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1291. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1292. #else
  1293. EXPECT_TRUE(ret == detail::EncodingType::None);
  1294. #endif
  1295. }
  1296. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1297. // q value should determine priority, not hardcoded order
  1298. Request req;
  1299. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1300. Response res;
  1301. res.set_header("Content-Type", "text/plain");
  1302. auto ret = detail::encoding_type(req, res);
  1303. // gzip has highest q=1.0, so it should be selected even though
  1304. // br and zstd are also supported
  1305. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1306. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1307. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1308. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1309. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1310. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1311. #else
  1312. EXPECT_TRUE(ret == detail::EncodingType::None);
  1313. #endif
  1314. }
  1315. TEST(BufferStreamTest, read) {
  1316. detail::BufferStream strm1;
  1317. Stream &strm = strm1;
  1318. EXPECT_EQ(5, strm.write("hello"));
  1319. char buf[512];
  1320. EXPECT_EQ(2, strm.read(buf, 2));
  1321. EXPECT_EQ('h', buf[0]);
  1322. EXPECT_EQ('e', buf[1]);
  1323. EXPECT_EQ(2, strm.read(buf, 2));
  1324. EXPECT_EQ('l', buf[0]);
  1325. EXPECT_EQ('l', buf[1]);
  1326. EXPECT_EQ(1, strm.read(buf, 1));
  1327. EXPECT_EQ('o', buf[0]);
  1328. EXPECT_EQ(0, strm.read(buf, 1));
  1329. }
  1330. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1331. auto host = "www.httpwatch.com";
  1332. auto ip = hosted_at(host);
  1333. EXPECT_EQ("23.96.13.243", ip);
  1334. std::vector<std::string> addrs;
  1335. hosted_at(host, addrs);
  1336. EXPECT_EQ(1u, addrs.size());
  1337. }
  1338. #if 0 // It depends on each test environment...
  1339. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1340. auto host = "www.youtube.com";
  1341. std::vector<std::string> addrs;
  1342. hosted_at(host, addrs);
  1343. EXPECT_EQ(20u, addrs.size());
  1344. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1345. EXPECT_TRUE(it != addrs.end());
  1346. }
  1347. #endif
  1348. class ChunkedEncodingTest : public ::testing::Test {
  1349. protected:
  1350. ChunkedEncodingTest()
  1351. : cli_(HOST, PORT)
  1352. #ifdef CPPHTTPLIB_SSL_ENABLED
  1353. ,
  1354. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1355. #endif
  1356. {
  1357. cli_.set_connection_timeout(2);
  1358. #ifdef CPPHTTPLIB_SSL_ENABLED
  1359. cli_.enable_server_certificate_verification(false);
  1360. #endif
  1361. }
  1362. virtual void SetUp() {
  1363. read_file("./image.jpg", image_data_);
  1364. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1365. res.set_content("Hello World!", "text/plain");
  1366. });
  1367. svr_.Get(
  1368. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1369. res.set_chunked_content_provider(
  1370. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1371. size_t remaining = image_data_.size() - offset;
  1372. if (remaining == 0) {
  1373. sink.done();
  1374. } else {
  1375. constexpr size_t CHUNK_SIZE = 1024;
  1376. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1377. sink.write(&image_data_[offset], send_size);
  1378. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1379. }
  1380. return true;
  1381. });
  1382. });
  1383. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1384. svr_.wait_until_ready();
  1385. }
  1386. virtual void TearDown() {
  1387. svr_.stop();
  1388. if (!request_threads_.empty()) {
  1389. std::this_thread::sleep_for(std::chrono::seconds(1));
  1390. for (auto &t : request_threads_) {
  1391. t.join();
  1392. }
  1393. }
  1394. t_.join();
  1395. }
  1396. #ifdef CPPHTTPLIB_SSL_ENABLED
  1397. SSLClient cli_;
  1398. SSLServer svr_;
  1399. #else
  1400. Client cli_;
  1401. Server svr_;
  1402. #endif
  1403. thread t_;
  1404. std::vector<thread> request_threads_;
  1405. std::string image_data_;
  1406. };
  1407. TEST_F(ChunkedEncodingTest, NormalGet) {
  1408. auto res = cli_.Get("/chunked");
  1409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1410. std::string out;
  1411. read_file("./image.jpg", out);
  1412. EXPECT_EQ(StatusCode::OK_200, res->status);
  1413. EXPECT_EQ(out, res->body);
  1414. }
  1415. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1416. std::string body;
  1417. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1418. body.append(data, data_length);
  1419. return true;
  1420. });
  1421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1422. std::string out;
  1423. read_file("./image.jpg", out);
  1424. EXPECT_EQ(StatusCode::OK_200, res->status);
  1425. EXPECT_EQ(out, body);
  1426. }
  1427. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1428. std::string body;
  1429. auto res = cli_.Get(
  1430. "/chunked",
  1431. [&](const Response &response) {
  1432. EXPECT_EQ(StatusCode::OK_200, response.status);
  1433. return true;
  1434. },
  1435. [&](const char *data, size_t data_length) {
  1436. body.append(data, data_length);
  1437. return true;
  1438. });
  1439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1440. std::string out;
  1441. read_file("./image.jpg", out);
  1442. EXPECT_EQ(StatusCode::OK_200, res->status);
  1443. EXPECT_EQ(out, body);
  1444. }
  1445. TEST(RangeTest, FromHTTPBin_Online) {
  1446. auto host = "httpbingo.org";
  1447. auto path = std::string{"/range/32"};
  1448. #ifdef CPPHTTPLIB_SSL_ENABLED
  1449. auto port = 443;
  1450. SSLClient cli(host, port);
  1451. #else
  1452. auto port = 80;
  1453. Client cli(host, port);
  1454. #endif
  1455. cli.set_connection_timeout(5);
  1456. {
  1457. auto res = cli.Get(path);
  1458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1459. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1460. EXPECT_EQ(StatusCode::OK_200, res->status);
  1461. }
  1462. {
  1463. Headers headers = {make_range_header({{1, -1}})};
  1464. auto res = cli.Get(path, headers);
  1465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1466. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1468. }
  1469. {
  1470. Headers headers = {make_range_header({{1, 10}})};
  1471. auto res = cli.Get(path, headers);
  1472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1473. EXPECT_EQ("bcdefghijk", res->body);
  1474. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1475. }
  1476. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1477. // entire resource, while the original httpbin returned 200. Both are
  1478. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1479. {
  1480. Headers headers = {make_range_header({{0, 31}})};
  1481. auto res = cli.Get(path, headers);
  1482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1483. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1484. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1485. res->status == StatusCode::PartialContent_206);
  1486. }
  1487. {
  1488. Headers headers = {make_range_header({{0, -1}})};
  1489. auto res = cli.Get(path, headers);
  1490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1491. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1492. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1493. res->status == StatusCode::PartialContent_206);
  1494. }
  1495. // go-httpbin returns 206 with clamped range for over-range requests,
  1496. // while the original httpbin returned 416. Both behaviors are observed
  1497. // in real servers, so we only verify the request succeeds.
  1498. {
  1499. Headers headers = {make_range_header({{0, 32}})};
  1500. auto res = cli.Get(path, headers);
  1501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1502. }
  1503. }
  1504. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1505. auto host = "unresolvableaddress.local";
  1506. auto path = std::string{"/"};
  1507. #ifdef CPPHTTPLIB_SSL_ENABLED
  1508. auto port = 443;
  1509. SSLClient cli(host, port);
  1510. #else
  1511. auto port = 80;
  1512. Client cli(host, port);
  1513. #endif
  1514. cli.set_connection_timeout(1);
  1515. {
  1516. auto res = cli.Get(path);
  1517. ASSERT_FALSE(res);
  1518. }
  1519. std::this_thread::sleep_for(std::chrono::seconds(8));
  1520. }
  1521. #if defined(__linux__) && defined(__GLIBC__) && \
  1522. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1523. // Forward declaration: in split builds split.py strips `inline` and moves the
  1524. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1525. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1526. // against the symbol in both header-only and split builds.
  1527. namespace httplib {
  1528. namespace detail {
  1529. int getaddrinfo_with_timeout(const char *node, const char *service,
  1530. const struct addrinfo *hints,
  1531. struct addrinfo **res, time_t timeout_sec);
  1532. } // namespace detail
  1533. } // namespace httplib
  1534. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1535. //
  1536. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1537. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1538. // gai_suspend() call hits the connection timeout the function calls
  1539. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1540. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1541. // still alive and still references the now-destroyed stack frame.
  1542. //
  1543. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1544. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1545. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1546. // and runs them in a container.
  1547. namespace {
  1548. bool should_run_issue_2431_tests() {
  1549. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1550. return v && *v && std::string(v) != "0";
  1551. }
  1552. std::string unique_unresolvable_host(int n) {
  1553. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1554. // glibc still asks the configured nameserver — which is exactly the path
  1555. // we want to exercise. A unique label per call avoids the resolver cache.
  1556. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1557. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1558. std::to_string(n) + ".invalid";
  1559. }
  1560. } // namespace
  1561. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1562. if (!should_run_issue_2431_tests()) {
  1563. GTEST_SKIP()
  1564. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1565. }
  1566. for (int i = 0; i < 8; ++i) {
  1567. struct addrinfo hints;
  1568. memset(&hints, 0, sizeof(hints));
  1569. hints.ai_family = AF_UNSPEC;
  1570. hints.ai_socktype = SOCK_STREAM;
  1571. auto host = unique_unresolvable_host(i);
  1572. struct addrinfo *result = nullptr;
  1573. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1574. &result, /*timeout_sec=*/1);
  1575. if (rc == 0 && result) { freeaddrinfo(result); }
  1576. }
  1577. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1578. // stack region they still believe holds their gaicb.
  1579. std::this_thread::sleep_for(std::chrono::seconds(3));
  1580. }
  1581. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1582. if (!should_run_issue_2431_tests()) {
  1583. GTEST_SKIP()
  1584. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1585. }
  1586. std::atomic<bool> stop{false};
  1587. std::vector<std::thread> threads;
  1588. for (int t = 0; t < 8; ++t) {
  1589. threads.emplace_back([t, &stop] {
  1590. int i = 0;
  1591. while (!stop.load(std::memory_order_relaxed)) {
  1592. struct addrinfo hints;
  1593. memset(&hints, 0, sizeof(hints));
  1594. hints.ai_family = AF_UNSPEC;
  1595. hints.ai_socktype = SOCK_STREAM;
  1596. auto host = unique_unresolvable_host(t * 100000 + i++);
  1597. struct addrinfo *result = nullptr;
  1598. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1599. &result, /*timeout_sec=*/1);
  1600. if (rc == 0 && result) { freeaddrinfo(result); }
  1601. }
  1602. });
  1603. }
  1604. std::this_thread::sleep_for(std::chrono::seconds(8));
  1605. stop.store(true, std::memory_order_relaxed);
  1606. for (auto &th : threads) {
  1607. th.join();
  1608. }
  1609. std::this_thread::sleep_for(std::chrono::seconds(3));
  1610. }
  1611. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1612. if (!should_run_issue_2431_tests()) {
  1613. GTEST_SKIP()
  1614. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1615. }
  1616. std::atomic<bool> stop{false};
  1617. std::vector<std::thread> threads;
  1618. for (int t = 0; t < 8; ++t) {
  1619. threads.emplace_back([t, &stop] {
  1620. int i = 0;
  1621. while (!stop.load(std::memory_order_relaxed)) {
  1622. auto host = unique_unresolvable_host(t * 100000 + i++);
  1623. Client cli(host, 80);
  1624. cli.set_connection_timeout(1, 0);
  1625. cli.set_read_timeout(1, 0);
  1626. cli.set_write_timeout(1, 0);
  1627. (void)cli.Get("/");
  1628. }
  1629. });
  1630. }
  1631. std::this_thread::sleep_for(std::chrono::seconds(8));
  1632. stop.store(true, std::memory_order_relaxed);
  1633. for (auto &th : threads) {
  1634. th.join();
  1635. }
  1636. std::this_thread::sleep_for(std::chrono::seconds(3));
  1637. }
  1638. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1639. TEST(ConnectionErrorTest, InvalidHost) {
  1640. auto host = "-abcde.com";
  1641. #ifdef CPPHTTPLIB_SSL_ENABLED
  1642. auto port = 443;
  1643. SSLClient cli(host, port);
  1644. #else
  1645. auto port = 80;
  1646. Client cli(host, port);
  1647. #endif
  1648. cli.set_connection_timeout(std::chrono::seconds(2));
  1649. auto res = cli.Get("/");
  1650. ASSERT_TRUE(!res);
  1651. EXPECT_EQ(Error::Connection, res.error());
  1652. }
  1653. TEST(ConnectionErrorTest, InvalidHost2) {
  1654. auto host = "httpcan.org/";
  1655. #ifdef CPPHTTPLIB_SSL_ENABLED
  1656. SSLClient cli(host);
  1657. #else
  1658. Client cli(host);
  1659. #endif
  1660. cli.set_connection_timeout(std::chrono::seconds(2));
  1661. auto res = cli.Get("/");
  1662. ASSERT_TRUE(!res);
  1663. EXPECT_EQ(Error::Connection, res.error());
  1664. }
  1665. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1666. auto host = "httpcan.org/";
  1667. #ifdef CPPHTTPLIB_SSL_ENABLED
  1668. SSLClient cli(host);
  1669. #else
  1670. Client cli(host);
  1671. #endif
  1672. cli.set_connection_timeout(std::chrono::seconds(2));
  1673. auto res = cli.Get("/");
  1674. ASSERT_TRUE(!res);
  1675. stringstream s;
  1676. s << "error code: " << res.error();
  1677. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1678. }
  1679. TEST(ConnectionErrorTest, InvalidPort) {
  1680. auto host = "localhost";
  1681. auto port = 44380;
  1682. #ifdef CPPHTTPLIB_SSL_ENABLED
  1683. SSLClient cli(host, port);
  1684. #else
  1685. Client cli(host, port);
  1686. #endif
  1687. cli.set_connection_timeout(std::chrono::seconds(2));
  1688. auto res = cli.Get("/");
  1689. ASSERT_TRUE(!res);
  1690. EXPECT_TRUE(Error::Connection == res.error() ||
  1691. Error::ConnectionTimeout == res.error());
  1692. }
  1693. TEST(ConnectionErrorTest, Timeout_Online) {
  1694. auto host = "google.com";
  1695. #ifdef CPPHTTPLIB_SSL_ENABLED
  1696. auto port = 44380;
  1697. SSLClient cli(host, port);
  1698. #else
  1699. auto port = 8080;
  1700. Client cli(host, port);
  1701. #endif
  1702. cli.set_connection_timeout(std::chrono::seconds(2));
  1703. // only probe one address type so that the error reason
  1704. // correlates to the timed-out IPv4, not the unsupported
  1705. // IPv6 connection attempt
  1706. cli.set_address_family(AF_INET);
  1707. auto res = cli.Get("/");
  1708. ASSERT_TRUE(!res);
  1709. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1710. }
  1711. TEST(CancelTest, NoCancel_Online) {
  1712. auto host = "httpbingo.org";
  1713. auto path = std::string{"/range/32"};
  1714. #ifdef CPPHTTPLIB_SSL_ENABLED
  1715. auto port = 443;
  1716. SSLClient cli(host, port);
  1717. #else
  1718. auto port = 80;
  1719. Client cli(host, port);
  1720. #endif
  1721. cli.set_connection_timeout(std::chrono::seconds(5));
  1722. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1724. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1725. EXPECT_EQ(StatusCode::OK_200, res->status);
  1726. }
  1727. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1728. // Use /bytes with a large payload so that the DownloadProgress callback
  1729. // (which only fires for Content-Length responses) is invoked before the
  1730. // entire body is received, giving cancellation a chance to fire.
  1731. auto host = "httpbingo.org";
  1732. auto path = std::string{"/bytes/524288"};
  1733. #ifdef CPPHTTPLIB_SSL_ENABLED
  1734. auto port = 443;
  1735. SSLClient cli(host, port);
  1736. #else
  1737. auto port = 80;
  1738. Client cli(host, port);
  1739. #endif
  1740. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1741. cli.set_connection_timeout(std::chrono::seconds(5));
  1742. ASSERT_TRUE(!res);
  1743. EXPECT_EQ(Error::Canceled, res.error());
  1744. }
  1745. TEST(CancelTest, WithCancelLargePayload_Online) {
  1746. auto host = "httpbingo.org";
  1747. auto path = std::string{"/bytes/524288"};
  1748. #ifdef CPPHTTPLIB_SSL_ENABLED
  1749. auto port = 443;
  1750. SSLClient cli(host, port);
  1751. #else
  1752. auto port = 80;
  1753. Client cli(host, port);
  1754. #endif
  1755. cli.set_connection_timeout(std::chrono::seconds(5));
  1756. uint32_t count = 0;
  1757. auto res =
  1758. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1759. ASSERT_TRUE(!res);
  1760. EXPECT_EQ(Error::Canceled, res.error());
  1761. }
  1762. TEST(CancelTest, NoCancelPost) {
  1763. Server svr;
  1764. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1765. res.set_content("Hello World!", "text/plain");
  1766. });
  1767. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1768. auto se = detail::scope_exit([&] {
  1769. svr.stop();
  1770. thread.join();
  1771. ASSERT_FALSE(svr.is_running());
  1772. });
  1773. svr.wait_until_ready();
  1774. Client cli(HOST, PORT);
  1775. cli.set_connection_timeout(std::chrono::seconds(5));
  1776. auto res =
  1777. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1778. "application/json", [](uint64_t, uint64_t) { return true; });
  1779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1780. EXPECT_EQ("Hello World!", res->body);
  1781. EXPECT_EQ(StatusCode::OK_200, res->status);
  1782. }
  1783. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1784. Server svr;
  1785. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1786. res.set_content("Hello World!", "text/plain");
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. Client cli(HOST, PORT);
  1796. cli.set_connection_timeout(std::chrono::seconds(5));
  1797. auto res =
  1798. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1799. "application/json", [](uint64_t, uint64_t) { return false; });
  1800. ASSERT_TRUE(!res);
  1801. EXPECT_EQ(Error::Canceled, res.error());
  1802. }
  1803. TEST(CancelTest, WithCancelLargePayloadPost) {
  1804. Server svr;
  1805. svr.set_payload_max_length(200 * 1024 * 1024);
  1806. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1807. res.set_content(LARGE_DATA, "text/plain");
  1808. });
  1809. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1810. auto se = detail::scope_exit([&] {
  1811. svr.stop();
  1812. thread.join();
  1813. ASSERT_FALSE(svr.is_running());
  1814. });
  1815. svr.wait_until_ready();
  1816. Client cli(HOST, PORT);
  1817. cli.set_payload_max_length(200 * 1024 * 1024);
  1818. cli.set_connection_timeout(std::chrono::seconds(5));
  1819. auto res =
  1820. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1821. "application/json", [](uint64_t, uint64_t) { return false; });
  1822. ASSERT_TRUE(!res);
  1823. EXPECT_EQ(Error::Canceled, res.error());
  1824. }
  1825. TEST(CancelTest, NoCancelPut) {
  1826. Server svr;
  1827. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1828. res.set_content("Hello World!", "text/plain");
  1829. });
  1830. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1831. auto se = detail::scope_exit([&] {
  1832. svr.stop();
  1833. thread.join();
  1834. ASSERT_FALSE(svr.is_running());
  1835. });
  1836. svr.wait_until_ready();
  1837. Client cli(HOST, PORT);
  1838. cli.set_connection_timeout(std::chrono::seconds(5));
  1839. auto res =
  1840. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1841. "application/json", [](uint64_t, uint64_t) { return true; });
  1842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1843. EXPECT_EQ("Hello World!", res->body);
  1844. EXPECT_EQ(StatusCode::OK_200, res->status);
  1845. }
  1846. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1847. Server svr;
  1848. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1849. res.set_content("Hello World!", "text/plain");
  1850. });
  1851. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1852. auto se = detail::scope_exit([&] {
  1853. svr.stop();
  1854. thread.join();
  1855. ASSERT_FALSE(svr.is_running());
  1856. });
  1857. svr.wait_until_ready();
  1858. Client cli(HOST, PORT);
  1859. cli.set_connection_timeout(std::chrono::seconds(5));
  1860. auto res =
  1861. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1862. "application/json", [](uint64_t, uint64_t) { return false; });
  1863. ASSERT_TRUE(!res);
  1864. EXPECT_EQ(Error::Canceled, res.error());
  1865. }
  1866. TEST(CancelTest, WithCancelLargePayloadPut) {
  1867. Server svr;
  1868. svr.set_payload_max_length(200 * 1024 * 1024);
  1869. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1870. res.set_content(LARGE_DATA, "text/plain");
  1871. });
  1872. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1873. auto se = detail::scope_exit([&] {
  1874. svr.stop();
  1875. thread.join();
  1876. ASSERT_FALSE(svr.is_running());
  1877. });
  1878. svr.wait_until_ready();
  1879. Client cli(HOST, PORT);
  1880. cli.set_payload_max_length(200 * 1024 * 1024);
  1881. cli.set_connection_timeout(std::chrono::seconds(5));
  1882. auto res =
  1883. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1884. "application/json", [](uint64_t, uint64_t) { return false; });
  1885. ASSERT_TRUE(!res);
  1886. EXPECT_EQ(Error::Canceled, res.error());
  1887. }
  1888. TEST(CancelTest, NoCancelPatch) {
  1889. Server svr;
  1890. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1891. res.set_content("Hello World!", "text/plain");
  1892. });
  1893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1894. auto se = detail::scope_exit([&] {
  1895. svr.stop();
  1896. thread.join();
  1897. ASSERT_FALSE(svr.is_running());
  1898. });
  1899. svr.wait_until_ready();
  1900. Client cli(HOST, PORT);
  1901. cli.set_connection_timeout(std::chrono::seconds(5));
  1902. auto res =
  1903. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1904. "application/json", [](uint64_t, uint64_t) { return true; });
  1905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1906. EXPECT_EQ("Hello World!", res->body);
  1907. EXPECT_EQ(StatusCode::OK_200, res->status);
  1908. }
  1909. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1910. Server svr;
  1911. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1912. res.set_content("Hello World!", "text/plain");
  1913. });
  1914. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1915. auto se = detail::scope_exit([&] {
  1916. svr.stop();
  1917. thread.join();
  1918. ASSERT_FALSE(svr.is_running());
  1919. });
  1920. svr.wait_until_ready();
  1921. Client cli(HOST, PORT);
  1922. cli.set_connection_timeout(std::chrono::seconds(5));
  1923. auto res =
  1924. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1925. "application/json", [](uint64_t, uint64_t) { return false; });
  1926. ASSERT_TRUE(!res);
  1927. EXPECT_EQ(Error::Canceled, res.error());
  1928. }
  1929. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1930. Server svr;
  1931. svr.set_payload_max_length(200 * 1024 * 1024);
  1932. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1933. res.set_content(LARGE_DATA, "text/plain");
  1934. });
  1935. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1936. auto se = detail::scope_exit([&] {
  1937. svr.stop();
  1938. thread.join();
  1939. ASSERT_FALSE(svr.is_running());
  1940. });
  1941. svr.wait_until_ready();
  1942. Client cli(HOST, PORT);
  1943. cli.set_payload_max_length(200 * 1024 * 1024);
  1944. cli.set_connection_timeout(std::chrono::seconds(5));
  1945. auto res =
  1946. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1947. "application/json", [](uint64_t, uint64_t) { return false; });
  1948. ASSERT_TRUE(!res);
  1949. EXPECT_EQ(Error::Canceled, res.error());
  1950. }
  1951. TEST(CancelTest, NoCancelDelete) {
  1952. Server svr;
  1953. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1954. res.set_content("Hello World!", "text/plain");
  1955. });
  1956. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1957. auto se = detail::scope_exit([&] {
  1958. svr.stop();
  1959. thread.join();
  1960. ASSERT_FALSE(svr.is_running());
  1961. });
  1962. svr.wait_until_ready();
  1963. Client cli(HOST, PORT);
  1964. cli.set_connection_timeout(std::chrono::seconds(5));
  1965. auto res =
  1966. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1967. "application/json", [](uint64_t, uint64_t) { return true; });
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("Hello World!", res->body);
  1970. EXPECT_EQ(StatusCode::OK_200, res->status);
  1971. }
  1972. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1973. Server svr;
  1974. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1975. res.set_content("Hello World!", "text/plain");
  1976. });
  1977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1978. auto se = detail::scope_exit([&] {
  1979. svr.stop();
  1980. thread.join();
  1981. ASSERT_FALSE(svr.is_running());
  1982. });
  1983. svr.wait_until_ready();
  1984. Client cli(HOST, PORT);
  1985. cli.set_connection_timeout(std::chrono::seconds(5));
  1986. auto res =
  1987. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1988. "application/json", [](uint64_t, uint64_t) { return false; });
  1989. ASSERT_TRUE(!res);
  1990. EXPECT_EQ(Error::Canceled, res.error());
  1991. }
  1992. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1993. Server svr;
  1994. svr.set_payload_max_length(200 * 1024 * 1024);
  1995. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1996. res.set_content(LARGE_DATA, "text/plain");
  1997. });
  1998. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1999. auto se = detail::scope_exit([&] {
  2000. svr.stop();
  2001. thread.join();
  2002. ASSERT_FALSE(svr.is_running());
  2003. });
  2004. svr.wait_until_ready();
  2005. Client cli(HOST, PORT);
  2006. cli.set_payload_max_length(200 * 1024 * 1024);
  2007. cli.set_connection_timeout(std::chrono::seconds(5));
  2008. auto res =
  2009. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2010. "application/json", [](uint64_t, uint64_t) { return false; });
  2011. ASSERT_TRUE(!res);
  2012. EXPECT_EQ(Error::Canceled, res.error());
  2013. }
  2014. static std::string remove_whitespace(const std::string &input) {
  2015. std::string output;
  2016. output.reserve(input.size());
  2017. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2018. [](unsigned char c) { return !std::isspace(c); });
  2019. return output;
  2020. }
  2021. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2022. auto host = "httpbingo.org";
  2023. auto path = std::string{"/basic-auth/hello/world"};
  2024. #ifdef CPPHTTPLIB_SSL_ENABLED
  2025. auto port = 443;
  2026. SSLClient cli(host, port);
  2027. #else
  2028. auto port = 80;
  2029. Client cli(host, port);
  2030. #endif
  2031. {
  2032. auto res = cli.Get(path);
  2033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2034. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2035. }
  2036. {
  2037. auto res = cli.Get(
  2038. path, Headers{make_basic_authentication_header("hello", "world")});
  2039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2040. auto body = remove_whitespace(res->body);
  2041. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2042. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2043. EXPECT_EQ(StatusCode::OK_200, res->status);
  2044. }
  2045. {
  2046. cli.set_basic_auth("hello", "world");
  2047. auto res = cli.Get(path);
  2048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2049. auto body = remove_whitespace(res->body);
  2050. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2051. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2052. EXPECT_EQ(StatusCode::OK_200, res->status);
  2053. }
  2054. {
  2055. cli.set_basic_auth("hello", "bad");
  2056. auto res = cli.Get(path);
  2057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2058. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2059. }
  2060. {
  2061. cli.set_basic_auth("bad", "world");
  2062. auto res = cli.Get(path);
  2063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2064. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2065. }
  2066. }
  2067. #ifdef CPPHTTPLIB_SSL_ENABLED
  2068. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2069. auto host = "httpbingo.org";
  2070. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2071. auto paths = std::vector<std::string>{
  2072. "/digest-auth/auth/hello/world/MD5",
  2073. "/digest-auth/auth/hello/world/SHA-256",
  2074. };
  2075. auto port = 443;
  2076. SSLClient cli(host, port);
  2077. {
  2078. auto res = cli.Get(unauth_path);
  2079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2080. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2081. }
  2082. {
  2083. cli.set_digest_auth("hello", "world");
  2084. for (const auto &path : paths) {
  2085. auto res = cli.Get(path.c_str());
  2086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2087. auto body = remove_whitespace(res->body);
  2088. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2089. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2090. EXPECT_EQ(StatusCode::OK_200, res->status);
  2091. }
  2092. cli.set_digest_auth("hello", "bad");
  2093. for (const auto &path : paths) {
  2094. auto res = cli.Get(path.c_str());
  2095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2096. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2097. }
  2098. }
  2099. }
  2100. #endif
  2101. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2102. auto host = "google.com";
  2103. auto another_host = "example.com";
  2104. auto wrong_ip = "0.0.0.0";
  2105. #ifdef CPPHTTPLIB_SSL_ENABLED
  2106. SSLClient cli(host);
  2107. #else
  2108. Client cli(host);
  2109. #endif
  2110. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2111. auto res = cli.Get("/");
  2112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2113. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2114. }
  2115. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2116. auto host = "google.com";
  2117. auto wrong_ip = "0.0.0.0";
  2118. #ifdef CPPHTTPLIB_SSL_ENABLED
  2119. SSLClient cli(host);
  2120. #else
  2121. Client cli(host);
  2122. #endif
  2123. cli.set_hostname_addr_map({{host, wrong_ip}});
  2124. auto res = cli.Get("/");
  2125. ASSERT_TRUE(!res);
  2126. EXPECT_EQ(Error::Connection, res.error());
  2127. }
  2128. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2129. // A mapped value that is not an IP literal must be resolved. "localhost"
  2130. // resolves from the hosts file, so this test needs no external DNS.
  2131. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2132. auto host = "target.invalid";
  2133. Server svr;
  2134. std::string received_host;
  2135. svr.Get("/hi", [&](const Request &req, Response &res) {
  2136. received_host = req.get_header_value("Host");
  2137. res.set_content("Hello World!", "text/plain");
  2138. });
  2139. auto port = svr.bind_to_any_port(HOST);
  2140. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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_hostname_addr_map({{host, HOST}});
  2149. auto res = cli.Get("/hi");
  2150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2151. EXPECT_EQ(StatusCode::OK_200, res->status);
  2152. // The mapping only redirects the connection; the identity stays host_.
  2153. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2154. }
  2155. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2156. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2157. auto host = "target.invalid";
  2158. Server svr;
  2159. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2160. res.set_content("Hello World!", "text/plain");
  2161. });
  2162. auto port = svr.bind_to_any_port("127.0.0.1");
  2163. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2164. auto se = detail::scope_exit([&] {
  2165. svr.stop();
  2166. thread.join();
  2167. ASSERT_FALSE(svr.is_running());
  2168. });
  2169. svr.wait_until_ready();
  2170. Client cli(host, port);
  2171. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2172. auto res = cli.Get("/hi");
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ(StatusCode::OK_200, res->status);
  2175. }
  2176. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2177. // An empty mapped value must leave host_ as the connection target. Without
  2178. // that guard the empty value would become the host argument, getaddrinfo
  2179. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2180. // loopback - silently connecting somewhere the caller never asked for.
  2181. // The server listens on loopback, so such a fallback would succeed and is
  2182. // therefore observable as a failure of this test.
  2183. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2184. Server svr;
  2185. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2186. res.set_content("Hello World!", "text/plain");
  2187. });
  2188. auto port = svr.bind_to_any_port(HOST);
  2189. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. Client cli(blackhole, port);
  2197. cli.set_hostname_addr_map({{blackhole, ""}});
  2198. cli.set_connection_timeout(1);
  2199. auto res = cli.Get("/hi");
  2200. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2201. }
  2202. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2203. auto host = "httpbingo.org";
  2204. auto path = std::string{"/absolute-redirect/3"};
  2205. #ifdef CPPHTTPLIB_SSL_ENABLED
  2206. SSLClient cli(host);
  2207. #else
  2208. Client cli(host);
  2209. #endif
  2210. cli.set_follow_location(true);
  2211. auto res = cli.Get(path);
  2212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2213. EXPECT_EQ(StatusCode::OK_200, res->status);
  2214. }
  2215. TEST(RedirectTest, Redirect_Online) {
  2216. auto host = "httpbingo.org";
  2217. auto path = std::string{"/redirect/3"};
  2218. #ifdef CPPHTTPLIB_SSL_ENABLED
  2219. SSLClient cli(host);
  2220. #else
  2221. Client cli(host);
  2222. #endif
  2223. cli.set_follow_location(true);
  2224. auto res = cli.Get(path);
  2225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2226. EXPECT_EQ(StatusCode::OK_200, res->status);
  2227. }
  2228. TEST(RelativeRedirectTest, Redirect_Online) {
  2229. auto host = "httpbingo.org";
  2230. auto path = std::string{"/relative-redirect/3"};
  2231. #ifdef CPPHTTPLIB_SSL_ENABLED
  2232. SSLClient cli(host);
  2233. #else
  2234. Client cli(host);
  2235. #endif
  2236. cli.set_follow_location(true);
  2237. auto res = cli.Get(path);
  2238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2239. EXPECT_EQ(StatusCode::OK_200, res->status);
  2240. }
  2241. TEST(TooManyRedirectTest, Redirect_Online) {
  2242. auto host = "httpbingo.org";
  2243. auto path = std::string{"/redirect/21"};
  2244. #ifdef CPPHTTPLIB_SSL_ENABLED
  2245. SSLClient cli(host);
  2246. #else
  2247. Client cli(host);
  2248. #endif
  2249. cli.set_follow_location(true);
  2250. auto res = cli.Get(path);
  2251. ASSERT_TRUE(!res);
  2252. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2253. }
  2254. #ifdef CPPHTTPLIB_SSL_ENABLED
  2255. TEST(YahooRedirectTest, Redirect_Online) {
  2256. Client cli("yahoo.com");
  2257. auto res = cli.Get("/");
  2258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2259. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2260. cli.set_follow_location(true);
  2261. res = cli.Get("/");
  2262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2263. EXPECT_EQ(StatusCode::OK_200, res->status);
  2264. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2265. }
  2266. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2267. #define REDIR_HOST "httpbingo.org"
  2268. #define REDIR_PATH "/redirect-to"
  2269. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2270. SSLClient cli(REDIR_HOST);
  2271. cli.set_follow_location(true);
  2272. auto res =
  2273. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2275. EXPECT_EQ(StatusCode::OK_200, res->status);
  2276. }
  2277. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2278. SSLClient cli(REDIR_HOST);
  2279. cli.set_follow_location(true);
  2280. Params params;
  2281. params.emplace("url", "http://example.com");
  2282. params.emplace("status_code", "302");
  2283. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. }
  2287. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2288. SSLClient cli(REDIR_HOST);
  2289. cli.set_follow_location(true);
  2290. Params params;
  2291. params.emplace("url", "http://example.com");
  2292. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2294. EXPECT_EQ(StatusCode::OK_200, res->status);
  2295. }
  2296. TEST(UrlWithSpace, Redirect_Online) {
  2297. SSLClient cli("edge.forgecdn.net");
  2298. cli.set_follow_location(true);
  2299. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2303. }
  2304. #endif
  2305. #if !defined(_WIN32) && !defined(_WIN64)
  2306. TEST(ReceiveSignals, Signal) {
  2307. auto setupSignalHandlers = []() {
  2308. struct sigaction act;
  2309. sigemptyset(&act.sa_mask);
  2310. act.sa_flags = SA_SIGINFO;
  2311. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2312. switch (sig) {
  2313. case SIGINT:
  2314. default: break;
  2315. }
  2316. };
  2317. ::sigaction(SIGINT, &act, nullptr);
  2318. };
  2319. Server svr;
  2320. int port = 0;
  2321. auto thread = std::thread([&]() {
  2322. setupSignalHandlers();
  2323. port = svr.bind_to_any_port(HOST);
  2324. svr.listen_after_bind();
  2325. });
  2326. auto se = detail::scope_exit([&] {
  2327. svr.stop();
  2328. thread.join();
  2329. ASSERT_FALSE(svr.is_running());
  2330. });
  2331. svr.wait_until_ready();
  2332. ASSERT_TRUE(svr.is_running());
  2333. pthread_kill(thread.native_handle(), SIGINT);
  2334. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2335. ASSERT_TRUE(svr.is_running());
  2336. }
  2337. #endif
  2338. TEST(RedirectToDifferentPort, Redirect) {
  2339. Server svr1;
  2340. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2341. res.set_content("Hello World!", "text/plain");
  2342. });
  2343. int svr1_port = 0;
  2344. auto thread1 = std::thread([&]() {
  2345. svr1_port = svr1.bind_to_any_port(HOST);
  2346. svr1.listen_after_bind();
  2347. });
  2348. Server svr2;
  2349. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2350. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2351. });
  2352. int svr2_port = 0;
  2353. auto thread2 = std::thread([&]() {
  2354. svr2_port = svr2.bind_to_any_port(HOST);
  2355. svr2.listen_after_bind();
  2356. });
  2357. auto se = detail::scope_exit([&] {
  2358. svr2.stop();
  2359. thread2.join();
  2360. svr1.stop();
  2361. thread1.join();
  2362. ASSERT_FALSE(svr2.is_running());
  2363. ASSERT_FALSE(svr1.is_running());
  2364. });
  2365. svr1.wait_until_ready();
  2366. svr2.wait_until_ready();
  2367. Client cli("localhost", svr2_port);
  2368. cli.set_follow_location(true);
  2369. auto res = cli.Get("/2");
  2370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2371. EXPECT_EQ(StatusCode::OK_200, res->status);
  2372. EXPECT_EQ("Hello World!", res->body);
  2373. }
  2374. static void
  2375. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2376. Server svr1;
  2377. std::string captured_authorization;
  2378. svr1.Get("/target", [&](const Request &req, Response &res) {
  2379. captured_authorization = req.get_header_value("Authorization");
  2380. res.set_content("OK", "text/plain");
  2381. });
  2382. int svr1_port = 0;
  2383. auto thread1 = std::thread([&]() {
  2384. svr1_port = svr1.bind_to_any_port(HOST);
  2385. svr1.listen_after_bind();
  2386. });
  2387. Server svr2;
  2388. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2389. res.set_redirect(
  2390. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2391. });
  2392. int svr2_port = 0;
  2393. auto thread2 = std::thread([&]() {
  2394. svr2_port = svr2.bind_to_any_port(HOST);
  2395. svr2.listen_after_bind();
  2396. });
  2397. auto se = detail::scope_exit([&] {
  2398. svr2.stop();
  2399. thread2.join();
  2400. svr1.stop();
  2401. thread1.join();
  2402. ASSERT_FALSE(svr2.is_running());
  2403. ASSERT_FALSE(svr1.is_running());
  2404. });
  2405. svr1.wait_until_ready();
  2406. svr2.wait_until_ready();
  2407. Client cli("localhost", svr2_port);
  2408. cli.set_follow_location(true);
  2409. set_auth(cli);
  2410. auto res = cli.Get("/redir");
  2411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2412. EXPECT_EQ(StatusCode::OK_200, res->status);
  2413. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2414. EXPECT_TRUE(captured_authorization.empty());
  2415. }
  2416. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2417. TestDoNotForwardCredentialsOnRedirect(
  2418. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2419. }
  2420. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2421. TestDoNotForwardCredentialsOnRedirect(
  2422. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2423. }
  2424. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2425. Server svr1;
  2426. std::string captured_cookie;
  2427. bool target_hit = false;
  2428. svr1.Get("/target", [&](const Request &req, Response &res) {
  2429. captured_cookie = req.get_header_value("Cookie");
  2430. target_hit = true;
  2431. res.set_content("OK", "text/plain");
  2432. });
  2433. int svr1_port = 0;
  2434. auto thread1 = std::thread([&]() {
  2435. svr1_port = svr1.bind_to_any_port(HOST);
  2436. svr1.listen_after_bind();
  2437. });
  2438. Server svr2;
  2439. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2440. res.set_redirect(
  2441. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2442. });
  2443. int svr2_port = 0;
  2444. auto thread2 = std::thread([&]() {
  2445. svr2_port = svr2.bind_to_any_port(HOST);
  2446. svr2.listen_after_bind();
  2447. });
  2448. auto se = detail::scope_exit([&] {
  2449. svr2.stop();
  2450. thread2.join();
  2451. svr1.stop();
  2452. thread1.join();
  2453. ASSERT_FALSE(svr2.is_running());
  2454. ASSERT_FALSE(svr1.is_running());
  2455. });
  2456. svr1.wait_until_ready();
  2457. svr2.wait_until_ready();
  2458. Client cli("localhost", svr2_port);
  2459. cli.set_follow_location(true);
  2460. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2461. auto res = cli.Get("/redir", headers);
  2462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2463. EXPECT_EQ(StatusCode::OK_200, res->status);
  2464. EXPECT_TRUE(target_hit);
  2465. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2466. EXPECT_TRUE(captured_cookie.empty());
  2467. }
  2468. TEST(RedirectToSamePort, ForwardCookie) {
  2469. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2470. // header so that ordinary session flows keep working.
  2471. Server svr;
  2472. std::string captured_cookie;
  2473. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2474. res.set_redirect("/target", 302);
  2475. });
  2476. svr.Get("/target", [&](const Request &req, Response &res) {
  2477. captured_cookie = req.get_header_value("Cookie");
  2478. res.set_content("OK", "text/plain");
  2479. });
  2480. auto port = svr.bind_to_any_port(HOST);
  2481. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2482. auto se = detail::scope_exit([&] {
  2483. svr.stop();
  2484. thread.join();
  2485. ASSERT_FALSE(svr.is_running());
  2486. });
  2487. svr.wait_until_ready();
  2488. Client cli(HOST, port);
  2489. cli.set_follow_location(true);
  2490. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2491. auto res = cli.Get("/redir", headers);
  2492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2493. EXPECT_EQ(StatusCode::OK_200, res->status);
  2494. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2495. }
  2496. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2497. Server svr;
  2498. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2499. // Port number that overflows int — should not crash
  2500. res.set_redirect("http://localhost:99999999999999999999/target");
  2501. });
  2502. auto port = svr.bind_to_any_port(HOST);
  2503. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2504. auto se = detail::scope_exit([&] {
  2505. svr.stop();
  2506. thread.join();
  2507. ASSERT_FALSE(svr.is_running());
  2508. });
  2509. svr.wait_until_ready();
  2510. Client cli(HOST, port);
  2511. cli.set_follow_location(true);
  2512. auto res = cli.Get("/redir");
  2513. // Should fail gracefully, not crash (no valid response due to bad port)
  2514. EXPECT_FALSE(res);
  2515. }
  2516. TEST(RedirectFromPageWithContent, Redirect) {
  2517. Server svr;
  2518. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2519. res.set_content("___", "text/plain");
  2520. res.set_redirect("/2");
  2521. });
  2522. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2523. res.set_content("Hello World!", "text/plain");
  2524. });
  2525. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2526. auto se = detail::scope_exit([&] {
  2527. svr.stop();
  2528. th.join();
  2529. ASSERT_FALSE(svr.is_running());
  2530. });
  2531. svr.wait_until_ready();
  2532. {
  2533. Client cli("localhost", PORT);
  2534. cli.set_follow_location(true);
  2535. std::string body;
  2536. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2537. body.append(data, data_length);
  2538. return true;
  2539. });
  2540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2541. EXPECT_EQ(StatusCode::OK_200, res->status);
  2542. EXPECT_EQ("Hello World!", body);
  2543. }
  2544. {
  2545. Client cli("localhost", PORT);
  2546. std::string body;
  2547. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2548. body.append(data, data_length);
  2549. return true;
  2550. });
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ(StatusCode::Found_302, res->status);
  2553. EXPECT_EQ("___", body);
  2554. }
  2555. }
  2556. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2557. Server svr;
  2558. auto port_str = std::to_string(PORT);
  2559. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2560. auto expected_host = "[::1]:" + port_str;
  2561. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2562. res.set_content("___", "text/plain");
  2563. // res.set_redirect("/2");
  2564. res.set_redirect(redirect_url);
  2565. });
  2566. svr.Get("/2", [&](const Request &req, Response &res) {
  2567. auto host_header = req.headers.find("Host");
  2568. ASSERT_TRUE(host_header != req.headers.end());
  2569. EXPECT_EQ(expected_host, host_header->second);
  2570. res.set_content("Hello World!", "text/plain");
  2571. });
  2572. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. th.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2579. // actually starts anything, so the condition !svr.is_running() will
  2580. // always remain true, and the loop never stops.
  2581. // This basically counts how many milliseconds have passed since the
  2582. // call to svr.listen(), and if after 5 seconds nothing started yet
  2583. // aborts the test.
  2584. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2585. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2586. ASSERT_LT(milliseconds, 5000U);
  2587. }
  2588. {
  2589. Client cli("::1", PORT);
  2590. cli.set_follow_location(true);
  2591. std::string body;
  2592. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2593. body.append(data, data_length);
  2594. return true;
  2595. });
  2596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2597. EXPECT_EQ(StatusCode::OK_200, res->status);
  2598. EXPECT_EQ("Hello World!", body);
  2599. }
  2600. {
  2601. Client cli("::1", PORT);
  2602. std::string body;
  2603. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2604. body.append(data, data_length);
  2605. return true;
  2606. });
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ(StatusCode::Found_302, res->status);
  2609. EXPECT_EQ("___", body);
  2610. }
  2611. }
  2612. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2613. Server svr;
  2614. svr.Get("/foo", [](const Request &req, Response &res) {
  2615. auto a = req.params.find("a");
  2616. if (a != req.params.end()) {
  2617. res.set_content((*a).second, "text/plain");
  2618. res.status = StatusCode::OK_200;
  2619. } else {
  2620. res.status = StatusCode::BadRequest_400;
  2621. }
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. {
  2631. Client cli(HOST, PORT);
  2632. cli.set_path_encode(false);
  2633. auto res = cli.Get("/foo?a=explicitly+encoded");
  2634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2635. EXPECT_EQ(StatusCode::OK_200, res->status);
  2636. // This expects it back with a space, as the `+` won't have been
  2637. // url-encoded, and server-side the params get decoded turning `+`
  2638. // into spaces.
  2639. EXPECT_EQ("explicitly encoded", res->body);
  2640. }
  2641. }
  2642. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2643. // When path encoding is disabled the client must transmit the supplied
  2644. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2645. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2646. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2647. // than a space (0x20). Assert on the raw wire target to catch this.
  2648. Server svr;
  2649. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2650. svr.Get("/foo", [&](const Request &req, Response &res) {
  2651. EXPECT_EQ(expected_target, req.target);
  2652. res.status = StatusCode::OK_200;
  2653. });
  2654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2655. auto se = detail::scope_exit([&] {
  2656. svr.stop();
  2657. thread.join();
  2658. ASSERT_FALSE(svr.is_running());
  2659. });
  2660. svr.wait_until_ready();
  2661. {
  2662. Client cli(HOST, PORT);
  2663. cli.set_path_encode(false);
  2664. auto res = cli.Get(expected_target.c_str());
  2665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2666. EXPECT_EQ(StatusCode::OK_200, res->status);
  2667. }
  2668. }
  2669. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2670. // `open_stream()` used to skip the path encoding that the buffered send
  2671. // path applies, so the same `path` produced different bytes in the request
  2672. // line depending on which API was used. Assert the two agree.
  2673. Server svr;
  2674. std::string target;
  2675. svr.Get(".*", [&](const Request &req, Response &res) {
  2676. target = req.target;
  2677. res.status = StatusCode::OK_200;
  2678. });
  2679. auto port = svr.bind_to_any_port(HOST);
  2680. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2681. auto se = detail::scope_exit([&] {
  2682. svr.stop();
  2683. thread.join();
  2684. ASSERT_FALSE(svr.is_running());
  2685. });
  2686. svr.wait_until_ready();
  2687. struct {
  2688. const char *path;
  2689. const char *expected;
  2690. } cases[] = {
  2691. {"/a b?x=1", "/a%20b?x=1"},
  2692. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2693. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2694. };
  2695. for (const auto &c : cases) {
  2696. Client cli(HOST, port);
  2697. target.clear();
  2698. auto res = cli.Get(c.path);
  2699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2700. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2701. auto buffered_target = target;
  2702. target.clear();
  2703. auto handle = cli.open_stream("GET", c.path);
  2704. EXPECT_TRUE(handle.is_valid())
  2705. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2706. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2707. }
  2708. }
  2709. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2710. // The `set_path_encode(false)` contract — transmit the supplied target
  2711. // verbatim — must hold for the streaming API too.
  2712. Server svr;
  2713. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2714. std::string target;
  2715. svr.Get("/foo", [&](const Request &req, Response &res) {
  2716. target = req.target;
  2717. res.status = StatusCode::OK_200;
  2718. });
  2719. auto port = svr.bind_to_any_port(HOST);
  2720. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. {
  2728. Client cli(HOST, port);
  2729. cli.set_path_encode(false);
  2730. auto handle = cli.open_stream("GET", expected_target);
  2731. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2732. EXPECT_EQ(expected_target, target);
  2733. }
  2734. }
  2735. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  2736. // With path encoding enabled a CR/LF in the target is percent-encoded
  2737. // rather than rejected, matching the buffered send path. The CR/LF guard in
  2738. // write_request_line still backstops `set_path_encode(false)`, which is
  2739. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  2740. Server svr;
  2741. // Captured before routing: the decoded path contains a newline, which a
  2742. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  2743. std::string target;
  2744. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  2745. target = req.target;
  2746. res.status = StatusCode::OK_200;
  2747. return Server::HandlerResponse::Handled;
  2748. });
  2749. auto port = svr.bind_to_any_port(HOST);
  2750. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2751. auto se = detail::scope_exit([&] {
  2752. svr.stop();
  2753. thread.join();
  2754. ASSERT_FALSE(svr.is_running());
  2755. });
  2756. svr.wait_until_ready();
  2757. {
  2758. Client cli(HOST, port);
  2759. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2760. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2761. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  2762. }
  2763. }
  2764. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  2765. // Nothing may reach the wire: a raw CR/LF target would split the request
  2766. // line and inject headers.
  2767. Server svr;
  2768. // Pre-routing so that "not called" means nothing reached the server at all,
  2769. // rather than merely failing to match a handler pattern.
  2770. auto handler_called = false;
  2771. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  2772. handler_called = true;
  2773. res.status = StatusCode::OK_200;
  2774. return Server::HandlerResponse::Handled;
  2775. });
  2776. auto port = svr.bind_to_any_port(HOST);
  2777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2778. auto se = detail::scope_exit([&] {
  2779. svr.stop();
  2780. thread.join();
  2781. ASSERT_FALSE(svr.is_running());
  2782. });
  2783. svr.wait_until_ready();
  2784. {
  2785. Client cli(HOST, port);
  2786. cli.set_path_encode(false);
  2787. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2788. EXPECT_FALSE(handle.is_valid());
  2789. EXPECT_EQ(Error::Write, handle.error);
  2790. EXPECT_FALSE(handler_called);
  2791. }
  2792. }
  2793. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  2794. // Which of the two branches runs is decided by whether the query component
  2795. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  2796. // an empty query and must still fall back to building one from
  2797. // `req.params`, while a non-empty query must win over `req.params`.
  2798. Server svr;
  2799. std::string target;
  2800. svr.Get("/foo", [&](const Request &req, Response &res) {
  2801. target = req.target;
  2802. res.status = StatusCode::OK_200;
  2803. });
  2804. auto port = svr.bind_to_any_port(HOST);
  2805. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2806. auto se = detail::scope_exit([&] {
  2807. svr.stop();
  2808. thread.join();
  2809. ASSERT_FALSE(svr.is_running());
  2810. });
  2811. svr.wait_until_ready();
  2812. {
  2813. // Trailing `?` -> empty query component -> `req.params` is used.
  2814. Client cli(HOST, port);
  2815. Request req;
  2816. req.method = "GET";
  2817. req.path = "/foo?";
  2818. req.params.emplace("a", "1");
  2819. target.clear();
  2820. auto res = cli.send(req);
  2821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2822. EXPECT_EQ("/foo?a=1", target);
  2823. }
  2824. {
  2825. // Non-empty query in `req.path` -> `req.params` is not appended.
  2826. Client cli(HOST, port);
  2827. Request req;
  2828. req.method = "GET";
  2829. req.path = "/foo?b=2";
  2830. req.params.emplace("a", "1");
  2831. target.clear();
  2832. auto res = cli.send(req);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. EXPECT_EQ("/foo?b=2", target);
  2835. }
  2836. }
  2837. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2838. Server svr;
  2839. svr.Get("/", [](const Request &req, Response &) {
  2840. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2841. });
  2842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2843. auto se = detail::scope_exit([&] {
  2844. svr.stop();
  2845. thread.join();
  2846. ASSERT_FALSE(svr.is_running());
  2847. });
  2848. svr.wait_until_ready();
  2849. {
  2850. Client cli(HOST, PORT);
  2851. cli.set_path_encode(false);
  2852. auto res = cli.Get("/?something=%0A");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::OK_200, res->status);
  2855. }
  2856. }
  2857. TEST(BindServerTest, BindDualStack) {
  2858. Server svr;
  2859. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2860. res.set_content("Hello World!", "text/plain");
  2861. });
  2862. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2863. auto se = detail::scope_exit([&] {
  2864. svr.stop();
  2865. thread.join();
  2866. ASSERT_FALSE(svr.is_running());
  2867. });
  2868. svr.wait_until_ready();
  2869. {
  2870. Client cli("127.0.0.1", PORT);
  2871. auto res = cli.Get("/1");
  2872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2873. EXPECT_EQ(StatusCode::OK_200, res->status);
  2874. EXPECT_EQ("Hello World!", res->body);
  2875. }
  2876. {
  2877. Client cli("::1", PORT);
  2878. auto res = cli.Get("/1");
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. EXPECT_EQ("Hello World!", res->body);
  2882. }
  2883. }
  2884. TEST(BindServerTest, BindAndListenSeparately) {
  2885. Server svr;
  2886. int port = svr.bind_to_any_port("0.0.0.0");
  2887. ASSERT_TRUE(svr.is_valid());
  2888. ASSERT_TRUE(port > 0);
  2889. svr.stop();
  2890. }
  2891. // Reports whether anything is still listening on a loopback port. A plain
  2892. // connect() is used instead of a Client request because a socket left bound by
  2893. // mistake accepts the connection into its backlog and never answers, which
  2894. // would hang the test instead of failing it.
  2895. static bool is_loopback_port_accepting(int port) {
  2896. sockaddr_in addr{};
  2897. addr.sin_family = AF_INET;
  2898. addr.sin_port = htons(static_cast<uint16_t>(port));
  2899. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2900. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  2901. EXPECT_NE(sock, INVALID_SOCKET);
  2902. if (sock == INVALID_SOCKET) { return false; }
  2903. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  2904. static_cast<socklen_t>(sizeof(addr)));
  2905. detail::close_socket(sock);
  2906. return ret == 0;
  2907. }
  2908. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  2909. Server svr;
  2910. auto port = svr.bind_to_any_port("127.0.0.1");
  2911. ASSERT_TRUE(port > 0);
  2912. svr.stop();
  2913. // bind_to_any_port() already called listen(2), so until stop() closed the
  2914. // descriptor the port kept accepting connections into the backlog. ASSERT
  2915. // rather than EXPECT: with the socket still open, the listen_after_bind()
  2916. // below blocks forever in the accept loop.
  2917. ASSERT_FALSE(is_loopback_port_accepting(port));
  2918. // Nothing is left to accept on, so listen_after_bind() must report failure
  2919. // instead of returning success without ever serving.
  2920. EXPECT_FALSE(svr.listen_after_bind());
  2921. // The failed listen marks the server decommissioned, so a waiter returns
  2922. // instead of spinning forever.
  2923. svr.wait_until_ready();
  2924. }
  2925. #ifdef CPPHTTPLIB_SSL_ENABLED
  2926. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2928. CLIENT_CA_CERT_DIR);
  2929. int port = svr.bind_to_any_port("0.0.0.0");
  2930. ASSERT_TRUE(svr.is_valid());
  2931. ASSERT_TRUE(port > 0);
  2932. svr.stop();
  2933. }
  2934. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2935. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2936. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2937. int port = svr.bind_to_any_port("0.0.0.0");
  2938. ASSERT_TRUE(svr.is_valid());
  2939. ASSERT_TRUE(port > 0);
  2940. svr.stop();
  2941. }
  2942. TEST(BindServerTest, UpdateCertsPem) {
  2943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2944. int port = svr.bind_to_any_port("0.0.0.0");
  2945. ASSERT_TRUE(svr.is_valid());
  2946. ASSERT_TRUE(port > 0);
  2947. // Read PEM files
  2948. std::string cert_pem, key_pem, ca_pem;
  2949. read_file(SERVER_CERT_FILE, cert_pem);
  2950. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2951. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2952. // Update server certificates using PEM API
  2953. ASSERT_TRUE(
  2954. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2955. ASSERT_TRUE(svr.is_valid());
  2956. svr.stop();
  2957. }
  2958. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2959. // Start server with client CA (enables client auth)
  2960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2961. ASSERT_TRUE(svr.is_valid());
  2962. bool handler_called = false;
  2963. svr.Get("/test", [&](const Request &req, Response &res) {
  2964. handler_called = true;
  2965. // Verify client certificate is present
  2966. auto cert = req.peer_cert();
  2967. EXPECT_TRUE(static_cast<bool>(cert));
  2968. res.set_content("ok", "text/plain");
  2969. });
  2970. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2971. auto se = detail::scope_exit([&] {
  2972. svr.stop();
  2973. t.join();
  2974. ASSERT_FALSE(svr.is_running());
  2975. });
  2976. svr.wait_until_ready();
  2977. // Read PEM files
  2978. std::string cert_pem, key_pem, ca_pem;
  2979. read_file(SERVER_CERT_FILE, cert_pem);
  2980. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2981. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2982. // Update server certificates and client CA using PEM API while server running
  2983. ASSERT_TRUE(
  2984. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2985. // Connect with client certificate
  2986. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2987. cli.enable_server_certificate_verification(false);
  2988. cli.set_connection_timeout(30);
  2989. auto res = cli.Get("/test");
  2990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2991. ASSERT_EQ(StatusCode::OK_200, res->status);
  2992. ASSERT_TRUE(handler_called);
  2993. EXPECT_EQ("ok", res->body);
  2994. }
  2995. #endif
  2996. TEST(ErrorHandlerTest, ContentLength) {
  2997. Server svr;
  2998. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2999. res.status = StatusCode::OK_200;
  3000. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3001. "text/html"); // <= Content-Length still 13
  3002. });
  3003. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3004. res.set_content("Hello World!\n", "text/plain");
  3005. res.status = 524;
  3006. });
  3007. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3008. auto se = detail::scope_exit([&] {
  3009. svr.stop();
  3010. thread.join();
  3011. ASSERT_FALSE(svr.is_running());
  3012. });
  3013. svr.wait_until_ready();
  3014. {
  3015. Client cli(HOST, PORT);
  3016. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ(StatusCode::OK_200, res->status);
  3019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3020. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3021. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3022. }
  3023. }
  3024. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3025. TEST(ExceptionTest, WithoutExceptionHandler) {
  3026. Server svr;
  3027. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3028. throw std::runtime_error("exception...");
  3029. });
  3030. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3031. throw std::runtime_error("exception\r\n...");
  3032. });
  3033. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3034. auto se = detail::scope_exit([&] {
  3035. svr.stop();
  3036. listen_thread.join();
  3037. ASSERT_FALSE(svr.is_running());
  3038. });
  3039. svr.wait_until_ready();
  3040. Client cli("localhost", PORT);
  3041. {
  3042. auto res = cli.Get("/exception");
  3043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3044. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3045. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3046. }
  3047. {
  3048. auto res = cli.Get("/unknown");
  3049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3050. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3051. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3052. }
  3053. }
  3054. TEST(ExceptionTest, WithExceptionHandler) {
  3055. Server svr;
  3056. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3057. std::exception_ptr ep) {
  3058. EXPECT_FALSE(ep == nullptr);
  3059. try {
  3060. std::rethrow_exception(ep);
  3061. } catch (std::exception &e) {
  3062. EXPECT_EQ("abc", std::string(e.what()));
  3063. } catch (...) {}
  3064. res.status = StatusCode::InternalServerError_500;
  3065. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3066. "text/html"); // <= Content-Length still 13 at this point
  3067. });
  3068. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3069. res.set_content("Hello World!\n", "text/plain");
  3070. throw std::runtime_error("abc");
  3071. });
  3072. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3073. auto se = detail::scope_exit([&] {
  3074. svr.stop();
  3075. thread.join();
  3076. ASSERT_FALSE(svr.is_running());
  3077. });
  3078. svr.wait_until_ready();
  3079. for (size_t i = 0; i < 10; i++) {
  3080. Client cli(HOST, PORT);
  3081. for (size_t j = 0; j < 100; j++) {
  3082. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3084. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3085. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3086. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3087. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3088. }
  3089. cli.set_keep_alive(true);
  3090. for (size_t j = 0; j < 100; j++) {
  3091. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3094. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3095. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3096. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3097. }
  3098. }
  3099. }
  3100. TEST(ExceptionTest, AndErrorHandler) {
  3101. Server svr;
  3102. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3103. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3104. });
  3105. svr.set_exception_handler(
  3106. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3107. EXPECT_FALSE(ep == nullptr);
  3108. try {
  3109. std::rethrow_exception(ep);
  3110. } catch (std::exception &e) {
  3111. res.set_content(e.what(), "text/html");
  3112. } catch (...) {}
  3113. res.status = StatusCode::InternalServerError_500;
  3114. });
  3115. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3116. throw std::runtime_error("EXCEPTION");
  3117. });
  3118. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3119. res.set_content("ERROR", "text/html");
  3120. res.status = StatusCode::InternalServerError_500;
  3121. });
  3122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3123. auto se = detail::scope_exit([&] {
  3124. svr.stop();
  3125. thread.join();
  3126. ASSERT_FALSE(svr.is_running());
  3127. });
  3128. svr.wait_until_ready();
  3129. Client cli(HOST, PORT);
  3130. {
  3131. auto res = cli.Get("/exception");
  3132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3134. EXPECT_EQ("EXCEPTION", res->body);
  3135. }
  3136. {
  3137. auto res = cli.Get("/error");
  3138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3139. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3140. EXPECT_EQ("ERROR", res->body);
  3141. }
  3142. {
  3143. auto res = cli.Get("/invalid");
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3146. EXPECT_EQ("NOT_FOUND", res->body);
  3147. }
  3148. }
  3149. #endif
  3150. TEST(NoContentTest, ContentLength) {
  3151. Server svr;
  3152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3153. res.status = StatusCode::NoContent_204;
  3154. });
  3155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. {
  3163. Client cli(HOST, PORT);
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3167. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3168. }
  3169. }
  3170. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3171. #ifdef CPPHTTPLIB_SSL_ENABLED
  3172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3173. ASSERT_TRUE(svr.is_valid());
  3174. #else
  3175. Server svr;
  3176. #endif
  3177. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3178. if (req.path == "/routing_handler") {
  3179. res.set_header("PRE_ROUTING", "on");
  3180. res.set_content("Routing Handler", "text/plain");
  3181. return httplib::Server::HandlerResponse::Handled;
  3182. }
  3183. return httplib::Server::HandlerResponse::Unhandled;
  3184. });
  3185. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3186. res.set_content("Error", "text/html");
  3187. });
  3188. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3189. if (req.path == "/routing_handler") {
  3190. res.set_header("POST_ROUTING", "on");
  3191. }
  3192. });
  3193. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3194. res.set_content("Hello World!\n", "text/plain");
  3195. });
  3196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3197. auto se = detail::scope_exit([&] {
  3198. svr.stop();
  3199. thread.join();
  3200. ASSERT_FALSE(svr.is_running());
  3201. });
  3202. svr.wait_until_ready();
  3203. {
  3204. #ifdef CPPHTTPLIB_SSL_ENABLED
  3205. SSLClient cli(HOST, PORT);
  3206. cli.enable_server_certificate_verification(false);
  3207. #else
  3208. Client cli(HOST, PORT);
  3209. #endif
  3210. auto res = cli.Get("/routing_handler");
  3211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3212. EXPECT_EQ(StatusCode::OK_200, res->status);
  3213. EXPECT_EQ("Routing Handler", res->body);
  3214. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3215. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3216. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3217. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3218. }
  3219. {
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(HOST, PORT);
  3222. cli.enable_server_certificate_verification(false);
  3223. #else
  3224. Client cli(HOST, PORT);
  3225. #endif
  3226. auto res = cli.Get("/hi");
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("Hello World!\n", res->body);
  3230. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3231. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3232. }
  3233. {
  3234. #ifdef CPPHTTPLIB_SSL_ENABLED
  3235. SSLClient cli(HOST, PORT);
  3236. cli.enable_server_certificate_verification(false);
  3237. #else
  3238. Client cli(HOST, PORT);
  3239. #endif
  3240. auto res = cli.Get("/aaa");
  3241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3243. EXPECT_EQ("Error", res->body);
  3244. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3245. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3246. }
  3247. }
  3248. TEST(RequestHandlerTest, PreRequestHandler) {
  3249. auto route_path = "/user/:user";
  3250. Server svr;
  3251. svr.Get("/hi", [](const Request &, Response &res) {
  3252. res.set_content("hi", "text/plain");
  3253. });
  3254. svr.Get(route_path, [](const Request &req, Response &res) {
  3255. res.set_content(req.path_params.at("user"), "text/plain");
  3256. });
  3257. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3258. if (req.matched_route == route_path) {
  3259. auto user = req.path_params.at("user");
  3260. if (user != "john") {
  3261. res.status = StatusCode::Forbidden_403;
  3262. res.set_content("error", "text/html");
  3263. return Server::HandlerResponse::Handled;
  3264. }
  3265. }
  3266. return Server::HandlerResponse::Unhandled;
  3267. });
  3268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3269. auto se = detail::scope_exit([&] {
  3270. svr.stop();
  3271. thread.join();
  3272. ASSERT_FALSE(svr.is_running());
  3273. });
  3274. svr.wait_until_ready();
  3275. Client cli(HOST, PORT);
  3276. {
  3277. auto res = cli.Get("/hi");
  3278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3279. EXPECT_EQ(StatusCode::OK_200, res->status);
  3280. EXPECT_EQ("hi", res->body);
  3281. }
  3282. {
  3283. auto res = cli.Get("/user/john");
  3284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3285. EXPECT_EQ(StatusCode::OK_200, res->status);
  3286. EXPECT_EQ("john", res->body);
  3287. }
  3288. {
  3289. auto res = cli.Get("/user/invalid-user");
  3290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3291. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3292. EXPECT_EQ("error", res->body);
  3293. }
  3294. }
  3295. // The pre-request handler must run before the request body is read, so a
  3296. // rejected request never forces the server to buffer a (potentially large)
  3297. // body. Here the posted body is larger than the payload limit: if the body
  3298. // were read first the server would answer 413, but because the pre-request
  3299. // handler runs first it answers 403 and the body is never read.
  3300. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3301. Server svr;
  3302. svr.set_payload_max_length(8);
  3303. auto handler_ran = false;
  3304. svr.Post("/reject", [&](const Request &req, Response &res) {
  3305. handler_ran = true;
  3306. res.set_content(req.body, "text/plain");
  3307. });
  3308. svr.Post("/accept", [](const Request &req, Response &res) {
  3309. res.set_content(req.body, "text/plain");
  3310. });
  3311. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3312. if (req.matched_route == "/reject") {
  3313. res.status = StatusCode::Forbidden_403;
  3314. res.set_content("denied", "text/plain");
  3315. return Server::HandlerResponse::Handled;
  3316. }
  3317. return Server::HandlerResponse::Unhandled;
  3318. });
  3319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3320. auto se = detail::scope_exit([&] {
  3321. svr.stop();
  3322. thread.join();
  3323. ASSERT_FALSE(svr.is_running());
  3324. });
  3325. svr.wait_until_ready();
  3326. Client cli(HOST, PORT);
  3327. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3328. // rejects with 403 before the body is read, so 413 is never reached.
  3329. {
  3330. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3332. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3333. EXPECT_EQ("denied", res->body);
  3334. EXPECT_FALSE(handler_ran);
  3335. }
  3336. // An approved route still reads the body and enforces the payload limit.
  3337. {
  3338. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3341. }
  3342. }
  3343. TEST(UserDataTest, BasicOperations) {
  3344. httplib::UserData ud;
  3345. // Initially empty
  3346. EXPECT_FALSE(ud.has("key"));
  3347. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3348. // set and get
  3349. ud.set("key", 42);
  3350. EXPECT_TRUE(ud.has("key"));
  3351. auto *p = ud.get<int>("key");
  3352. ASSERT_NE(nullptr, p);
  3353. EXPECT_EQ(42, *p);
  3354. // Type mismatch → nullptr
  3355. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3356. // Overwrite with different type
  3357. ud.set("key", std::string("hello"));
  3358. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3359. auto *s = ud.get<std::string>("key");
  3360. ASSERT_NE(nullptr, s);
  3361. EXPECT_EQ("hello", *s);
  3362. // erase
  3363. ud.erase("key");
  3364. EXPECT_FALSE(ud.has("key"));
  3365. // clear
  3366. ud.set("a", 1);
  3367. ud.set("b", 2);
  3368. ud.clear();
  3369. EXPECT_FALSE(ud.has("a"));
  3370. EXPECT_FALSE(ud.has("b"));
  3371. }
  3372. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3373. struct AuthCtx {
  3374. std::string user_id;
  3375. };
  3376. Server svr;
  3377. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3378. res.user_data.set("auth", AuthCtx{"alice"});
  3379. return Server::HandlerResponse::Unhandled;
  3380. });
  3381. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3382. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3383. ASSERT_NE(nullptr, ctx);
  3384. res.set_content("Hello " + ctx->user_id, "text/plain");
  3385. });
  3386. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3387. auto se = detail::scope_exit([&] {
  3388. svr.stop();
  3389. thread.join();
  3390. ASSERT_FALSE(svr.is_running());
  3391. });
  3392. svr.wait_until_ready();
  3393. Client cli(HOST, PORT);
  3394. auto res = cli.Get("/me");
  3395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3396. EXPECT_EQ(StatusCode::OK_200, res->status);
  3397. EXPECT_EQ("Hello alice", res->body);
  3398. }
  3399. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3400. struct RoleCtx {
  3401. std::string role;
  3402. };
  3403. Server svr;
  3404. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3405. res.user_data.set("role", RoleCtx{"admin"});
  3406. return Server::HandlerResponse::Unhandled;
  3407. });
  3408. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3409. auto *ctx = res.user_data.get<RoleCtx>("role");
  3410. ASSERT_NE(nullptr, ctx);
  3411. res.set_content(ctx->role, "text/plain");
  3412. });
  3413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3414. auto se = detail::scope_exit([&] {
  3415. svr.stop();
  3416. thread.join();
  3417. ASSERT_FALSE(svr.is_running());
  3418. });
  3419. svr.wait_until_ready();
  3420. Client cli(HOST, PORT);
  3421. auto res = cli.Get("/role");
  3422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3423. EXPECT_EQ(StatusCode::OK_200, res->status);
  3424. EXPECT_EQ("admin", res->body);
  3425. }
  3426. TEST(InvalidFormatTest, StatusCode) {
  3427. Server svr;
  3428. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3429. res.set_content("Hello World!\n", "text/plain");
  3430. res.status = 9999; // Status should be a three-digit code...
  3431. });
  3432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3433. auto se = detail::scope_exit([&] {
  3434. svr.stop();
  3435. thread.join();
  3436. ASSERT_FALSE(svr.is_running());
  3437. });
  3438. svr.wait_until_ready();
  3439. {
  3440. Client cli(HOST, PORT);
  3441. auto res = cli.Get("/hi");
  3442. ASSERT_FALSE(res);
  3443. }
  3444. }
  3445. TEST(URLFragmentTest, WithFragment) {
  3446. Server svr;
  3447. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3448. EXPECT_TRUE(req.target == "/hi");
  3449. });
  3450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. });
  3456. svr.wait_until_ready();
  3457. {
  3458. Client cli(HOST, PORT);
  3459. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3460. EXPECT_TRUE(res);
  3461. EXPECT_EQ(StatusCode::OK_200, res->status);
  3462. res = cli.Get("/hi%23key1=val1=key2=val2");
  3463. EXPECT_TRUE(res);
  3464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3465. }
  3466. }
  3467. TEST(HeaderWriter, SetHeaderWriter) {
  3468. Server svr;
  3469. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3470. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3471. return detail::write_headers(strm, hdrs);
  3472. });
  3473. svr.Get("/hi", [](const Request &req, Response &res) {
  3474. auto it = req.headers.find("CustomClientHeader");
  3475. EXPECT_TRUE(it != req.headers.end());
  3476. EXPECT_EQ(it->second, "CustomClientValue");
  3477. res.set_content("Hello World!\n", "text/plain");
  3478. });
  3479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3480. auto se = detail::scope_exit([&] {
  3481. svr.stop();
  3482. thread.join();
  3483. ASSERT_FALSE(svr.is_running());
  3484. });
  3485. svr.wait_until_ready();
  3486. {
  3487. Client cli(HOST, PORT);
  3488. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3489. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3490. return detail::write_headers(strm, hdrs);
  3491. });
  3492. auto res = cli.Get("/hi");
  3493. EXPECT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. auto it = res->headers.find("CustomServerHeader");
  3496. EXPECT_TRUE(it != res->headers.end());
  3497. EXPECT_EQ(it->second, "CustomServerValue");
  3498. }
  3499. }
  3500. class ServerTest : public ::testing::Test {
  3501. protected:
  3502. ServerTest()
  3503. : cli_(HOST, PORT)
  3504. #ifdef CPPHTTPLIB_SSL_ENABLED
  3505. ,
  3506. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3507. #endif
  3508. {
  3509. #ifdef CPPHTTPLIB_SSL_ENABLED
  3510. cli_.enable_server_certificate_verification(false);
  3511. #endif
  3512. // Allow LARGE_DATA (100MB) responses
  3513. cli_.set_payload_max_length(200 * 1024 * 1024);
  3514. }
  3515. virtual void SetUp() {
  3516. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3517. svr_.set_payload_max_length(200 * 1024 * 1024);
  3518. svr_.set_mount_point("/", "./www");
  3519. svr_.set_mount_point("/mount", "./www2");
  3520. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3521. svr_.Get("/hi",
  3522. [&](const Request & /*req*/, Response &res) {
  3523. res.set_content("Hello World!", "text/plain");
  3524. })
  3525. .Get("/file_content",
  3526. [&](const Request & /*req*/, Response &res) {
  3527. res.set_file_content("./www/dir/test.html");
  3528. })
  3529. .Get("/file_content_with_content_type",
  3530. [&](const Request & /*req*/, Response &res) {
  3531. res.set_file_content("./www/file", "text/plain");
  3532. })
  3533. .Get("/invalid_file_content",
  3534. [&](const Request & /*req*/, Response &res) {
  3535. res.set_file_content("./www/dir/invalid_file_path");
  3536. })
  3537. .Get("/http_response_splitting",
  3538. [&](const Request & /*req*/, Response &res) {
  3539. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3540. EXPECT_EQ(0U, res.headers.size());
  3541. EXPECT_FALSE(res.has_header("a"));
  3542. res.set_header("a", "1\nSet-Cookie: a=1");
  3543. EXPECT_EQ(0U, res.headers.size());
  3544. EXPECT_FALSE(res.has_header("a"));
  3545. res.set_header("a", "1\rSet-Cookie: a=1");
  3546. EXPECT_EQ(0U, res.headers.size());
  3547. EXPECT_FALSE(res.has_header("a"));
  3548. res.set_header("a\r\nb", "0");
  3549. EXPECT_EQ(0U, res.headers.size());
  3550. EXPECT_FALSE(res.has_header("a"));
  3551. res.set_header("a\rb", "0");
  3552. EXPECT_EQ(0U, res.headers.size());
  3553. EXPECT_FALSE(res.has_header("a"));
  3554. res.set_header("a\nb", "0");
  3555. EXPECT_EQ(0U, res.headers.size());
  3556. EXPECT_FALSE(res.has_header("a"));
  3557. res.set_redirect("1\r\nSet-Cookie: a=1");
  3558. EXPECT_EQ(0U, res.headers.size());
  3559. EXPECT_FALSE(res.has_header("Location"));
  3560. })
  3561. .Get("/slow",
  3562. [&](const Request & /*req*/, Response &res) {
  3563. std::this_thread::sleep_for(std::chrono::seconds(4));
  3564. res.set_content("slow", "text/plain");
  3565. })
  3566. #if 0
  3567. .Post("/slowpost",
  3568. [&](const Request & /*req*/, Response &res) {
  3569. std::this_thread::sleep_for(std::chrono::seconds(2));
  3570. res.set_content("slow", "text/plain");
  3571. })
  3572. #endif
  3573. .Get("/remote_addr",
  3574. [&](const Request &req, Response &res) {
  3575. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3576. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3577. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3578. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3579. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3580. #endif
  3581. res.set_content(req.remote_addr, "text/plain");
  3582. })
  3583. .Get("/local_addr",
  3584. [&](const Request &req, Response &res) {
  3585. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3586. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3587. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3588. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3589. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3590. #endif
  3591. auto local_addr = req.local_addr;
  3592. auto local_port = std::to_string(req.local_port);
  3593. res.set_content(local_addr.append(":").append(local_port),
  3594. "text/plain");
  3595. })
  3596. .Get("/endwith%",
  3597. [&](const Request & /*req*/, Response &res) {
  3598. res.set_content("Hello World!", "text/plain");
  3599. })
  3600. .Get("/a\\+\\+b",
  3601. [&](const Request &req, Response &res) {
  3602. ASSERT_TRUE(req.has_param("a +b"));
  3603. auto val = req.get_param_value("a +b");
  3604. res.set_content(val, "text/plain");
  3605. })
  3606. .Get("/", [&](const Request & /*req*/,
  3607. Response &res) { res.set_redirect("/hi"); })
  3608. .Post("/1",
  3609. [](const Request & /*req*/, Response &res) {
  3610. res.set_redirect("/2", StatusCode::SeeOther_303);
  3611. })
  3612. .Get("/2",
  3613. [](const Request & /*req*/, Response &res) {
  3614. res.set_content("redirected.", "text/plain");
  3615. res.status = StatusCode::OK_200;
  3616. })
  3617. .Post("/person",
  3618. [&](const Request &req, Response &res) {
  3619. if (req.has_param("name") && req.has_param("note")) {
  3620. persons_[req.get_param_value("name")] =
  3621. req.get_param_value("note");
  3622. } else {
  3623. res.status = StatusCode::BadRequest_400;
  3624. }
  3625. })
  3626. .Put("/person",
  3627. [&](const Request &req, Response &res) {
  3628. if (req.has_param("name") && req.has_param("note")) {
  3629. persons_[req.get_param_value("name")] =
  3630. req.get_param_value("note");
  3631. } else {
  3632. res.status = StatusCode::BadRequest_400;
  3633. }
  3634. })
  3635. .Get("/person/(.*)",
  3636. [&](const Request &req, Response &res) {
  3637. string name = req.matches[1];
  3638. if (persons_.find(name) != persons_.end()) {
  3639. auto note = persons_[name];
  3640. res.set_content(note, "text/plain");
  3641. } else {
  3642. res.status = StatusCode::NotFound_404;
  3643. }
  3644. })
  3645. .Delete("/person",
  3646. [&](const Request &req, Response &res) {
  3647. if (req.has_param("name")) {
  3648. string name = req.get_param_value("name");
  3649. if (persons_.find(name) != persons_.end()) {
  3650. persons_.erase(name);
  3651. res.set_content("DELETED", "text/plain");
  3652. } else {
  3653. res.status = StatusCode::NotFound_404;
  3654. }
  3655. } else {
  3656. res.status = StatusCode::BadRequest_400;
  3657. }
  3658. })
  3659. .Post("/x-www-form-urlencoded-json",
  3660. [&](const Request &req, Response &res) {
  3661. auto json = req.get_param_value("json");
  3662. ASSERT_EQ(JSON_DATA, json);
  3663. res.set_content(json, "appliation/json");
  3664. res.status = StatusCode::OK_200;
  3665. })
  3666. .Get("/streamed-chunked",
  3667. [&](const Request & /*req*/, Response &res) {
  3668. res.set_chunked_content_provider(
  3669. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3670. sink.os << "123";
  3671. sink.os << "456";
  3672. sink.os << "789";
  3673. sink.done();
  3674. return true;
  3675. });
  3676. })
  3677. .Get("/streamed-chunked-with-prohibited-trailer",
  3678. [&](const Request & /*req*/, Response &res) {
  3679. auto i = new int(0);
  3680. // Declare both a prohibited trailer (Content-Length) and an
  3681. // allowed one
  3682. res.set_header("Trailer", "Content-Length, X-Allowed");
  3683. res.set_chunked_content_provider(
  3684. "text/plain",
  3685. [i](size_t /*offset*/, DataSink &sink) {
  3686. switch (*i) {
  3687. case 0: sink.os << "123"; break;
  3688. case 1: sink.os << "456"; break;
  3689. case 2: sink.os << "789"; break;
  3690. case 3: {
  3691. sink.done_with_trailer(
  3692. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3693. } break;
  3694. }
  3695. (*i)++;
  3696. return true;
  3697. },
  3698. [i](bool success) {
  3699. EXPECT_TRUE(success);
  3700. delete i;
  3701. });
  3702. })
  3703. .Get("/streamed-chunked2",
  3704. [&](const Request & /*req*/, Response &res) {
  3705. auto i = new int(0);
  3706. res.set_chunked_content_provider(
  3707. "text/plain",
  3708. [i](size_t /*offset*/, DataSink &sink) {
  3709. switch (*i) {
  3710. case 0: sink.os << "123"; break;
  3711. case 1: sink.os << "456"; break;
  3712. case 2: sink.os << "789"; break;
  3713. case 3: sink.done(); break;
  3714. }
  3715. (*i)++;
  3716. return true;
  3717. },
  3718. [i](bool success) {
  3719. EXPECT_TRUE(success);
  3720. delete i;
  3721. });
  3722. })
  3723. .Get("/streamed-chunked-with-trailer",
  3724. [&](const Request & /*req*/, Response &res) {
  3725. auto i = new int(0);
  3726. res.set_header("Trailer", "Dummy1, Dummy2");
  3727. res.set_chunked_content_provider(
  3728. "text/plain",
  3729. [i](size_t /*offset*/, DataSink &sink) {
  3730. switch (*i) {
  3731. case 0: sink.os << "123"; break;
  3732. case 1: sink.os << "456"; break;
  3733. case 2: sink.os << "789"; break;
  3734. case 3: {
  3735. sink.done_with_trailer(
  3736. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3737. } break;
  3738. }
  3739. (*i)++;
  3740. return true;
  3741. },
  3742. [i](bool success) {
  3743. EXPECT_TRUE(success);
  3744. delete i;
  3745. });
  3746. })
  3747. .Get("/streamed",
  3748. [&](const Request & /*req*/, Response &res) {
  3749. res.set_content_provider(
  3750. 6, "text/plain",
  3751. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3752. sink.os << (offset < 3 ? "a" : "b");
  3753. return true;
  3754. });
  3755. })
  3756. .Get("/streamed-without-length",
  3757. [&](const Request & /*req*/, Response &res) {
  3758. auto data = new std::string("abcdefg");
  3759. res.set_content_provider(
  3760. "text/plain",
  3761. [data](size_t offset, DataSink &sink) {
  3762. if (offset < data->size()) {
  3763. sink.os << data->substr(offset);
  3764. }
  3765. sink.done();
  3766. return true;
  3767. },
  3768. [data](bool success) {
  3769. EXPECT_TRUE(success);
  3770. delete data;
  3771. });
  3772. })
  3773. .Get("/streamed-with-range",
  3774. [&](const Request &req, Response &res) {
  3775. auto data = new std::string("abcdefg");
  3776. // An explicit status keeps the server from picking the 206 it
  3777. // would otherwise choose for a ranged request, so the response
  3778. // is not a partial representation.
  3779. auto status = req.get_param_value("status");
  3780. if (status == "200") {
  3781. res.status = StatusCode::OK_200;
  3782. } else if (status == "403") {
  3783. res.status = StatusCode::Forbidden_403;
  3784. }
  3785. res.set_content_provider(
  3786. data->size(), "text/plain",
  3787. [data](size_t offset, size_t length, DataSink &sink) {
  3788. size_t DATA_CHUNK_SIZE = 4;
  3789. const auto &d = *data;
  3790. auto out_len =
  3791. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3792. auto ret =
  3793. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3794. EXPECT_TRUE(ret);
  3795. return true;
  3796. },
  3797. [data, &req](bool success) {
  3798. EXPECT_EQ(success, !req.has_param("error"));
  3799. delete data;
  3800. });
  3801. })
  3802. .Get("/streamed-cancel",
  3803. [&](const Request & /*req*/, Response &res) {
  3804. res.set_content_provider(
  3805. size_t(-1), "text/plain",
  3806. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3807. sink.os << "data_chunk";
  3808. return true;
  3809. });
  3810. })
  3811. .Get("/regex-with-delimiter",
  3812. [&](const Request &req, Response & /*res*/) {
  3813. ASSERT_TRUE(req.has_param("key"));
  3814. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3815. })
  3816. .Get("/with-range",
  3817. [&](const Request & /*req*/, Response &res) {
  3818. res.set_content("abcdefg", "text/plain");
  3819. })
  3820. .Get("/test-start-time",
  3821. [&](const Request &req, Response & /*res*/) {
  3822. EXPECT_NE(req.start_time_,
  3823. std::chrono::steady_clock::time_point::min());
  3824. })
  3825. .Get("/with-range-customized-response",
  3826. [&](const Request & /*req*/, Response &res) {
  3827. res.status = StatusCode::BadRequest_400;
  3828. res.set_content(JSON_DATA, "application/json");
  3829. })
  3830. .Post("/chunked",
  3831. [&](const Request &req, Response & /*res*/) {
  3832. EXPECT_EQ(req.body, "dechunked post body");
  3833. })
  3834. .Post("/large-chunked",
  3835. [&](const Request &req, Response & /*res*/) {
  3836. std::string expected(6 * 30 * 1024u, 'a');
  3837. EXPECT_EQ(req.body, expected);
  3838. })
  3839. .Post("/multipart",
  3840. [&](const Request &req, Response & /*res*/) {
  3841. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3842. req.form.get_field_count("text2") +
  3843. req.form.get_field_count("file3") +
  3844. req.form.get_field_count("file4"));
  3845. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3846. req.form.get_file_count("file2"));
  3847. ASSERT_TRUE(!req.form.has_file("???"));
  3848. ASSERT_TRUE(!req.form.has_field("???"));
  3849. ASSERT_TRUE(req.body.empty());
  3850. {
  3851. const auto &text = req.form.get_field("text1");
  3852. EXPECT_EQ("text default", text);
  3853. }
  3854. {
  3855. const auto &text = req.form.get_field("text2");
  3856. EXPECT_EQ("aωb", text);
  3857. }
  3858. {
  3859. const auto &file = req.form.get_file("file1");
  3860. EXPECT_EQ("hello.txt", file.filename);
  3861. EXPECT_EQ("text/plain", file.content_type);
  3862. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3863. }
  3864. {
  3865. const auto &file = req.form.get_file("file2");
  3866. EXPECT_EQ("world.json", file.filename);
  3867. EXPECT_EQ("application/json", file.content_type);
  3868. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3869. }
  3870. {
  3871. const auto &text = req.form.get_field("file3");
  3872. EXPECT_EQ(0u, text.size());
  3873. }
  3874. {
  3875. const auto &text = req.form.get_field("file4");
  3876. EXPECT_EQ(0u, text.size());
  3877. }
  3878. })
  3879. .Post("/multipart/multi_file_values",
  3880. [&](const Request &req, Response & /*res*/) {
  3881. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3882. req.form.get_field_count("multi_text1"));
  3883. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3884. ASSERT_TRUE(!req.form.has_file("???"));
  3885. ASSERT_TRUE(!req.form.has_field("???"));
  3886. ASSERT_TRUE(req.body.empty());
  3887. {
  3888. const auto &text = req.form.get_field("text");
  3889. EXPECT_EQ("default text", text);
  3890. }
  3891. {
  3892. const auto &text1_values = req.form.get_fields("multi_text1");
  3893. EXPECT_EQ(2u, text1_values.size());
  3894. EXPECT_EQ("aaaaa", text1_values[0]);
  3895. EXPECT_EQ("bbbbb", text1_values[1]);
  3896. }
  3897. {
  3898. const auto &file1_values = req.form.get_files("multi_file1");
  3899. EXPECT_EQ(2u, file1_values.size());
  3900. auto file1 = file1_values[0];
  3901. EXPECT_EQ(file1.filename, "hello.txt");
  3902. EXPECT_EQ(file1.content_type, "text/plain");
  3903. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3904. auto file2 = file1_values[1];
  3905. EXPECT_EQ(file2.filename, "world.json");
  3906. EXPECT_EQ(file2.content_type, "application/json");
  3907. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3908. }
  3909. })
  3910. .Post("/empty",
  3911. [&](const Request &req, Response &res) {
  3912. EXPECT_EQ(req.body, "");
  3913. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3914. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3915. res.set_content("empty", "text/plain");
  3916. })
  3917. .Post("/empty-no-content-type",
  3918. [&](const Request &req, Response &res) {
  3919. EXPECT_EQ(req.body, "");
  3920. EXPECT_FALSE(req.has_header("Content-Type"));
  3921. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3922. res.set_content("empty-no-content-type", "text/plain");
  3923. })
  3924. .Post("/path-only",
  3925. [&](const Request &req, Response &res) {
  3926. EXPECT_EQ(req.body, "");
  3927. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3928. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3929. res.set_content("path-only", "text/plain");
  3930. })
  3931. .Post("/path-headers-only",
  3932. [&](const Request &req, Response &res) {
  3933. EXPECT_EQ(req.body, "");
  3934. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3935. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3936. EXPECT_EQ("world", req.get_header_value("hello"));
  3937. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3938. res.set_content("path-headers-only", "text/plain");
  3939. })
  3940. .Post("/post-large",
  3941. [&](const Request &req, Response &res) {
  3942. EXPECT_EQ(req.body, LARGE_DATA);
  3943. res.set_content(req.body, "text/plain");
  3944. })
  3945. .Post("/post-loopback",
  3946. [&](const Request &, Response &res,
  3947. ContentReader const &content_reader) {
  3948. std::string body;
  3949. content_reader([&](const char *data, size_t data_length) {
  3950. body.append(data, data_length);
  3951. return true;
  3952. });
  3953. res.set_content(body, "text/plain");
  3954. })
  3955. .Put("/put-loopback",
  3956. [&](const Request &, Response &res,
  3957. ContentReader const &content_reader) {
  3958. std::string body;
  3959. content_reader([&](const char *data, size_t data_length) {
  3960. body.append(data, data_length);
  3961. return true;
  3962. });
  3963. res.set_content(body, "text/plain");
  3964. })
  3965. .Patch("/patch-loopback",
  3966. [&](const Request &, Response &res,
  3967. ContentReader const &content_reader) {
  3968. std::string body;
  3969. content_reader([&](const char *data, size_t data_length) {
  3970. body.append(data, data_length);
  3971. return true;
  3972. });
  3973. res.set_content(body, "text/plain");
  3974. })
  3975. .Put("/empty-no-content-type",
  3976. [&](const Request &req, Response &res) {
  3977. EXPECT_EQ(req.body, "");
  3978. EXPECT_FALSE(req.has_header("Content-Type"));
  3979. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3980. res.set_content("empty-no-content-type", "text/plain");
  3981. })
  3982. .Put("/put",
  3983. [&](const Request &req, Response &res) {
  3984. EXPECT_EQ(req.body, "PUT");
  3985. res.set_content(req.body, "text/plain");
  3986. })
  3987. .Put("/put-large",
  3988. [&](const Request &req, Response &res) {
  3989. EXPECT_EQ(req.body, LARGE_DATA);
  3990. res.set_content(req.body, "text/plain");
  3991. })
  3992. .Patch("/patch",
  3993. [&](const Request &req, Response &res) {
  3994. EXPECT_EQ(req.body, "PATCH");
  3995. res.set_content(req.body, "text/plain");
  3996. })
  3997. .Delete("/delete",
  3998. [&](const Request & /*req*/, Response &res) {
  3999. res.set_content("DELETE", "text/plain");
  4000. })
  4001. .Delete("/delete-body",
  4002. [&](const Request &req, Response &res) {
  4003. EXPECT_EQ(req.body, "content");
  4004. res.set_content(req.body, "text/plain");
  4005. })
  4006. .Options(R"(\*)",
  4007. [&](const Request & /*req*/, Response &res) {
  4008. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4009. })
  4010. .Get("/request-target",
  4011. [&](const Request &req, Response & /*res*/) {
  4012. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4013. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4014. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4015. })
  4016. .Get("/long-query-value",
  4017. [&](const Request &req, Response & /*res*/) {
  4018. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4019. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4020. })
  4021. .Get("/too-long-query-value",
  4022. [&](const Request &req, Response & /*res*/) {
  4023. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4024. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4025. })
  4026. .Get("/array-param",
  4027. [&](const Request &req, Response & /*res*/) {
  4028. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4029. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4030. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4031. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4032. })
  4033. .Get("/array-param-values",
  4034. [&](const Request &req, Response & /*res*/) {
  4035. auto values = req.get_param_values("array");
  4036. EXPECT_EQ(3u, values.size());
  4037. EXPECT_EQ("value1", values[0]);
  4038. EXPECT_EQ("value2", values[1]);
  4039. EXPECT_EQ("value3", values[2]);
  4040. auto empty = req.get_param_values("nonexistent");
  4041. EXPECT_TRUE(empty.empty());
  4042. })
  4043. .Post("/validate-no-multiple-headers",
  4044. [&](const Request &req, Response & /*res*/) {
  4045. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4046. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4047. })
  4048. .Post("/content_receiver",
  4049. [&](const Request &req, Response &res,
  4050. const ContentReader &content_reader) {
  4051. if (req.is_multipart_form_data()) {
  4052. std::vector<FormData> items;
  4053. content_reader(
  4054. [&](const FormData &file) {
  4055. items.push_back(file);
  4056. return true;
  4057. },
  4058. [&](const char *data, size_t data_length) {
  4059. items.back().content.append(data, data_length);
  4060. return true;
  4061. });
  4062. EXPECT_EQ(5u, items.size());
  4063. {
  4064. const auto &file = get_file_value(items, "text1");
  4065. EXPECT_TRUE(file.filename.empty());
  4066. EXPECT_EQ("text default", file.content);
  4067. }
  4068. {
  4069. const auto &file = get_file_value(items, "text2");
  4070. EXPECT_TRUE(file.filename.empty());
  4071. EXPECT_EQ("aωb", file.content);
  4072. }
  4073. {
  4074. const auto &file = get_file_value(items, "file1");
  4075. EXPECT_EQ("hello.txt", file.filename);
  4076. EXPECT_EQ("text/plain", file.content_type);
  4077. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4078. }
  4079. {
  4080. const auto &file = get_file_value(items, "file2");
  4081. EXPECT_EQ("world.json", file.filename);
  4082. EXPECT_EQ("application/json", file.content_type);
  4083. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4084. }
  4085. {
  4086. const auto &file = get_file_value(items, "file3");
  4087. EXPECT_TRUE(file.filename.empty());
  4088. EXPECT_EQ("application/octet-stream", file.content_type);
  4089. EXPECT_EQ(0u, file.content.size());
  4090. }
  4091. } else {
  4092. std::string body;
  4093. content_reader([&](const char *data, size_t data_length) {
  4094. EXPECT_EQ(7U, data_length);
  4095. body.append(data, data_length);
  4096. return true;
  4097. });
  4098. EXPECT_EQ(body, "content");
  4099. res.set_content(body, "text/plain");
  4100. }
  4101. })
  4102. .Put("/content_receiver",
  4103. [&](const Request & /*req*/, Response &res,
  4104. const ContentReader &content_reader) {
  4105. std::string body;
  4106. content_reader([&](const char *data, size_t data_length) {
  4107. body.append(data, data_length);
  4108. return true;
  4109. });
  4110. EXPECT_EQ(body, "content");
  4111. res.set_content(body, "text/plain");
  4112. })
  4113. .Patch("/content_receiver",
  4114. [&](const Request & /*req*/, Response &res,
  4115. const ContentReader &content_reader) {
  4116. std::string body;
  4117. content_reader([&](const char *data, size_t data_length) {
  4118. body.append(data, data_length);
  4119. return true;
  4120. });
  4121. EXPECT_EQ(body, "content");
  4122. res.set_content(body, "text/plain");
  4123. })
  4124. .Post("/query-string-and-body",
  4125. [&](const Request &req, Response & /*res*/) {
  4126. ASSERT_TRUE(req.has_param("key"));
  4127. EXPECT_EQ(req.get_param_value("key"), "value");
  4128. EXPECT_EQ(req.body, "content");
  4129. })
  4130. .Get("/last-request",
  4131. [&](const Request &req, Response & /*res*/) {
  4132. EXPECT_EQ("close", req.get_header_value("Connection"));
  4133. })
  4134. .Get(R"(/redirect/(\d+))",
  4135. [&](const Request &req, Response &res) {
  4136. auto num = std::stoi(req.matches[1]) + 1;
  4137. std::string url = "/redirect/" + std::to_string(num);
  4138. res.set_redirect(url);
  4139. })
  4140. .Post("/binary",
  4141. [&](const Request &req, Response &res) {
  4142. EXPECT_EQ(4U, req.body.size());
  4143. EXPECT_EQ("application/octet-stream",
  4144. req.get_header_value("Content-Type"));
  4145. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4146. res.set_content(req.body, "application/octet-stream");
  4147. })
  4148. .Put("/binary",
  4149. [&](const Request &req, Response &res) {
  4150. EXPECT_EQ(4U, req.body.size());
  4151. EXPECT_EQ("application/octet-stream",
  4152. req.get_header_value("Content-Type"));
  4153. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4154. res.set_content(req.body, "application/octet-stream");
  4155. })
  4156. .Patch("/binary",
  4157. [&](const Request &req, Response &res) {
  4158. EXPECT_EQ(4U, req.body.size());
  4159. EXPECT_EQ("application/octet-stream",
  4160. req.get_header_value("Content-Type"));
  4161. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4162. res.set_content(req.body, "application/octet-stream");
  4163. })
  4164. .Delete("/binary",
  4165. [&](const Request &req, Response &res) {
  4166. EXPECT_EQ(4U, req.body.size());
  4167. EXPECT_EQ("application/octet-stream",
  4168. req.get_header_value("Content-Type"));
  4169. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4170. res.set_content(req.body, "application/octet-stream");
  4171. })
  4172. .Get("/issue1772",
  4173. [&](const Request & /*req*/, Response &res) {
  4174. res.status = 401;
  4175. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4176. })
  4177. .Delete("/issue609",
  4178. [](const httplib::Request &, httplib::Response &res,
  4179. const httplib::ContentReader &) {
  4180. res.set_content("ok", "text/plain");
  4181. })
  4182. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4183. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4184. .Get("/compress",
  4185. [&](const Request & /*req*/, Response &res) {
  4186. res.set_content(
  4187. "12345678901234567890123456789012345678901234567890123456789"
  4188. "01234567890123456789012345678901234567890",
  4189. "text/plain");
  4190. })
  4191. .Get("/compress-with-charset",
  4192. [&](const Request & /*req*/, Response &res) {
  4193. res.set_content(
  4194. "12345678901234567890123456789012345678901234567890123456789"
  4195. "01234567890123456789012345678901234567890",
  4196. "application/json; charset=utf-8");
  4197. })
  4198. .Get("/nocompress",
  4199. [&](const Request & /*req*/, Response &res) {
  4200. res.set_content(
  4201. "12345678901234567890123456789012345678901234567890123456789"
  4202. "01234567890123456789012345678901234567890",
  4203. "application/octet-stream");
  4204. })
  4205. .Post("/compress-multipart",
  4206. [&](const Request &req, Response & /*res*/) {
  4207. EXPECT_EQ(2u, req.form.fields.size());
  4208. ASSERT_TRUE(!req.form.has_field("???"));
  4209. {
  4210. const auto &text = req.form.get_field("key1");
  4211. EXPECT_EQ("test", text);
  4212. }
  4213. {
  4214. const auto &text = req.form.get_field("key2");
  4215. EXPECT_EQ("--abcdefg123", text);
  4216. }
  4217. })
  4218. #endif
  4219. ;
  4220. persons_["john"] = "programmer";
  4221. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4222. svr_.wait_until_ready();
  4223. }
  4224. virtual void TearDown() {
  4225. svr_.stop();
  4226. if (!request_threads_.empty()) {
  4227. std::this_thread::sleep_for(std::chrono::seconds(1));
  4228. for (auto &t : request_threads_) {
  4229. t.join();
  4230. }
  4231. }
  4232. t_.join();
  4233. }
  4234. map<string, string> persons_;
  4235. #ifdef CPPHTTPLIB_SSL_ENABLED
  4236. SSLClient cli_;
  4237. SSLServer svr_;
  4238. #else
  4239. Client cli_;
  4240. Server svr_;
  4241. #endif
  4242. thread t_;
  4243. std::vector<thread> request_threads_;
  4244. };
  4245. TEST_F(ServerTest, GetMethod200) {
  4246. auto res = cli_.Get("/hi");
  4247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4248. EXPECT_EQ("HTTP/1.1", res->version);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("OK", res->reason);
  4251. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4252. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4253. EXPECT_EQ("Hello World!", res->body);
  4254. }
  4255. TEST_F(ServerTest, GetEmptyFile) {
  4256. auto res = cli_.Get("/empty_file");
  4257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4260. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4261. EXPECT_EQ("", res->body);
  4262. }
  4263. TEST_F(ServerTest, GetFileContent) {
  4264. auto res = cli_.Get("/file_content");
  4265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4266. EXPECT_EQ(StatusCode::OK_200, res->status);
  4267. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4268. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4269. EXPECT_EQ("test.html", res->body);
  4270. }
  4271. TEST_F(ServerTest, GetFileContentWithRange) {
  4272. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4274. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4276. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4277. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4278. EXPECT_EQ("est", res->body);
  4279. }
  4280. TEST_F(ServerTest, GetFileContentWithContentType) {
  4281. auto res = cli_.Get("/file_content_with_content_type");
  4282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4285. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4286. EXPECT_EQ("file\n", res->body);
  4287. }
  4288. TEST_F(ServerTest, GetInvalidFileContent) {
  4289. auto res = cli_.Get("/invalid_file_content");
  4290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4292. }
  4293. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4294. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4296. EXPECT_EQ("HTTP/1.1", res->version);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4299. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4300. EXPECT_EQ("Hello World!", res->body);
  4301. }
  4302. TEST_F(ServerTest, GetMethod302) {
  4303. auto res = cli_.Get("/");
  4304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4305. EXPECT_EQ(StatusCode::Found_302, res->status);
  4306. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4307. }
  4308. TEST_F(ServerTest, GetMethod302Redirect) {
  4309. cli_.set_follow_location(true);
  4310. auto res = cli_.Get("/");
  4311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4312. EXPECT_EQ(StatusCode::OK_200, res->status);
  4313. EXPECT_EQ("Hello World!", res->body);
  4314. EXPECT_EQ("/hi", res->location);
  4315. }
  4316. TEST_F(ServerTest, GetMethod404) {
  4317. auto res = cli_.Get("/invalid");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4320. }
  4321. TEST_F(ServerTest, HeadMethod200) {
  4322. auto res = cli_.Head("/hi");
  4323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4324. EXPECT_EQ(StatusCode::OK_200, res->status);
  4325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4326. EXPECT_TRUE(res->body.empty());
  4327. }
  4328. TEST_F(ServerTest, HeadMethod200Static) {
  4329. auto res = cli_.Head("/mount/dir/index.html");
  4330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4331. EXPECT_EQ(StatusCode::OK_200, res->status);
  4332. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4333. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4334. EXPECT_TRUE(res->body.empty());
  4335. }
  4336. TEST_F(ServerTest, HeadMethod404) {
  4337. auto res = cli_.Head("/invalid");
  4338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4340. EXPECT_TRUE(res->body.empty());
  4341. }
  4342. TEST_F(ServerTest, GetMethodPersonJohn) {
  4343. auto res = cli_.Get("/person/john");
  4344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4345. EXPECT_EQ(StatusCode::OK_200, res->status);
  4346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4347. EXPECT_EQ("programmer", res->body);
  4348. }
  4349. TEST_F(ServerTest, PostMethod1) {
  4350. auto res = cli_.Get("/person/john1");
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4353. res = cli_.Post("/person", "name=john1&note=coder",
  4354. "application/x-www-form-urlencoded");
  4355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4356. ASSERT_EQ(StatusCode::OK_200, res->status);
  4357. res = cli_.Get("/person/john1");
  4358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4359. ASSERT_EQ(StatusCode::OK_200, res->status);
  4360. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4361. ASSERT_EQ("coder", res->body);
  4362. }
  4363. TEST_F(ServerTest, PostMethod2) {
  4364. auto res = cli_.Get("/person/john2");
  4365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4366. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4367. Params params;
  4368. params.emplace("name", "john2");
  4369. params.emplace("note", "coder");
  4370. res = cli_.Post("/person", params);
  4371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4372. ASSERT_EQ(StatusCode::OK_200, res->status);
  4373. res = cli_.Get("/person/john2");
  4374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4375. ASSERT_EQ(StatusCode::OK_200, res->status);
  4376. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4377. ASSERT_EQ("coder", res->body);
  4378. }
  4379. TEST_F(ServerTest, PutMethod3) {
  4380. auto res = cli_.Get("/person/john3");
  4381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4382. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4383. Params params;
  4384. params.emplace("name", "john3");
  4385. params.emplace("note", "coder");
  4386. res = cli_.Put("/person", params);
  4387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4388. ASSERT_EQ(StatusCode::OK_200, res->status);
  4389. res = cli_.Get("/person/john3");
  4390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4391. ASSERT_EQ(StatusCode::OK_200, res->status);
  4392. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4393. ASSERT_EQ("coder", res->body);
  4394. }
  4395. TEST_F(ServerTest, DeleteMethod1) {
  4396. auto res = cli_.Get("/person/john4");
  4397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4398. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4399. Params params;
  4400. params.emplace("name", "john4");
  4401. params.emplace("note", "coder");
  4402. res = cli_.Post("/person", params);
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. ASSERT_EQ(StatusCode::OK_200, res->status);
  4405. res = cli_.Get("/person/john4");
  4406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4407. ASSERT_EQ(StatusCode::OK_200, res->status);
  4408. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4409. ASSERT_EQ("coder", res->body);
  4410. Params delete_params;
  4411. delete_params.emplace("name", "john4");
  4412. res = cli_.Delete("/person", delete_params);
  4413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4414. ASSERT_EQ(StatusCode::OK_200, res->status);
  4415. ASSERT_EQ("DELETED", res->body);
  4416. res = cli_.Get("/person/john4");
  4417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4418. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4419. }
  4420. TEST_F(ServerTest, DeleteMethod2) {
  4421. auto res = cli_.Get("/person/john5");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4424. Params params;
  4425. params.emplace("name", "john5");
  4426. params.emplace("note", "developer");
  4427. res = cli_.Post("/person", params);
  4428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4429. ASSERT_EQ(StatusCode::OK_200, res->status);
  4430. res = cli_.Get("/person/john5");
  4431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4432. ASSERT_EQ(StatusCode::OK_200, res->status);
  4433. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4434. ASSERT_EQ("developer", res->body);
  4435. Params delete_params;
  4436. delete_params.emplace("name", "john5");
  4437. Headers headers;
  4438. headers.emplace("Custom-Header", "test-value");
  4439. res = cli_.Delete("/person", headers, delete_params);
  4440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4441. ASSERT_EQ(StatusCode::OK_200, res->status);
  4442. ASSERT_EQ("DELETED", res->body);
  4443. res = cli_.Get("/person/john5");
  4444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4445. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4446. }
  4447. TEST_F(ServerTest, DeleteMethod3) {
  4448. auto res = cli_.Get("/person/john6");
  4449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4450. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4451. Params params;
  4452. params.emplace("name", "john6");
  4453. params.emplace("note", "tester");
  4454. res = cli_.Post("/person", params);
  4455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4456. ASSERT_EQ(StatusCode::OK_200, res->status);
  4457. res = cli_.Get("/person/john6");
  4458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4459. ASSERT_EQ(StatusCode::OK_200, res->status);
  4460. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4461. ASSERT_EQ("tester", res->body);
  4462. Params delete_params;
  4463. delete_params.emplace("name", "john6");
  4464. Headers headers;
  4465. headers.emplace("Custom-Header", "test-value");
  4466. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4468. ASSERT_EQ(StatusCode::OK_200, res->status);
  4469. ASSERT_EQ("DELETED", res->body);
  4470. res = cli_.Get("/person/john6");
  4471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4472. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4473. }
  4474. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4475. Params params;
  4476. params.emplace("json", JSON_DATA);
  4477. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4479. ASSERT_EQ(StatusCode::OK_200, res->status);
  4480. ASSERT_EQ(JSON_DATA, res->body);
  4481. }
  4482. TEST_F(ServerTest, PostEmptyContent) {
  4483. auto res = cli_.Post("/empty", "", "text/plain");
  4484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4485. ASSERT_EQ(StatusCode::OK_200, res->status);
  4486. ASSERT_EQ("empty", res->body);
  4487. }
  4488. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4489. auto res = cli_.Post("/empty-no-content-type");
  4490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4491. ASSERT_EQ(StatusCode::OK_200, res->status);
  4492. ASSERT_EQ("empty-no-content-type", res->body);
  4493. }
  4494. TEST_F(ServerTest, PostPathOnly) {
  4495. auto res = cli_.Post("/path-only");
  4496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4497. ASSERT_EQ(StatusCode::OK_200, res->status);
  4498. ASSERT_EQ("path-only", res->body);
  4499. }
  4500. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4501. auto res = cli_.Post("/path-headers-only",
  4502. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. ASSERT_EQ(StatusCode::OK_200, res->status);
  4505. ASSERT_EQ("path-headers-only", res->body);
  4506. }
  4507. TEST_F(ServerTest, PostLarge) {
  4508. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4510. ASSERT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ(LARGE_DATA, res->body);
  4512. }
  4513. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4514. auto res = cli_.Put("/empty-no-content-type");
  4515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4516. ASSERT_EQ(StatusCode::OK_200, res->status);
  4517. ASSERT_EQ("empty-no-content-type", res->body);
  4518. }
  4519. TEST_F(ServerTest, GetMethodDir) {
  4520. auto res = cli_.Get("/dir/");
  4521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4524. auto body = R"(<html>
  4525. <head>
  4526. </head>
  4527. <body>
  4528. <a href="/dir/test.html">Test</a>
  4529. <a href="/hi">hi</a>
  4530. </body>
  4531. </html>
  4532. )";
  4533. EXPECT_EQ(body, res->body);
  4534. }
  4535. TEST_F(ServerTest, GetMethodDirTest) {
  4536. auto res = cli_.Get("/dir/test.html");
  4537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4538. EXPECT_EQ(StatusCode::OK_200, res->status);
  4539. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4540. EXPECT_EQ("test.html", res->body);
  4541. }
  4542. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4543. auto res = cli_.Get("/dir/../dir/test.html");
  4544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4545. EXPECT_EQ(StatusCode::OK_200, res->status);
  4546. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4547. EXPECT_EQ("test.html", res->body);
  4548. }
  4549. TEST_F(ServerTest, GetMethodInvalidPath) {
  4550. auto res = cli_.Get("/dir/../test.html");
  4551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4552. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4553. }
  4554. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4555. auto res = cli_.Get("/../www/dir/test.html");
  4556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4557. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4558. }
  4559. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4560. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4563. }
  4564. TEST_F(ServerTest, GetMethodDirMountTest) {
  4565. auto res = cli_.Get("/mount/dir/test.html");
  4566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4567. EXPECT_EQ(StatusCode::OK_200, res->status);
  4568. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4569. EXPECT_EQ("test.html", res->body);
  4570. }
  4571. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4572. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4574. EXPECT_EQ(StatusCode::OK_200, res->status);
  4575. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4576. EXPECT_EQ("test.html", res->body);
  4577. }
  4578. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4579. auto res = cli_.Get("/mount/dir/../test.html");
  4580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4581. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4582. }
  4583. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4584. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4586. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4587. }
  4588. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4589. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4591. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4592. }
  4593. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4594. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4596. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4597. }
  4598. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4599. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4601. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4602. }
  4603. TEST_F(ServerTest, PostMethod303) {
  4604. auto res = cli_.Post("/1", "body", "text/plain");
  4605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4606. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4607. EXPECT_EQ("/2", res->get_header_value("Location"));
  4608. }
  4609. TEST_F(ServerTest, PostMethod303Redirect) {
  4610. cli_.set_follow_location(true);
  4611. auto res = cli_.Post("/1", "body", "text/plain");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("redirected.", res->body);
  4615. EXPECT_EQ("/2", res->location);
  4616. }
  4617. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4618. auto res = cli_.Get("/dir/test.abcde");
  4619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4620. EXPECT_EQ(StatusCode::OK_200, res->status);
  4621. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4622. EXPECT_EQ("abcde", res->body);
  4623. }
  4624. TEST_F(ServerTest, StaticFileRange) {
  4625. auto res =
  4626. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4629. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4630. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4631. EXPECT_EQ(true, res->has_header("Content-Range"));
  4632. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4633. EXPECT_EQ(std::string("cd"), res->body);
  4634. }
  4635. TEST_F(ServerTest, StaticFileRanges) {
  4636. auto res = cli_.Get("/dir/test.abcde",
  4637. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4640. EXPECT_TRUE(
  4641. res->get_header_value("Content-Type")
  4642. .find(
  4643. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4644. 0);
  4645. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4646. }
  4647. TEST_F(ServerTest, StaticFileRangeHead) {
  4648. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4650. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4651. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4652. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4653. EXPECT_EQ(true, res->has_header("Content-Range"));
  4654. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4655. }
  4656. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4657. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4661. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4662. EXPECT_EQ(true, res->has_header("Content-Range"));
  4663. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4664. res->get_header_value("Content-Range"));
  4665. EXPECT_EQ("LAST\n", res->body);
  4666. }
  4667. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4668. auto res =
  4669. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4673. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4674. EXPECT_EQ(true, res->has_header("Content-Range"));
  4675. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4676. }
  4677. TEST_F(ServerTest, StaticFileBigFile) {
  4678. auto res = cli_.Get("/dir/1MB.txt");
  4679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4680. EXPECT_EQ(StatusCode::OK_200, res->status);
  4681. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4682. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4683. }
  4684. TEST_F(ServerTest, InvalidBaseDirMount) {
  4685. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4686. }
  4687. TEST_F(ServerTest, Binary) {
  4688. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4689. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4690. "application/octet-stream");
  4691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4692. ASSERT_EQ(StatusCode::OK_200, res->status);
  4693. ASSERT_EQ(4U, res->body.size());
  4694. res = cli_.Put("/binary", binary.data(), binary.size(),
  4695. "application/octet-stream");
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. ASSERT_EQ(StatusCode::OK_200, res->status);
  4698. ASSERT_EQ(4U, res->body.size());
  4699. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4700. "application/octet-stream");
  4701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4702. ASSERT_EQ(StatusCode::OK_200, res->status);
  4703. ASSERT_EQ(4U, res->body.size());
  4704. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4705. "application/octet-stream");
  4706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4707. ASSERT_EQ(StatusCode::OK_200, res->status);
  4708. ASSERT_EQ(4U, res->body.size());
  4709. }
  4710. TEST_F(ServerTest, BinaryString) {
  4711. auto binary = std::string("\x00\x01\x02\x03", 4);
  4712. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4714. ASSERT_EQ(StatusCode::OK_200, res->status);
  4715. ASSERT_EQ(4U, res->body.size());
  4716. res = cli_.Put("/binary", binary, "application/octet-stream");
  4717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4718. ASSERT_EQ(StatusCode::OK_200, res->status);
  4719. ASSERT_EQ(4U, res->body.size());
  4720. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4722. ASSERT_EQ(StatusCode::OK_200, res->status);
  4723. ASSERT_EQ(4U, res->body.size());
  4724. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4726. ASSERT_EQ(StatusCode::OK_200, res->status);
  4727. ASSERT_EQ(4U, res->body.size());
  4728. }
  4729. TEST_F(ServerTest, EmptyRequest) {
  4730. auto res = cli_.Get("");
  4731. ASSERT_TRUE(!res);
  4732. EXPECT_EQ(Error::Connection, res.error());
  4733. }
  4734. TEST_F(ServerTest, LongRequest) {
  4735. std::string request;
  4736. for (size_t i = 0; i < 545; i++) {
  4737. request += "/TooLongRequest";
  4738. }
  4739. request += "OK";
  4740. auto res = cli_.Get(request.c_str());
  4741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4742. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4743. }
  4744. TEST_F(ServerTest, TooLongRequest) {
  4745. std::string request;
  4746. for (size_t i = 0; i < 546; i++) {
  4747. request += "/TooLongRequest";
  4748. }
  4749. request += "_NG";
  4750. auto start = std::chrono::high_resolution_clock::now();
  4751. cli_.set_keep_alive(true);
  4752. auto res = cli_.Get(request.c_str());
  4753. auto end = std::chrono::high_resolution_clock::now();
  4754. auto elapsed =
  4755. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4756. .count();
  4757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4758. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4759. EXPECT_LE(elapsed, 1000);
  4760. EXPECT_EQ("close", res->get_header_value("Connection"));
  4761. EXPECT_FALSE(cli_.is_socket_open());
  4762. }
  4763. TEST_F(ServerTest, AlmostTooLongRequest) {
  4764. // test for #2046 - URI length check shouldn't include other content on req
  4765. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4766. // leading /, space, HTTP/1.1)
  4767. std::string request =
  4768. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4769. auto res = cli_.Get(request.c_str());
  4770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4772. }
  4773. TEST_F(ServerTest, LongHeader) {
  4774. Request req;
  4775. req.method = "GET";
  4776. req.path = "/hi";
  4777. std::string host_and_port;
  4778. host_and_port += HOST;
  4779. host_and_port += ":";
  4780. host_and_port += std::to_string(PORT);
  4781. req.headers.emplace("Host", host_and_port.c_str());
  4782. req.headers.emplace("Accept", "*/*");
  4783. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4784. req.headers.emplace(
  4785. "Header-Name",
  4786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4814. "@@@@@@@@@@@@@@@@");
  4815. auto res = std::make_shared<Response>();
  4816. auto error = Error::Success;
  4817. auto ret = cli_.send(req, *res, error);
  4818. ASSERT_TRUE(ret);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. }
  4821. TEST_F(ServerTest, LongQueryValue) {
  4822. auto start = std::chrono::high_resolution_clock::now();
  4823. cli_.set_keep_alive(true);
  4824. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4825. auto end = std::chrono::high_resolution_clock::now();
  4826. auto elapsed =
  4827. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4828. .count();
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4831. EXPECT_LE(elapsed, 1000);
  4832. EXPECT_EQ("close", res->get_header_value("Connection"));
  4833. EXPECT_FALSE(cli_.is_socket_open());
  4834. }
  4835. TEST_F(ServerTest, TooLongQueryValue) {
  4836. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4837. ASSERT_FALSE(res);
  4838. EXPECT_EQ(Error::Read, res.error());
  4839. }
  4840. TEST_F(ServerTest, TooLongHeader) {
  4841. Request req;
  4842. req.method = "GET";
  4843. req.path = "/hi";
  4844. std::string host_and_port;
  4845. host_and_port += HOST;
  4846. host_and_port += ":";
  4847. host_and_port += std::to_string(PORT);
  4848. req.headers.emplace("Host", host_and_port.c_str());
  4849. req.headers.emplace("Accept", "*/*");
  4850. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4851. req.headers.emplace(
  4852. "Header-Name",
  4853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4881. "@@@@@@@@@@@@@@@@@");
  4882. auto res = std::make_shared<Response>();
  4883. auto error = Error::Success;
  4884. auto ret = cli_.send(req, *res, error);
  4885. ASSERT_TRUE(ret);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. }
  4888. TEST_F(ServerTest, HeaderCountAtLimit) {
  4889. // Test with headers just under the 100 limit
  4890. httplib::Headers headers;
  4891. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4892. // This should keep us just under the 100 header limit
  4893. for (int i = 0; i < 95; i++) {
  4894. std::string name = "X-Test-Header-" + std::to_string(i);
  4895. std::string value = "value" + std::to_string(i);
  4896. headers.emplace(name, value);
  4897. }
  4898. // This should work fine as we're under the limit
  4899. auto res = cli_.Get("/hi", headers);
  4900. EXPECT_TRUE(res);
  4901. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4902. }
  4903. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4904. // Test with many headers to exceed the 100 limit
  4905. httplib::Headers headers;
  4906. // Add 150 headers to definitely exceed the 100 limit
  4907. for (int i = 0; i < 150; i++) {
  4908. std::string name = "X-Test-Header-" + std::to_string(i);
  4909. std::string value = "value" + std::to_string(i);
  4910. headers.emplace(name, value);
  4911. }
  4912. // This should fail due to exceeding header count limit
  4913. cli_.set_keep_alive(true);
  4914. auto res = cli_.Get("/hi", headers);
  4915. // The server should respond with 400 Bad Request
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4918. EXPECT_EQ("close", res->get_header_value("Connection"));
  4919. EXPECT_FALSE(cli_.is_socket_open());
  4920. }
  4921. TEST_F(ServerTest, PercentEncoding) {
  4922. auto res = cli_.Get("/e%6edwith%");
  4923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4924. EXPECT_EQ(StatusCode::OK_200, res->status);
  4925. }
  4926. TEST_F(ServerTest, PercentEncodingUnicode) {
  4927. auto res = cli_.Get("/e%u006edwith%");
  4928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4929. EXPECT_EQ(StatusCode::OK_200, res->status);
  4930. }
  4931. TEST_F(ServerTest, InvalidPercentEncoding) {
  4932. auto res = cli_.Get("/%endwith%");
  4933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4934. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4935. }
  4936. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4937. auto res = cli_.Get("/%uendwith%");
  4938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4939. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4940. }
  4941. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4942. auto res = cli_.Get("/hello?aaa=bbb%");
  4943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4945. }
  4946. TEST_F(ServerTest, PlusSignEncoding) {
  4947. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4949. EXPECT_EQ(StatusCode::OK_200, res->status);
  4950. EXPECT_EQ("a +b", res->body);
  4951. }
  4952. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4953. // This test simulates a potential DoS attack using many headers
  4954. // to verify our security fix prevents memory exhaustion
  4955. httplib::Headers attack_headers;
  4956. // Attempt to add many headers like an attacker would (200 headers to far
  4957. // exceed limit)
  4958. for (int i = 0; i < 200; i++) {
  4959. std::string name = "X-Attack-Header-" + std::to_string(i);
  4960. std::string value = "attack_payload_" + std::to_string(i);
  4961. attack_headers.emplace(name, value);
  4962. }
  4963. // Try to POST with excessive headers
  4964. cli_.set_keep_alive(true);
  4965. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4966. // Should either fail or return 400 Bad Request due to security limit
  4967. if (res) {
  4968. // If we get a response, it should be 400 Bad Request
  4969. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4970. EXPECT_EQ("close", res->get_header_value("Connection"));
  4971. }
  4972. EXPECT_FALSE(cli_.is_socket_open());
  4973. }
  4974. TEST_F(ServerTest, MultipartFormData) {
  4975. UploadFormDataItems items = {
  4976. {"text1", "text default", "", ""},
  4977. {"text2", "aωb", "", ""},
  4978. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4979. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4980. {"file3", "", "", "application/octet-stream"},
  4981. {"file4", "", "", " application/json tmp-string "}};
  4982. auto res = cli_.Post("/multipart", items);
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. }
  4986. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4987. UploadFormDataItems items = {
  4988. {"text", "default text", "", ""},
  4989. {"multi_text1", "aaaaa", "", ""},
  4990. {"multi_text1", "bbbbb", "", ""},
  4991. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4992. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4993. "application/json"},
  4994. };
  4995. auto res = cli_.Post("/multipart/multi_file_values", items);
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. }
  4999. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5000. auto res = cli_.Get("/hi");
  5001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5002. EXPECT_EQ(StatusCode::OK_200, res->status);
  5003. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5004. EXPECT_EQ("Hello World!", res->body);
  5005. }
  5006. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5007. Request req;
  5008. req.method = "POST";
  5009. req.path = "/chunked";
  5010. std::string host_and_port;
  5011. host_and_port += HOST;
  5012. host_and_port += ":";
  5013. host_and_port += std::to_string(PORT);
  5014. req.headers.emplace("Host", host_and_port.c_str());
  5015. req.headers.emplace("Accept", "*/*");
  5016. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5017. req.headers.emplace("Content-Type", "text/plain");
  5018. req.headers.emplace("Content-Length", "0");
  5019. req.headers.emplace(
  5020. "Transfer-Encoding",
  5021. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5022. // Client does not chunk, so make a chunked body manually.
  5023. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5024. auto res = std::make_shared<Response>();
  5025. auto error = Error::Success;
  5026. auto ret = cli_.send(req, *res, error);
  5027. ASSERT_TRUE(ret);
  5028. EXPECT_EQ(StatusCode::OK_200, res->status);
  5029. }
  5030. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5031. // rather than treat them as valid lengths.
  5032. template <typename ClientT>
  5033. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5034. Request req;
  5035. req.method = "POST";
  5036. req.path = "/chunked";
  5037. std::string host_and_port;
  5038. host_and_port += HOST;
  5039. host_and_port += ":";
  5040. host_and_port += std::to_string(PORT);
  5041. req.headers.emplace("Host", host_and_port.c_str());
  5042. req.headers.emplace("Content-Length", "0");
  5043. req.headers.emplace("Transfer-Encoding", "chunked");
  5044. req.body = body;
  5045. auto res = std::make_shared<Response>();
  5046. auto error = Error::Success;
  5047. ASSERT_TRUE(cli.send(req, *res, error));
  5048. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5049. }
  5050. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5051. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5052. }
  5053. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5054. expect_chunked_body_rejected(
  5055. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5056. }
  5057. TEST_F(ServerTest, GetStreamed2) {
  5058. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5061. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5062. EXPECT_EQ(true, res->has_header("Content-Range"));
  5063. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5064. EXPECT_EQ(std::string("ab"), res->body);
  5065. }
  5066. TEST_F(ServerTest, GetStreamed) {
  5067. auto res = cli_.Get("/streamed");
  5068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5069. EXPECT_EQ(StatusCode::OK_200, res->status);
  5070. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5071. EXPECT_EQ(std::string("aaabbb"), res->body);
  5072. }
  5073. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5074. auto res = cli_.Get("/streamed-without-length",
  5075. Headers{make_range_header({{0, -1}})});
  5076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5077. EXPECT_EQ(StatusCode::OK_200, res->status);
  5078. EXPECT_EQ(false, res->has_header("Content-Length"));
  5079. EXPECT_EQ(false, res->has_header("Content-Range"));
  5080. EXPECT_EQ(std::string("abcdefg"), res->body);
  5081. }
  5082. TEST_F(ServerTest, GetStreamedWithRange1) {
  5083. auto res =
  5084. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5087. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5088. EXPECT_EQ(true, res->has_header("Content-Range"));
  5089. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5090. EXPECT_EQ(std::string("def"), res->body);
  5091. }
  5092. TEST_F(ServerTest, GetStreamedWithRange2) {
  5093. auto res =
  5094. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5097. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5098. EXPECT_EQ(true, res->has_header("Content-Range"));
  5099. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5100. EXPECT_EQ(std::string("bcdefg"), res->body);
  5101. }
  5102. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5103. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5106. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5107. EXPECT_EQ(true, res->has_header("Content-Range"));
  5108. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5109. EXPECT_EQ(std::string("efg"), res->body);
  5110. }
  5111. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5112. auto res =
  5113. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5115. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5116. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5117. EXPECT_EQ(false, res->has_header("Content-Range"));
  5118. EXPECT_EQ(0U, res->body.size());
  5119. }
  5120. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  5121. // Only a 206 is served as a partial representation. Under any other status
  5122. // `apply_ranges()` reported the full content length, so the body must match
  5123. // that header, and the content provider must never be asked for an offset
  5124. // outside the representation.
  5125. auto check = [&](int status, const char *range) {
  5126. auto path =
  5127. std::string("/streamed-with-range?status=") + std::to_string(status);
  5128. auto ctx = path + " Range: " + range;
  5129. auto res = cli_.Get(path, Headers{{"Range", range}});
  5130. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  5131. EXPECT_EQ(status, res->status) << ctx;
  5132. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  5133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  5134. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  5135. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  5136. };
  5137. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  5138. check(403, "bytes=3-5");
  5139. // The offset is far past the representation.
  5140. check(403, "bytes=100000-100200");
  5141. // `first_pos` is still -1 here, and the bounds asserts in
  5142. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  5143. check(403, "bytes=-3");
  5144. // `apply_ranges()` makes no boundary for a non-206 response, so the
  5145. // multipart branch would have written one that is empty.
  5146. check(403, "bytes=1-2, 4-5");
  5147. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  5148. // covers the whole representation.
  5149. check(200, "bytes=3-5");
  5150. check(200, "bytes=1-2, 4-5");
  5151. }
  5152. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5153. auto res =
  5154. cli_.Get("/streamed-with-range",
  5155. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5156. "92233720368547758079223372036854775807"}});
  5157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5158. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5159. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5160. EXPECT_EQ(false, res->has_header("Content-Range"));
  5161. EXPECT_EQ(0U, res->body.size());
  5162. }
  5163. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5164. auto res = cli_.Get(
  5165. "/with-range",
  5166. Headers{{"Range",
  5167. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5168. {"Accept-Encoding", ""}});
  5169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5171. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5172. EXPECT_EQ(true, res->has_header("Content-Range"));
  5173. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5174. EXPECT_EQ(std::string("abcdefg"), res->body);
  5175. }
  5176. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5177. auto res = cli_.Get("/with-range", Headers{
  5178. {"Range", "bytes=0-"},
  5179. {"Accept-Encoding", ""},
  5180. });
  5181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5183. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5184. EXPECT_EQ(true, res->has_header("Content-Range"));
  5185. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5186. EXPECT_EQ(std::string("abcdefg"), res->body);
  5187. }
  5188. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5189. auto res = cli_.Get("/streamed-with-range",
  5190. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5193. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5194. EXPECT_EQ(false, res->has_header("Content-Range"));
  5195. EXPECT_EQ(267U, res->body.size());
  5196. // Check that both range contents are present
  5197. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5198. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5199. // Check that Content-Range headers are present for both ranges
  5200. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5201. std::string::npos);
  5202. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5203. std::string::npos);
  5204. }
  5205. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5206. Ranges ranges;
  5207. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5208. ranges.emplace_back(0, -1);
  5209. }
  5210. auto res = cli_.Get("/streamed-with-range?error",
  5211. Headers{{make_range_header(ranges)}});
  5212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5213. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5214. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5215. EXPECT_EQ(false, res->has_header("Content-Range"));
  5216. EXPECT_EQ(0U, res->body.size());
  5217. }
  5218. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5219. auto res = cli_.Get("/streamed-with-range",
  5220. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5222. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5223. EXPECT_EQ(5U, res->body.size());
  5224. // Check that overlapping ranges are coalesced into a single range
  5225. EXPECT_EQ("bcdef", res->body);
  5226. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5227. // Should be single range, not multipart
  5228. EXPECT_TRUE(res->has_header("Content-Range"));
  5229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5230. }
  5231. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5232. auto res = cli_.Get("/streamed-with-range",
  5233. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5235. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5236. EXPECT_EQ(268U, res->body.size());
  5237. // Check that both range contents are present
  5238. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5239. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5240. // Check that Content-Range headers are present for both ranges
  5241. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5242. std::string::npos);
  5243. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5244. std::string::npos);
  5245. }
  5246. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5247. auto res = cli_.Get("/streamed-with-range",
  5248. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5251. EXPECT_EQ(269U, res->body.size());
  5252. // Check that both duplicate range contents are present
  5253. size_t first_abc = res->body.find("abc\r\n");
  5254. EXPECT_TRUE(first_abc != std::string::npos);
  5255. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5256. EXPECT_TRUE(second_abc != std::string::npos);
  5257. // Check that Content-Range headers are present for both ranges
  5258. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5259. EXPECT_TRUE(first_range != std::string::npos);
  5260. size_t second_range =
  5261. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5262. EXPECT_TRUE(second_range != std::string::npos);
  5263. }
  5264. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5265. auto res =
  5266. cli_.Get("/streamed-with-range?error",
  5267. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5269. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5270. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5271. EXPECT_EQ(false, res->has_header("Content-Range"));
  5272. EXPECT_EQ(0U, res->body.size());
  5273. }
  5274. TEST_F(ServerTest, GetStreamedEndless) {
  5275. uint64_t offset = 0;
  5276. auto res = cli_.Get("/streamed-cancel",
  5277. [&](const char * /*data*/, uint64_t data_length) {
  5278. if (offset < 100) {
  5279. offset += data_length;
  5280. return true;
  5281. }
  5282. return false;
  5283. });
  5284. ASSERT_TRUE(!res);
  5285. EXPECT_EQ(Error::Canceled, res.error());
  5286. }
  5287. TEST_F(ServerTest, ClientStop) {
  5288. std::atomic_size_t count{4};
  5289. std::vector<std::thread> threads;
  5290. for (auto i = count.load(); i != 0; --i) {
  5291. threads.emplace_back([&]() {
  5292. auto res = cli_.Get("/streamed-cancel",
  5293. [&](const char *, uint64_t) { return true; });
  5294. --count;
  5295. ASSERT_TRUE(!res);
  5296. EXPECT_TRUE(res.error() == Error::Canceled ||
  5297. res.error() == Error::Read || res.error() == Error::Write);
  5298. });
  5299. }
  5300. std::this_thread::sleep_for(std::chrono::seconds(2));
  5301. while (count != 0) {
  5302. cli_.stop();
  5303. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5304. }
  5305. for (auto &t : threads) {
  5306. t.join();
  5307. }
  5308. }
  5309. TEST_F(ServerTest, GetWithRange1) {
  5310. auto res = cli_.Get("/with-range", Headers{
  5311. make_range_header({{3, 5}}),
  5312. {"Accept-Encoding", ""},
  5313. });
  5314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5315. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5316. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5317. EXPECT_EQ(true, res->has_header("Content-Range"));
  5318. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5319. EXPECT_EQ(std::string("def"), res->body);
  5320. }
  5321. TEST_F(ServerTest, GetWithRange2) {
  5322. auto res = cli_.Get("/with-range", Headers{
  5323. make_range_header({{1, -1}}),
  5324. {"Accept-Encoding", ""},
  5325. });
  5326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5327. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5328. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5329. EXPECT_EQ(true, res->has_header("Content-Range"));
  5330. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5331. EXPECT_EQ(std::string("bcdefg"), res->body);
  5332. }
  5333. TEST_F(ServerTest, GetWithRange3) {
  5334. auto res = cli_.Get("/with-range", Headers{
  5335. make_range_header({{0, 0}}),
  5336. {"Accept-Encoding", ""},
  5337. });
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5340. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5341. EXPECT_EQ(true, res->has_header("Content-Range"));
  5342. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5343. EXPECT_EQ(std::string("a"), res->body);
  5344. }
  5345. TEST_F(ServerTest, GetWithRange4) {
  5346. auto res = cli_.Get("/with-range", Headers{
  5347. make_range_header({{-1, 2}}),
  5348. {"Accept-Encoding", ""},
  5349. });
  5350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5351. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5352. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5353. EXPECT_EQ(true, res->has_header("Content-Range"));
  5354. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5355. EXPECT_EQ(std::string("fg"), res->body);
  5356. }
  5357. TEST_F(ServerTest, GetWithRange5) {
  5358. auto res = cli_.Get("/with-range", Headers{
  5359. make_range_header({{0, 5}}),
  5360. {"Accept-Encoding", ""},
  5361. });
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5364. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5365. EXPECT_EQ(true, res->has_header("Content-Range"));
  5366. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5367. EXPECT_EQ(std::string("abcdef"), res->body);
  5368. }
  5369. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5370. auto res =
  5371. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5374. }
  5375. TEST_F(ServerTest, GetWithRangeMultipart) {
  5376. auto res =
  5377. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5380. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5381. EXPECT_EQ(false, res->has_header("Content-Range"));
  5382. EXPECT_EQ(267U, res->body.size());
  5383. }
  5384. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5385. auto res = cli_.Get("/with-range",
  5386. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5389. }
  5390. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5391. auto res = cli_.Get("/with-range-customized-response",
  5392. Headers{{make_range_header({{1, 2}})}});
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5395. EXPECT_EQ(true, res->has_header("Content-Length"));
  5396. EXPECT_EQ(false, res->has_header("Content-Range"));
  5397. EXPECT_EQ(JSON_DATA, res->body);
  5398. }
  5399. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5400. auto res = cli_.Get("/with-range-customized-response",
  5401. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5404. EXPECT_EQ(true, res->has_header("Content-Length"));
  5405. EXPECT_EQ(false, res->has_header("Content-Range"));
  5406. EXPECT_EQ(JSON_DATA, res->body);
  5407. }
  5408. TEST_F(ServerTest, Issue1772) {
  5409. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5411. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5412. }
  5413. TEST_F(ServerTest, Issue609) {
  5414. auto res = cli_.Delete("/issue609");
  5415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5416. EXPECT_EQ(StatusCode::OK_200, res->status);
  5417. EXPECT_EQ(std::string("ok"), res->body);
  5418. }
  5419. TEST_F(ServerTest, GetStreamedChunked) {
  5420. auto res = cli_.Get("/streamed-chunked");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. EXPECT_EQ(StatusCode::OK_200, res->status);
  5423. EXPECT_EQ(std::string("123456789"), res->body);
  5424. }
  5425. TEST_F(ServerTest, GetStreamedChunked2) {
  5426. auto res = cli_.Get("/streamed-chunked2");
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. EXPECT_EQ(StatusCode::OK_200, res->status);
  5429. EXPECT_EQ(std::string("123456789"), res->body);
  5430. }
  5431. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5432. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. EXPECT_EQ(std::string("123456789"), res->body);
  5436. EXPECT_TRUE(res->has_header("Trailer"));
  5437. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5438. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5439. // Trailers are now stored separately from headers (security fix)
  5440. EXPECT_EQ(2U, res->trailers.size());
  5441. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5442. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5443. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5444. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5445. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5446. // Verify trailers are NOT in headers (security verification)
  5447. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5448. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5449. }
  5450. TEST_F(ServerTest, LargeChunkedPost) {
  5451. Request req;
  5452. req.method = "POST";
  5453. req.path = "/large-chunked";
  5454. std::string host_and_port;
  5455. host_and_port += HOST;
  5456. host_and_port += ":";
  5457. host_and_port += std::to_string(PORT);
  5458. req.headers.emplace("Host", host_and_port.c_str());
  5459. req.headers.emplace("Accept", "*/*");
  5460. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5461. req.headers.emplace("Content-Type", "text/plain");
  5462. req.headers.emplace("Content-Length", "0");
  5463. req.headers.emplace("Transfer-Encoding", "chunked");
  5464. std::string long_string(30 * 1024u, 'a');
  5465. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5466. // Attempt to make a large enough post to exceed OS buffers, to test that
  5467. // the server handles short reads if the full chunk data isn't available.
  5468. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5469. auto res = std::make_shared<Response>();
  5470. auto error = Error::Success;
  5471. auto ret = cli_.send(req, *res, error);
  5472. ASSERT_TRUE(ret);
  5473. EXPECT_EQ(StatusCode::OK_200, res->status);
  5474. }
  5475. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5476. auto res = cli_.Get("/remote_addr");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5480. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5481. }
  5482. TEST_F(ServerTest, GetMethodLocalAddr) {
  5483. auto res = cli_.Get("/local_addr");
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5487. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5488. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5489. }
  5490. TEST_F(ServerTest, HTTPResponseSplitting) {
  5491. auto res = cli_.Get("/http_response_splitting");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::OK_200, res->status);
  5494. }
  5495. TEST_F(ServerTest, SlowRequest) {
  5496. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5497. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5498. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5499. }
  5500. #if 0
  5501. TEST_F(ServerTest, SlowPost) {
  5502. char buffer[64 * 1024];
  5503. memset(buffer, 0x42, sizeof(buffer));
  5504. auto res = cli_.Post(
  5505. "/slowpost", 64 * 1024 * 1024,
  5506. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5507. auto ret = sink.write(buffer, sizeof(buffer));
  5508. EXPECT_TRUE(ret);
  5509. return true;
  5510. },
  5511. "text/plain");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::OK_200, res->status);
  5514. }
  5515. TEST_F(ServerTest, SlowPostFail) {
  5516. char buffer[64 * 1024];
  5517. memset(buffer, 0x42, sizeof(buffer));
  5518. cli_.set_write_timeout(std::chrono::seconds(0));
  5519. auto res = cli_.Post(
  5520. "/slowpost", 64 * 1024 * 1024,
  5521. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5522. sink.write(buffer, sizeof(buffer));
  5523. return true;
  5524. },
  5525. "text/plain");
  5526. ASSERT_TRUE(!res);
  5527. EXPECT_EQ(Error::Write, res.error());
  5528. }
  5529. #endif
  5530. TEST_F(ServerTest, Put) {
  5531. auto res = cli_.Put("/put", "PUT", "text/plain");
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. EXPECT_EQ(StatusCode::OK_200, res->status);
  5534. EXPECT_EQ("PUT", res->body);
  5535. }
  5536. TEST_F(ServerTest, PutWithContentProvider) {
  5537. auto res = cli_.Put(
  5538. "/put", 3,
  5539. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5540. sink.os << "PUT";
  5541. return true;
  5542. },
  5543. "text/plain");
  5544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5545. EXPECT_EQ(StatusCode::OK_200, res->status);
  5546. EXPECT_EQ("PUT", res->body);
  5547. }
  5548. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5549. auto res = cli_.Post(
  5550. "/post", 42,
  5551. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5552. return false;
  5553. },
  5554. "text/plain");
  5555. ASSERT_TRUE(!res);
  5556. EXPECT_EQ(Error::Canceled, res.error());
  5557. }
  5558. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5559. auto res = cli_.Put(
  5560. "/put",
  5561. [](size_t /*offset*/, DataSink &sink) {
  5562. sink.os << "PUT";
  5563. sink.done();
  5564. return true;
  5565. },
  5566. "text/plain");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::OK_200, res->status);
  5569. EXPECT_EQ("PUT", res->body);
  5570. }
  5571. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5572. auto res = cli_.Post(
  5573. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5574. "text/plain");
  5575. ASSERT_TRUE(!res);
  5576. EXPECT_EQ(Error::Canceled, res.error());
  5577. }
  5578. TEST_F(ServerTest, PostLoopBack) {
  5579. std::string body;
  5580. auto res = cli_.Post(
  5581. "/post-loopback", 9,
  5582. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5583. EXPECT_EQ(9u, length);
  5584. sink.write("123", 3);
  5585. sink.write("456", 3);
  5586. sink.write("789", 3);
  5587. return true;
  5588. },
  5589. "text/plain",
  5590. [&body](const char *data, size_t data_length) {
  5591. body.append(data, data_length);
  5592. return true;
  5593. });
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::OK_200, res->status);
  5596. EXPECT_EQ("123456789", body);
  5597. }
  5598. TEST_F(ServerTest, PutLoopBack) {
  5599. std::string body;
  5600. auto res = cli_.Put(
  5601. "/put-loopback", 9,
  5602. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5603. EXPECT_EQ(9u, length);
  5604. sink.write("123", 3);
  5605. sink.write("456", 3);
  5606. sink.write("789", 3);
  5607. return true;
  5608. },
  5609. "text/plain",
  5610. [&body](const char *data, size_t data_length) {
  5611. body.append(data, data_length);
  5612. return true;
  5613. });
  5614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5615. EXPECT_EQ(StatusCode::OK_200, res->status);
  5616. EXPECT_EQ("123456789", body);
  5617. }
  5618. TEST_F(ServerTest, PatchLoopBack) {
  5619. std::string body;
  5620. auto res = cli_.Patch(
  5621. "/patch-loopback", 9,
  5622. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5623. EXPECT_EQ(9u, length);
  5624. sink.write("123", 3);
  5625. sink.write("456", 3);
  5626. sink.write("789", 3);
  5627. return true;
  5628. },
  5629. "text/plain",
  5630. [&body](const char *data, size_t data_length) {
  5631. body.append(data, data_length);
  5632. return true;
  5633. });
  5634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5635. EXPECT_EQ(StatusCode::OK_200, res->status);
  5636. EXPECT_EQ("123456789", body);
  5637. }
  5638. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5639. std::string body;
  5640. auto res = cli_.Post(
  5641. "/post-loopback",
  5642. [](size_t /*offset*/, DataSink &sink) {
  5643. sink.write("123", 3);
  5644. sink.write("456", 3);
  5645. sink.write("789", 3);
  5646. sink.done();
  5647. return true;
  5648. },
  5649. "text/plain",
  5650. [&body](const char *data, size_t data_length) {
  5651. body.append(data, data_length);
  5652. return true;
  5653. });
  5654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5655. EXPECT_EQ(StatusCode::OK_200, res->status);
  5656. EXPECT_EQ("123456789", body);
  5657. }
  5658. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5659. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5660. cli_.set_compress(true);
  5661. auto res = cli_.Put(
  5662. "/put", 3,
  5663. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5664. sink.os << "PUT";
  5665. return true;
  5666. },
  5667. "text/plain");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. EXPECT_EQ(StatusCode::OK_200, res->status);
  5670. EXPECT_EQ("PUT", res->body);
  5671. }
  5672. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5673. cli_.set_compress(true);
  5674. auto res = cli_.Post(
  5675. "/post", 42,
  5676. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5677. return false;
  5678. },
  5679. "text/plain");
  5680. ASSERT_TRUE(!res);
  5681. EXPECT_EQ(Error::Canceled, res.error());
  5682. }
  5683. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5684. cli_.set_compress(true);
  5685. auto res = cli_.Put(
  5686. "/put",
  5687. [](size_t /*offset*/, DataSink &sink) {
  5688. sink.os << "PUT";
  5689. sink.done();
  5690. return true;
  5691. },
  5692. "text/plain");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. EXPECT_EQ(StatusCode::OK_200, res->status);
  5695. EXPECT_EQ("PUT", res->body);
  5696. }
  5697. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5698. cli_.set_compress(true);
  5699. auto res = cli_.Post(
  5700. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5701. "text/plain");
  5702. ASSERT_TRUE(!res);
  5703. EXPECT_EQ(Error::Canceled, res.error());
  5704. }
  5705. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5706. cli_.set_compress(true);
  5707. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. EXPECT_EQ(StatusCode::OK_200, res->status);
  5710. EXPECT_EQ(LARGE_DATA, res->body);
  5711. }
  5712. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5713. #ifdef CPPHTTPLIB_SSL_ENABLED
  5714. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5715. Client cli(s.c_str());
  5716. cli.enable_server_certificate_verification(false);
  5717. #else
  5718. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5719. Client cli(s.c_str());
  5720. #endif
  5721. cli.set_compress(true);
  5722. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5724. EXPECT_EQ(StatusCode::OK_200, res->status);
  5725. EXPECT_EQ(LARGE_DATA, res->body);
  5726. // The compressed size should be less than a 10th of the original. May vary
  5727. // depending on the zlib library.
  5728. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5729. static_cast<uint64_t>(10 * 1024 * 1024));
  5730. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5731. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5732. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5733. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5734. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5735. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5736. #endif
  5737. }
  5738. TEST_F(ServerTest, PutContentWithDeflate) {
  5739. cli_.set_compress(false);
  5740. Headers headers;
  5741. headers.emplace("Content-Encoding", "deflate");
  5742. // PUT in deflate format:
  5743. auto res = cli_.Put("/put", headers,
  5744. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("PUT", res->body);
  5748. }
  5749. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5750. Headers headers;
  5751. headers.emplace("Accept-Encoding", "gzip, deflate");
  5752. auto res = cli_.Get("/streamed-chunked", headers);
  5753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5754. EXPECT_EQ(StatusCode::OK_200, res->status);
  5755. EXPECT_EQ(std::string("123456789"), res->body);
  5756. }
  5757. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5758. Headers headers;
  5759. headers.emplace("Accept-Encoding", "gzip, deflate");
  5760. auto res = cli_.Get("/streamed-chunked2", headers);
  5761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5762. EXPECT_EQ(StatusCode::OK_200, res->status);
  5763. EXPECT_EQ(std::string("123456789"), res->body);
  5764. }
  5765. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5766. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. }
  5770. TEST(GzipDecompressor, ChunkedDecompression) {
  5771. std::string data;
  5772. for (size_t i = 0; i < 32 * 1024; ++i) {
  5773. data.push_back(static_cast<char>('a' + i % 26));
  5774. }
  5775. std::string compressed_data;
  5776. {
  5777. httplib::detail::gzip_compressor compressor;
  5778. bool result = compressor.compress(
  5779. data.data(), data.size(),
  5780. /*last=*/true,
  5781. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5782. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5783. compressed_data_size);
  5784. return true;
  5785. });
  5786. ASSERT_TRUE(result);
  5787. }
  5788. std::string decompressed_data;
  5789. {
  5790. httplib::detail::gzip_decompressor decompressor;
  5791. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5792. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5793. size_t chunk_size = 130;
  5794. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5795. chunk_begin += chunk_size) {
  5796. size_t current_chunk_size =
  5797. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5798. bool result = decompressor.decompress(
  5799. compressed_data.data() + chunk_begin, current_chunk_size,
  5800. [&](const char *decompressed_data_chunk,
  5801. size_t decompressed_data_chunk_size) {
  5802. decompressed_data.insert(decompressed_data.size(),
  5803. decompressed_data_chunk,
  5804. decompressed_data_chunk_size);
  5805. return true;
  5806. });
  5807. ASSERT_TRUE(result);
  5808. }
  5809. }
  5810. ASSERT_EQ(data, decompressed_data);
  5811. }
  5812. TEST(GzipDecompressor, DeflateDecompression) {
  5813. std::string original_text = "Raw deflate without gzip";
  5814. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5815. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5816. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5817. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5818. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5819. std::string decompressed_data;
  5820. {
  5821. httplib::detail::gzip_decompressor decompressor;
  5822. bool result = decompressor.decompress(
  5823. compressed_data.data(), compressed_data.size(),
  5824. [&](const char *decompressed_data_chunk,
  5825. size_t decompressed_data_chunk_size) {
  5826. decompressed_data.insert(decompressed_data.size(),
  5827. decompressed_data_chunk,
  5828. decompressed_data_chunk_size);
  5829. return true;
  5830. });
  5831. ASSERT_TRUE(result);
  5832. }
  5833. ASSERT_EQ(original_text, decompressed_data);
  5834. }
  5835. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5836. std::string original_text = "Raw deflate without gzip";
  5837. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5838. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5839. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5840. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5841. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5842. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5843. std::string decompressed_data;
  5844. {
  5845. httplib::detail::gzip_decompressor decompressor;
  5846. bool result = decompressor.decompress(
  5847. compressed_data.data(), compressed_data.size(),
  5848. [&](const char *decompressed_data_chunk,
  5849. size_t decompressed_data_chunk_size) {
  5850. decompressed_data.insert(decompressed_data.size(),
  5851. decompressed_data_chunk,
  5852. decompressed_data_chunk_size);
  5853. return true;
  5854. });
  5855. ASSERT_TRUE(result);
  5856. }
  5857. ASSERT_EQ(original_text, decompressed_data);
  5858. }
  5859. #endif
  5860. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5861. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5862. Headers headers;
  5863. headers.emplace("Accept-Encoding", "br");
  5864. auto res = cli_.Get("/streamed-chunked", headers);
  5865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5866. EXPECT_EQ(StatusCode::OK_200, res->status);
  5867. EXPECT_EQ(std::string("123456789"), res->body);
  5868. }
  5869. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5870. Headers headers;
  5871. headers.emplace("Accept-Encoding", "br");
  5872. auto res = cli_.Get("/streamed-chunked2", headers);
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::OK_200, res->status);
  5875. EXPECT_EQ(std::string("123456789"), res->body);
  5876. }
  5877. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5878. cli_.set_compress(true);
  5879. auto res = cli_.Put(
  5880. "/put", 3,
  5881. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5882. sink.os << "PUT";
  5883. return true;
  5884. },
  5885. "text/plain");
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. EXPECT_EQ(StatusCode::OK_200, res->status);
  5888. EXPECT_EQ("PUT", res->body);
  5889. }
  5890. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5891. cli_.set_compress(true);
  5892. auto res = cli_.Put(
  5893. "/put",
  5894. [](size_t /*offset*/, DataSink &sink) {
  5895. sink.os << "PUT";
  5896. sink.done();
  5897. return true;
  5898. },
  5899. "text/plain");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. EXPECT_EQ("PUT", res->body);
  5903. }
  5904. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5905. cli_.set_compress(true);
  5906. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::OK_200, res->status);
  5909. EXPECT_EQ(LARGE_DATA, res->body);
  5910. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5911. }
  5912. #endif
  5913. TEST_F(ServerTest, Patch) {
  5914. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::OK_200, res->status);
  5917. EXPECT_EQ("PATCH", res->body);
  5918. }
  5919. TEST_F(ServerTest, Delete) {
  5920. auto res = cli_.Delete("/delete");
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. EXPECT_EQ(StatusCode::OK_200, res->status);
  5923. EXPECT_EQ("DELETE", res->body);
  5924. }
  5925. TEST_F(ServerTest, DeleteContentReceiver) {
  5926. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5928. EXPECT_EQ(StatusCode::OK_200, res->status);
  5929. EXPECT_EQ("content", res->body);
  5930. }
  5931. TEST_F(ServerTest, Options) {
  5932. auto res = cli_.Options("*");
  5933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5934. EXPECT_EQ(StatusCode::OK_200, res->status);
  5935. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5936. EXPECT_TRUE(res->body.empty());
  5937. }
  5938. TEST_F(ServerTest, URL) {
  5939. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. }
  5943. TEST_F(ServerTest, ArrayParam) {
  5944. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5946. EXPECT_EQ(StatusCode::OK_200, res->status);
  5947. }
  5948. TEST_F(ServerTest, ArrayParamValues) {
  5949. auto res =
  5950. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5952. EXPECT_EQ(StatusCode::OK_200, res->status);
  5953. }
  5954. TEST_F(ServerTest, NoMultipleHeaders) {
  5955. Headers headers = {{"Content-Length", "5"}};
  5956. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5957. "text/plain");
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::OK_200, res->status);
  5960. }
  5961. TEST_F(ServerTest, PostContentReceiver) {
  5962. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5964. ASSERT_EQ(StatusCode::OK_200, res->status);
  5965. ASSERT_EQ("content", res->body);
  5966. }
  5967. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5968. UploadFormDataItems items = {
  5969. {"text1", "text default", "", ""},
  5970. {"text2", "aωb", "", ""},
  5971. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5972. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5973. {"file3", "", "", "application/octet-stream"},
  5974. };
  5975. auto res = cli_.Post("/content_receiver", items);
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. }
  5979. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5980. UploadFormDataItems items = {
  5981. {"text1", "text default", "", ""},
  5982. {"text2", "aωb", "", ""},
  5983. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5984. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5985. {"file3", "", "", "application/octet-stream"},
  5986. };
  5987. auto boundary = std::string("+++++");
  5988. std::string body;
  5989. for (const auto &item : items) {
  5990. body += "--" + boundary + "\r\n";
  5991. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5992. if (!item.filename.empty()) {
  5993. body += "; filename=\"" + item.filename + "\"";
  5994. }
  5995. body += "\r\n";
  5996. if (!item.content_type.empty()) {
  5997. body += "Content-Type: " + item.content_type + "\r\n";
  5998. }
  5999. body += "\r\n";
  6000. body += item.content + "\r\n";
  6001. }
  6002. body += "--" + boundary + "--\r\n";
  6003. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6004. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. EXPECT_EQ(StatusCode::OK_200, res->status);
  6007. }
  6008. TEST(MultipartFormDataTest, FieldEscaping) {
  6009. Server svr;
  6010. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6011. const ContentReader &content_reader) {
  6012. ASSERT_TRUE(req.is_multipart_form_data());
  6013. std::vector<FormData> received;
  6014. content_reader(
  6015. [&](const FormData &file) {
  6016. received.push_back(file);
  6017. return true;
  6018. },
  6019. [&](const char *data, size_t data_length) {
  6020. received.back().content.append(data, data_length);
  6021. return true;
  6022. });
  6023. // '"', CR and LF in names and filenames are escaped following the
  6024. // WHATWG HTML standard, so each part still parses as a single part
  6025. // with no injected headers. Content types get CR/LF escaped too,
  6026. // while '"' (legal there, e.g. quoted charset) is preserved.
  6027. ASSERT_EQ(4U, received.size());
  6028. EXPECT_EQ("na%22me", received[0].name);
  6029. EXPECT_EQ("quoted name", received[0].content);
  6030. EXPECT_EQ("file", received[1].name);
  6031. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6032. received[1].filename);
  6033. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6034. EXPECT_EQ("injected", received[1].content);
  6035. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6036. EXPECT_EQ("my%22file.txt", received[2].filename);
  6037. EXPECT_EQ("cr lf name", received[2].content);
  6038. EXPECT_EQ("typed", received[3].name);
  6039. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6040. received[3].content_type);
  6041. EXPECT_EQ("typed content", received[3].content);
  6042. });
  6043. auto port = svr.bind_to_any_port("localhost");
  6044. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6045. auto se = detail::scope_exit([&] {
  6046. svr.stop();
  6047. t.join();
  6048. ASSERT_FALSE(svr.is_running());
  6049. });
  6050. svr.wait_until_ready();
  6051. Client cli("localhost", port);
  6052. UploadFormDataItems items = {
  6053. {"na\"me", "quoted name", "", ""},
  6054. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6055. "application/octet-stream"},
  6056. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6057. {"typed", "typed content", "",
  6058. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6059. };
  6060. auto res = cli.Post("/post", items);
  6061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6062. EXPECT_EQ(StatusCode::OK_200, res->status);
  6063. }
  6064. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6065. const UploadFormDataItems items = {
  6066. {"name1", "Content 1", "", ""},
  6067. {"name2", "Content 2", "file2.txt", "text/plain"},
  6068. };
  6069. Server svr;
  6070. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6071. const ContentReader &content_reader) {
  6072. ASSERT_TRUE(req.is_multipart_form_data());
  6073. std::vector<FormData> received;
  6074. content_reader(
  6075. [&](const FormData &file) {
  6076. received.push_back(file);
  6077. return true;
  6078. },
  6079. [&](const char *data, size_t data_length) {
  6080. received.back().content.append(data, data_length);
  6081. return true;
  6082. });
  6083. ASSERT_EQ(2U, received.size());
  6084. EXPECT_EQ("name1", received[0].name);
  6085. EXPECT_EQ("Content 1", received[0].content);
  6086. EXPECT_EQ("name2", received[1].name);
  6087. EXPECT_EQ("Content 2", received[1].content);
  6088. EXPECT_EQ("file2.txt", received[1].filename);
  6089. EXPECT_EQ("text/plain", received[1].content_type);
  6090. });
  6091. auto port = svr.bind_to_any_port("localhost");
  6092. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6093. auto se = detail::scope_exit([&] {
  6094. svr.stop();
  6095. t.join();
  6096. ASSERT_FALSE(svr.is_running());
  6097. });
  6098. svr.wait_until_ready();
  6099. Client cli("localhost", port);
  6100. // Whole-body serialization with a generated boundary
  6101. {
  6102. MultipartFormDataWriter writer;
  6103. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6104. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6105. writer.content_type());
  6106. auto body = writer.serialize(items);
  6107. EXPECT_EQ(body.size(), writer.content_length(items));
  6108. auto res = cli.Post("/post", body, writer.content_type());
  6109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6110. EXPECT_EQ(StatusCode::OK_200, res->status);
  6111. }
  6112. // Per-part framing with a custom boundary via a content provider
  6113. {
  6114. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6115. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6116. MultipartFormDataWriter writer("custom-boundary_123");
  6117. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6118. std::string body;
  6119. for (const auto &item : items) {
  6120. body += writer.item_begin(item);
  6121. body += item.content;
  6122. body += MultipartFormDataWriter::item_end();
  6123. }
  6124. body += writer.finish();
  6125. EXPECT_EQ(body.size(), writer.content_length(items));
  6126. auto res = cli.Post(
  6127. "/post", body.size(),
  6128. [&](size_t offset, size_t length, DataSink &sink) {
  6129. sink.write(body.data() + offset, length);
  6130. return true;
  6131. },
  6132. writer.content_type());
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::OK_200, res->status);
  6135. }
  6136. }
  6137. TEST_F(ServerTest, PostContentReceiverGzip) {
  6138. cli_.set_compress(true);
  6139. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::OK_200, res->status);
  6142. ASSERT_EQ("content", res->body);
  6143. }
  6144. TEST_F(ServerTest, PutContentReceiver) {
  6145. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. ASSERT_EQ(StatusCode::OK_200, res->status);
  6148. ASSERT_EQ("content", res->body);
  6149. }
  6150. TEST_F(ServerTest, PatchContentReceiver) {
  6151. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6153. ASSERT_EQ(StatusCode::OK_200, res->status);
  6154. ASSERT_EQ("content", res->body);
  6155. }
  6156. template <typename ClientType>
  6157. void TestWithHeadersAndContentReceiver(
  6158. ClientType &cli,
  6159. std::function<Result(ClientType &, const std::string &, const Headers &,
  6160. const std::string &, const std::string &,
  6161. ContentReceiver, DownloadProgress)>
  6162. request_func) {
  6163. Headers headers;
  6164. headers.emplace("X-Custom-Header", "test-value");
  6165. std::string received_body;
  6166. auto res = request_func(
  6167. cli, "/content_receiver", headers, "content", "application/json",
  6168. [&](const char *data, size_t data_length) {
  6169. received_body.append(data, data_length);
  6170. return true;
  6171. },
  6172. nullptr);
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::OK_200, res->status);
  6175. EXPECT_EQ("content", received_body);
  6176. }
  6177. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6178. #ifdef CPPHTTPLIB_SSL_ENABLED
  6179. using ClientT = SSLClient;
  6180. #else
  6181. using ClientT = Client;
  6182. #endif
  6183. TestWithHeadersAndContentReceiver<ClientT>(
  6184. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6185. const std::string &body, const std::string &content_type,
  6186. ContentReceiver receiver, DownloadProgress progress) {
  6187. return cli.Post(path, headers, body, content_type, receiver, progress);
  6188. });
  6189. }
  6190. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6191. #ifdef CPPHTTPLIB_SSL_ENABLED
  6192. using ClientT = SSLClient;
  6193. #else
  6194. using ClientT = Client;
  6195. #endif
  6196. TestWithHeadersAndContentReceiver<ClientT>(
  6197. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6198. const std::string &body, const std::string &content_type,
  6199. ContentReceiver receiver, DownloadProgress progress) {
  6200. return cli.Put(path, headers, body, content_type, receiver, progress);
  6201. });
  6202. }
  6203. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6204. #ifdef CPPHTTPLIB_SSL_ENABLED
  6205. using ClientT = SSLClient;
  6206. #else
  6207. using ClientT = Client;
  6208. #endif
  6209. TestWithHeadersAndContentReceiver<ClientT>(
  6210. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6211. const std::string &body, const std::string &content_type,
  6212. ContentReceiver receiver, DownloadProgress progress) {
  6213. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6214. });
  6215. }
  6216. template <typename ClientType>
  6217. void TestWithHeadersAndContentReceiverWithProgress(
  6218. ClientType &cli,
  6219. std::function<Result(ClientType &, const std::string &, const Headers &,
  6220. const std::string &, const std::string &,
  6221. ContentReceiver, DownloadProgress)>
  6222. request_func) {
  6223. Headers headers;
  6224. headers.emplace("X-Test-Header", "progress-test");
  6225. std::string received_body;
  6226. auto progress_called = false;
  6227. auto res = request_func(
  6228. cli, "/content_receiver", headers, "content", "text/plain",
  6229. [&](const char *data, size_t data_length) {
  6230. received_body.append(data, data_length);
  6231. return true;
  6232. },
  6233. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6234. progress_called = true;
  6235. return true;
  6236. });
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. EXPECT_EQ(StatusCode::OK_200, res->status);
  6239. EXPECT_EQ("content", received_body);
  6240. EXPECT_TRUE(progress_called);
  6241. }
  6242. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6243. #ifdef CPPHTTPLIB_SSL_ENABLED
  6244. using ClientT = SSLClient;
  6245. #else
  6246. using ClientT = Client;
  6247. #endif
  6248. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6249. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6250. const std::string &body, const std::string &content_type,
  6251. ContentReceiver receiver, DownloadProgress progress) {
  6252. return cli.Post(path, headers, body, content_type, receiver, progress);
  6253. });
  6254. }
  6255. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6256. #ifdef CPPHTTPLIB_SSL_ENABLED
  6257. using ClientT = SSLClient;
  6258. #else
  6259. using ClientT = Client;
  6260. #endif
  6261. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6262. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6263. const std::string &body, const std::string &content_type,
  6264. ContentReceiver receiver, DownloadProgress progress) {
  6265. return cli.Put(path, headers, body, content_type, receiver, progress);
  6266. });
  6267. }
  6268. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6269. #ifdef CPPHTTPLIB_SSL_ENABLED
  6270. using ClientT = SSLClient;
  6271. #else
  6272. using ClientT = Client;
  6273. #endif
  6274. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6275. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6276. const std::string &body, const std::string &content_type,
  6277. ContentReceiver receiver, DownloadProgress progress) {
  6278. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6279. });
  6280. }
  6281. template <typename ClientType>
  6282. void TestWithHeadersAndContentReceiverError(
  6283. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6284. const Headers &, const std::string &,
  6285. const std::string &, ContentReceiver)>
  6286. request_func) {
  6287. Headers headers;
  6288. headers.emplace("X-Error-Test", "true");
  6289. std::string received_body;
  6290. auto receiver_failed = false;
  6291. auto res =
  6292. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6293. [&](const char *data, size_t data_length) {
  6294. received_body.append(data, data_length);
  6295. receiver_failed = true;
  6296. return false;
  6297. });
  6298. ASSERT_FALSE(res);
  6299. EXPECT_TRUE(receiver_failed);
  6300. }
  6301. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6302. #ifdef CPPHTTPLIB_SSL_ENABLED
  6303. using ClientT = SSLClient;
  6304. #else
  6305. using ClientT = Client;
  6306. #endif
  6307. TestWithHeadersAndContentReceiverError<ClientT>(
  6308. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6309. const std::string &body, const std::string &content_type,
  6310. ContentReceiver receiver) {
  6311. return cli.Post(path, headers, body, content_type, receiver);
  6312. });
  6313. }
  6314. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6315. #ifdef CPPHTTPLIB_SSL_ENABLED
  6316. using ClientT = SSLClient;
  6317. #else
  6318. using ClientT = Client;
  6319. #endif
  6320. TestWithHeadersAndContentReceiverError<ClientT>(
  6321. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6322. const std::string &body, const std::string &content_type,
  6323. ContentReceiver receiver) {
  6324. return cli.Put(path, headers, body, content_type, receiver);
  6325. });
  6326. }
  6327. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6328. #ifdef CPPHTTPLIB_SSL_ENABLED
  6329. using ClientT = SSLClient;
  6330. #else
  6331. using ClientT = Client;
  6332. #endif
  6333. TestWithHeadersAndContentReceiverError<ClientT>(
  6334. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6335. const std::string &body, const std::string &content_type,
  6336. ContentReceiver receiver) {
  6337. return cli.Patch(path, headers, body, content_type, receiver);
  6338. });
  6339. }
  6340. TEST_F(ServerTest, PostQueryStringAndBody) {
  6341. auto res =
  6342. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. ASSERT_EQ(StatusCode::OK_200, res->status);
  6345. }
  6346. TEST_F(ServerTest, HTTP2Magic) {
  6347. Request req;
  6348. req.method = "PRI";
  6349. req.path = "*";
  6350. req.body = "SM";
  6351. auto res = std::make_shared<Response>();
  6352. auto error = Error::Success;
  6353. auto ret = cli_.send(req, *res, error);
  6354. ASSERT_TRUE(ret);
  6355. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6356. }
  6357. TEST_F(ServerTest, KeepAlive) {
  6358. auto res = cli_.Get("/hi");
  6359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6360. EXPECT_EQ(StatusCode::OK_200, res->status);
  6361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6362. EXPECT_EQ("Hello World!", res->body);
  6363. res = cli_.Get("/hi");
  6364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6365. EXPECT_EQ(StatusCode::OK_200, res->status);
  6366. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6367. EXPECT_EQ("Hello World!", res->body);
  6368. res = cli_.Get("/hi");
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::OK_200, res->status);
  6371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6372. EXPECT_EQ("Hello World!", res->body);
  6373. res = cli_.Get("/not-exist");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6376. res = cli_.Post("/empty", "", "text/plain");
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6380. EXPECT_EQ("empty", res->body);
  6381. EXPECT_EQ("close", res->get_header_value("Connection"));
  6382. res = cli_.Post(
  6383. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6384. "text/plain");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6388. EXPECT_EQ("empty", res->body);
  6389. cli_.set_keep_alive(false);
  6390. res = cli_.Get("/last-request");
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. EXPECT_EQ("close", res->get_header_value("Connection"));
  6394. }
  6395. TEST_F(ServerTest, TooManyRedirect) {
  6396. cli_.set_follow_location(true);
  6397. auto res = cli_.Get("/redirect/0");
  6398. ASSERT_TRUE(!res);
  6399. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6400. }
  6401. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6402. Request req;
  6403. req.method = "FOOBAR";
  6404. req.path = "/hi";
  6405. cli_.set_keep_alive(true);
  6406. auto res = cli_.send(req);
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6409. EXPECT_EQ("close", res->get_header_value("Connection"));
  6410. EXPECT_FALSE(cli_.is_socket_open());
  6411. }
  6412. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6413. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6414. TEST_F(ServerTest, Gzip) {
  6415. Headers headers;
  6416. headers.emplace("Accept-Encoding", "gzip, deflate");
  6417. auto res = cli_.Get("/compress", headers);
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6421. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6423. "7890123456789012345678901234567890",
  6424. res->body);
  6425. EXPECT_EQ(StatusCode::OK_200, res->status);
  6426. }
  6427. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6428. Headers headers;
  6429. headers.emplace("Accept-Encoding", "gzip, deflate");
  6430. auto res = cli_.Get("/compress-with-charset", headers);
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6433. EXPECT_EQ("application/json; charset=utf-8",
  6434. res->get_header_value("Content-Type"));
  6435. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6436. "7890123456789012345678901234567890",
  6437. res->body);
  6438. EXPECT_EQ(StatusCode::OK_200, res->status);
  6439. }
  6440. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6441. Headers headers;
  6442. headers.emplace("Accept-Encoding", "");
  6443. auto res = cli_.Get("/compress", headers);
  6444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6445. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6446. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6447. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6448. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6449. "7890123456789012345678901234567890",
  6450. res->body);
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. }
  6453. TEST_F(ServerTest, GzipWithContentReceiver) {
  6454. Headers headers;
  6455. headers.emplace("Accept-Encoding", "gzip, deflate");
  6456. std::string body;
  6457. auto res = cli_.Get("/compress", headers,
  6458. [&](const char *data, uint64_t data_length) {
  6459. EXPECT_EQ(100U, data_length);
  6460. body.append(data, data_length);
  6461. return true;
  6462. });
  6463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6464. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6465. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6466. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6467. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6468. "7890123456789012345678901234567890",
  6469. body);
  6470. EXPECT_EQ(StatusCode::OK_200, res->status);
  6471. }
  6472. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6473. Headers headers;
  6474. headers.emplace("Accept-Encoding", "gzip, deflate");
  6475. cli_.set_decompress(false);
  6476. auto res = cli_.Get("/compress", headers);
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6479. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6480. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6481. EXPECT_EQ(33U, res->body.size());
  6482. EXPECT_EQ(StatusCode::OK_200, res->status);
  6483. }
  6484. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6485. Headers headers;
  6486. headers.emplace("Accept-Encoding", "");
  6487. std::string body;
  6488. auto res = cli_.Get("/compress", headers,
  6489. [&](const char *data, uint64_t data_length) {
  6490. EXPECT_EQ(100U, data_length);
  6491. body.append(data, data_length);
  6492. return true;
  6493. });
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6496. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6497. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6498. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6499. "7890123456789012345678901234567890",
  6500. body);
  6501. EXPECT_EQ(StatusCode::OK_200, res->status);
  6502. }
  6503. TEST_F(ServerTest, NoGzip) {
  6504. Headers headers;
  6505. headers.emplace("Accept-Encoding", "gzip, deflate");
  6506. auto res = cli_.Get("/nocompress", headers);
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6509. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6510. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6511. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6512. "7890123456789012345678901234567890",
  6513. res->body);
  6514. EXPECT_EQ(StatusCode::OK_200, res->status);
  6515. }
  6516. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6517. Headers headers;
  6518. headers.emplace("Accept-Encoding", "gzip, deflate");
  6519. std::string body;
  6520. auto res = cli_.Get("/nocompress", headers,
  6521. [&](const char *data, uint64_t data_length) {
  6522. EXPECT_EQ(100U, data_length);
  6523. body.append(data, data_length);
  6524. return true;
  6525. });
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6528. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6529. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6530. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6531. "7890123456789012345678901234567890",
  6532. body);
  6533. EXPECT_EQ(StatusCode::OK_200, res->status);
  6534. }
  6535. TEST_F(ServerTest, MultipartFormDataGzip) {
  6536. UploadFormDataItems items = {
  6537. {"key1", "test", "", ""},
  6538. {"key2", "--abcdefg123", "", ""},
  6539. };
  6540. cli_.set_compress(true);
  6541. auto res = cli_.Post("/compress-multipart", items);
  6542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6543. EXPECT_EQ(StatusCode::OK_200, res->status);
  6544. }
  6545. #endif
  6546. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6547. TEST_F(ServerTest, Brotli) {
  6548. Headers headers;
  6549. headers.emplace("Accept-Encoding", "br");
  6550. auto res = cli_.Get("/compress", headers);
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6554. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6555. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6556. "7890123456789012345678901234567890",
  6557. res->body);
  6558. EXPECT_EQ(StatusCode::OK_200, res->status);
  6559. }
  6560. #endif
  6561. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6562. TEST_F(ServerTest, Zstd) {
  6563. Headers headers;
  6564. headers.emplace("Accept-Encoding", "zstd");
  6565. auto res = cli_.Get("/compress", headers);
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6569. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6571. "7890123456789012345678901234567890",
  6572. res->body);
  6573. EXPECT_EQ(StatusCode::OK_200, res->status);
  6574. }
  6575. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6576. Headers headers;
  6577. headers.emplace("Accept-Encoding", "");
  6578. auto res = cli_.Get("/compress", headers);
  6579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6580. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6582. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6583. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6584. "7890123456789012345678901234567890",
  6585. res->body);
  6586. EXPECT_EQ(StatusCode::OK_200, res->status);
  6587. }
  6588. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6589. Headers headers;
  6590. headers.emplace("Accept-Encoding", "zstd");
  6591. std::string body;
  6592. auto res = cli_.Get("/compress", headers,
  6593. [&](const char *data, uint64_t data_length) {
  6594. EXPECT_EQ(100U, data_length);
  6595. body.append(data, data_length);
  6596. return true;
  6597. });
  6598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6599. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6601. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6602. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6603. "7890123456789012345678901234567890",
  6604. body);
  6605. EXPECT_EQ(StatusCode::OK_200, res->status);
  6606. }
  6607. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6608. Headers headers;
  6609. headers.emplace("Accept-Encoding", "zstd");
  6610. cli_.set_decompress(false);
  6611. auto res = cli_.Get("/compress", headers);
  6612. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6613. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6614. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6615. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6617. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6618. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6619. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6620. EXPECT_EQ(StatusCode::OK_200, res->status);
  6621. ASSERT_EQ(26U, res->body.size());
  6622. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6623. 0);
  6624. }
  6625. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6626. Headers headers;
  6627. headers.emplace("Accept-Encoding", "");
  6628. std::string body;
  6629. auto res = cli_.Get("/compress", headers,
  6630. [&](const char *data, uint64_t data_length) {
  6631. EXPECT_EQ(100U, data_length);
  6632. body.append(data, data_length);
  6633. return true;
  6634. });
  6635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6636. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6637. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6638. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6639. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6640. "7890123456789012345678901234567890",
  6641. body);
  6642. EXPECT_EQ(StatusCode::OK_200, res->status);
  6643. }
  6644. TEST_F(ServerTest, NoZstd) {
  6645. Headers headers;
  6646. headers.emplace("Accept-Encoding", "zstd");
  6647. auto res = cli_.Get("/nocompress", headers);
  6648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6649. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6650. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6651. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6652. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6653. "7890123456789012345678901234567890",
  6654. res->body);
  6655. EXPECT_EQ(StatusCode::OK_200, res->status);
  6656. }
  6657. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6658. Headers headers;
  6659. headers.emplace("Accept-Encoding", "zstd");
  6660. std::string body;
  6661. auto res = cli_.Get("/nocompress", headers,
  6662. [&](const char *data, uint64_t data_length) {
  6663. EXPECT_EQ(100U, data_length);
  6664. body.append(data, data_length);
  6665. return true;
  6666. });
  6667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6668. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6669. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6670. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6671. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6672. "7890123456789012345678901234567890",
  6673. body);
  6674. EXPECT_EQ(StatusCode::OK_200, res->status);
  6675. }
  6676. // TODO: How to enable zstd ??
  6677. TEST_F(ServerTest, MultipartFormDataZstd) {
  6678. UploadFormDataItems items = {
  6679. {"key1", "test", "", ""},
  6680. {"key2", "--abcdefg123", "", ""},
  6681. };
  6682. Headers headers;
  6683. headers.emplace("Accept-Encoding", "zstd");
  6684. cli_.set_compress(true);
  6685. auto res = cli_.Post("/compress-multipart", headers, items);
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::OK_200, res->status);
  6688. }
  6689. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6690. Headers headers;
  6691. headers.emplace("Accept-Encoding", "zstd");
  6692. cli_.set_compress(true);
  6693. auto res = cli_.Put(
  6694. "/put", headers, 3,
  6695. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6696. sink.os << "PUT";
  6697. return true;
  6698. },
  6699. "text/plain");
  6700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6701. EXPECT_EQ(StatusCode::OK_200, res->status);
  6702. EXPECT_EQ("PUT", res->body);
  6703. }
  6704. // Pre-compression logging tests
  6705. TEST_F(ServerTest, PreCompressionLogging) {
  6706. // Test data for compression (matches the actual /compress endpoint content)
  6707. const std::string test_content =
  6708. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6709. "3456789012345678901234567890";
  6710. // Variables to capture logging data
  6711. std::string pre_compression_body;
  6712. std::string pre_compression_content_type;
  6713. std::string pre_compression_content_encoding;
  6714. std::string post_compression_body;
  6715. std::string post_compression_content_type;
  6716. std::string post_compression_content_encoding;
  6717. // Set up pre-compression logger
  6718. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6719. const Response &res) {
  6720. pre_compression_body = res.body;
  6721. pre_compression_content_type = res.get_header_value("Content-Type");
  6722. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6723. });
  6724. // Set up post-compression logger
  6725. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6726. post_compression_body = res.body;
  6727. post_compression_content_type = res.get_header_value("Content-Type");
  6728. post_compression_content_encoding =
  6729. res.get_header_value("Content-Encoding");
  6730. });
  6731. // Test with gzip compression
  6732. Headers headers;
  6733. headers.emplace("Accept-Encoding", "gzip");
  6734. auto res = cli_.Get("/compress", headers);
  6735. // Verify response was compressed
  6736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6737. EXPECT_EQ(StatusCode::OK_200, res->status);
  6738. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6739. // Verify pre-compression logger captured uncompressed content
  6740. EXPECT_EQ(test_content, pre_compression_body);
  6741. EXPECT_EQ("text/plain", pre_compression_content_type);
  6742. EXPECT_TRUE(pre_compression_content_encoding
  6743. .empty()); // No encoding header before compression
  6744. // Verify post-compression logger captured compressed content
  6745. EXPECT_NE(test_content,
  6746. post_compression_body); // Should be different after compression
  6747. EXPECT_EQ("text/plain", post_compression_content_type);
  6748. EXPECT_EQ("gzip", post_compression_content_encoding);
  6749. // Verify compressed content is smaller
  6750. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6751. }
  6752. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6753. const std::string test_content =
  6754. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6755. "3456789012345678901234567890";
  6756. std::string pre_compression_body;
  6757. std::string post_compression_body;
  6758. svr_.set_pre_compression_logger(
  6759. [&](const Request & /*req*/, const Response &res) {
  6760. pre_compression_body = res.body;
  6761. });
  6762. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6763. post_compression_body = res.body;
  6764. });
  6765. Headers headers;
  6766. headers.emplace("Accept-Encoding", "br");
  6767. auto res = cli_.Get("/compress", headers);
  6768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6769. EXPECT_EQ(StatusCode::OK_200, res->status);
  6770. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6771. // Verify pre-compression content is uncompressed
  6772. EXPECT_EQ(test_content, pre_compression_body);
  6773. // Verify post-compression content is compressed
  6774. EXPECT_NE(test_content, post_compression_body);
  6775. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6776. }
  6777. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6778. const std::string test_content =
  6779. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6780. "3456789012345678901234567890";
  6781. std::string pre_compression_body;
  6782. std::string post_compression_body;
  6783. svr_.set_pre_compression_logger(
  6784. [&](const Request & /*req*/, const Response &res) {
  6785. pre_compression_body = res.body;
  6786. });
  6787. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6788. post_compression_body = res.body;
  6789. });
  6790. // Request without compression (use /nocompress endpoint)
  6791. Headers headers;
  6792. auto res = cli_.Get("/nocompress", headers);
  6793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6794. EXPECT_EQ(StatusCode::OK_200, res->status);
  6795. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6796. // Pre-compression logger should not be called when no compression is applied
  6797. EXPECT_TRUE(
  6798. pre_compression_body.empty()); // Pre-compression logger not called
  6799. EXPECT_EQ(
  6800. test_content,
  6801. post_compression_body); // Post-compression logger captures final content
  6802. }
  6803. TEST_F(ServerTest, LoggerSeesContentLength) {
  6804. size_t logged_content_length = 0;
  6805. std::string logged_content_length_header;
  6806. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6807. logged_content_length = res.content_length_;
  6808. logged_content_length_header = res.get_header_value("Content-Length");
  6809. });
  6810. auto res = cli_.Get("/nocompress");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. EXPECT_EQ(StatusCode::OK_200, res->status);
  6813. EXPECT_EQ(res->body.size(), logged_content_length);
  6814. EXPECT_EQ(std::to_string(logged_content_length),
  6815. logged_content_length_header);
  6816. }
  6817. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6818. const std::string test_content =
  6819. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6820. "3456789012345678901234567890";
  6821. std::string pre_compression_body;
  6822. bool pre_logger_called = false;
  6823. // Set only pre-compression logger
  6824. svr_.set_pre_compression_logger(
  6825. [&](const Request & /*req*/, const Response &res) {
  6826. pre_compression_body = res.body;
  6827. pre_logger_called = true;
  6828. });
  6829. Headers headers;
  6830. headers.emplace("Accept-Encoding", "gzip");
  6831. auto res = cli_.Get("/compress", headers);
  6832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6835. // Verify pre-compression logger was called
  6836. EXPECT_TRUE(pre_logger_called);
  6837. EXPECT_EQ(test_content, pre_compression_body);
  6838. }
  6839. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6840. {
  6841. // Test with Expect: 100-continue header - success case
  6842. // Server returns 100 Continue, client sends body, server returns 200 OK
  6843. Request req;
  6844. req.method = "POST";
  6845. req.path = "/post-large";
  6846. req.set_header("Expect", "100-continue");
  6847. req.body = LARGE_DATA;
  6848. Response res;
  6849. auto error = Error::Success;
  6850. cli_.set_keep_alive(true);
  6851. auto ret = cli_.send(req, res, error);
  6852. EXPECT_TRUE(ret);
  6853. EXPECT_EQ(StatusCode::OK_200, res.status);
  6854. EXPECT_EQ(LARGE_DATA, res.body);
  6855. }
  6856. {
  6857. // Test with Expect: 100-continue header - error case
  6858. // Client should not send the body when server returns an error
  6859. Request req;
  6860. req.method = "POST";
  6861. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6862. req.set_header("Expect", "100-continue");
  6863. req.body = LARGE_DATA;
  6864. Response res;
  6865. auto error = Error::Success;
  6866. auto start = std::chrono::high_resolution_clock::now();
  6867. cli_.set_keep_alive(true);
  6868. auto ret = cli_.send(req, res, error);
  6869. auto end = std::chrono::high_resolution_clock::now();
  6870. auto elapsed =
  6871. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6872. .count();
  6873. // With Expect: 100-continue, request completes successfully but with error
  6874. EXPECT_TRUE(ret);
  6875. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6876. EXPECT_EQ("close", res.get_header_value("Connection"));
  6877. EXPECT_FALSE(cli_.is_socket_open());
  6878. EXPECT_LE(elapsed, 2000);
  6879. }
  6880. {
  6881. // Send an extra GET request to ensure error recovery without hanging
  6882. Request req;
  6883. req.method = "GET";
  6884. req.path = "/hi";
  6885. auto start = std::chrono::high_resolution_clock::now();
  6886. auto res = cli_.send(req);
  6887. auto end = std::chrono::high_resolution_clock::now();
  6888. auto elapsed =
  6889. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6890. .count();
  6891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6892. EXPECT_EQ(StatusCode::OK_200, res->status);
  6893. EXPECT_EQ("Hello World!", res->body);
  6894. EXPECT_LE(elapsed, 500);
  6895. }
  6896. }
  6897. TEST(ZstdDecompressor, ChunkedDecompression) {
  6898. std::string data;
  6899. for (size_t i = 0; i < 32 * 1024; ++i) {
  6900. data.push_back(static_cast<char>('a' + i % 26));
  6901. }
  6902. std::string compressed_data;
  6903. {
  6904. httplib::detail::zstd_compressor compressor;
  6905. bool result = compressor.compress(
  6906. data.data(), data.size(),
  6907. /*last=*/true,
  6908. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6909. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6910. compressed_data_size);
  6911. return true;
  6912. });
  6913. ASSERT_TRUE(result);
  6914. }
  6915. std::string decompressed_data;
  6916. {
  6917. httplib::detail::zstd_decompressor decompressor;
  6918. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6919. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6920. size_t chunk_size = 130;
  6921. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6922. chunk_begin += chunk_size) {
  6923. size_t current_chunk_size =
  6924. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6925. bool result = decompressor.decompress(
  6926. compressed_data.data() + chunk_begin, current_chunk_size,
  6927. [&](const char *decompressed_data_chunk,
  6928. size_t decompressed_data_chunk_size) {
  6929. decompressed_data.insert(decompressed_data.size(),
  6930. decompressed_data_chunk,
  6931. decompressed_data_chunk_size);
  6932. return true;
  6933. });
  6934. ASSERT_TRUE(result);
  6935. }
  6936. }
  6937. ASSERT_EQ(data, decompressed_data);
  6938. }
  6939. TEST(ZstdDecompressor, Decompress) {
  6940. std::string original_text = "Compressed with ZSTD";
  6941. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6942. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6943. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6944. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6945. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6946. std::string decompressed_data;
  6947. {
  6948. httplib::detail::zstd_decompressor decompressor;
  6949. bool result = decompressor.decompress(
  6950. compressed_data.data(), compressed_data.size(),
  6951. [&](const char *decompressed_data_chunk,
  6952. size_t decompressed_data_chunk_size) {
  6953. decompressed_data.insert(decompressed_data.size(),
  6954. decompressed_data_chunk,
  6955. decompressed_data_chunk_size);
  6956. return true;
  6957. });
  6958. ASSERT_TRUE(result);
  6959. }
  6960. ASSERT_EQ(original_text, decompressed_data);
  6961. }
  6962. #endif
  6963. // Sends a raw request to a server listening at HOST:PORT.
  6964. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6965. std::string *resp = nullptr) {
  6966. auto error = Error::Success;
  6967. auto client_sock = detail::create_client_socket(
  6968. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6969. /*connection_timeout_sec=*/5, 0,
  6970. /*read_timeout_sec=*/5, 0,
  6971. /*write_timeout_sec=*/5, 0, std::string(), error);
  6972. if (client_sock == INVALID_SOCKET) { return false; }
  6973. auto ret = detail::process_client_socket(
  6974. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6975. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6976. if (req.size() !=
  6977. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6978. return false;
  6979. }
  6980. char buf[512];
  6981. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6982. while (line_reader.getline()) {
  6983. if (resp) { *resp += line_reader.ptr(); }
  6984. }
  6985. return true;
  6986. });
  6987. detail::close_socket(client_sock);
  6988. return ret;
  6989. }
  6990. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6991. Server svr;
  6992. std::string header_value;
  6993. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6994. header_value = req.get_header_value("foo");
  6995. res.set_content("ok", "text/plain");
  6996. });
  6997. thread t = thread([&] { svr.listen(HOST, PORT); });
  6998. auto se = detail::scope_exit([&] {
  6999. svr.stop();
  7000. t.join();
  7001. ASSERT_FALSE(svr.is_running());
  7002. });
  7003. svr.wait_until_ready();
  7004. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7005. // like characters are not treated the same - use vertical tab and escape.
  7006. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7007. "foo: \t \v bar \x1B\t \r\n"
  7008. "Connection: close\r\n"
  7009. "\r\n";
  7010. std::string res;
  7011. ASSERT_TRUE(send_request(5, req, &res));
  7012. EXPECT_EQ(header_value, "");
  7013. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7014. }
  7015. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7016. Server svr;
  7017. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7018. auto i = new int(0);
  7019. res.set_header("Trailer", "X-Safe, X-Reflected");
  7020. res.set_chunked_content_provider(
  7021. "text/plain",
  7022. [i](size_t /*offset*/, DataSink &sink) {
  7023. if (*i == 0) {
  7024. sink.os << "body";
  7025. } else {
  7026. Headers trailer;
  7027. // A valid trailer that must survive.
  7028. trailer.emplace("X-Safe", "safe");
  7029. // Attacker-controlled value carrying CR/LF (response splitting).
  7030. trailer.emplace("X-Reflected",
  7031. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7032. // Attacker-controlled name carrying CR/LF.
  7033. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7034. sink.done_with_trailer(trailer);
  7035. }
  7036. (*i)++;
  7037. return true;
  7038. },
  7039. [i](bool /*success*/) { delete i; });
  7040. });
  7041. thread t = thread([&] { svr.listen(HOST, PORT); });
  7042. auto se = detail::scope_exit([&] {
  7043. svr.stop();
  7044. t.join();
  7045. ASSERT_FALSE(svr.is_running());
  7046. });
  7047. svr.wait_until_ready();
  7048. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7049. "Host: " + HOST +
  7050. "\r\n"
  7051. "Connection: close\r\n"
  7052. "\r\n";
  7053. std::string res;
  7054. ASSERT_TRUE(send_request(5, req, &res));
  7055. // The injected fields must not appear anywhere in the raw response.
  7056. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7057. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7058. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7059. // Invalid trailers are dropped entirely, matching set_header().
  7060. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7061. // The valid trailer still passes through.
  7062. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7063. }
  7064. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7065. Server svr;
  7066. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7067. // res.headers is a public field an application can populate directly,
  7068. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7069. // A valid header that must survive.
  7070. res.headers.emplace("X-Safe", "safe");
  7071. // Attacker-controlled value carrying CR/LF (response splitting).
  7072. res.headers.emplace("X-Reflected",
  7073. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7074. // Attacker-controlled name carrying CR/LF.
  7075. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7076. res.set_content("body", "text/plain");
  7077. });
  7078. thread t = thread([&] { svr.listen(HOST, PORT); });
  7079. auto se = detail::scope_exit([&] {
  7080. svr.stop();
  7081. t.join();
  7082. ASSERT_FALSE(svr.is_running());
  7083. });
  7084. svr.wait_until_ready();
  7085. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7086. "Host: " + HOST +
  7087. "\r\n"
  7088. "Connection: close\r\n"
  7089. "\r\n";
  7090. std::string res;
  7091. ASSERT_TRUE(send_request(5, req, &res));
  7092. // The injected fields must not appear anywhere in the raw response.
  7093. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7094. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7095. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7096. // Invalid headers are dropped entirely, matching set_header().
  7097. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7098. // The valid header still passes through.
  7099. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7100. }
  7101. // Forward declaration: in split builds split.py strips `inline` and moves the
  7102. // definition into httplib.cc, so detail::write_request_line is not visible from
  7103. // the public httplib.h. Re-declaring it here lets the tests link against the
  7104. // symbol in both header-only and split builds.
  7105. namespace httplib {
  7106. namespace detail {
  7107. ssize_t write_request_line(Stream &strm, const std::string &method,
  7108. const std::string &path);
  7109. } // namespace detail
  7110. } // namespace httplib
  7111. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7112. // A well-formed target is written verbatim.
  7113. {
  7114. detail::BufferStream strm;
  7115. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7116. EXPECT_GT(n, 0);
  7117. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7118. }
  7119. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7120. // otherwise it splits the request line and injects a header or a whole
  7121. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7122. // when path encoding is disabled.
  7123. const std::string evil_targets[] = {
  7124. "/a\r\nInjected: pwned",
  7125. "/a\rInjected",
  7126. "/a\nInjected",
  7127. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7128. };
  7129. for (const auto &evil : evil_targets) {
  7130. detail::BufferStream strm;
  7131. auto n = detail::write_request_line(strm, "GET", evil);
  7132. EXPECT_LT(n, 0);
  7133. EXPECT_TRUE(strm.get_buffer().empty());
  7134. }
  7135. }
  7136. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7137. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7138. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7139. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7140. // client must fail cleanly with Error::Write instead of putting a
  7141. // request-line-less, header-injecting request on the wire.
  7142. Server svr;
  7143. svr.Get("/a", [](const Request &, Response &res) {
  7144. res.set_content("ok", "text/plain");
  7145. });
  7146. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7147. auto se = detail::scope_exit([&] {
  7148. svr.stop();
  7149. thread.join();
  7150. ASSERT_FALSE(svr.is_running());
  7151. });
  7152. svr.wait_until_ready();
  7153. {
  7154. Client cli(HOST, PORT);
  7155. cli.set_path_encode(false);
  7156. // The request is rejected before anything is written, so the connection
  7157. // stays silent and the subsequent response read would otherwise block for
  7158. // the full default read timeout. Shorten it -- the assertion is on the
  7159. // error, not the timeout.
  7160. cli.set_read_timeout(1, 0);
  7161. auto res = cli.Get("/a\r\nInjected: pwned");
  7162. EXPECT_FALSE(res);
  7163. EXPECT_EQ(Error::Write, res.error());
  7164. }
  7165. }
  7166. // Sends a raw request and verifies that there isn't a crash or exception.
  7167. static void test_raw_request(const std::string &req,
  7168. std::string *out = nullptr) {
  7169. Server svr;
  7170. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7171. res.set_content("ok", "text/plain");
  7172. });
  7173. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7174. res.set_content("ok", "text/plain");
  7175. });
  7176. svr.Get("/header_field_value_check",
  7177. [&](const Request & /*req*/, Response &res) {
  7178. res.set_content("ok", "text/plain");
  7179. });
  7180. // Server read timeout must be longer than the client read timeout for the
  7181. // bug to reproduce, probably to force the server to process a request
  7182. // without a trailing blank line.
  7183. const time_t client_read_timeout_sec = 1;
  7184. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7185. bool listen_thread_ok = false;
  7186. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7187. auto se = detail::scope_exit([&] {
  7188. svr.stop();
  7189. t.join();
  7190. ASSERT_FALSE(svr.is_running());
  7191. EXPECT_TRUE(listen_thread_ok);
  7192. });
  7193. svr.wait_until_ready();
  7194. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7195. }
  7196. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7197. // A certain header line causes an exception if the header property is parsed
  7198. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7199. test_raw_request(
  7200. "GET /hi HTTP/1.1\r\n"
  7201. " : "
  7202. " "
  7203. " ");
  7204. }
  7205. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7206. // A certain header line causes an exception if the header property *name* is
  7207. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7208. // greedy matcher and requires backtracking when there are a lot of ":"
  7209. // characters.
  7210. // This occurs with libc++ but not libstdc++.
  7211. test_raw_request(
  7212. "GET /hi HTTP/1.1\r\n"
  7213. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7214. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7215. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7216. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7217. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7218. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7219. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7220. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7221. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7222. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7223. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7224. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7225. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7226. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7227. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7228. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7229. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7230. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7231. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7232. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7233. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7234. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7235. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7236. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7237. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7238. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7239. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7240. "&&&%%%");
  7241. }
  7242. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7243. // Make sure this doesn't crash the server.
  7244. // In a previous version of the header line regex, the "\r" rendered the line
  7245. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7246. // a new position where the leading white space ended and the field value
  7247. // began.
  7248. // The crash occurs with libc++ but not libstdc++.
  7249. test_raw_request("GET /hi HTTP/1.1\r\n"
  7250. "a:" +
  7251. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7252. "\r\n"
  7253. "\r\n");
  7254. }
  7255. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7256. std::string out;
  7257. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7258. "Content-Type: text/plain\r\n"
  7259. "Transfer-Encoding: chunked\r\n"
  7260. "\r\n"
  7261. "nothex\r\n",
  7262. &out);
  7263. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7264. }
  7265. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7266. std::string out;
  7267. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7268. "Content-Type: text/plain\r\n"
  7269. "Transfer-Encoding: chunked\r\n"
  7270. "\r\n"
  7271. "3\r\n"
  7272. "xyz\r\n"
  7273. "NaN\r\n",
  7274. &out);
  7275. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7276. }
  7277. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7278. std::string out;
  7279. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7280. "Content-Type: text/plain\r\n"
  7281. "Transfer-Encoding: chunked\r\n"
  7282. "\r\n"
  7283. // Length is too large for 64 bits.
  7284. "1ffffffffffffffff\r\n"
  7285. "xyz\r\n",
  7286. &out);
  7287. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7288. }
  7289. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7290. test_raw_request("GET /hi HTTP/1.1\r\n"
  7291. "Content-Type: text/plain\r\n\r");
  7292. }
  7293. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7294. std::string out;
  7295. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7296. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7297. }
  7298. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7299. Server svr;
  7300. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7301. EXPECT_TRUE(!req.remote_addr.empty());
  7302. });
  7303. thread t = thread([&] { svr.listen(HOST, PORT); });
  7304. auto se = detail::scope_exit([&] {
  7305. svr.stop();
  7306. t.join();
  7307. ASSERT_FALSE(svr.is_running());
  7308. });
  7309. svr.wait_until_ready();
  7310. // Send an invalid request line to trigger Bad Request
  7311. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7312. std::string out;
  7313. ASSERT_TRUE(send_request(5, bad_req, &out));
  7314. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7315. }
  7316. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7317. std::string out;
  7318. std::string request(
  7319. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7320. test_raw_request(request, &out);
  7321. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7322. }
  7323. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7324. std::string out;
  7325. std::string request(
  7326. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7327. test_raw_request(request, &out);
  7328. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7329. }
  7330. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7331. std::string out;
  7332. std::string request(
  7333. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7334. test_raw_request(request, &out);
  7335. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7336. }
  7337. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7338. std::string out;
  7339. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7340. "Test: \r\n\r\n",
  7341. &out);
  7342. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7343. }
  7344. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7345. Server svr;
  7346. std::string x_custom;
  7347. std::string cookie;
  7348. std::string xff;
  7349. std::string x_unicode;
  7350. std::string x_iis;
  7351. svr.Get("/check", [&](const Request &req, Response &res) {
  7352. x_custom = req.get_header_value("X-Custom");
  7353. cookie = req.get_header_value("Cookie");
  7354. xff = req.get_header_value("X-Forwarded-For");
  7355. x_unicode = req.get_header_value("X-Unicode");
  7356. x_iis = req.get_header_value("X-IIS");
  7357. res.set_content("ok", "text/plain");
  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 = "GET /check HTTP/1.1\r\n"
  7367. "Host: localhost\r\n"
  7368. "X-Custom: a%0D%0AInjected: b\r\n"
  7369. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7370. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7371. "X-Unicode: %E3%81%82\r\n"
  7372. "X-IIS: %u00E9\r\n"
  7373. "Connection: close\r\n"
  7374. "\r\n";
  7375. std::string res;
  7376. ASSERT_TRUE(send_request(5, req, &res));
  7377. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7378. // Every value must be returned verbatim (wire form), with no decoding.
  7379. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7380. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7381. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7382. EXPECT_EQ("%E3%81%82", x_unicode);
  7383. EXPECT_EQ("%u00E9", x_iis);
  7384. }
  7385. // Applications that previously relied on automatic percent-decoding can
  7386. // reproduce the old behavior by explicitly calling decode_path_component()
  7387. // or, for RFC 3986 conformance, decode_uri_component().
  7388. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7389. Server svr;
  7390. std::string decoded;
  7391. svr.Get("/check", [&](const Request &req, Response &res) {
  7392. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7393. res.set_content("ok", "text/plain");
  7394. });
  7395. thread t = thread([&] { svr.listen(HOST, PORT); });
  7396. auto se = detail::scope_exit([&] {
  7397. svr.stop();
  7398. t.join();
  7399. ASSERT_FALSE(svr.is_running());
  7400. });
  7401. svr.wait_until_ready();
  7402. const std::string req = "GET /check HTTP/1.1\r\n"
  7403. "Host: localhost\r\n"
  7404. "X-Custom: hello%20world\r\n"
  7405. "Connection: close\r\n"
  7406. "\r\n";
  7407. std::string res;
  7408. ASSERT_TRUE(send_request(5, req, &res));
  7409. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7410. EXPECT_EQ("hello world", decoded);
  7411. }
  7412. // Regression test for #2033. Browsers send Referer values that include
  7413. // percent-encoded characters such as %0A inside the URL. Decoding the
  7414. // header value would either trip the post-decode CR/LF/NUL guard (the
  7415. // original bug, returning 400) or, after that guard was relaxed, silently
  7416. // store a literal LF — both unacceptable. The wire form must round-trip.
  7417. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7418. Server svr;
  7419. std::string referer;
  7420. svr.Get("/check", [&](const Request &req, Response &res) {
  7421. referer = req.get_header_value("Referer");
  7422. res.set_content("ok", "text/plain");
  7423. });
  7424. thread t = thread([&] { svr.listen(HOST, PORT); });
  7425. auto se = detail::scope_exit([&] {
  7426. svr.stop();
  7427. t.join();
  7428. ASSERT_FALSE(svr.is_running());
  7429. });
  7430. svr.wait_until_ready();
  7431. const std::string req = "GET /check HTTP/1.1\r\n"
  7432. "Host: localhost\r\n"
  7433. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7434. "Connection: close\r\n"
  7435. "\r\n";
  7436. std::string res;
  7437. ASSERT_TRUE(send_request(5, req, &res));
  7438. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7439. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7440. }
  7441. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7442. Server svr;
  7443. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7444. res.set_header("Cache-Control", "no-cache");
  7445. res.set_chunked_content_provider(
  7446. "text/event-stream", [](size_t offset, DataSink &sink) {
  7447. std::string s = "data:";
  7448. s += std::to_string(offset);
  7449. s += "\n\n";
  7450. auto ret = sink.write(s.data(), s.size());
  7451. EXPECT_TRUE(ret);
  7452. std::this_thread::sleep_for(std::chrono::seconds(1));
  7453. return true;
  7454. });
  7455. });
  7456. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7457. svr.wait_until_ready();
  7458. Client client(HOST, PORT);
  7459. const Headers headers = {{"Accept", "text/event-stream"}};
  7460. auto get_thread = std::thread([&client, &headers]() {
  7461. auto res = client.Get(
  7462. "/events", headers,
  7463. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7464. });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. get_thread.join();
  7468. listen_thread.join();
  7469. ASSERT_FALSE(svr.is_running());
  7470. });
  7471. // Give GET time to get a few messages.
  7472. std::this_thread::sleep_for(std::chrono::seconds(2));
  7473. }
  7474. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7475. httplib::Server svr;
  7476. svr.Post("/hi",
  7477. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7478. res.status = StatusCode::OK_200;
  7479. });
  7480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7481. svr.wait_until_ready();
  7482. Client cli(HOST, PORT);
  7483. auto res = cli.Post("/hi", "data", "text/plain");
  7484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7485. EXPECT_EQ(StatusCode::OK_200, res->status);
  7486. svr.stop();
  7487. thread.join();
  7488. ASSERT_FALSE(svr.is_running());
  7489. res = cli.Post("/hi", "data", "text/plain");
  7490. ASSERT_FALSE(res);
  7491. }
  7492. TEST(ServerStopTest, ListenFailure) {
  7493. Server svr;
  7494. auto t = thread([&]() {
  7495. auto ret = svr.listen("????", PORT);
  7496. EXPECT_FALSE(ret);
  7497. });
  7498. svr.wait_until_ready();
  7499. svr.stop();
  7500. t.join();
  7501. }
  7502. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7503. TEST(ServerStopTest, Decommision) {
  7504. Server svr;
  7505. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7506. for (int i = 0; i < 4; i++) {
  7507. auto is_even = !(i % 2);
  7508. std::thread t{[&] {
  7509. try {
  7510. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7511. if (is_even) {
  7512. throw std::runtime_error("Some thing that happens to go wrong.");
  7513. }
  7514. svr.listen(HOST, PORT);
  7515. } catch (...) { svr.decommission(); }
  7516. }};
  7517. svr.wait_until_ready();
  7518. // Server is up
  7519. {
  7520. Client cli(HOST, PORT);
  7521. auto res = cli.Get("/hi");
  7522. if (is_even) {
  7523. EXPECT_FALSE(res);
  7524. } else {
  7525. EXPECT_TRUE(res);
  7526. EXPECT_EQ("hi...", res->body);
  7527. }
  7528. }
  7529. svr.stop();
  7530. t.join();
  7531. // Server is down...
  7532. {
  7533. Client cli(HOST, PORT);
  7534. auto res = cli.Get("/hi");
  7535. EXPECT_FALSE(res);
  7536. }
  7537. }
  7538. }
  7539. #endif
  7540. // Helper function for string body upload progress tests
  7541. template <typename SetupHandler, typename ClientCall>
  7542. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7543. ClientCall &&client_call,
  7544. const string &body) {
  7545. Server svr;
  7546. setup_handler(svr);
  7547. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7548. auto se = detail::scope_exit([&] {
  7549. svr.stop();
  7550. t.join();
  7551. });
  7552. svr.wait_until_ready();
  7553. Client cli(HOST, PORT);
  7554. vector<uint64_t> progress_values;
  7555. bool progress_called = false;
  7556. auto res =
  7557. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7558. progress_values.push_back(current);
  7559. progress_called = true;
  7560. return true;
  7561. });
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(200, res->status);
  7564. EXPECT_TRUE(progress_called);
  7565. }
  7566. TEST(UploadProgressTest, PostStringBodyBasic) {
  7567. TestStringBodyUploadProgress(
  7568. [](Server &svr) {
  7569. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7570. res.set_content("received", "text/plain");
  7571. });
  7572. },
  7573. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7574. return cli.Post("/test", body, "text/plain", progress_callback);
  7575. },
  7576. "test data for upload progress");
  7577. }
  7578. TEST(UploadProgressTest, PutStringBodyBasic) {
  7579. TestStringBodyUploadProgress(
  7580. [](Server &svr) {
  7581. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7582. res.set_content("put received", "text/plain");
  7583. });
  7584. },
  7585. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7586. return cli.Put("/test", body, "text/plain", progress_callback);
  7587. },
  7588. "put test data for upload progress");
  7589. }
  7590. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7591. TestStringBodyUploadProgress(
  7592. [](Server &svr) {
  7593. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7594. res.set_content("patch received", "text/plain");
  7595. });
  7596. },
  7597. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7598. return cli.Patch("/test", body, "text/plain", progress_callback);
  7599. },
  7600. "patch test data for upload progress");
  7601. }
  7602. // Helper function for content provider upload progress tests
  7603. template <typename SetupHandler, typename ClientCall>
  7604. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7605. ClientCall &&client_call) {
  7606. Server svr;
  7607. setup_handler(svr);
  7608. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7609. auto se = detail::scope_exit([&] {
  7610. svr.stop();
  7611. t.join();
  7612. });
  7613. svr.wait_until_ready();
  7614. Client cli(HOST, PORT);
  7615. vector<uint64_t> progress_values;
  7616. auto res =
  7617. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7618. progress_values.push_back(current);
  7619. return true;
  7620. });
  7621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7622. EXPECT_EQ(200, res->status);
  7623. EXPECT_FALSE(progress_values.empty());
  7624. }
  7625. TEST(UploadProgressTest, PostContentProviderProgress) {
  7626. TestContentProviderUploadProgress(
  7627. [](Server &svr) {
  7628. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7629. res.set_content("provider received", "text/plain");
  7630. });
  7631. },
  7632. [](Client &cli, UploadProgress progress_callback) {
  7633. return cli.Post(
  7634. "/test", 10,
  7635. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7636. sink.os << "test data";
  7637. return true;
  7638. },
  7639. "text/plain", progress_callback);
  7640. });
  7641. }
  7642. // Helper function for multipart upload progress tests
  7643. template <typename SetupHandler, typename ClientCall>
  7644. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7645. ClientCall &&client_call,
  7646. const string &endpoint) {
  7647. Server svr;
  7648. setup_handler(svr);
  7649. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7650. auto se = detail::scope_exit([&] {
  7651. svr.stop();
  7652. t.join();
  7653. });
  7654. svr.wait_until_ready();
  7655. Client cli(HOST, PORT);
  7656. vector<uint64_t> progress_values;
  7657. UploadFormDataItems items = {
  7658. {"field1", "value1", "", ""},
  7659. {"field2", "longer value for progress tracking test", "", ""},
  7660. {"file1", "file content data for upload progress", "test.txt",
  7661. "text/plain"}};
  7662. auto res = client_call(cli, endpoint, items,
  7663. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7664. progress_values.push_back(current);
  7665. return true;
  7666. });
  7667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7668. EXPECT_EQ(200, res->status);
  7669. EXPECT_FALSE(progress_values.empty());
  7670. }
  7671. TEST(UploadProgressTest, PostMultipartProgress) {
  7672. TestMultipartUploadProgress(
  7673. [](Server &svr) {
  7674. svr.Post("/multipart", [](const Request &req, Response &res) {
  7675. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7676. res.set_content("multipart received", "text/plain");
  7677. });
  7678. },
  7679. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7680. UploadProgress progress_callback) {
  7681. return cli.Post(endpoint, items, progress_callback);
  7682. },
  7683. "/multipart");
  7684. }
  7685. // Helper function for basic download progress tests
  7686. template <typename SetupHandler, typename ClientCall>
  7687. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7688. ClientCall &&client_call, const string &endpoint,
  7689. size_t expected_content_size) {
  7690. Server svr;
  7691. setup_handler(svr);
  7692. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7693. auto se = detail::scope_exit([&] {
  7694. svr.stop();
  7695. t.join();
  7696. });
  7697. svr.wait_until_ready();
  7698. Client cli(HOST, PORT);
  7699. vector<uint64_t> progress_values;
  7700. auto res = client_call(cli, endpoint,
  7701. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7702. progress_values.push_back(current);
  7703. return true;
  7704. });
  7705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7706. EXPECT_EQ(200, res->status);
  7707. EXPECT_FALSE(progress_values.empty());
  7708. EXPECT_EQ(expected_content_size, res->body.size());
  7709. }
  7710. TEST(DownloadProgressTest, GetBasic) {
  7711. TestBasicDownloadProgress(
  7712. [](Server &svr) {
  7713. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7714. string content(1000, 'D');
  7715. res.set_content(content, "text/plain");
  7716. });
  7717. },
  7718. [](Client &cli, const string &endpoint,
  7719. DownloadProgress progress_callback) {
  7720. return cli.Get(endpoint, progress_callback);
  7721. },
  7722. "/download", 1000u);
  7723. }
  7724. // Helper function for content receiver download progress tests
  7725. template <typename SetupHandler, typename ClientCall>
  7726. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7727. ClientCall &&client_call,
  7728. const string &endpoint,
  7729. size_t expected_content_size) {
  7730. Server svr;
  7731. setup_handler(svr);
  7732. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7733. auto se = detail::scope_exit([&] {
  7734. svr.stop();
  7735. t.join();
  7736. });
  7737. svr.wait_until_ready();
  7738. Client cli(HOST, PORT);
  7739. vector<uint64_t> progress_values;
  7740. string received_body;
  7741. auto res = client_call(
  7742. cli, endpoint,
  7743. [&](const char *data, size_t data_length) -> bool {
  7744. received_body.append(data, data_length);
  7745. return true;
  7746. },
  7747. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7748. progress_values.push_back(current);
  7749. return true;
  7750. });
  7751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7752. EXPECT_EQ(200, res->status);
  7753. EXPECT_FALSE(progress_values.empty());
  7754. EXPECT_EQ(expected_content_size, received_body.size());
  7755. EXPECT_TRUE(res->body.empty());
  7756. }
  7757. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7758. TestContentReceiverDownloadProgress(
  7759. [](Server &svr) {
  7760. svr.Get("/download-receiver",
  7761. [](const Request & /*req*/, Response &res) {
  7762. string content(2000, 'R');
  7763. res.set_content(content, "text/plain");
  7764. });
  7765. },
  7766. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7767. DownloadProgress progress_callback) {
  7768. return cli.Get(endpoint, content_receiver, progress_callback);
  7769. },
  7770. "/download-receiver", 2000u);
  7771. }
  7772. TEST(StreamingTest, NoContentLengthStreaming) {
  7773. Server svr;
  7774. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7775. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7776. if (offset < 6) {
  7777. sink.os << (offset < 3 ? "a" : "b");
  7778. } else {
  7779. sink.done();
  7780. }
  7781. return true;
  7782. });
  7783. });
  7784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7785. auto listen_se = detail::scope_exit([&] {
  7786. svr.stop();
  7787. listen_thread.join();
  7788. ASSERT_FALSE(svr.is_running());
  7789. });
  7790. svr.wait_until_ready();
  7791. Client client(HOST, PORT);
  7792. auto get_thread = std::thread([&client]() {
  7793. std::string s;
  7794. auto res =
  7795. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7796. s += std::string(data, len);
  7797. return true;
  7798. });
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::OK_200, res->status);
  7801. EXPECT_EQ("aaabbb", s);
  7802. });
  7803. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7804. // Give GET time to get a few messages.
  7805. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7806. }
  7807. TEST(MountTest, Unmount) {
  7808. Server svr;
  7809. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7810. auto se = detail::scope_exit([&] {
  7811. svr.stop();
  7812. listen_thread.join();
  7813. ASSERT_FALSE(svr.is_running());
  7814. });
  7815. svr.wait_until_ready();
  7816. Client cli("localhost", PORT);
  7817. svr.set_mount_point("/mount2", "./www2");
  7818. auto res = cli.Get("/");
  7819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7821. res = cli.Get("/mount2/dir/test.html");
  7822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7823. EXPECT_EQ(StatusCode::OK_200, res->status);
  7824. svr.set_mount_point("/", "./www");
  7825. res = cli.Get("/dir/");
  7826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7827. EXPECT_EQ(StatusCode::OK_200, res->status);
  7828. svr.remove_mount_point("/");
  7829. res = cli.Get("/dir/");
  7830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7831. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7832. svr.remove_mount_point("/mount2");
  7833. res = cli.Get("/mount2/dir/test.html");
  7834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7835. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7836. }
  7837. TEST(MountTest, Redicect) {
  7838. Server svr;
  7839. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7840. auto se = detail::scope_exit([&] {
  7841. svr.stop();
  7842. listen_thread.join();
  7843. ASSERT_FALSE(svr.is_running());
  7844. });
  7845. svr.set_mount_point("/", "./www");
  7846. svr.wait_until_ready();
  7847. Client cli("localhost", PORT);
  7848. auto res = cli.Get("/dir/");
  7849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7850. EXPECT_EQ(StatusCode::OK_200, res->status);
  7851. res = cli.Get("/dir");
  7852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7853. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7854. res = cli.Get("/file");
  7855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7856. EXPECT_EQ(StatusCode::OK_200, res->status);
  7857. res = cli.Get("/file/");
  7858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7860. cli.set_follow_location(true);
  7861. res = cli.Get("/dir");
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::OK_200, res->status);
  7864. }
  7865. TEST(MountTest, MultibytesPathName) {
  7866. Server svr;
  7867. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7868. auto se = detail::scope_exit([&] {
  7869. svr.stop();
  7870. listen_thread.join();
  7871. ASSERT_FALSE(svr.is_running());
  7872. });
  7873. svr.set_mount_point("/", "./www");
  7874. svr.wait_until_ready();
  7875. Client cli("localhost", PORT);
  7876. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7878. EXPECT_EQ(StatusCode::OK_200, res->status);
  7879. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7880. }
  7881. #ifdef _WIN32
  7882. // Issue #2435: mmap::open() must succeed even when another handle holds
  7883. // the file open for writing (e.g. an active log file).
  7884. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7885. const char *path = "mmap_concurrent_writer_test.txt";
  7886. const char *content = "hello";
  7887. {
  7888. std::ofstream f(path, std::ios::binary);
  7889. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7890. }
  7891. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7892. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7893. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7894. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7895. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7896. detail::mmap m(path);
  7897. ASSERT_TRUE(m.is_open());
  7898. EXPECT_EQ(strlen(content), m.size());
  7899. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7900. }
  7901. #endif
  7902. TEST(KeepAliveTest, ReadTimeout) {
  7903. Server svr;
  7904. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7905. std::this_thread::sleep_for(std::chrono::seconds(2));
  7906. res.set_content("a", "text/plain");
  7907. });
  7908. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7909. res.set_content("b", "text/plain");
  7910. });
  7911. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7912. auto se = detail::scope_exit([&] {
  7913. svr.stop();
  7914. listen_thread.join();
  7915. ASSERT_FALSE(svr.is_running());
  7916. });
  7917. svr.wait_until_ready();
  7918. Client cli("localhost", PORT);
  7919. cli.set_keep_alive(true);
  7920. cli.set_read_timeout(std::chrono::seconds(1));
  7921. auto resa = cli.Get("/a");
  7922. ASSERT_FALSE(resa);
  7923. EXPECT_EQ(Error::Read, resa.error());
  7924. auto resb = cli.Get("/b");
  7925. ASSERT_TRUE(resb);
  7926. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7927. EXPECT_EQ("b", resb->body);
  7928. }
  7929. TEST(KeepAliveTest, MaxCount) {
  7930. size_t keep_alive_max_count = 3;
  7931. Server svr;
  7932. svr.set_keep_alive_max_count(keep_alive_max_count);
  7933. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7934. res.set_content("Hello World!", "text/plain");
  7935. });
  7936. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7937. auto se = detail::scope_exit([&] {
  7938. svr.stop();
  7939. listen_thread.join();
  7940. ASSERT_FALSE(svr.is_running());
  7941. });
  7942. svr.wait_until_ready();
  7943. Client cli(HOST, PORT);
  7944. cli.set_keep_alive(true);
  7945. for (size_t i = 0; i < 5; i++) {
  7946. auto result = cli.Get("/hi");
  7947. ASSERT_TRUE(result);
  7948. EXPECT_EQ(StatusCode::OK_200, result->status);
  7949. if (i == keep_alive_max_count - 1) {
  7950. EXPECT_EQ("close", result->get_header_value("Connection"));
  7951. } else {
  7952. EXPECT_FALSE(result->has_header("Connection"));
  7953. }
  7954. }
  7955. }
  7956. TEST(KeepAliveTest, Issue1041) {
  7957. Server svr;
  7958. svr.set_keep_alive_timeout(3);
  7959. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7960. res.set_content("Hello World!", "text/plain");
  7961. });
  7962. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7963. auto se = detail::scope_exit([&] {
  7964. svr.stop();
  7965. listen_thread.join();
  7966. ASSERT_FALSE(svr.is_running());
  7967. });
  7968. svr.wait_until_ready();
  7969. Client cli(HOST, PORT);
  7970. cli.set_keep_alive(true);
  7971. auto result = cli.Get("/hi");
  7972. ASSERT_TRUE(result);
  7973. EXPECT_EQ(StatusCode::OK_200, result->status);
  7974. std::this_thread::sleep_for(std::chrono::seconds(5));
  7975. result = cli.Get("/hi");
  7976. ASSERT_TRUE(result);
  7977. EXPECT_EQ(StatusCode::OK_200, result->status);
  7978. }
  7979. TEST(KeepAliveTest, Issue1959) {
  7980. Server svr;
  7981. svr.set_keep_alive_timeout(5);
  7982. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7983. res.set_content("a", "text/plain");
  7984. });
  7985. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7986. auto se = detail::scope_exit([&] {
  7987. if (!svr.is_running()) return;
  7988. svr.stop();
  7989. listen_thread.join();
  7990. ASSERT_FALSE(svr.is_running());
  7991. });
  7992. svr.wait_until_ready();
  7993. Client cli("localhost", PORT);
  7994. cli.set_keep_alive(true);
  7995. using namespace std::chrono;
  7996. auto start = steady_clock::now();
  7997. cli.Get("/a");
  7998. svr.stop();
  7999. listen_thread.join();
  8000. auto end = steady_clock::now();
  8001. auto elapsed = duration_cast<milliseconds>(end - start).count();
  8002. EXPECT_LT(elapsed, 5000);
  8003. }
  8004. #ifdef CPPHTTPLIB_SSL_ENABLED
  8005. TEST(KeepAliveTest, SSLClientReconnection) {
  8006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8007. ASSERT_TRUE(svr.is_valid());
  8008. svr.set_keep_alive_timeout(1);
  8009. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8010. res.set_content("Hello World!", "text/plain");
  8011. });
  8012. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8013. auto se = detail::scope_exit([&] {
  8014. svr.stop();
  8015. listen_thread.join();
  8016. ASSERT_FALSE(svr.is_running());
  8017. });
  8018. svr.wait_until_ready();
  8019. SSLClient cli(HOST, PORT);
  8020. cli.enable_server_certificate_verification(false);
  8021. cli.set_keep_alive(true);
  8022. auto result = cli.Get("/hi");
  8023. ASSERT_TRUE(result);
  8024. EXPECT_EQ(StatusCode::OK_200, result->status);
  8025. result = cli.Get("/hi");
  8026. ASSERT_TRUE(result);
  8027. EXPECT_EQ(StatusCode::OK_200, result->status);
  8028. std::this_thread::sleep_for(std::chrono::seconds(2));
  8029. // Recoonect
  8030. result = cli.Get("/hi");
  8031. ASSERT_TRUE(result);
  8032. EXPECT_EQ(StatusCode::OK_200, result->status);
  8033. result = cli.Get("/hi");
  8034. ASSERT_TRUE(result);
  8035. EXPECT_EQ(StatusCode::OK_200, result->status);
  8036. }
  8037. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8039. ASSERT_TRUE(svr.is_valid());
  8040. svr.set_keep_alive_timeout(1);
  8041. std::string content = "reconnect";
  8042. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8043. res.set_content("Hello World!", "text/plain");
  8044. });
  8045. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8046. auto se = detail::scope_exit([&] {
  8047. svr.stop();
  8048. listen_thread.join();
  8049. ASSERT_FALSE(svr.is_running());
  8050. });
  8051. svr.wait_until_ready();
  8052. SSLClient cli(HOST, PORT);
  8053. cli.enable_server_certificate_verification(false);
  8054. cli.set_keep_alive(true);
  8055. auto result = cli.Post(
  8056. "/hi", content.size(),
  8057. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8058. sink.write(content.c_str(), content.size());
  8059. return true;
  8060. },
  8061. "text/plain");
  8062. ASSERT_TRUE(result);
  8063. EXPECT_EQ(200, result->status);
  8064. std::this_thread::sleep_for(std::chrono::seconds(2));
  8065. // Recoonect
  8066. result = cli.Post(
  8067. "/hi", content.size(),
  8068. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8069. sink.write(content.c_str(), content.size());
  8070. return true;
  8071. },
  8072. "text/plain");
  8073. ASSERT_TRUE(result);
  8074. EXPECT_EQ(200, result->status);
  8075. result = cli.Post(
  8076. "/hi", content.size(),
  8077. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8078. sink.write(content.c_str(), content.size());
  8079. return true;
  8080. },
  8081. "text/plain");
  8082. ASSERT_TRUE(result);
  8083. EXPECT_EQ(200, result->status);
  8084. }
  8085. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8086. using namespace httplib::tls;
  8087. {
  8088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8089. ASSERT_TRUE(svr.is_valid());
  8090. svr.Get("/sni", [&](const Request &req, Response &res) {
  8091. std::string expected = req.sni();
  8092. EXPECT_EQ(expected, req.get_param_value("expected"));
  8093. res.set_content("ok", "text/plain");
  8094. });
  8095. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8096. auto se = detail::scope_exit([&] {
  8097. svr.stop();
  8098. listen_thread.join();
  8099. ASSERT_FALSE(svr.is_running());
  8100. });
  8101. svr.wait_until_ready();
  8102. {
  8103. SSLClient cli("localhost", PORT);
  8104. cli.enable_server_certificate_verification(false);
  8105. auto res = cli.Get("/sni?expected=localhost");
  8106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8107. }
  8108. {
  8109. SSLClient cli("::1", PORT);
  8110. cli.enable_server_certificate_verification(false);
  8111. auto res = cli.Get("/sni?expected=");
  8112. // NOTE: This may fail if the server is listening on IPv4 only
  8113. // (e.g., when localhost resolves to 127.0.0.1 only)
  8114. if (res) {
  8115. EXPECT_EQ(StatusCode::OK_200, res->status);
  8116. } else {
  8117. EXPECT_EQ(Error::Connection, res.error());
  8118. }
  8119. }
  8120. }
  8121. }
  8122. #endif
  8123. TEST(ClientProblemDetectionTest, ContentProvider) {
  8124. Server svr;
  8125. size_t content_length = 1024 * 1024;
  8126. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8127. res.set_content_provider(
  8128. content_length, "text/plain",
  8129. [&](size_t offset, size_t length, DataSink &sink) {
  8130. auto out_len = std::min(length, static_cast<size_t>(1024));
  8131. std::string out(out_len, '@');
  8132. sink.write(out.data(), out_len);
  8133. return offset < 4096;
  8134. },
  8135. [](bool success) { ASSERT_FALSE(success); });
  8136. });
  8137. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8138. res.set_content_provider(
  8139. 0, "text/plain",
  8140. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8141. EXPECT_TRUE(false);
  8142. return true;
  8143. },
  8144. [](bool success) { ASSERT_FALSE(success); });
  8145. });
  8146. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8147. auto se = detail::scope_exit([&] {
  8148. svr.stop();
  8149. listen_thread.join();
  8150. ASSERT_FALSE(svr.is_running());
  8151. });
  8152. svr.wait_until_ready();
  8153. Client cli("localhost", PORT);
  8154. {
  8155. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8156. size_t /*data_length*/) { return false; });
  8157. ASSERT_FALSE(res);
  8158. }
  8159. {
  8160. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8161. size_t /*data_length*/) { return false; });
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. }
  8164. }
  8165. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8166. Server svr;
  8167. svr.set_error_handler([](Request const &, Response &res) -> void {
  8168. res.set_chunked_content_provider(
  8169. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8170. sink.os << "hello";
  8171. sink.os << "world";
  8172. sink.done();
  8173. return true;
  8174. });
  8175. });
  8176. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8177. auto se = detail::scope_exit([&] {
  8178. svr.stop();
  8179. listen_thread.join();
  8180. ASSERT_FALSE(svr.is_running());
  8181. });
  8182. svr.wait_until_ready();
  8183. Client cli("localhost", PORT);
  8184. auto res = cli.Get("/");
  8185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8187. EXPECT_EQ("helloworld", res->body);
  8188. }
  8189. TEST(LongPollingTest, ClientCloseDetection) {
  8190. Server svr;
  8191. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8192. res.set_chunked_content_provider(
  8193. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8194. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8195. sink.os << "hello";
  8196. auto count = 10;
  8197. while (count > 0 && sink.is_writable()) {
  8198. this_thread::sleep_for(chrono::milliseconds(10));
  8199. count--;
  8200. }
  8201. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8202. return true;
  8203. });
  8204. });
  8205. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8206. auto se = detail::scope_exit([&] {
  8207. svr.stop();
  8208. listen_thread.join();
  8209. ASSERT_FALSE(svr.is_running());
  8210. });
  8211. svr.wait_until_ready();
  8212. Client cli("localhost", PORT);
  8213. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8214. EXPECT_EQ("hello", string(data, data_length));
  8215. return false; // close the socket immediately.
  8216. });
  8217. ASSERT_FALSE(res);
  8218. }
  8219. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8220. Server svr;
  8221. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8222. res.set_chunked_content_provider(
  8223. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8224. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8225. sink.os << "hello";
  8226. EXPECT_TRUE(sink.os.good());
  8227. // Wait for the client to close the connection
  8228. auto count = 10;
  8229. while (count > 0 && sink.is_writable()) {
  8230. this_thread::sleep_for(chrono::milliseconds(10));
  8231. count--;
  8232. }
  8233. // After client disconnect, write repeatedly until the socket
  8234. // write actually fails (small writes may be absorbed by the
  8235. // kernel buffer)
  8236. std::string chunk(1024, 'x');
  8237. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8238. sink.os << chunk;
  8239. }
  8240. EXPECT_TRUE(sink.os.fail());
  8241. return true;
  8242. });
  8243. });
  8244. auto port = svr.bind_to_any_port("localhost");
  8245. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8246. auto se = detail::scope_exit([&] {
  8247. svr.stop();
  8248. listen_thread.join();
  8249. ASSERT_FALSE(svr.is_running());
  8250. });
  8251. svr.wait_until_ready();
  8252. Client cli("localhost", port);
  8253. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8254. EXPECT_EQ("hello", string(data, data_length));
  8255. return false; // close the socket immediately.
  8256. });
  8257. ASSERT_FALSE(res);
  8258. }
  8259. TEST(GetWithParametersTest, GetWithParameters) {
  8260. Server svr;
  8261. svr.Get("/", [&](const Request &req, Response &) {
  8262. EXPECT_EQ("world", req.get_param_value("hello"));
  8263. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8264. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8265. });
  8266. svr.Get("/params", [&](const Request &req, Response &) {
  8267. EXPECT_EQ("world", req.get_param_value("hello"));
  8268. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8269. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8270. });
  8271. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8272. EXPECT_EQ("resource-id", req.matches[1]);
  8273. EXPECT_EQ("foo", req.get_param_value("param1"));
  8274. EXPECT_EQ("bar", req.get_param_value("param2"));
  8275. });
  8276. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8277. EXPECT_EQ("user-id", req.path_params.at("id"));
  8278. EXPECT_EQ("foo", req.get_param_value("param1"));
  8279. EXPECT_EQ("bar", req.get_param_value("param2"));
  8280. });
  8281. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8282. auto se = detail::scope_exit([&] {
  8283. svr.stop();
  8284. listen_thread.join();
  8285. ASSERT_FALSE(svr.is_running());
  8286. });
  8287. svr.wait_until_ready();
  8288. {
  8289. Client cli(HOST, PORT);
  8290. Params params;
  8291. params.emplace("hello", "world");
  8292. params.emplace("hello2", "world2");
  8293. params.emplace("hello3", "world3");
  8294. auto res = cli.Get("/", params, Headers{});
  8295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8296. EXPECT_EQ(StatusCode::OK_200, res->status);
  8297. }
  8298. {
  8299. Client cli(HOST, PORT);
  8300. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::OK_200, res->status);
  8303. }
  8304. {
  8305. Client cli(HOST, PORT);
  8306. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8308. EXPECT_EQ(StatusCode::OK_200, res->status);
  8309. }
  8310. {
  8311. Client cli(HOST, PORT);
  8312. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ(StatusCode::OK_200, res->status);
  8315. }
  8316. }
  8317. TEST(GetWithParametersTest, GetWithParameters2) {
  8318. Server svr;
  8319. svr.Get("/", [&](const Request &req, Response &res) {
  8320. auto text = req.get_param_value("hello");
  8321. res.set_content(text, "text/plain");
  8322. });
  8323. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8324. auto se = detail::scope_exit([&] {
  8325. svr.stop();
  8326. listen_thread.join();
  8327. ASSERT_FALSE(svr.is_running());
  8328. });
  8329. svr.wait_until_ready();
  8330. Client cli("localhost", PORT);
  8331. Params params;
  8332. params.emplace("hello", "world");
  8333. std::string body;
  8334. auto res = cli.Get("/", params, Headers{},
  8335. [&](const char *data, size_t data_length) {
  8336. body.append(data, data_length);
  8337. return true;
  8338. });
  8339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. EXPECT_EQ("world", body);
  8342. }
  8343. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8344. Server svr;
  8345. svr.Get("/search", [&](const Request &req, Response &res) {
  8346. auto q = req.get_param_value("q");
  8347. res.set_content(q, "text/plain");
  8348. });
  8349. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8350. auto se = detail::scope_exit([&] {
  8351. svr.stop();
  8352. listen_thread.join();
  8353. ASSERT_FALSE(svr.is_running());
  8354. });
  8355. svr.wait_until_ready();
  8356. Client cli("localhost", PORT);
  8357. // Verify that Get(path, params) works without requiring Headers argument
  8358. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8360. EXPECT_EQ(StatusCode::OK_200, res->status);
  8361. EXPECT_EQ("cpp-httplib", res->body);
  8362. }
  8363. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8364. auto host = "httpbingo.org";
  8365. auto path = std::string{"/range/32"};
  8366. #ifdef CPPHTTPLIB_SSL_ENABLED
  8367. SSLClient cli(host);
  8368. #else
  8369. Client cli(host);
  8370. #endif
  8371. cli.set_default_headers({make_range_header({{1, 10}})});
  8372. cli.set_connection_timeout(5);
  8373. {
  8374. auto res = cli.Get(path);
  8375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8376. EXPECT_EQ("bcdefghijk", res->body);
  8377. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8378. }
  8379. {
  8380. auto res = cli.Get(path);
  8381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8382. EXPECT_EQ("bcdefghijk", res->body);
  8383. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8384. }
  8385. }
  8386. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8387. Server svr;
  8388. svr.set_default_headers({{"Hello", "World"}});
  8389. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8390. res.set_content("ok", "text/plain");
  8391. });
  8392. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8393. auto se = detail::scope_exit([&] {
  8394. svr.stop();
  8395. listen_thread.join();
  8396. ASSERT_FALSE(svr.is_running());
  8397. });
  8398. svr.wait_until_ready();
  8399. Client cli("localhost", PORT);
  8400. auto res = cli.Get("/");
  8401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8402. EXPECT_EQ(StatusCode::OK_200, res->status);
  8403. EXPECT_EQ("ok", res->body);
  8404. EXPECT_EQ("World", res->get_header_value("Hello"));
  8405. }
  8406. #ifdef CPPHTTPLIB_SSL_ENABLED
  8407. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8409. ASSERT_TRUE(svr.is_valid());
  8410. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8411. std::this_thread::sleep_for(std::chrono::seconds(2));
  8412. res.set_content("a", "text/plain");
  8413. });
  8414. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8415. res.set_content("b", "text/plain");
  8416. });
  8417. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8418. auto se = detail::scope_exit([&] {
  8419. svr.stop();
  8420. listen_thread.join();
  8421. ASSERT_FALSE(svr.is_running());
  8422. });
  8423. svr.wait_until_ready();
  8424. SSLClient cli("localhost", PORT);
  8425. cli.enable_server_certificate_verification(false);
  8426. cli.set_keep_alive(true);
  8427. cli.set_read_timeout(std::chrono::seconds(1));
  8428. auto resa = cli.Get("/a");
  8429. ASSERT_TRUE(!resa);
  8430. EXPECT_EQ(Error::Read, resa.error());
  8431. auto resb = cli.Get("/b");
  8432. ASSERT_TRUE(resb);
  8433. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8434. EXPECT_EQ("b", resb->body);
  8435. }
  8436. #endif
  8437. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8438. protected:
  8439. ServerTestWithAI_PASSIVE()
  8440. : cli_(HOST, PORT)
  8441. #ifdef CPPHTTPLIB_SSL_ENABLED
  8442. ,
  8443. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8444. #endif
  8445. {
  8446. #ifdef CPPHTTPLIB_SSL_ENABLED
  8447. cli_.enable_server_certificate_verification(false);
  8448. #endif
  8449. }
  8450. virtual void SetUp() {
  8451. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8452. res.set_content("Hello World!", "text/plain");
  8453. });
  8454. t_ = thread(
  8455. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8456. svr_.wait_until_ready();
  8457. }
  8458. virtual void TearDown() {
  8459. svr_.stop();
  8460. t_.join();
  8461. }
  8462. #ifdef CPPHTTPLIB_SSL_ENABLED
  8463. SSLClient cli_;
  8464. SSLServer svr_;
  8465. #else
  8466. Client cli_;
  8467. Server svr_;
  8468. #endif
  8469. thread t_;
  8470. };
  8471. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8472. auto res = cli_.Get("/hi");
  8473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8474. EXPECT_EQ(StatusCode::OK_200, res->status);
  8475. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8476. EXPECT_EQ("Hello World!", res->body);
  8477. }
  8478. class ServerUpDownTest : public ::testing::Test {
  8479. protected:
  8480. ServerUpDownTest() : cli_(HOST, PORT) {}
  8481. virtual void SetUp() {
  8482. t_ = thread([&]() {
  8483. svr_.bind_to_any_port(HOST);
  8484. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8485. ASSERT_TRUE(svr_.listen_after_bind());
  8486. });
  8487. svr_.wait_until_ready();
  8488. }
  8489. virtual void TearDown() {
  8490. svr_.stop();
  8491. t_.join();
  8492. }
  8493. Client cli_;
  8494. Server svr_;
  8495. thread t_;
  8496. };
  8497. TEST_F(ServerUpDownTest, QuickStartStop) {
  8498. // Should not crash, especially when run with
  8499. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8500. }
  8501. class PayloadMaxLengthTest : public ::testing::Test {
  8502. protected:
  8503. PayloadMaxLengthTest()
  8504. : cli_(HOST, PORT)
  8505. #ifdef CPPHTTPLIB_SSL_ENABLED
  8506. ,
  8507. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8508. #endif
  8509. {
  8510. #ifdef CPPHTTPLIB_SSL_ENABLED
  8511. cli_.enable_server_certificate_verification(false);
  8512. #endif
  8513. }
  8514. virtual void SetUp() {
  8515. svr_.set_payload_max_length(8);
  8516. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8517. res.set_content("test", "text/plain");
  8518. });
  8519. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8520. svr_.wait_until_ready();
  8521. }
  8522. virtual void TearDown() {
  8523. svr_.stop();
  8524. t_.join();
  8525. }
  8526. #ifdef CPPHTTPLIB_SSL_ENABLED
  8527. SSLClient cli_;
  8528. SSLServer svr_;
  8529. #else
  8530. Client cli_;
  8531. Server svr_;
  8532. #endif
  8533. thread t_;
  8534. };
  8535. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8536. auto res = cli_.Post("/test", "123456789", "text/plain");
  8537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8538. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8539. res = cli_.Post("/test", "12345678", "text/plain");
  8540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8541. EXPECT_EQ(StatusCode::OK_200, res->status);
  8542. }
  8543. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8544. // Test chunked encoding with payload exceeding the 8-byte limit
  8545. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8546. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8548. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8549. }
  8550. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8551. // Test chunked encoding with payload within the 8-byte limit
  8552. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8553. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8555. EXPECT_EQ(StatusCode::OK_200, res->status);
  8556. }
  8557. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8558. // Test using send_request to send chunked data exceeding payload limit
  8559. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8560. "Host: " +
  8561. std::string(HOST) + ":" + std::to_string(PORT) +
  8562. "\r\n"
  8563. "Transfer-Encoding: chunked\r\n"
  8564. "Connection: close\r\n"
  8565. "\r\n"
  8566. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8567. "0123456789\r\n"
  8568. "0\r\n" // End chunk
  8569. "\r\n";
  8570. std::string response;
  8571. bool result = send_request(1, chunked_request, &response);
  8572. if (!result) {
  8573. // If send_request fails, it might be because the server closed the
  8574. // connection due to payload limit enforcement, which is acceptable
  8575. SUCCEED()
  8576. << "Server rejected oversized chunked request (connection closed)";
  8577. } else {
  8578. // If we got a response, check if it's an error response or connection was
  8579. // closed early Short response length indicates connection was closed due to
  8580. // payload limit
  8581. if (response.length() <= 10) {
  8582. SUCCEED() << "Server closed connection for oversized chunked request";
  8583. } else {
  8584. // Check for error status codes
  8585. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8586. response.find("Payload Too Large") != std::string::npos ||
  8587. response.find("400") != std::string::npos);
  8588. }
  8589. }
  8590. }
  8591. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8592. // Test request without Content-Length header exceeding payload limit
  8593. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8594. "Host: " +
  8595. std::string(HOST) + ":" +
  8596. std::to_string(PORT) +
  8597. "\r\n"
  8598. "Connection: close\r\n"
  8599. "\r\n";
  8600. // Add payload exceeding the 8-byte limit
  8601. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8602. request_without_content_length += large_payload;
  8603. std::string response;
  8604. bool result = send_request(1, request_without_content_length, &response);
  8605. if (!result) {
  8606. // If send_request fails, server likely closed connection due to payload
  8607. // limit
  8608. SUCCEED() << "Server rejected oversized request without Content-Length "
  8609. "(connection closed)";
  8610. } else {
  8611. // Check if server responded with error or closed connection early
  8612. if (response.length() <= 10) {
  8613. SUCCEED() << "Server closed connection for oversized request without "
  8614. "Content-Length";
  8615. } else {
  8616. // Check for error status codes
  8617. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8618. response.find("Payload Too Large") != std::string::npos ||
  8619. response.find("400") != std::string::npos);
  8620. }
  8621. }
  8622. }
  8623. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8624. // Test request without Content-Length header within payload limit
  8625. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8626. "Host: " +
  8627. std::string(HOST) + ":" +
  8628. std::to_string(PORT) +
  8629. "\r\n"
  8630. "Connection: close\r\n"
  8631. "\r\n";
  8632. // Add payload within the 8-byte limit
  8633. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8634. request_without_content_length += small_payload;
  8635. std::string response;
  8636. bool result = send_request(1, request_without_content_length, &response);
  8637. // For requests without Content-Length, the server may have different behavior
  8638. // The key is that it should not reject due to payload limit for small
  8639. // payloads
  8640. if (result) {
  8641. // Check for any HTTP response (success or error, but not connection closed)
  8642. if (response.length() > 10) {
  8643. SUCCEED()
  8644. << "Server processed request without Content-Length within limit";
  8645. } else {
  8646. // Short response might indicate connection closed, which is acceptable
  8647. SUCCEED() << "Server closed connection for request without "
  8648. "Content-Length (acceptable behavior)";
  8649. }
  8650. } else {
  8651. // Connection failure might be due to protocol requirements
  8652. SUCCEED() << "Connection issue with request without Content-Length "
  8653. "(environment-specific)";
  8654. }
  8655. }
  8656. class LargePayloadMaxLengthTest : public ::testing::Test {
  8657. protected:
  8658. LargePayloadMaxLengthTest()
  8659. : cli_(HOST, PORT)
  8660. #ifdef CPPHTTPLIB_SSL_ENABLED
  8661. ,
  8662. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8663. #endif
  8664. {
  8665. #ifdef CPPHTTPLIB_SSL_ENABLED
  8666. cli_.enable_server_certificate_verification(false);
  8667. #endif
  8668. }
  8669. virtual void SetUp() {
  8670. // Set 10MB payload limit
  8671. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8672. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8673. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8674. res.set_content("Large payload test", "text/plain");
  8675. });
  8676. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8677. svr_.wait_until_ready();
  8678. }
  8679. virtual void TearDown() {
  8680. svr_.stop();
  8681. t_.join();
  8682. }
  8683. #ifdef CPPHTTPLIB_SSL_ENABLED
  8684. SSLClient cli_;
  8685. SSLServer svr_;
  8686. #else
  8687. Client cli_;
  8688. Server svr_;
  8689. #endif
  8690. thread t_;
  8691. };
  8692. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8693. // Test chunked encoding with payload within 10MB limit
  8694. std::string medium_payload(5 * 1024 * 1024,
  8695. 'A'); // 5MB payload, within 10MB limit
  8696. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8698. EXPECT_EQ(StatusCode::OK_200, res->status);
  8699. }
  8700. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8701. // Test chunked encoding with payload exceeding 10MB limit
  8702. std::string large_payload(12 * 1024 * 1024,
  8703. 'B'); // 12MB payload, exceeds 10MB limit
  8704. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8705. // Server may either return 413 or close the connection
  8706. if (res) {
  8707. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8708. } else {
  8709. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8710. }
  8711. }
  8712. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8713. // Test request without Content-Length header within 10MB limit
  8714. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8715. "Host: " +
  8716. std::string(HOST) + ":" +
  8717. std::to_string(PORT) +
  8718. "\r\n"
  8719. "Connection: close\r\n"
  8720. "\r\n";
  8721. // Add 1MB payload (within 10MB limit)
  8722. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8723. request_without_content_length += medium_payload;
  8724. std::string response;
  8725. bool result = send_request(5, request_without_content_length, &response);
  8726. if (result) {
  8727. // Should get a proper HTTP response for payloads within limit
  8728. if (response.length() > 10) {
  8729. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8730. "10MB limit";
  8731. } else {
  8732. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8733. "Content-Length)";
  8734. }
  8735. } else {
  8736. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8737. }
  8738. }
  8739. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8740. // Test request without Content-Length header exceeding 10MB limit
  8741. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8742. "Host: " +
  8743. std::string(HOST) + ":" +
  8744. std::to_string(PORT) +
  8745. "\r\n"
  8746. "Connection: close\r\n"
  8747. "\r\n";
  8748. // Add 12MB payload (exceeds 10MB limit)
  8749. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8750. request_without_content_length += large_payload;
  8751. std::string response;
  8752. bool result = send_request(10, request_without_content_length, &response);
  8753. if (!result) {
  8754. // Server should close connection due to payload limit
  8755. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8756. "(connection closed)";
  8757. } else {
  8758. // Check for error response
  8759. if (response.length() <= 10) {
  8760. SUCCEED()
  8761. << "Server closed connection for 12MB request exceeding 10MB limit";
  8762. } else {
  8763. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8764. response.find("Payload Too Large") != std::string::npos ||
  8765. response.find("400") != std::string::npos);
  8766. }
  8767. }
  8768. }
  8769. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8770. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8771. // path.
  8772. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8773. Server svr;
  8774. const size_t LIMIT = 64 * 1024; // 64KB
  8775. svr.set_payload_max_length(LIMIT);
  8776. size_t total = 0;
  8777. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8778. const ContentReader &content_reader) {
  8779. content_reader([&](const char * /*data*/, size_t len) {
  8780. total += len;
  8781. return true;
  8782. });
  8783. res.status = 200;
  8784. res.set_content("stream_ok", "text/plain");
  8785. });
  8786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8787. auto se = detail::scope_exit([&] {
  8788. svr.stop();
  8789. thread.join();
  8790. ASSERT_FALSE(svr.is_running());
  8791. });
  8792. svr.wait_until_ready();
  8793. // Prepare 256KB raw data and gzip-compress it
  8794. std::string raw(256 * 1024, 'A');
  8795. std::string gz;
  8796. {
  8797. z_stream zs{};
  8798. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8799. Z_DEFAULT_STRATEGY);
  8800. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8801. zs.avail_in = static_cast<uInt>(raw.size());
  8802. char outbuf[4096];
  8803. int ret;
  8804. do {
  8805. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8806. zs.avail_out = sizeof(outbuf);
  8807. ret = deflate(&zs, Z_FINISH);
  8808. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8809. } while (ret != Z_STREAM_END);
  8810. deflateEnd(&zs);
  8811. }
  8812. Client cli(HOST, PORT);
  8813. cli.set_connection_timeout(std::chrono::seconds(5));
  8814. Headers headers = {{"Content-Encoding", "gzip"}};
  8815. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8816. "application/octet-stream");
  8817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8818. // Server must reject oversized decompressed payloads with 413.
  8819. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8820. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8821. EXPECT_LE(total, LIMIT);
  8822. }
  8823. #endif
  8824. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  8825. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  8826. // the payload must be passed through untouched instead of being rejected.
  8827. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  8828. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  8829. Server svr;
  8830. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  8831. res.set_content(body, "image/jpeg");
  8832. res.set_header("Content-Encoding", "UTF-8");
  8833. });
  8834. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  8835. res.set_content(body, "image/jpeg");
  8836. res.set_header("Content-Encoding", "identity");
  8837. });
  8838. svr.Post("/echo", [](const Request &req, Response &res) {
  8839. res.set_content(req.body, "image/jpeg");
  8840. });
  8841. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8842. auto se = detail::scope_exit([&] {
  8843. svr.stop();
  8844. t.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. svr.wait_until_ready();
  8848. Client cli(HOST, PORT);
  8849. {
  8850. auto res = cli.Get("/image");
  8851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8852. EXPECT_EQ(StatusCode::OK_200, res->status);
  8853. EXPECT_EQ(body, res->body);
  8854. }
  8855. {
  8856. auto res = cli.Get("/identity");
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ(StatusCode::OK_200, res->status);
  8859. EXPECT_EQ(body, res->body);
  8860. }
  8861. {
  8862. // The same applies to a request body reaching the server.
  8863. Headers headers = {{"Content-Encoding", "UTF-8"}};
  8864. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  8865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8866. EXPECT_EQ(StatusCode::OK_200, res->status);
  8867. EXPECT_EQ(body, res->body);
  8868. }
  8869. }
  8870. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  8871. // gzip-encoded response even when the build has no zlib support.
  8872. static const char GZIPPED_HELLO_WORLD[] = {
  8873. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  8874. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  8875. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  8876. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  8877. // A content coding cpp-httplib recognizes but was not built with must be
  8878. // reported as such. Handing the still-compressed payload back to the caller
  8879. // would silently corrupt it.
  8880. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  8881. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  8882. Server svr;
  8883. // "image/jpeg" keeps the server from applying a content coding of its own,
  8884. // so the hand-crafted Content-Encoding below survives.
  8885. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  8886. res.set_content(gzipped, "image/jpeg");
  8887. res.set_header("Content-Encoding", "gzip");
  8888. });
  8889. // Content codings are case-insensitive (RFC 9110 8.4.1).
  8890. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  8891. res.set_content(gzipped, "image/jpeg");
  8892. res.set_header("Content-Encoding", "GZIP");
  8893. });
  8894. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8895. auto se = detail::scope_exit([&] {
  8896. svr.stop();
  8897. t.join();
  8898. ASSERT_FALSE(svr.is_running());
  8899. });
  8900. svr.wait_until_ready();
  8901. Client cli(HOST, PORT);
  8902. {
  8903. auto res = cli.Get("/gzipped");
  8904. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8906. EXPECT_EQ("Hello World!", res->body);
  8907. #else
  8908. ASSERT_FALSE(res);
  8909. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  8910. #endif
  8911. }
  8912. {
  8913. // open_stream() must behave the same way.
  8914. auto handle = cli.open_stream("GET", "/gzipped");
  8915. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8916. ASSERT_TRUE(handle.is_valid());
  8917. std::string received;
  8918. char buf[256];
  8919. ssize_t n;
  8920. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  8921. received.append(buf, static_cast<size_t>(n));
  8922. }
  8923. EXPECT_EQ("Hello World!", received);
  8924. #else
  8925. EXPECT_FALSE(handle.is_valid());
  8926. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  8927. #endif
  8928. }
  8929. {
  8930. // A differently-cased coding must not be mistaken for an unknown one, or
  8931. // the body would be handed back still compressed.
  8932. auto res = cli.Get("/gzipped-uppercase");
  8933. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8935. EXPECT_EQ("Hello World!", res->body);
  8936. #else
  8937. ASSERT_FALSE(res);
  8938. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  8939. #endif
  8940. }
  8941. }
  8942. // Regression test for DoS vulnerability: a malicious server sending a response
  8943. // without Content-Length header must not cause unbounded memory consumption on
  8944. // the client side. The client should stop reading after a reasonable limit,
  8945. // similar to the server-side set_payload_max_length protection.
  8946. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8947. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8948. #ifndef _WIN32
  8949. signal(SIGPIPE, SIG_IGN);
  8950. #endif
  8951. auto server_thread = std::thread([] {
  8952. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8953. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8954. default_socket_options(srv);
  8955. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8956. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8957. sockaddr_in addr{};
  8958. addr.sin_family = AF_INET;
  8959. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8960. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8961. int opt = 1;
  8962. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8963. #ifdef _WIN32
  8964. reinterpret_cast<const char *>(&opt),
  8965. #else
  8966. &opt,
  8967. #endif
  8968. sizeof(opt));
  8969. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8970. ::listen(srv, 1);
  8971. sockaddr_in cli_addr{};
  8972. socklen_t cli_len = sizeof(cli_addr);
  8973. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8974. if (cli != INVALID_SOCKET) {
  8975. char buf[4096];
  8976. ::recv(cli, buf, sizeof(buf), 0);
  8977. // Malicious response: no Content-Length, no chunked encoding
  8978. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8979. "Connection: close\r\n"
  8980. "\r\n";
  8981. ::send(cli,
  8982. #ifdef _WIN32
  8983. static_cast<const char *>(response_header.c_str()),
  8984. static_cast<int>(response_header.size()),
  8985. #else
  8986. response_header.c_str(), response_header.size(),
  8987. #endif
  8988. 0);
  8989. // Send 10MB of data
  8990. std::string chunk(64 * 1024, 'A');
  8991. size_t total_sent = 0;
  8992. while (total_sent < MALICIOUS_DATA_SIZE) {
  8993. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8994. auto sent = ::send(cli,
  8995. #ifdef _WIN32
  8996. static_cast<const char *>(chunk.c_str()),
  8997. static_cast<int>(to_send),
  8998. #else
  8999. chunk.c_str(), to_send,
  9000. #endif
  9001. 0);
  9002. if (sent <= 0) break;
  9003. total_sent += static_cast<size_t>(sent);
  9004. }
  9005. detail::close_socket(cli);
  9006. }
  9007. detail::close_socket(srv);
  9008. });
  9009. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9010. size_t total_read = 0;
  9011. {
  9012. Client cli("127.0.0.1", PORT + 2);
  9013. cli.set_read_timeout(5, 0);
  9014. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9015. auto stream = cli.open_stream("GET", "/malicious");
  9016. ASSERT_TRUE(stream.is_valid());
  9017. char buffer[64 * 1024];
  9018. ssize_t n;
  9019. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9020. total_read += static_cast<size_t>(n);
  9021. }
  9022. } // StreamHandle and Client destroyed here, closing the socket
  9023. server_thread.join();
  9024. // With set_payload_max_length, the client must stop reading before consuming
  9025. // all 10MB. The read loop should be cut off at or near the configured limit.
  9026. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9027. << "Client read " << total_read << " bytes, exceeding the configured "
  9028. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9029. }
  9030. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9031. // the entire response body without truncation.
  9032. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9033. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9034. #ifndef _WIN32
  9035. signal(SIGPIPE, SIG_IGN);
  9036. #endif
  9037. auto server_thread = std::thread([] {
  9038. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9039. default_socket_options(srv);
  9040. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9041. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9042. sockaddr_in addr{};
  9043. addr.sin_family = AF_INET;
  9044. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9045. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9046. int opt = 1;
  9047. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9048. #ifdef _WIN32
  9049. reinterpret_cast<const char *>(&opt),
  9050. #else
  9051. &opt,
  9052. #endif
  9053. sizeof(opt));
  9054. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9055. ::listen(srv, 1);
  9056. sockaddr_in cli_addr{};
  9057. socklen_t cli_len = sizeof(cli_addr);
  9058. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9059. if (cli != INVALID_SOCKET) {
  9060. char buf[4096];
  9061. ::recv(cli, buf, sizeof(buf), 0);
  9062. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9063. "Connection: close\r\n"
  9064. "\r\n";
  9065. ::send(cli,
  9066. #ifdef _WIN32
  9067. static_cast<const char *>(response_header.c_str()),
  9068. static_cast<int>(response_header.size()),
  9069. #else
  9070. response_header.c_str(), response_header.size(),
  9071. #endif
  9072. 0);
  9073. std::string chunk(64 * 1024, 'A');
  9074. size_t total_sent = 0;
  9075. while (total_sent < DATA_SIZE) {
  9076. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9077. auto sent = ::send(cli,
  9078. #ifdef _WIN32
  9079. static_cast<const char *>(chunk.c_str()),
  9080. static_cast<int>(to_send),
  9081. #else
  9082. chunk.c_str(), to_send,
  9083. #endif
  9084. 0);
  9085. if (sent <= 0) break;
  9086. total_sent += static_cast<size_t>(sent);
  9087. }
  9088. #ifdef _WIN32
  9089. ::shutdown(cli, SD_SEND);
  9090. #else
  9091. ::shutdown(cli, SHUT_WR);
  9092. #endif
  9093. // Drain until the client closes its end, ensuring all data is delivered
  9094. char drain[1024];
  9095. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9096. detail::close_socket(cli);
  9097. }
  9098. detail::close_socket(srv);
  9099. });
  9100. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9101. size_t total_read = 0;
  9102. {
  9103. Client cli("127.0.0.1", PORT + 2);
  9104. cli.set_read_timeout(5, 0);
  9105. cli.set_payload_max_length(0); // 0 means no limit
  9106. auto stream = cli.open_stream("GET", "/data");
  9107. ASSERT_TRUE(stream.is_valid());
  9108. char buffer[64 * 1024];
  9109. ssize_t n;
  9110. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9111. total_read += static_cast<size_t>(n);
  9112. }
  9113. }
  9114. server_thread.join();
  9115. EXPECT_EQ(total_read, DATA_SIZE)
  9116. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9117. << " bytes without truncation, but only read " << total_read << " bytes.";
  9118. }
  9119. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9120. // enormous Content-Length must not cause the client to pre-allocate a huge
  9121. // response body buffer. The reservation is capped at payload_max_length_, and
  9122. // the read itself fails when the body exceeds the limit.
  9123. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9124. #ifndef _WIN32
  9125. signal(SIGPIPE, SIG_IGN);
  9126. #endif
  9127. auto server_thread = std::thread([] {
  9128. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9129. default_socket_options(srv);
  9130. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9131. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9132. sockaddr_in addr{};
  9133. addr.sin_family = AF_INET;
  9134. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9135. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9136. int opt = 1;
  9137. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9138. #ifdef _WIN32
  9139. reinterpret_cast<const char *>(&opt),
  9140. #else
  9141. &opt,
  9142. #endif
  9143. sizeof(opt));
  9144. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9145. ::listen(srv, 1);
  9146. sockaddr_in cli_addr{};
  9147. socklen_t cli_len = sizeof(cli_addr);
  9148. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9149. if (cli != INVALID_SOCKET) {
  9150. char buf[4096];
  9151. ::recv(cli, buf, sizeof(buf), 0);
  9152. // Malicious response: claim a 20GB body but send only a tiny payload.
  9153. std::string response = "HTTP/1.1 200 OK\r\n"
  9154. "Content-Length: 20000000000\r\n"
  9155. "\r\n"
  9156. "abc";
  9157. ::send(cli,
  9158. #ifdef _WIN32
  9159. static_cast<const char *>(response.c_str()),
  9160. static_cast<int>(response.size()),
  9161. #else
  9162. response.c_str(), response.size(),
  9163. #endif
  9164. 0);
  9165. detail::close_socket(cli);
  9166. }
  9167. detail::close_socket(srv);
  9168. });
  9169. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9170. {
  9171. Client cli("127.0.0.1", PORT + 2);
  9172. cli.set_read_timeout(5, 0);
  9173. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9174. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9175. // (server claims more bytes than payload_max_length permits), but it must
  9176. // not exhaust memory before getting there.
  9177. auto res = cli.Get("/malicious");
  9178. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9179. }
  9180. server_thread.join();
  9181. }
  9182. // Verify that content_receiver bypasses the default payload_max_length,
  9183. // allowing streaming downloads larger than 100MB without requiring an explicit
  9184. // set_payload_max_length call.
  9185. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9186. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9187. #ifndef _WIN32
  9188. signal(SIGPIPE, SIG_IGN);
  9189. #endif
  9190. auto server_thread = std::thread([] {
  9191. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9192. default_socket_options(srv);
  9193. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9194. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9195. sockaddr_in addr{};
  9196. addr.sin_family = AF_INET;
  9197. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9198. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9199. int opt = 1;
  9200. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9201. #ifdef _WIN32
  9202. reinterpret_cast<const char *>(&opt),
  9203. #else
  9204. &opt,
  9205. #endif
  9206. sizeof(opt));
  9207. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9208. ::listen(srv, 1);
  9209. sockaddr_in cli_addr{};
  9210. socklen_t cli_len = sizeof(cli_addr);
  9211. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9212. if (cli != INVALID_SOCKET) {
  9213. char buf[4096];
  9214. ::recv(cli, buf, sizeof(buf), 0);
  9215. // Response with Content-Length larger than default 100MB limit
  9216. auto content_length = std::to_string(DATA_SIZE);
  9217. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9218. "Content-Length: " +
  9219. content_length +
  9220. "\r\n"
  9221. "Connection: close\r\n"
  9222. "\r\n";
  9223. ::send(cli,
  9224. #ifdef _WIN32
  9225. static_cast<const char *>(response_header.c_str()),
  9226. static_cast<int>(response_header.size()),
  9227. #else
  9228. response_header.c_str(), response_header.size(),
  9229. #endif
  9230. 0);
  9231. std::string chunk(64 * 1024, 'A');
  9232. size_t total_sent = 0;
  9233. while (total_sent < DATA_SIZE) {
  9234. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9235. auto sent = ::send(cli,
  9236. #ifdef _WIN32
  9237. static_cast<const char *>(chunk.c_str()),
  9238. static_cast<int>(to_send),
  9239. #else
  9240. chunk.c_str(), to_send,
  9241. #endif
  9242. 0);
  9243. if (sent <= 0) break;
  9244. total_sent += static_cast<size_t>(sent);
  9245. }
  9246. detail::close_socket(cli);
  9247. }
  9248. detail::close_socket(srv);
  9249. });
  9250. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9251. size_t total_received = 0;
  9252. {
  9253. Client cli("127.0.0.1", PORT + 2);
  9254. cli.set_read_timeout(10, 0);
  9255. // Do NOT call set_payload_max_length — use the default 100MB limit
  9256. auto res =
  9257. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9258. total_received += data_length;
  9259. return true;
  9260. });
  9261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9262. EXPECT_EQ(StatusCode::OK_200, res->status);
  9263. }
  9264. server_thread.join();
  9265. EXPECT_EQ(total_received, DATA_SIZE)
  9266. << "With content_receiver, the client should read all " << DATA_SIZE
  9267. << " bytes despite the default 100MB payload_max_length, but only read "
  9268. << total_received << " bytes.";
  9269. }
  9270. // Verify that an explicit set_payload_max_length smaller than the response is
  9271. // enforced even when a content_receiver is used.
  9272. TEST(ClientVulnerabilityTest,
  9273. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9274. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9275. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9276. #ifndef _WIN32
  9277. signal(SIGPIPE, SIG_IGN);
  9278. #endif
  9279. auto server_thread = std::thread([] {
  9280. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9281. default_socket_options(srv);
  9282. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9283. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9284. sockaddr_in addr{};
  9285. addr.sin_family = AF_INET;
  9286. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9287. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9288. int opt = 1;
  9289. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9290. #ifdef _WIN32
  9291. reinterpret_cast<const char *>(&opt),
  9292. #else
  9293. &opt,
  9294. #endif
  9295. sizeof(opt));
  9296. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9297. ::listen(srv, 1);
  9298. sockaddr_in cli_addr{};
  9299. socklen_t cli_len = sizeof(cli_addr);
  9300. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9301. if (cli != INVALID_SOCKET) {
  9302. char buf[4096];
  9303. ::recv(cli, buf, sizeof(buf), 0);
  9304. auto content_length = std::to_string(DATA_SIZE);
  9305. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9306. "Content-Length: " +
  9307. content_length +
  9308. "\r\n"
  9309. "Connection: close\r\n"
  9310. "\r\n";
  9311. ::send(cli,
  9312. #ifdef _WIN32
  9313. static_cast<const char *>(response_header.c_str()),
  9314. static_cast<int>(response_header.size()),
  9315. #else
  9316. response_header.c_str(), response_header.size(),
  9317. #endif
  9318. 0);
  9319. std::string chunk(64 * 1024, 'A');
  9320. size_t total_sent = 0;
  9321. while (total_sent < DATA_SIZE) {
  9322. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9323. auto sent = ::send(cli,
  9324. #ifdef _WIN32
  9325. static_cast<const char *>(chunk.c_str()),
  9326. static_cast<int>(to_send),
  9327. #else
  9328. chunk.c_str(), to_send,
  9329. #endif
  9330. 0);
  9331. if (sent <= 0) break;
  9332. total_sent += static_cast<size_t>(sent);
  9333. }
  9334. detail::close_socket(cli);
  9335. }
  9336. detail::close_socket(srv);
  9337. });
  9338. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9339. size_t total_received = 0;
  9340. {
  9341. Client cli("127.0.0.1", PORT + 2);
  9342. cli.set_read_timeout(10, 0);
  9343. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9344. auto res =
  9345. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9346. total_received += data_length;
  9347. return true;
  9348. });
  9349. // Should fail because 200MB exceeds the explicit 150MB limit
  9350. EXPECT_FALSE(res);
  9351. }
  9352. server_thread.join();
  9353. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9354. << "Client with content_receiver should respect the explicit "
  9355. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9356. << total_received << " bytes.";
  9357. }
  9358. // Verify that an explicit set_payload_max_length larger than the response
  9359. // allows the content_receiver to read all data successfully.
  9360. TEST(ClientVulnerabilityTest,
  9361. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9362. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9363. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9364. #ifndef _WIN32
  9365. signal(SIGPIPE, SIG_IGN);
  9366. #endif
  9367. auto server_thread = std::thread([] {
  9368. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9369. default_socket_options(srv);
  9370. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9371. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9372. sockaddr_in addr{};
  9373. addr.sin_family = AF_INET;
  9374. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9375. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9376. int opt = 1;
  9377. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9378. #ifdef _WIN32
  9379. reinterpret_cast<const char *>(&opt),
  9380. #else
  9381. &opt,
  9382. #endif
  9383. sizeof(opt));
  9384. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9385. ::listen(srv, 1);
  9386. sockaddr_in cli_addr{};
  9387. socklen_t cli_len = sizeof(cli_addr);
  9388. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9389. if (cli != INVALID_SOCKET) {
  9390. char buf[4096];
  9391. ::recv(cli, buf, sizeof(buf), 0);
  9392. auto content_length = std::to_string(DATA_SIZE);
  9393. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9394. "Content-Length: " +
  9395. content_length +
  9396. "\r\n"
  9397. "Connection: close\r\n"
  9398. "\r\n";
  9399. ::send(cli,
  9400. #ifdef _WIN32
  9401. static_cast<const char *>(response_header.c_str()),
  9402. static_cast<int>(response_header.size()),
  9403. #else
  9404. response_header.c_str(), response_header.size(),
  9405. #endif
  9406. 0);
  9407. std::string chunk(64 * 1024, 'A');
  9408. size_t total_sent = 0;
  9409. while (total_sent < DATA_SIZE) {
  9410. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9411. auto sent = ::send(cli,
  9412. #ifdef _WIN32
  9413. static_cast<const char *>(chunk.c_str()),
  9414. static_cast<int>(to_send),
  9415. #else
  9416. chunk.c_str(), to_send,
  9417. #endif
  9418. 0);
  9419. if (sent <= 0) break;
  9420. total_sent += static_cast<size_t>(sent);
  9421. }
  9422. #ifdef _WIN32
  9423. ::shutdown(cli, SD_SEND);
  9424. #else
  9425. ::shutdown(cli, SHUT_WR);
  9426. #endif
  9427. char drain[1024];
  9428. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9429. detail::close_socket(cli);
  9430. }
  9431. detail::close_socket(srv);
  9432. });
  9433. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9434. size_t total_received = 0;
  9435. {
  9436. Client cli("127.0.0.1", PORT + 2);
  9437. cli.set_read_timeout(10, 0);
  9438. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9439. auto res =
  9440. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9441. total_received += data_length;
  9442. return true;
  9443. });
  9444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9445. EXPECT_EQ(StatusCode::OK_200, res->status);
  9446. }
  9447. server_thread.join();
  9448. EXPECT_EQ(total_received, DATA_SIZE)
  9449. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9450. << " bytes (larger than " << DATA_SIZE
  9451. << " bytes response), content_receiver should read all data, but only "
  9452. "read "
  9453. << total_received << " bytes.";
  9454. }
  9455. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9456. // Regression test for "zip bomb" attack on the client side: a malicious server
  9457. // sends a small gzip-compressed response that decompresses to a huge payload.
  9458. // The client must enforce payload_max_length on the decompressed size.
  9459. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9460. constexpr size_t DECOMPRESSED_SIZE =
  9461. 10 * 1024 * 1024; // 10MB after decompression
  9462. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9463. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9464. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9465. std::string compressed;
  9466. {
  9467. httplib::detail::gzip_compressor compressor;
  9468. bool ok =
  9469. compressor.compress(uncompressed.data(), uncompressed.size(),
  9470. /*last=*/true, [&](const char *buf, size_t len) {
  9471. compressed.append(buf, len);
  9472. return true;
  9473. });
  9474. ASSERT_TRUE(ok);
  9475. }
  9476. // Sanity: compressed data should be much smaller than the decompressed size
  9477. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9478. #ifndef _WIN32
  9479. signal(SIGPIPE, SIG_IGN);
  9480. #endif
  9481. // Set up the listening socket in the main thread so the server is guaranteed
  9482. // to be ready before the client connects (eliminates race condition).
  9483. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9484. default_socket_options(srv);
  9485. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9486. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9487. sockaddr_in addr{};
  9488. addr.sin_family = AF_INET;
  9489. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9490. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9491. int opt = 1;
  9492. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9493. #ifdef _WIN32
  9494. reinterpret_cast<const char *>(&opt),
  9495. #else
  9496. &opt,
  9497. #endif
  9498. sizeof(opt));
  9499. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9500. ASSERT_EQ(0, ::listen(srv, 1));
  9501. auto server_thread = std::thread([&compressed, srv] {
  9502. sockaddr_in cli_addr{};
  9503. socklen_t cli_len = sizeof(cli_addr);
  9504. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9505. if (cli != INVALID_SOCKET) {
  9506. // Read the full HTTP request (until \r\n\r\n)
  9507. char buf[4096];
  9508. size_t total = 0;
  9509. while (total < sizeof(buf)) {
  9510. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9511. if (n <= 0) break;
  9512. total += static_cast<size_t>(n);
  9513. // Check for end of headers
  9514. if (total >= 4) {
  9515. std::string req(buf, total);
  9516. if (req.find("\r\n\r\n") != std::string::npos) break;
  9517. }
  9518. }
  9519. // Malicious response: gzip-compressed body, no Content-Length
  9520. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9521. "Content-Encoding: gzip\r\n"
  9522. "Connection: close\r\n"
  9523. "\r\n";
  9524. ::send(cli,
  9525. #ifdef _WIN32
  9526. static_cast<const char *>(response_header.c_str()),
  9527. static_cast<int>(response_header.size()),
  9528. #else
  9529. response_header.c_str(), response_header.size(),
  9530. #endif
  9531. 0);
  9532. // Send the compressed payload (small on the wire, huge when decompressed)
  9533. size_t total_sent = 0;
  9534. while (total_sent < compressed.size()) {
  9535. auto to_send = std::min(compressed.size() - total_sent,
  9536. static_cast<size_t>(64 * 1024));
  9537. auto sent =
  9538. ::send(cli,
  9539. #ifdef _WIN32
  9540. static_cast<const char *>(compressed.c_str() + total_sent),
  9541. static_cast<int>(to_send),
  9542. #else
  9543. compressed.c_str() + total_sent, to_send,
  9544. #endif
  9545. 0);
  9546. if (sent <= 0) break;
  9547. total_sent += static_cast<size_t>(sent);
  9548. }
  9549. detail::close_socket(cli);
  9550. }
  9551. });
  9552. auto se = detail::scope_exit([&] {
  9553. detail::close_socket(srv);
  9554. server_thread.join();
  9555. });
  9556. size_t total_decompressed = 0;
  9557. {
  9558. Client cli("127.0.0.1", PORT + 3);
  9559. cli.set_read_timeout(5, 0);
  9560. cli.set_decompress(true);
  9561. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9562. auto stream = cli.open_stream("GET", "/zipbomb");
  9563. ASSERT_TRUE(stream.is_valid());
  9564. char buffer[64 * 1024];
  9565. ssize_t n;
  9566. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9567. total_decompressed += static_cast<size_t>(n);
  9568. }
  9569. }
  9570. // The decompressed size must be capped by payload_max_length. Without
  9571. // protection, the client would decompress the full 10MB from a tiny
  9572. // compressed payload, enabling a zip bomb DoS attack.
  9573. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9574. << "Client decompressed " << total_decompressed
  9575. << " bytes from a gzip response. The decompressed size should be "
  9576. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9577. }
  9578. #endif
  9579. TEST(HostAndPortPropertiesTest, NoSSL) {
  9580. httplib::Client cli("www.google.com", 1234);
  9581. ASSERT_EQ("www.google.com", cli.host());
  9582. ASSERT_EQ(1234, cli.port());
  9583. }
  9584. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9585. httplib::Client cli("www.google.com:1234");
  9586. ASSERT_EQ("www.google.com", cli.host());
  9587. ASSERT_EQ(1234, cli.port());
  9588. }
  9589. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9590. // Port number that overflows int — should not crash, client becomes invalid
  9591. httplib::Client cli("http://www.google.com:99999999999999999999");
  9592. ASSERT_FALSE(cli.is_valid());
  9593. }
  9594. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9595. // Port 99999 exceeds valid range (1-65535) — should not crash
  9596. httplib::Client cli("http://www.google.com:99999");
  9597. ASSERT_FALSE(cli.is_valid());
  9598. }
  9599. #ifdef CPPHTTPLIB_SSL_ENABLED
  9600. TEST(HostAndPortPropertiesTest, SSL) {
  9601. httplib::SSLClient cli("www.google.com");
  9602. ASSERT_EQ("www.google.com", cli.host());
  9603. ASSERT_EQ(443, cli.port());
  9604. }
  9605. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9606. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9607. std::string cert;
  9608. read_file(CA_CERT_FILE, cert);
  9609. httplib::SSLClient httplib_client("www.google.com");
  9610. // Load CA store first time
  9611. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9612. // Load CA store second time (update)
  9613. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9614. // Verify client is still valid and can make connections
  9615. httplib_client.enable_server_certificate_verification(true);
  9616. auto res = httplib_client.Get("/");
  9617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9618. // Google may return 200 or 301 depending on various factors
  9619. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9620. res->status == StatusCode::MovedPermanently_301);
  9621. }
  9622. TEST(SSLClientTest, ServerNameIndication_Online) {
  9623. auto host = "httpbingo.org";
  9624. auto path = std::string{"/get"};
  9625. SSLClient cli(host, 443);
  9626. auto res = cli.Get(path);
  9627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9628. ASSERT_EQ(StatusCode::OK_200, res->status);
  9629. }
  9630. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9631. // Use a site that will cause SSL verification failure due to self-signed cert
  9632. SSLClient cli("self-signed.badssl.com", 443);
  9633. cli.enable_server_certificate_verification(true);
  9634. auto res = cli.Get("/");
  9635. ASSERT_TRUE(!res);
  9636. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9637. // Verify backend error is captured for SSLServerVerification
  9638. // This occurs when certificate verification fails
  9639. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9640. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9641. EXPECT_NE(0UL, res.ssl_backend_error());
  9642. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9643. // For OpenSSL, ssl_error is 0 for verification errors
  9644. EXPECT_EQ(0, res.ssl_error());
  9645. #if !defined(_WIN32) || \
  9646. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9647. // On non-Windows or when Windows Schannel is disabled, the error comes
  9648. // from OpenSSL's verification
  9649. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9650. res.ssl_backend_error());
  9651. #endif
  9652. #endif
  9653. }
  9654. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9655. // Use a site where hostname doesn't match the certificate
  9656. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9657. SSLClient cli("wrong.host.badssl.com", 443);
  9658. cli.enable_server_certificate_verification(true);
  9659. cli.enable_server_hostname_verification(true);
  9660. auto res = cli.Get("/");
  9661. ASSERT_TRUE(!res);
  9662. // The error type depends on when hostname verification occurs:
  9663. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9664. // - Mbed TLS: SSLServerVerification (during handshake)
  9665. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9666. res.error() == Error::SSLServerVerification);
  9667. // Verify backend error is captured for hostname verification failure
  9668. EXPECT_NE(0UL, res.ssl_backend_error());
  9669. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9670. // For OpenSSL, ssl_error is 0 for verification errors
  9671. EXPECT_EQ(0, res.ssl_error());
  9672. #if !defined(_WIN32) || \
  9673. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9674. // On non-Windows or when Windows Schannel is disabled, the error comes
  9675. // from OpenSSL's hostname verification
  9676. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9677. res.ssl_backend_error());
  9678. #endif
  9679. #endif
  9680. }
  9681. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9682. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9683. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9684. SSLClient cli("www.google.com", 443);
  9685. cli.enable_server_certificate_verification(true);
  9686. auto res = cli.Get("/");
  9687. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9688. }
  9689. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9690. SSLClient cli("www.google.com", 443);
  9691. cli.enable_server_certificate_verification(true);
  9692. cli.enable_windows_certificate_verification(false);
  9693. auto res = cli.Get("/");
  9694. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9695. }
  9696. #endif
  9697. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9698. Client cli("https://google.com");
  9699. auto res = cli.Get("/");
  9700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9701. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9702. }
  9703. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9704. SSLClient cli("google.com");
  9705. cli.set_ca_cert_path(CA_CERT_FILE);
  9706. auto res = cli.Get("/");
  9707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9708. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9709. }
  9710. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9711. SSLClient cli("google.com");
  9712. cli.enable_server_certificate_verification(true);
  9713. cli.set_ca_cert_path("hello");
  9714. auto res = cli.Get("/");
  9715. ASSERT_TRUE(!res);
  9716. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9717. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9718. // should be set
  9719. EXPECT_EQ(0, res.ssl_error());
  9720. // Verify backend error is captured for SSLLoadingCerts
  9721. // This error occurs when loading CA certificates fails
  9722. EXPECT_NE(0UL, res.ssl_backend_error());
  9723. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9724. // OpenSSL specific error codes:
  9725. // > openssl errstr 0x80000002
  9726. // error:80000002:system library::No such file or directory
  9727. // > openssl errstr 0xA000126
  9728. // error:0A000126:SSL routines::unexpected eof while reading
  9729. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9730. res.ssl_backend_error() == 0xA000126);
  9731. #endif
  9732. }
  9733. TEST(SSLClientTest, ServerCertificateVerification4) {
  9734. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9735. ASSERT_TRUE(svr.is_valid());
  9736. svr.Get("/test", [&](const Request &, Response &res) {
  9737. res.set_content("test", "text/plain");
  9738. svr.stop();
  9739. ASSERT_TRUE(true);
  9740. });
  9741. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9742. auto se = detail::scope_exit([&] {
  9743. t.join();
  9744. ASSERT_FALSE(svr.is_running());
  9745. });
  9746. svr.wait_until_ready();
  9747. SSLClient cli("127.0.0.1", PORT);
  9748. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9749. cli.enable_server_certificate_verification(true);
  9750. cli.set_connection_timeout(30);
  9751. auto res = cli.Get("/test");
  9752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9753. ASSERT_EQ(StatusCode::OK_200, res->status);
  9754. }
  9755. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9756. std::string cert;
  9757. read_file(CA_CERT_FILE, cert);
  9758. SSLClient cli("google.com");
  9759. cli.load_ca_cert_store(cert.data(), cert.size());
  9760. const auto res = cli.Get("/");
  9761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9762. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9763. }
  9764. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9765. // clang-format off
  9766. static constexpr char cert[] =
  9767. "GlobalSign Root CA\n"
  9768. "==================\n"
  9769. "-----BEGIN CERTIFICATE-----\n"
  9770. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9771. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9772. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9773. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9774. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9775. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9776. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9777. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9778. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9779. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9780. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9781. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9782. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9783. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9784. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9785. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9786. "-----END CERTIFICATE-----\n";
  9787. // clang-format on
  9788. SSLClient cli("google.com");
  9789. cli.load_ca_cert_store(cert, sizeof(cert));
  9790. const auto res = cli.Get("/");
  9791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9792. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9793. }
  9794. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9795. SSLClient cli("www.youtube.com");
  9796. cli.set_ca_cert_path(CA_CERT_FILE);
  9797. cli.enable_server_certificate_verification(true);
  9798. cli.set_follow_location(true);
  9799. auto res = cli.Get("/");
  9800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9801. ASSERT_EQ(StatusCode::OK_200, res->status);
  9802. }
  9803. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9804. SSLClient cli("wWw.YouTube.Com");
  9805. cli.set_ca_cert_path(CA_CERT_FILE);
  9806. cli.enable_server_certificate_verification(true);
  9807. cli.enable_server_hostname_verification(true);
  9808. cli.set_follow_location(true);
  9809. auto res = cli.Get("/");
  9810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9811. ASSERT_EQ(StatusCode::OK_200, res->status);
  9812. }
  9813. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9814. SSLClient cli("gOoGlE.COm");
  9815. cli.enable_server_certificate_verification(true);
  9816. cli.enable_server_hostname_verification(true);
  9817. cli.set_follow_location(true);
  9818. auto res = cli.Get("/");
  9819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9820. ASSERT_EQ(StatusCode::OK_200, res->status);
  9821. }
  9822. TEST(SSLClientTest, Issue2004_Online) {
  9823. Client client("https://google.com");
  9824. client.set_follow_location(true);
  9825. auto res = client.Get("/");
  9826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9827. ASSERT_EQ(StatusCode::OK_200, res->status);
  9828. auto body = res->body;
  9829. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9830. }
  9831. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9832. // Create SSLClient with invalid cert/key to make is_valid() return false
  9833. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9834. "nonexistent_key.pem");
  9835. // is_valid() should be false due to cert loading failure
  9836. ASSERT_FALSE(cli.is_valid());
  9837. auto res = cli.Get("/");
  9838. ASSERT_FALSE(res);
  9839. EXPECT_EQ(Error::SSLConnection, res.error());
  9840. }
  9841. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9842. // Test for Issue #2251: SSL error not properly reported when client cert
  9843. // and key paths are swapped or mismatched
  9844. // This simulates the scenario where user accidentally swaps the cert and key
  9845. // files
  9846. // Using client cert file as private key and vice versa (completely wrong)
  9847. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9848. // Should fail validation due to cert/key mismatch
  9849. ASSERT_FALSE(cli.is_valid());
  9850. // Attempt to make a request should fail with proper error
  9851. auto res = cli.Get("/");
  9852. ASSERT_FALSE(res);
  9853. EXPECT_EQ(Error::SSLConnection, res.error());
  9854. // SSL error should be recorded in the Result object (this is the key fix for
  9855. // Issue #2251)
  9856. auto backend_error = res.ssl_backend_error();
  9857. EXPECT_NE(0u, backend_error);
  9858. }
  9859. // Tests cert/key mismatch detection at the TLS context level
  9860. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9861. // Test that using mismatched cert/key causes connection failure.
  9862. // We verify this at the SSLClient level rather than through internal
  9863. // TLS API functions.
  9864. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9865. cli.enable_server_certificate_verification(false);
  9866. cli.set_connection_timeout(2);
  9867. // The mismatch should cause a connection or handshake error
  9868. auto res = cli.Get("/test");
  9869. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9870. // Either way, the request should fail
  9871. EXPECT_FALSE(res);
  9872. }
  9873. #endif
  9874. #if 0
  9875. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9876. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9877. ASSERT_TRUE(cli != nullptr);
  9878. cli->set_address_family(AF_INET6);
  9879. cli->set_interface("en0");
  9880. auto res = cli->Get("/get");
  9881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9882. ASSERT_EQ(StatusCode::OK_200, res->status);
  9883. }
  9884. #endif
  9885. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9886. #ifdef CPPHTTPLIB_SSL_ENABLED
  9887. void ClientCertPresent(
  9888. const std::string &client_cert_file,
  9889. const std::string &client_private_key_file,
  9890. const std::string &client_encrypted_private_key_pass = std::string()) {
  9891. using namespace httplib::tls;
  9892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9893. CLIENT_CA_CERT_DIR);
  9894. ASSERT_TRUE(svr.is_valid());
  9895. svr.Get("/test", [&](const Request &req, Response &res) {
  9896. res.set_content("test", "text/plain");
  9897. auto cert = req.peer_cert();
  9898. ASSERT_TRUE(static_cast<bool>(cert));
  9899. std::string common_name = cert.subject_cn();
  9900. EXPECT_EQ("Common Name", common_name);
  9901. });
  9902. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9903. auto se = detail::scope_exit([&] {
  9904. svr.stop();
  9905. t.join();
  9906. ASSERT_FALSE(svr.is_running());
  9907. });
  9908. svr.wait_until_ready();
  9909. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9910. client_encrypted_private_key_pass);
  9911. cli.enable_server_certificate_verification(false);
  9912. cli.set_connection_timeout(30);
  9913. auto res = cli.Get("/test");
  9914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9915. ASSERT_EQ(StatusCode::OK_200, res->status);
  9916. }
  9917. TEST(SSLClientServerTest, ClientCertPresent) {
  9918. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9919. }
  9920. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9921. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9922. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9923. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9924. }
  9925. // PEM memory-based constructor tests (works with all TLS backends)
  9926. void PemMemoryClientCertPresent(
  9927. const std::string &client_cert_file,
  9928. const std::string &client_private_key_file,
  9929. const std::string &client_encrypted_private_key_pass = std::string()) {
  9930. // Read PEM files into memory
  9931. std::string server_cert_pem, server_key_pem;
  9932. std::string client_ca_pem;
  9933. std::string client_cert_pem, client_key_pem;
  9934. read_file(SERVER_CERT_FILE, server_cert_pem);
  9935. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9936. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9937. read_file(client_cert_file, client_cert_pem);
  9938. read_file(client_private_key_file, client_key_pem);
  9939. // Create server with PEM memory
  9940. SSLServer::PemMemory server_pem = {
  9941. server_cert_pem.c_str(),
  9942. server_cert_pem.size(),
  9943. server_key_pem.c_str(),
  9944. server_key_pem.size(),
  9945. client_ca_pem.c_str(),
  9946. client_ca_pem.size(),
  9947. nullptr // no password for server key
  9948. };
  9949. SSLServer svr(server_pem);
  9950. ASSERT_TRUE(svr.is_valid());
  9951. svr.Get("/test", [&](const Request &, Response &res) {
  9952. res.set_content("test", "text/plain");
  9953. });
  9954. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9955. auto se = detail::scope_exit([&] {
  9956. svr.stop();
  9957. t.join();
  9958. ASSERT_FALSE(svr.is_running());
  9959. });
  9960. svr.wait_until_ready();
  9961. // Create client with PEM memory
  9962. const char *password = client_encrypted_private_key_pass.empty()
  9963. ? nullptr
  9964. : client_encrypted_private_key_pass.c_str();
  9965. SSLClient::PemMemory client_pem = {
  9966. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9967. client_key_pem.size(), password};
  9968. SSLClient cli(HOST, PORT, client_pem);
  9969. cli.enable_server_certificate_verification(false);
  9970. cli.set_connection_timeout(30);
  9971. auto res = cli.Get("/test");
  9972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9973. ASSERT_EQ(StatusCode::OK_200, res->status);
  9974. }
  9975. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9976. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9977. }
  9978. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9979. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9980. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9981. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9982. }
  9983. TEST(SSLClientServerTest, ClientCertMissing) {
  9984. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9985. CLIENT_CA_CERT_DIR);
  9986. ASSERT_TRUE(svr.is_valid());
  9987. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9989. auto se = detail::scope_exit([&] {
  9990. svr.stop();
  9991. t.join();
  9992. ASSERT_FALSE(svr.is_running());
  9993. });
  9994. svr.wait_until_ready();
  9995. SSLClient cli(HOST, PORT);
  9996. cli.set_connection_timeout(30);
  9997. auto res = cli.Get("/test");
  9998. ASSERT_TRUE(!res);
  9999. // When client cert is missing and server requires it, connection fails
  10000. // Error type depends on backend implementation
  10001. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10002. res.error() == Error::SSLConnection);
  10003. // Verify backend error is captured
  10004. // Note: This test may have different error codes depending on the exact
  10005. // verification failure
  10006. EXPECT_NE(0UL, res.ssl_backend_error());
  10007. }
  10008. TEST(SSLClientServerTest, TrustDirOptional) {
  10009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10010. ASSERT_TRUE(svr.is_valid());
  10011. svr.Get("/test", [&](const Request &, Response &res) {
  10012. res.set_content("test", "text/plain");
  10013. });
  10014. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10015. auto se = detail::scope_exit([&] {
  10016. svr.stop();
  10017. t.join();
  10018. ASSERT_FALSE(svr.is_running());
  10019. });
  10020. svr.wait_until_ready();
  10021. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10022. cli.enable_server_certificate_verification(false);
  10023. cli.set_connection_timeout(30);
  10024. auto res = cli.Get("/test");
  10025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10026. ASSERT_EQ(StatusCode::OK_200, res->status);
  10027. }
  10028. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10029. class NoListenSSLServer : public SSLServer {
  10030. public:
  10031. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10032. const char *client_ca_cert_file_path,
  10033. const char *client_ca_cert_dir_path = nullptr)
  10034. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10035. client_ca_cert_dir_path),
  10036. stop_(false) {}
  10037. std::atomic_bool stop_;
  10038. private:
  10039. bool process_and_close_socket(socket_t /*sock*/) override {
  10040. // Don't create SSL context
  10041. while (!stop_.load()) {
  10042. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10043. }
  10044. return true;
  10045. }
  10046. };
  10047. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10048. CLIENT_CA_CERT_FILE);
  10049. ASSERT_TRUE(svr.is_valid());
  10050. svr.Get("/test", [&](const Request &, Response &res) {
  10051. res.set_content("test", "text/plain");
  10052. });
  10053. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10054. auto se = detail::scope_exit([&] {
  10055. svr.stop_ = true;
  10056. svr.stop();
  10057. t.join();
  10058. ASSERT_FALSE(svr.is_running());
  10059. });
  10060. svr.wait_until_ready();
  10061. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10062. cli.enable_server_certificate_verification(false);
  10063. cli.set_connection_timeout(1);
  10064. auto res = cli.Get("/test");
  10065. ASSERT_TRUE(!res);
  10066. EXPECT_EQ(Error::SSLConnection, res.error());
  10067. // Timeout results in WantRead error code (maps to backend-specific value)
  10068. EXPECT_NE(0, res.ssl_error());
  10069. }
  10070. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10071. // Test SSLServer with client certificate verification using the standard
  10072. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10074. CLIENT_CA_CERT_DIR);
  10075. ASSERT_TRUE(svr.is_valid());
  10076. svr.Get("/test", [&](const Request &req, Response &res) {
  10077. res.set_content("test", "text/plain");
  10078. auto cert = req.peer_cert();
  10079. ASSERT_TRUE(static_cast<bool>(cert));
  10080. auto common_name = cert.subject_cn();
  10081. EXPECT_EQ("Common Name", common_name);
  10082. });
  10083. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10084. auto se = detail::scope_exit([&] {
  10085. svr.stop();
  10086. t.join();
  10087. ASSERT_FALSE(svr.is_running());
  10088. });
  10089. svr.wait_until_ready();
  10090. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10091. cli.enable_server_certificate_verification(false);
  10092. cli.set_connection_timeout(30);
  10093. auto res = cli.Get("/test");
  10094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10095. ASSERT_EQ(StatusCode::OK_200, res->status);
  10096. }
  10097. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10098. // Verifies that wildcard matching and exact matching work consistently
  10099. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10100. using namespace httplib::tls;
  10101. // We need a running server to test against
  10102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10103. ASSERT_TRUE(svr.is_valid());
  10104. svr.Get("/test", [](const Request &, Response &res) {
  10105. res.set_content("ok", "text/plain");
  10106. });
  10107. thread t([&]() { svr.listen(HOST, PORT); });
  10108. auto se = detail::scope_exit([&] {
  10109. svr.stop();
  10110. t.join();
  10111. });
  10112. svr.wait_until_ready();
  10113. bool verify_callback_called = false;
  10114. bool verify_result_wrong = false;
  10115. SSLClient cli(HOST, PORT);
  10116. cli.enable_server_certificate_verification(true);
  10117. cli.set_ca_cert_path(CA_CERT_FILE);
  10118. cli.set_connection_timeout(5);
  10119. // Note: Test certificate has CN="Common Name", not "localhost"
  10120. bool verify_result_cn = false;
  10121. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10122. verify_callback_called = true;
  10123. if (!ctx.cert) return false;
  10124. // Test 1: "Common Name" should match (our test server cert CN)
  10125. verify_result_cn = ctx.check_hostname("Common Name");
  10126. // Test 2: wrong hostname should not match
  10127. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10128. return true; // Accept for the purpose of this test
  10129. });
  10130. auto res = cli.Get("/test");
  10131. // The request may succeed or fail depending on cert configuration
  10132. // but the callback should have been called
  10133. ASSERT_TRUE(verify_callback_called)
  10134. << "Verify callback should have been called";
  10135. // CN="Common Name" should match our test certificate
  10136. //
  10137. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10138. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10139. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10140. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10141. // <openssl/base.h>, which is included transitively when
  10142. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10143. #if defined(OPENSSL_IS_BORINGSSL)
  10144. EXPECT_FALSE(verify_result_cn)
  10145. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10146. #else
  10147. EXPECT_TRUE(verify_result_cn)
  10148. << "verify_hostname should match 'Common Name' (certificate CN)";
  10149. #endif
  10150. // Wrong hostname should not match
  10151. EXPECT_FALSE(verify_result_wrong)
  10152. << "verify_hostname should not match 'wronghost.example.com'";
  10153. }
  10154. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10155. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10156. // X509_check_ip behavior and must hold for every backend.
  10157. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10158. using namespace httplib::tls;
  10159. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10160. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10161. ASSERT_TRUE(svr.is_valid());
  10162. svr.Get("/test", [](const Request &, Response &res) {
  10163. res.set_content("ok", "text/plain");
  10164. });
  10165. thread t([&]() { svr.listen(HOST, PORT); });
  10166. auto se = detail::scope_exit([&] {
  10167. svr.stop();
  10168. t.join();
  10169. });
  10170. svr.wait_until_ready();
  10171. bool verify_callback_called = false;
  10172. bool ip_matched_via_cn = true;
  10173. SSLClient cli(HOST, PORT);
  10174. cli.enable_server_certificate_verification(true);
  10175. cli.set_ca_cert_path(CA_CERT_FILE);
  10176. cli.set_connection_timeout(5);
  10177. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10178. verify_callback_called = true;
  10179. if (!ctx.cert) return false;
  10180. // The IP appears only in the CN, so it must NOT be accepted.
  10181. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10182. return true; // Accept for the purpose of this test
  10183. });
  10184. cli.Get("/test");
  10185. ASSERT_TRUE(verify_callback_called)
  10186. << "Verify callback should have been called";
  10187. EXPECT_FALSE(ip_matched_via_cn)
  10188. << "An IP host must not be authenticated via the certificate CN";
  10189. }
  10190. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10191. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10192. using namespace httplib::tls;
  10193. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10194. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10195. ASSERT_TRUE(svr.is_valid());
  10196. svr.Get("/test", [](const Request &, Response &res) {
  10197. res.set_content("ok", "text/plain");
  10198. });
  10199. thread t([&]() { svr.listen(HOST, PORT); });
  10200. auto se = detail::scope_exit([&] {
  10201. svr.stop();
  10202. t.join();
  10203. });
  10204. svr.wait_until_ready();
  10205. bool verify_callback_called = false;
  10206. bool san_matched = false;
  10207. bool wrong_ipv6_matched = true;
  10208. bool cn_ipv6_matched = true;
  10209. SSLClient cli(HOST, PORT);
  10210. cli.enable_server_certificate_verification(true);
  10211. cli.set_ca_cert_path(CA_CERT_FILE);
  10212. cli.set_connection_timeout(5);
  10213. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10214. verify_callback_called = true;
  10215. if (!ctx.cert) return false;
  10216. // Matches the IPv6 iPAddress SAN.
  10217. san_matched = ctx.check_hostname("2001:db8::1");
  10218. // A different IPv6 address must not match.
  10219. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10220. // "::1" lives only in the CN, so it must not be accepted.
  10221. cn_ipv6_matched = ctx.check_hostname("::1");
  10222. return true; // Accept for the purpose of this test
  10223. });
  10224. cli.Get("/test");
  10225. ASSERT_TRUE(verify_callback_called)
  10226. << "Verify callback should have been called";
  10227. EXPECT_TRUE(san_matched)
  10228. << "verify_hostname should match an IPv6 iPAddress SAN";
  10229. EXPECT_FALSE(wrong_ipv6_matched)
  10230. << "verify_hostname should not match a non-matching IPv6 address";
  10231. EXPECT_FALSE(cn_ipv6_matched)
  10232. << "An IPv6 host must not be authenticated via the certificate CN";
  10233. }
  10234. #endif
  10235. // mbedTLS-specific callback constructor test
  10236. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10237. #ifdef CPPHTTPLIB_SSL_ENABLED
  10238. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10239. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10240. ASSERT_TRUE(svr.is_valid());
  10241. // Set up a handler to verify client certificate is present
  10242. bool client_cert_verified = false;
  10243. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10244. // Verify that client certificate was provided
  10245. client_cert_verified = true;
  10246. res.set_content("success", "text/plain");
  10247. });
  10248. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10249. auto se = detail::scope_exit([&] {
  10250. svr.stop();
  10251. t.join();
  10252. ASSERT_FALSE(svr.is_running());
  10253. });
  10254. svr.wait_until_ready();
  10255. // Client with certificate
  10256. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10257. cli.enable_server_certificate_verification(false);
  10258. cli.set_connection_timeout(30);
  10259. auto res = cli.Get("/test");
  10260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10261. ASSERT_EQ(StatusCode::OK_200, res->status);
  10262. ASSERT_TRUE(client_cert_verified);
  10263. EXPECT_EQ("success", res->body);
  10264. }
  10265. #endif
  10266. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10267. // backends
  10268. #ifdef CPPHTTPLIB_SSL_ENABLED
  10269. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10270. using namespace httplib::tls;
  10271. // Test that when client CA cert file is provided,
  10272. // the server properly requests and validates client certificates
  10273. // Create a server with client authentication
  10274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10275. ASSERT_TRUE(svr.is_valid());
  10276. bool handler_called = false;
  10277. svr.Get("/test", [&](const Request &req, Response &res) {
  10278. handler_called = true;
  10279. // Verify that a client certificate was provided
  10280. auto cert = req.peer_cert();
  10281. ASSERT_TRUE(static_cast<bool>(cert));
  10282. // Get the issuer name
  10283. std::string issuer_str = cert.issuer_name();
  10284. ASSERT_FALSE(issuer_str.empty());
  10285. // The client certificate should be issued by our test CA
  10286. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10287. res.set_content("authenticated", "text/plain");
  10288. });
  10289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10290. auto se = detail::scope_exit([&] {
  10291. svr.stop();
  10292. t.join();
  10293. ASSERT_FALSE(svr.is_running());
  10294. });
  10295. svr.wait_until_ready();
  10296. // Connect with a client certificate issued by the CA
  10297. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10298. cli.enable_server_certificate_verification(false);
  10299. cli.set_connection_timeout(30);
  10300. auto res = cli.Get("/test");
  10301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10302. ASSERT_EQ(StatusCode::OK_200, res->status);
  10303. ASSERT_TRUE(handler_called);
  10304. EXPECT_EQ("authenticated", res->body);
  10305. }
  10306. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10307. using namespace httplib::tls;
  10308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10309. ASSERT_TRUE(svr.is_valid());
  10310. svr.Get("/test", [](const Request &, Response &res) {
  10311. res.set_content("ok", "text/plain");
  10312. });
  10313. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10314. auto se = detail::scope_exit([&] {
  10315. svr.stop();
  10316. t.join();
  10317. });
  10318. svr.wait_until_ready();
  10319. SSLClient cli(HOST, PORT);
  10320. cli.enable_server_certificate_verification(false);
  10321. cli.set_connection_timeout(30);
  10322. bool cert_checked = false;
  10323. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10324. if (ctx.cert) {
  10325. auto sans = ctx.sans();
  10326. // Test certificate may or may not have SANs - just verify the API
  10327. // works If SANs exist, verify the types are valid
  10328. for (const auto &san : sans) {
  10329. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10330. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10331. san.type == SanType::OTHER);
  10332. EXPECT_FALSE(san.value.empty());
  10333. }
  10334. cert_checked = true;
  10335. }
  10336. return true;
  10337. });
  10338. auto res = cli.Get("/test");
  10339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10340. EXPECT_TRUE(cert_checked);
  10341. }
  10342. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10343. using namespace httplib::tls;
  10344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10345. ASSERT_TRUE(svr.is_valid());
  10346. svr.Get("/test", [](const Request &, Response &res) {
  10347. res.set_content("ok", "text/plain");
  10348. });
  10349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10350. auto se = detail::scope_exit([&] {
  10351. svr.stop();
  10352. t.join();
  10353. });
  10354. svr.wait_until_ready();
  10355. SSLClient cli(HOST, PORT);
  10356. cli.enable_server_certificate_verification(false);
  10357. cli.set_connection_timeout(30);
  10358. bool validity_checked = false;
  10359. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10360. if (ctx.cert) {
  10361. time_t not_before = 0, not_after = 0;
  10362. bool result = ctx.validity(not_before, not_after);
  10363. EXPECT_TRUE(result);
  10364. // Verify that not_before < now < not_after for a valid cert
  10365. time_t now = time(nullptr);
  10366. EXPECT_LT(not_before, now);
  10367. EXPECT_GT(not_after, now);
  10368. validity_checked = true;
  10369. }
  10370. return true;
  10371. });
  10372. auto res = cli.Get("/test");
  10373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10374. EXPECT_TRUE(validity_checked);
  10375. }
  10376. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10377. using namespace httplib::tls;
  10378. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10379. ASSERT_TRUE(svr.is_valid());
  10380. svr.Get("/test", [](const Request &, Response &res) {
  10381. res.set_content("ok", "text/plain");
  10382. });
  10383. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10384. auto se = detail::scope_exit([&] {
  10385. svr.stop();
  10386. t.join();
  10387. });
  10388. svr.wait_until_ready();
  10389. SSLClient cli(HOST, PORT);
  10390. cli.enable_server_certificate_verification(false);
  10391. cli.set_connection_timeout(30);
  10392. bool serial_checked = false;
  10393. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10394. if (ctx.cert) {
  10395. std::string serial = ctx.serial();
  10396. EXPECT_FALSE(serial.empty());
  10397. // Serial should be a hex string
  10398. for (char c : serial) {
  10399. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10400. (c >= 'a' && c <= 'f'));
  10401. }
  10402. serial_checked = true;
  10403. }
  10404. return true;
  10405. });
  10406. auto res = cli.Get("/test");
  10407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10408. EXPECT_TRUE(serial_checked);
  10409. }
  10410. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10411. // Test 1: Valid CA file - no error should be recorded
  10412. {
  10413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10414. CLIENT_CA_CERT_FILE);
  10415. ASSERT_TRUE(svr.is_valid());
  10416. // With valid setup, last_ssl_error should be 0
  10417. EXPECT_EQ(0, svr.ssl_last_error());
  10418. }
  10419. // Test 2: Invalid CA file content
  10420. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10421. {
  10422. // Create a temporary file with completely invalid content
  10423. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10424. {
  10425. std::ofstream ofs(temp_invalid_ca);
  10426. ofs << "This is not a certificate file at all\n";
  10427. ofs << "Just plain text content\n";
  10428. }
  10429. // Create server with invalid CA file
  10430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10431. // Clean up temporary file
  10432. std::remove(temp_invalid_ca);
  10433. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10434. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10435. // Note: SSL_CTX_load_verify_locations typically fails first,
  10436. // but our error handling code path is still exercised
  10437. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10438. }
  10439. }
  10440. TEST(VerifyCallbackTest, VerifyContextFields) {
  10441. using namespace httplib::tls;
  10442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10443. ASSERT_TRUE(svr.is_valid());
  10444. svr.Get("/test", [](const Request &, Response &res) {
  10445. res.set_content("ok", "text/plain");
  10446. });
  10447. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10448. auto se = detail::scope_exit([&] {
  10449. svr.stop();
  10450. t.join();
  10451. });
  10452. svr.wait_until_ready();
  10453. SSLClient cli(HOST, PORT);
  10454. cli.enable_server_certificate_verification(false);
  10455. cli.set_connection_timeout(30);
  10456. int callback_count = 0;
  10457. bool saw_leaf_cert = false;
  10458. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10459. if (ctx.cert) {
  10460. callback_count++;
  10461. // We should see at least one certificate (the leaf)
  10462. std::string cn = ctx.subject_cn();
  10463. if (!cn.empty()) { saw_leaf_cert = true; }
  10464. // Verify context fields are populated
  10465. EXPECT_NE(ctx.session, nullptr);
  10466. EXPECT_GE(ctx.depth, 0);
  10467. }
  10468. return true;
  10469. });
  10470. auto res = cli.Get("/test");
  10471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10472. EXPECT_GT(callback_count, 0);
  10473. EXPECT_TRUE(saw_leaf_cert);
  10474. }
  10475. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10476. using httplib::tls::TlsError;
  10477. // Test that verify_error_to_string returns empty for success
  10478. std::string success_str = TlsError::verify_error_to_string(0);
  10479. EXPECT_TRUE(success_str.empty());
  10480. // Test that verify_error_to_string returns non-empty for error codes
  10481. // Using a common error code (certificate expired)
  10482. std::string error_str =
  10483. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10484. EXPECT_FALSE(error_str.empty());
  10485. }
  10486. TEST(SessionVerifierTest, CertificateAccepted) {
  10487. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10488. ASSERT_TRUE(svr.is_valid());
  10489. svr.Get("/test", [](const Request &, Response &res) {
  10490. res.set_content("ok", "text/plain");
  10491. });
  10492. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10493. auto se = detail::scope_exit([&] {
  10494. svr.stop();
  10495. t.join();
  10496. });
  10497. svr.wait_until_ready();
  10498. SSLClient cli(HOST, PORT);
  10499. cli.enable_server_certificate_verification(false);
  10500. cli.set_connection_timeout(30);
  10501. bool callback_called = false;
  10502. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10503. EXPECT_NE(session, nullptr);
  10504. callback_called = true;
  10505. return SSLVerifierResponse::CertificateAccepted;
  10506. });
  10507. auto res = cli.Get("/test");
  10508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10509. EXPECT_EQ(200, res->status);
  10510. EXPECT_TRUE(callback_called);
  10511. }
  10512. TEST(SessionVerifierTest, CertificateRejected) {
  10513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10514. ASSERT_TRUE(svr.is_valid());
  10515. svr.Get("/test", [](const Request &, Response &res) {
  10516. res.set_content("ok", "text/plain");
  10517. });
  10518. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10519. auto se = detail::scope_exit([&] {
  10520. svr.stop();
  10521. t.join();
  10522. });
  10523. svr.wait_until_ready();
  10524. SSLClient cli(HOST, PORT);
  10525. cli.enable_server_certificate_verification(false);
  10526. cli.set_connection_timeout(30);
  10527. bool callback_called = false;
  10528. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10529. EXPECT_NE(session, nullptr);
  10530. callback_called = true;
  10531. return SSLVerifierResponse::CertificateRejected;
  10532. });
  10533. auto res = cli.Get("/test");
  10534. EXPECT_FALSE(res);
  10535. EXPECT_TRUE(callback_called);
  10536. }
  10537. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10539. ASSERT_TRUE(svr.is_valid());
  10540. svr.Get("/test", [](const Request &, Response &res) {
  10541. res.set_content("ok", "text/plain");
  10542. });
  10543. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10544. auto se = detail::scope_exit([&] {
  10545. svr.stop();
  10546. t.join();
  10547. });
  10548. svr.wait_until_ready();
  10549. // NoDecisionMade with verification disabled should succeed (no default check)
  10550. SSLClient cli(HOST, PORT);
  10551. cli.enable_server_certificate_verification(false);
  10552. cli.set_connection_timeout(30);
  10553. bool callback_called = false;
  10554. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10555. EXPECT_NE(session, nullptr);
  10556. callback_called = true;
  10557. return SSLVerifierResponse::NoDecisionMade;
  10558. });
  10559. auto res = cli.Get("/test");
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. EXPECT_EQ(200, res->status);
  10562. EXPECT_TRUE(callback_called);
  10563. }
  10564. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10566. ASSERT_TRUE(svr.is_valid());
  10567. svr.Get("/test", [](const Request &, Response &res) {
  10568. res.set_content("ok", "text/plain");
  10569. });
  10570. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10571. auto se = detail::scope_exit([&] {
  10572. svr.stop();
  10573. t.join();
  10574. });
  10575. svr.wait_until_ready();
  10576. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10577. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10578. // so we only check that the request fails, not whether the callback was
  10579. // called.
  10580. SSLClient cli(HOST, PORT);
  10581. cli.enable_server_certificate_verification(true);
  10582. cli.set_connection_timeout(30);
  10583. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10584. EXPECT_NE(session, nullptr);
  10585. return SSLVerifierResponse::NoDecisionMade;
  10586. });
  10587. auto res = cli.Get("/test");
  10588. EXPECT_FALSE(res);
  10589. }
  10590. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10591. // Test SSL server using PemMemory constructor with client CA certificates
  10592. // Read PEM files
  10593. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10594. read_file(SERVER_CERT_FILE, server_cert_pem);
  10595. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10596. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10597. // Create SSLServer with PemMemory constructor including client CA
  10598. SSLServer::PemMemory server_pem = {
  10599. server_cert_pem.c_str(),
  10600. server_cert_pem.size(),
  10601. server_key_pem.c_str(),
  10602. server_key_pem.size(),
  10603. client_ca_pem.c_str(),
  10604. client_ca_pem.size(),
  10605. nullptr // no password for server key
  10606. };
  10607. SSLServer svr(server_pem);
  10608. ASSERT_TRUE(svr.is_valid());
  10609. // No SSL error should be recorded for valid setup
  10610. EXPECT_EQ(0, svr.ssl_last_error());
  10611. // Set up server endpoints
  10612. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10613. res.set_content("ok", "text/plain");
  10614. });
  10615. // Start server in a thread
  10616. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10617. svr.wait_until_ready();
  10618. // Connect with client certificate (using constructor with paths)
  10619. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10620. cli.enable_server_certificate_verification(false);
  10621. auto res = cli.Get("/test-pem-ca");
  10622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10623. EXPECT_EQ(200, res->status);
  10624. EXPECT_EQ("ok", res->body);
  10625. svr.stop();
  10626. server_thread.join();
  10627. }
  10628. #endif
  10629. #ifdef _WIN32
  10630. TEST(CleanupTest, WSACleanup) {
  10631. int ret = WSACleanup();
  10632. ASSERT_EQ(0, ret);
  10633. }
  10634. #endif
  10635. #ifndef CPPHTTPLIB_SSL_ENABLED
  10636. TEST(NoSSLSupport, SimpleInterface) {
  10637. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10638. }
  10639. #endif
  10640. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10641. TEST(InvalidScheme, SimpleInterface) {
  10642. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10643. }
  10644. #endif
  10645. TEST(NoScheme, SimpleInterface) {
  10646. Client cli("yahoo.com:80");
  10647. ASSERT_TRUE(cli.is_valid());
  10648. }
  10649. TEST(SendAPI, SimpleInterface_Online) {
  10650. Client cli("http://yahoo.com");
  10651. Request req;
  10652. req.method = "GET";
  10653. req.path = "/";
  10654. auto res = cli.send(req);
  10655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10656. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10657. }
  10658. TEST(SendAPI, WithParamsInRequest) {
  10659. Server svr;
  10660. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10661. EXPECT_TRUE(req.has_param("test"));
  10662. EXPECT_EQ("test_value", req.get_param_value("test"));
  10663. });
  10664. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10665. auto se = detail::scope_exit([&] {
  10666. svr.stop();
  10667. t.join();
  10668. ASSERT_FALSE(svr.is_running());
  10669. });
  10670. svr.wait_until_ready();
  10671. Client cli(HOST, PORT);
  10672. {
  10673. Request req;
  10674. req.method = "GET";
  10675. req.path = "/";
  10676. req.params.emplace("test", "test_value");
  10677. auto res = cli.send(req);
  10678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10679. }
  10680. {
  10681. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10683. }
  10684. }
  10685. TEST(ClientImplMethods, GetSocketTest) {
  10686. httplib::Server svr;
  10687. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10688. res.status = StatusCode::OK_200;
  10689. });
  10690. auto port = svr.bind_to_any_port("127.0.0.1");
  10691. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10692. auto se = detail::scope_exit([&] {
  10693. svr.stop();
  10694. thread.join();
  10695. ASSERT_FALSE(svr.is_running());
  10696. });
  10697. svr.wait_until_ready();
  10698. {
  10699. httplib::Client cli("127.0.0.1", port);
  10700. cli.set_keep_alive(true);
  10701. // Use the behavior of cpp-httplib of opening the connection
  10702. // only when the first request happens. If that changes,
  10703. // this test would be obsolete.
  10704. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10705. // This also implicitly tests the server. But other tests would fail much
  10706. // earlier than this one to be considered.
  10707. auto res = cli.Get("/");
  10708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10709. EXPECT_EQ(StatusCode::OK_200, res->status);
  10710. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10711. }
  10712. }
  10713. #ifdef CPPHTTPLIB_SSL_ENABLED
  10714. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10715. Client cli("http://yahoo.com");
  10716. auto res = cli.Get("/");
  10717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10718. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10719. cli.set_follow_location(true);
  10720. res = cli.Get("/");
  10721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10722. EXPECT_EQ(StatusCode::OK_200, res->status);
  10723. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10724. }
  10725. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10726. Client cli("https://yahoo.com");
  10727. auto res = cli.Get("/");
  10728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10730. cli.set_follow_location(true);
  10731. res = cli.Get("/");
  10732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10733. EXPECT_EQ(StatusCode::OK_200, res->status);
  10734. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10735. }
  10736. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10737. Client cli("https://yahoo.com");
  10738. auto res = cli.Get("/");
  10739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10740. ASSERT_FALSE(!res);
  10741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10742. ASSERT_FALSE(res == nullptr);
  10743. ASSERT_TRUE(res != nullptr);
  10744. EXPECT_EQ(Error::Success, res.error());
  10745. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10746. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10747. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10748. cli.set_follow_location(true);
  10749. res = cli.Get("/");
  10750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10751. EXPECT_EQ(Error::Success, res.error());
  10752. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10753. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10754. EXPECT_EQ(StatusCode::OK_200, res->status);
  10755. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10756. }
  10757. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10758. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10759. Client cli("https://cdnjs.cloudflare.com");
  10760. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10761. Headers{{"Accept-Encoding", "br"}});
  10762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10763. EXPECT_EQ(StatusCode::OK_200, res->status);
  10764. EXPECT_EQ(287630U, res->body.size());
  10765. EXPECT_EQ("application/javascript; charset=utf-8",
  10766. res->get_header_value("Content-Type"));
  10767. }
  10768. #endif
  10769. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10770. #undef REDIR_HOST // Silence compiler warning
  10771. #define REDIR_HOST "https://httpbingo.org"
  10772. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10773. Client cli(REDIR_HOST);
  10774. cli.set_follow_location(true);
  10775. auto res =
  10776. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10778. EXPECT_EQ(StatusCode::OK_200, res->status);
  10779. }
  10780. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10781. Client cli(REDIR_HOST);
  10782. cli.set_follow_location(true);
  10783. Params params;
  10784. params.emplace("url", "http://example.com");
  10785. params.emplace("status_code", "302");
  10786. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10788. EXPECT_EQ(StatusCode::OK_200, res->status);
  10789. }
  10790. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10791. Client cli(REDIR_HOST);
  10792. cli.set_follow_location(true);
  10793. Params params;
  10794. params.emplace("url", "http://example.com");
  10795. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10797. EXPECT_EQ(StatusCode::OK_200, res->status);
  10798. }
  10799. TEST(HttpToHttpsRedirectTest, CertFile) {
  10800. auto ssl_port = PORT + 1;
  10801. Server svr;
  10802. ASSERT_TRUE(svr.is_valid());
  10803. svr.Get("/index", [&](const Request &, Response &res) {
  10804. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10805. "/index");
  10806. svr.stop();
  10807. });
  10808. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10809. ASSERT_TRUE(ssl_svr.is_valid());
  10810. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10811. res.set_content("test", "text/plain");
  10812. ssl_svr.stop();
  10813. });
  10814. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10815. thread t2 =
  10816. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10817. auto se = detail::scope_exit([&] {
  10818. t2.join();
  10819. t.join();
  10820. ASSERT_FALSE(svr.is_running());
  10821. });
  10822. svr.wait_until_ready();
  10823. ssl_svr.wait_until_ready();
  10824. Client cli("127.0.0.1", PORT);
  10825. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10826. cli.enable_server_certificate_verification(true);
  10827. cli.set_follow_location(true);
  10828. cli.set_connection_timeout(30);
  10829. auto res = cli.Get("/index");
  10830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10831. ASSERT_EQ(StatusCode::OK_200, res->status);
  10832. }
  10833. TEST(SSLClientRedirectTest, CertFile) {
  10834. auto ssl_port = PORT + 1;
  10835. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10836. ASSERT_TRUE(ssl_svr1.is_valid());
  10837. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10838. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10839. "/index");
  10840. ssl_svr1.stop();
  10841. });
  10842. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10843. ASSERT_TRUE(ssl_svr2.is_valid());
  10844. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10845. res.set_content("test", "text/plain");
  10846. ssl_svr2.stop();
  10847. });
  10848. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10849. thread t2 =
  10850. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10851. auto se = detail::scope_exit([&] {
  10852. t2.join();
  10853. t.join();
  10854. ASSERT_FALSE(ssl_svr1.is_running());
  10855. });
  10856. ssl_svr1.wait_until_ready();
  10857. ssl_svr2.wait_until_ready();
  10858. SSLClient cli("127.0.0.1", PORT);
  10859. std::string cert;
  10860. read_file(SERVER_CERT2_FILE, cert);
  10861. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10862. cli.enable_server_certificate_verification(true);
  10863. cli.set_follow_location(true);
  10864. cli.set_connection_timeout(30);
  10865. auto res = cli.Get("/index");
  10866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10867. ASSERT_EQ(StatusCode::OK_200, res->status);
  10868. }
  10869. #endif
  10870. #ifdef CPPHTTPLIB_SSL_ENABLED
  10871. // Test that set_ca_cert_store() skips system certs (consistent with
  10872. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10873. // should be trusted - system certs should NOT be loaded.
  10874. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10875. // Load a specific cert that is NOT a system CA cert
  10876. std::string cert;
  10877. read_file(SERVER_CERT2_FILE, cert);
  10878. SSLClient cli("google.com");
  10879. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10880. cli.enable_server_certificate_verification(true);
  10881. // This should FAIL because:
  10882. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10883. // 2. System certs should NOT be loaded when custom store is set
  10884. // If system certs WERE loaded, this would succeed
  10885. auto res = cli.Get("/");
  10886. ASSERT_FALSE(res);
  10887. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10888. }
  10889. // Same as above, but through the native store handle path. Regression test:
  10890. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10891. // merged system certs into the user-provided store.
  10892. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10893. std::string cert;
  10894. read_file(SERVER_CERT2_FILE, cert);
  10895. SSLClient cli("google.com");
  10896. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10897. cli.enable_server_certificate_verification(true);
  10898. auto res = cli.Get("/");
  10899. ASSERT_FALSE(res);
  10900. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10901. }
  10902. // A custom store set via the native handle must still verify a server whose
  10903. // cert it does contain.
  10904. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10905. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10906. ASSERT_TRUE(svr.is_valid());
  10907. svr.Get("/test", [&](const Request &, Response &res) {
  10908. res.set_content("test", "text/plain");
  10909. });
  10910. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10911. auto se = detail::scope_exit([&] {
  10912. svr.stop();
  10913. t.join();
  10914. ASSERT_FALSE(svr.is_running());
  10915. });
  10916. svr.wait_until_ready();
  10917. SSLClient cli("127.0.0.1", PORT);
  10918. std::string cert;
  10919. read_file(SERVER_CERT2_FILE, cert);
  10920. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10921. cli.enable_server_certificate_verification(true);
  10922. cli.set_connection_timeout(30);
  10923. auto res = cli.Get("/test");
  10924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10925. ASSERT_EQ(StatusCode::OK_200, res->status);
  10926. }
  10927. // CA certs loaded through the universal Client must be transferred to the
  10928. // client created internally for following an HTTPS redirect. Regression test:
  10929. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10930. // the CA data for redirect transfer.
  10931. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10932. auto ssl_port = PORT + 1;
  10933. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10934. ASSERT_TRUE(ssl_svr1.is_valid());
  10935. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10936. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10937. "/index");
  10938. });
  10939. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10940. ASSERT_TRUE(ssl_svr2.is_valid());
  10941. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10942. res.set_content("test", "text/plain");
  10943. });
  10944. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10945. thread t2 =
  10946. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10947. auto se = detail::scope_exit([&] {
  10948. ssl_svr2.stop();
  10949. ssl_svr1.stop();
  10950. t2.join();
  10951. t.join();
  10952. ASSERT_FALSE(ssl_svr1.is_running());
  10953. });
  10954. ssl_svr1.wait_until_ready();
  10955. ssl_svr2.wait_until_ready();
  10956. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10957. std::string cert;
  10958. read_file(SERVER_CERT2_FILE, cert);
  10959. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10960. cli.enable_server_certificate_verification(true);
  10961. cli.set_follow_location(true);
  10962. cli.set_connection_timeout(30);
  10963. auto res = cli.Get("/index");
  10964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10965. ASSERT_EQ(StatusCode::OK_200, res->status);
  10966. }
  10967. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10968. // so a host signed by a system CA verifies even though a custom CA is set
  10969. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10970. std::string cert;
  10971. read_file(SERVER_CERT2_FILE, cert);
  10972. SSLClient cli("google.com");
  10973. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10974. cli.enable_system_ca(true);
  10975. cli.enable_server_certificate_verification(true);
  10976. auto res = cli.Get("/");
  10977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10978. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10979. }
  10980. // The custom CA remains effective when combined with the system CA
  10981. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10982. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10983. ASSERT_TRUE(svr.is_valid());
  10984. svr.Get("/test", [&](const Request &, Response &res) {
  10985. res.set_content("test", "text/plain");
  10986. });
  10987. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10988. auto se = detail::scope_exit([&] {
  10989. svr.stop();
  10990. t.join();
  10991. ASSERT_FALSE(svr.is_running());
  10992. });
  10993. svr.wait_until_ready();
  10994. SSLClient cli("127.0.0.1", PORT);
  10995. std::string cert;
  10996. read_file(SERVER_CERT2_FILE, cert);
  10997. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10998. cli.enable_system_ca(true);
  10999. cli.enable_server_certificate_verification(true);
  11000. cli.set_connection_timeout(30);
  11001. auto res = cli.Get("/test");
  11002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11003. ASSERT_EQ(StatusCode::OK_200, res->status);
  11004. }
  11005. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11006. // skip chain verification entirely (only the certificate identity was
  11007. // checked), so a server presenting an untrusted certificate with a matching
  11008. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11009. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11010. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11011. ASSERT_TRUE(svr.is_valid());
  11012. svr.Get("/test", [&](const Request &, Response &res) {
  11013. res.set_content("test", "text/plain");
  11014. });
  11015. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11016. auto se = detail::scope_exit([&] {
  11017. svr.stop();
  11018. t.join();
  11019. ASSERT_FALSE(svr.is_running());
  11020. });
  11021. svr.wait_until_ready();
  11022. SSLClient cli("127.0.0.1", PORT);
  11023. std::string cert;
  11024. // A trusted CA that did not sign the server certificate. The server cert
  11025. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11026. // this connection.
  11027. read_file(CLIENT_CA_CERT_FILE, cert);
  11028. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11029. cli.enable_server_certificate_verification(true);
  11030. cli.set_connection_timeout(30);
  11031. auto res = cli.Get("/test");
  11032. ASSERT_FALSE(res);
  11033. }
  11034. // enable_system_ca(false) prevents system CA loading entirely
  11035. TEST(SSLClientTest, DisableSystemCa_Online) {
  11036. SSLClient cli("google.com");
  11037. cli.enable_system_ca(false);
  11038. cli.enable_server_certificate_verification(true);
  11039. auto res = cli.Get("/");
  11040. ASSERT_FALSE(res);
  11041. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11042. // itself when the CA chain is empty
  11043. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11044. res.error() == Error::SSLConnection);
  11045. }
  11046. // The universal Client forwards enable_system_ca()
  11047. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11048. std::string cert;
  11049. read_file(SERVER_CERT2_FILE, cert);
  11050. Client cli("https://google.com");
  11051. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11052. cli.enable_system_ca(true);
  11053. cli.enable_server_certificate_verification(true);
  11054. auto res = cli.Get("/");
  11055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11056. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11057. }
  11058. // The system CA policy must carry over to the client created internally for
  11059. // following a cross-host HTTPS redirect
  11060. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11061. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11062. ASSERT_TRUE(svr.is_valid());
  11063. svr.Get("/index", [&](const Request &, Response &res) {
  11064. res.set_redirect("https://www.google.com/");
  11065. });
  11066. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11067. auto se = detail::scope_exit([&] {
  11068. svr.stop();
  11069. t.join();
  11070. ASSERT_FALSE(svr.is_running());
  11071. });
  11072. svr.wait_until_ready();
  11073. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11074. std::string cert;
  11075. read_file(SERVER_CERT2_FILE, cert);
  11076. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11077. cli.enable_system_ca(true);
  11078. cli.enable_server_certificate_verification(true);
  11079. cli.set_follow_location(true);
  11080. cli.set_connection_timeout(30);
  11081. // Receiving any response proves the redirect client completed the TLS
  11082. // handshake with a system-CA-signed host
  11083. auto res = cli.Get("/index");
  11084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11085. }
  11086. TEST(MultipartFormDataTest, LargeData) {
  11087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11088. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11089. const ContentReader &content_reader) {
  11090. if (req.is_multipart_form_data()) {
  11091. std::vector<FormData> items;
  11092. content_reader(
  11093. [&](const FormData &file) {
  11094. items.push_back(file);
  11095. return true;
  11096. },
  11097. [&](const char *data, size_t data_length) {
  11098. items.back().content.append(data, data_length);
  11099. return true;
  11100. });
  11101. EXPECT_TRUE(std::string(items[0].name) == "document");
  11102. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11103. EXPECT_TRUE(items[0].filename == "2MB_data");
  11104. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11105. EXPECT_TRUE(items[1].name == "hello");
  11106. EXPECT_TRUE(items[1].content == "world");
  11107. EXPECT_TRUE(items[1].filename == "");
  11108. EXPECT_TRUE(items[1].content_type == "");
  11109. } else {
  11110. std::string body;
  11111. content_reader([&](const char *data, size_t data_length) {
  11112. body.append(data, data_length);
  11113. return true;
  11114. });
  11115. }
  11116. });
  11117. auto port = svr.bind_to_any_port(HOST);
  11118. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. });
  11124. svr.wait_until_ready();
  11125. {
  11126. std::string data(1024 * 1024 * 2, '.');
  11127. std::stringstream buffer;
  11128. buffer << data;
  11129. SSLClient cli(HOST, port);
  11130. cli.enable_server_certificate_verification(false);
  11131. UploadFormDataItems items{
  11132. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11133. {"hello", "world", "", ""},
  11134. };
  11135. auto res = cli.Post("/post", items);
  11136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11137. ASSERT_EQ(StatusCode::OK_200, res->status);
  11138. }
  11139. }
  11140. TEST(MultipartFormDataTest, DataProviderItems) {
  11141. std::random_device seed_gen;
  11142. std::mt19937 random(seed_gen());
  11143. std::string rand1;
  11144. rand1.resize(1000);
  11145. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11146. std::string rand2;
  11147. rand2.resize(3000);
  11148. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11150. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11151. const ContentReader &content_reader) {
  11152. ASSERT_FALSE(req.is_multipart_form_data());
  11153. std::string body;
  11154. content_reader([&](const char *data, size_t data_length) {
  11155. body.append(data, data_length);
  11156. return true;
  11157. });
  11158. EXPECT_EQ(body, "");
  11159. });
  11160. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11161. const ContentReader &content_reader) {
  11162. ASSERT_TRUE(req.is_multipart_form_data());
  11163. std::vector<FormData> items;
  11164. content_reader(
  11165. [&](const FormData &file) {
  11166. items.push_back(file);
  11167. return true;
  11168. },
  11169. [&](const char *data, size_t data_length) {
  11170. items.back().content.append(data, data_length);
  11171. return true;
  11172. });
  11173. ASSERT_TRUE(items.size() == 2);
  11174. EXPECT_EQ(std::string(items[0].name), "name1");
  11175. EXPECT_EQ(items[0].content, "Testing123");
  11176. EXPECT_EQ(items[0].filename, "filename1");
  11177. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11178. EXPECT_EQ(items[1].name, "name2");
  11179. EXPECT_EQ(items[1].content, "Testing456");
  11180. EXPECT_EQ(items[1].filename, "");
  11181. EXPECT_EQ(items[1].content_type, "");
  11182. });
  11183. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11184. const ContentReader &content_reader) {
  11185. ASSERT_TRUE(req.is_multipart_form_data());
  11186. std::vector<FormData> items;
  11187. content_reader(
  11188. [&](const FormData &file) {
  11189. items.push_back(file);
  11190. return true;
  11191. },
  11192. [&](const char *data, size_t data_length) {
  11193. items.back().content.append(data, data_length);
  11194. return true;
  11195. });
  11196. ASSERT_TRUE(items.size() == 2);
  11197. EXPECT_EQ(items[0].name, "name3");
  11198. EXPECT_EQ(items[0].content, rand1);
  11199. EXPECT_EQ(items[0].filename, "filename3");
  11200. EXPECT_EQ(items[0].content_type, "");
  11201. EXPECT_EQ(items[1].name, "name4");
  11202. EXPECT_EQ(items[1].content, rand2);
  11203. EXPECT_EQ(items[1].filename, "filename4");
  11204. EXPECT_EQ(items[1].content_type, "");
  11205. });
  11206. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11207. const ContentReader &content_reader) {
  11208. ASSERT_TRUE(req.is_multipart_form_data());
  11209. std::vector<FormData> items;
  11210. content_reader(
  11211. [&](const FormData &file) {
  11212. items.push_back(file);
  11213. return true;
  11214. },
  11215. [&](const char *data, size_t data_length) {
  11216. items.back().content.append(data, data_length);
  11217. return true;
  11218. });
  11219. ASSERT_TRUE(items.size() == 4);
  11220. EXPECT_EQ(std::string(items[0].name), "name1");
  11221. EXPECT_EQ(items[0].content, "Testing123");
  11222. EXPECT_EQ(items[0].filename, "filename1");
  11223. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11224. EXPECT_EQ(items[1].name, "name2");
  11225. EXPECT_EQ(items[1].content, "Testing456");
  11226. EXPECT_EQ(items[1].filename, "");
  11227. EXPECT_EQ(items[1].content_type, "");
  11228. EXPECT_EQ(items[2].name, "name3");
  11229. EXPECT_EQ(items[2].content, rand1);
  11230. EXPECT_EQ(items[2].filename, "filename3");
  11231. EXPECT_EQ(items[2].content_type, "");
  11232. EXPECT_EQ(items[3].name, "name4");
  11233. EXPECT_EQ(items[3].content, rand2);
  11234. EXPECT_EQ(items[3].filename, "filename4");
  11235. EXPECT_EQ(items[3].content_type, "");
  11236. });
  11237. auto port = svr.bind_to_any_port("localhost");
  11238. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11239. auto se = detail::scope_exit([&] {
  11240. svr.stop();
  11241. t.join();
  11242. ASSERT_FALSE(svr.is_running());
  11243. });
  11244. svr.wait_until_ready();
  11245. {
  11246. SSLClient cli("localhost", port);
  11247. cli.enable_server_certificate_verification(false);
  11248. UploadFormDataItems items{
  11249. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11250. {"name2", "Testing456", "", ""}, // not a file
  11251. };
  11252. {
  11253. auto res = cli.Post("/post-none", {}, {}, {});
  11254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11255. ASSERT_EQ(StatusCode::OK_200, res->status);
  11256. }
  11257. FormDataProviderItems providers;
  11258. {
  11259. auto res =
  11260. cli.Post("/post-items", {}, items, providers); // empty providers
  11261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11262. ASSERT_EQ(StatusCode::OK_200, res->status);
  11263. }
  11264. providers.push_back({"name3",
  11265. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11266. // test the offset is given correctly at each step
  11267. if (!offset)
  11268. sink.os.write(rand1.data(), 30);
  11269. else if (offset == 30)
  11270. sink.os.write(rand1.data() + 30, 300);
  11271. else if (offset == 330)
  11272. sink.os.write(rand1.data() + 330, 670);
  11273. else if (offset == rand1.size())
  11274. sink.done();
  11275. return true;
  11276. },
  11277. "filename3",
  11278. {}});
  11279. providers.push_back({"name4",
  11280. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11281. // test the offset is given correctly at each step
  11282. if (!offset)
  11283. sink.os.write(rand2.data(), 2000);
  11284. else if (offset == 2000)
  11285. sink.os.write(rand2.data() + 2000, 1);
  11286. else if (offset == 2001)
  11287. sink.os.write(rand2.data() + 2001, 999);
  11288. else if (offset == rand2.size())
  11289. sink.done();
  11290. return true;
  11291. },
  11292. "filename4",
  11293. {}});
  11294. {
  11295. auto res = cli.Post("/post-providers", {}, {}, providers);
  11296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11297. ASSERT_EQ(StatusCode::OK_200, res->status);
  11298. }
  11299. {
  11300. auto res = cli.Post("/post-both", {}, items, providers);
  11301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11302. ASSERT_EQ(StatusCode::OK_200, res->status);
  11303. }
  11304. }
  11305. }
  11306. TEST(MultipartFormDataTest, BadHeader) {
  11307. Server svr;
  11308. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11309. res.set_content("ok", "text/plain");
  11310. });
  11311. thread t = thread([&] { svr.listen(HOST, PORT); });
  11312. auto se = detail::scope_exit([&] {
  11313. svr.stop();
  11314. t.join();
  11315. ASSERT_FALSE(svr.is_running());
  11316. });
  11317. svr.wait_until_ready();
  11318. const std::string body =
  11319. "This is the preamble. It is to be ignored, though it\r\n"
  11320. "is a handy place for composition agents to include an\r\n"
  11321. "explanatory note to non-MIME conformant readers.\r\n"
  11322. "\r\n"
  11323. "\r\n"
  11324. "--simple boundary\r\n"
  11325. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11326. ": BAD...\r\n"
  11327. "\r\n"
  11328. "value1\r\n"
  11329. "--simple boundary\r\n"
  11330. "Content-Disposition: form-data; name=\"field2\"; "
  11331. "filename=\"example.txt\"\r\n"
  11332. "\r\n"
  11333. "value2\r\n"
  11334. "--simple boundary--\r\n"
  11335. "This is the epilogue. It is also to be ignored.\r\n";
  11336. std::string content_type =
  11337. R"(multipart/form-data; boundary="simple boundary")";
  11338. Client cli(HOST, PORT);
  11339. auto res = cli.Post("/post", body, content_type.c_str());
  11340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11341. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11342. }
  11343. TEST(MultipartFormDataTest, WithPreamble) {
  11344. Server svr;
  11345. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11346. res.set_content("ok", "text/plain");
  11347. });
  11348. thread t = thread([&] { svr.listen(HOST, PORT); });
  11349. auto se = detail::scope_exit([&] {
  11350. svr.stop();
  11351. t.join();
  11352. ASSERT_FALSE(svr.is_running());
  11353. });
  11354. svr.wait_until_ready();
  11355. const std::string body =
  11356. "This is the preamble. It is to be ignored, though it\r\n"
  11357. "is a handy place for composition agents to include an\r\n"
  11358. "explanatory note to non-MIME conformant readers.\r\n"
  11359. "\r\n"
  11360. "\r\n"
  11361. "--simple boundary\r\n"
  11362. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11363. "\r\n"
  11364. "value1\r\n"
  11365. "--simple boundary\r\n"
  11366. "Content-Disposition: form-data; name=\"field2\"; "
  11367. "filename=\"example.txt\"\r\n"
  11368. "\r\n"
  11369. "value2\r\n"
  11370. "--simple boundary--\r\n"
  11371. "This is the epilogue. It is also to be ignored.\r\n";
  11372. std::string content_type =
  11373. R"(multipart/form-data; boundary="simple boundary")";
  11374. Client cli(HOST, PORT);
  11375. auto res = cli.Post("/post", body, content_type.c_str());
  11376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11377. EXPECT_EQ(StatusCode::OK_200, res->status);
  11378. }
  11379. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11381. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11382. const ContentReader &content_reader) {
  11383. if (req.is_multipart_form_data()) {
  11384. std::vector<FormData> items;
  11385. content_reader(
  11386. [&](const FormData &file) {
  11387. items.push_back(file);
  11388. return true;
  11389. },
  11390. [&](const char *data, size_t data_length) {
  11391. items.back().content.append(data, data_length);
  11392. return true;
  11393. });
  11394. EXPECT_TRUE(std::string(items[0].name) == "document");
  11395. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11396. EXPECT_TRUE(items[0].filename == "2MB_data");
  11397. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11398. EXPECT_TRUE(items[1].name == "hello");
  11399. EXPECT_TRUE(items[1].content == "world");
  11400. EXPECT_TRUE(items[1].filename == "");
  11401. EXPECT_TRUE(items[1].content_type == "");
  11402. } else {
  11403. std::string body;
  11404. content_reader([&](const char *data, size_t data_length) {
  11405. body.append(data, data_length);
  11406. return true;
  11407. });
  11408. }
  11409. });
  11410. auto port = svr.bind_to_any_port("localhost");
  11411. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11412. auto se = detail::scope_exit([&] {
  11413. svr.stop();
  11414. t.join();
  11415. ASSERT_FALSE(svr.is_running());
  11416. });
  11417. svr.wait_until_ready();
  11418. {
  11419. std::string data(1024 * 1024 * 2, '.');
  11420. std::stringstream buffer;
  11421. buffer << data;
  11422. SSLClient cli("localhost", port);
  11423. cli.enable_server_certificate_verification(false);
  11424. UploadFormDataItems items{
  11425. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11426. {"hello", "world", "", ""},
  11427. };
  11428. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11430. ASSERT_EQ(StatusCode::OK_200, res->status);
  11431. }
  11432. }
  11433. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11434. std::string data(1024 * 1024 * 2, '&');
  11435. std::stringstream buffer;
  11436. buffer << data;
  11437. Client cli("https://localhost:8080");
  11438. UploadFormDataItems items{
  11439. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11440. {"hello", "world", "", ""},
  11441. };
  11442. for (const char &c : " \t\r\n") {
  11443. auto res =
  11444. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11445. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11446. ASSERT_FALSE(res);
  11447. }
  11448. }
  11449. TEST(MultipartFormDataTest, PutFormData) {
  11450. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11451. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11452. const ContentReader &content_reader) {
  11453. if (req.is_multipart_form_data()) {
  11454. std::vector<FormData> items;
  11455. content_reader(
  11456. [&](const FormData &file) {
  11457. items.push_back(file);
  11458. return true;
  11459. },
  11460. [&](const char *data, size_t data_length) {
  11461. items.back().content.append(data, data_length);
  11462. return true;
  11463. });
  11464. EXPECT_TRUE(std::string(items[0].name) == "document");
  11465. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11466. EXPECT_TRUE(items[0].filename == "2MB_data");
  11467. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11468. EXPECT_TRUE(items[1].name == "hello");
  11469. EXPECT_TRUE(items[1].content == "world");
  11470. EXPECT_TRUE(items[1].filename == "");
  11471. EXPECT_TRUE(items[1].content_type == "");
  11472. } else {
  11473. std::string body;
  11474. content_reader([&](const char *data, size_t data_length) {
  11475. body.append(data, data_length);
  11476. return true;
  11477. });
  11478. }
  11479. });
  11480. auto port = svr.bind_to_any_port("localhost");
  11481. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11482. auto se = detail::scope_exit([&] {
  11483. svr.stop();
  11484. t.join();
  11485. ASSERT_FALSE(svr.is_running());
  11486. });
  11487. svr.wait_until_ready();
  11488. {
  11489. std::string data(1024 * 1024 * 2, '&');
  11490. std::stringstream buffer;
  11491. buffer << data;
  11492. SSLClient cli("localhost", port);
  11493. cli.enable_server_certificate_verification(false);
  11494. UploadFormDataItems items{
  11495. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11496. {"hello", "world", "", ""},
  11497. };
  11498. auto res = cli.Put("/put", items);
  11499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11500. ASSERT_EQ(StatusCode::OK_200, res->status);
  11501. }
  11502. }
  11503. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11505. svr.Put("/put_customboundary",
  11506. [&](const Request &req, const Response & /*res*/,
  11507. const ContentReader &content_reader) {
  11508. if (req.is_multipart_form_data()) {
  11509. std::vector<FormData> items;
  11510. content_reader(
  11511. [&](const FormData &file) {
  11512. items.push_back(file);
  11513. return true;
  11514. },
  11515. [&](const char *data, size_t data_length) {
  11516. items.back().content.append(data, data_length);
  11517. return true;
  11518. });
  11519. EXPECT_TRUE(std::string(items[0].name) == "document");
  11520. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11521. EXPECT_TRUE(items[0].filename == "2MB_data");
  11522. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11523. EXPECT_TRUE(items[1].name == "hello");
  11524. EXPECT_TRUE(items[1].content == "world");
  11525. EXPECT_TRUE(items[1].filename == "");
  11526. EXPECT_TRUE(items[1].content_type == "");
  11527. } else {
  11528. std::string body;
  11529. content_reader([&](const char *data, size_t data_length) {
  11530. body.append(data, data_length);
  11531. return true;
  11532. });
  11533. }
  11534. });
  11535. auto port = svr.bind_to_any_port("localhost");
  11536. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11537. auto se = detail::scope_exit([&] {
  11538. svr.stop();
  11539. t.join();
  11540. ASSERT_FALSE(svr.is_running());
  11541. });
  11542. svr.wait_until_ready();
  11543. {
  11544. std::string data(1024 * 1024 * 2, '&');
  11545. std::stringstream buffer;
  11546. buffer << data;
  11547. SSLClient cli("localhost", port);
  11548. cli.enable_server_certificate_verification(false);
  11549. UploadFormDataItems items{
  11550. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11551. {"hello", "world", "", ""},
  11552. };
  11553. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11555. ASSERT_EQ(StatusCode::OK_200, res->status);
  11556. }
  11557. }
  11558. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11559. std::string data(1024 * 1024 * 2, '&');
  11560. std::stringstream buffer;
  11561. buffer << data;
  11562. Client cli("https://localhost:8080");
  11563. cli.enable_server_certificate_verification(false);
  11564. UploadFormDataItems items{
  11565. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11566. {"hello", "world", "", ""},
  11567. };
  11568. for (const char &c : " \t\r\n") {
  11569. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11570. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11571. ASSERT_FALSE(res);
  11572. }
  11573. }
  11574. TEST(MultipartFormDataTest, AlternateFilename) {
  11575. auto handled = false;
  11576. Server svr;
  11577. svr.Post("/test", [&](const Request &req, Response &res) {
  11578. ASSERT_EQ(2u, req.form.files.size());
  11579. ASSERT_EQ(1u, req.form.fields.size());
  11580. // Test files
  11581. const auto &file1 = req.form.get_file("file1");
  11582. ASSERT_EQ("file1", file1.name);
  11583. ASSERT_EQ("A.txt", file1.filename);
  11584. ASSERT_EQ("text/plain", file1.content_type);
  11585. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11586. const auto &file2 = req.form.get_file("file2");
  11587. ASSERT_EQ("file2", file2.name);
  11588. ASSERT_EQ("a.html", file2.filename);
  11589. ASSERT_EQ("text/html", file2.content_type);
  11590. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11591. file2.content);
  11592. // Test text field
  11593. const auto &text = req.form.get_field("text");
  11594. ASSERT_EQ("text default", text);
  11595. res.set_content("ok", "text/plain");
  11596. handled = true;
  11597. });
  11598. thread t = thread([&] { svr.listen(HOST, PORT); });
  11599. auto se = detail::scope_exit([&] {
  11600. svr.stop();
  11601. t.join();
  11602. ASSERT_FALSE(svr.is_running());
  11603. ASSERT_TRUE(handled);
  11604. });
  11605. svr.wait_until_ready();
  11606. auto req = "POST /test HTTP/1.1\r\n"
  11607. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11608. "Content-Length: 399\r\n"
  11609. "\r\n"
  11610. "----------\r\n"
  11611. "Content-Disposition: form-data; name=\"text\"\r\n"
  11612. "\r\n"
  11613. "text default\r\n"
  11614. "----------\r\n"
  11615. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11616. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11617. "Content-Type: text/plain\r\n"
  11618. "\r\n"
  11619. "Content of a.txt.\r\n"
  11620. "\r\n"
  11621. "----------\r\n"
  11622. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11623. "\"a.html\"\r\n"
  11624. "Content-Type: text/html\r\n"
  11625. "\r\n"
  11626. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11627. "\r\n"
  11628. "------------\r\n";
  11629. ASSERT_TRUE(send_request(1, req));
  11630. }
  11631. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11632. auto handled = false;
  11633. Server svr;
  11634. svr.Post("/test", [&](const Request &req, Response &res) {
  11635. // Case-insensitive "utf-8''" prefix with a long value
  11636. const auto &file = req.form.get_file("file1");
  11637. ASSERT_EQ("file1", file.name);
  11638. // 8000 chars exercises both the Content-Disposition parser and the
  11639. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11640. // Prior to the fix, std::regex_match on this header would cause O(N)
  11641. // stack recursion in libstdc++, leading to SIGSEGV.
  11642. std::string expected_filename(8000, 'A');
  11643. ASSERT_EQ(expected_filename, file.filename);
  11644. res.set_content("ok", "text/plain");
  11645. handled = true;
  11646. });
  11647. thread t = thread([&] { svr.listen(HOST, PORT); });
  11648. auto se = detail::scope_exit([&] {
  11649. svr.stop();
  11650. t.join();
  11651. ASSERT_FALSE(svr.is_running());
  11652. ASSERT_TRUE(handled);
  11653. });
  11654. svr.wait_until_ready();
  11655. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11656. // Regression test for GHSA-qq6v-r583-3h69
  11657. std::string long_filename(8000, 'A');
  11658. std::string body = "----------\r\n"
  11659. "Content-Disposition: form-data; name=\"file1\"; "
  11660. "filename*=\"Utf-8''" +
  11661. long_filename +
  11662. "\"\r\n"
  11663. "\r\n"
  11664. "hello\r\n"
  11665. "------------\r\n";
  11666. auto req = "POST /test HTTP/1.1\r\n"
  11667. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11668. "Content-Length: " +
  11669. std::to_string(body.size()) + "\r\n\r\n" + body;
  11670. ASSERT_TRUE(send_request(1, req));
  11671. }
  11672. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11673. auto handled = false;
  11674. Server svr;
  11675. svr.Post("/test", [&](const Request &req, Response &) {
  11676. ASSERT_EQ(2u, req.form.fields.size());
  11677. const auto &text1 = req.form.get_field("text1");
  11678. ASSERT_EQ("text1", text1);
  11679. const auto &text2 = req.form.get_field("text2");
  11680. ASSERT_EQ("text2", text2);
  11681. handled = true;
  11682. });
  11683. thread t = thread([&] { svr.listen(HOST, PORT); });
  11684. auto se = detail::scope_exit([&] {
  11685. svr.stop();
  11686. t.join();
  11687. ASSERT_FALSE(svr.is_running());
  11688. ASSERT_TRUE(handled);
  11689. });
  11690. svr.wait_until_ready();
  11691. auto req = "POST /test HTTP/1.1\r\n"
  11692. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11693. "Content-Length: 146\r\n"
  11694. "\r\n----------\r\n"
  11695. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11696. "\r\n"
  11697. "text1"
  11698. "\r\n----------\r\n"
  11699. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11700. "\r\n"
  11701. "text2"
  11702. "\r\n------------";
  11703. std::string response;
  11704. ASSERT_TRUE(send_request(1, req, &response));
  11705. ASSERT_EQ("200", response.substr(9, 3));
  11706. }
  11707. TEST(MultipartFormDataTest, ContentLength) {
  11708. auto handled = false;
  11709. Server svr;
  11710. svr.Post("/test", [&](const Request &req, Response &) {
  11711. ASSERT_EQ(2u, req.form.fields.size());
  11712. const auto &text1 = req.form.get_field("text1");
  11713. ASSERT_EQ("text1", text1);
  11714. const auto &text2 = req.form.get_field("text2");
  11715. ASSERT_EQ("text2", text2);
  11716. handled = true;
  11717. });
  11718. thread t = thread([&] { svr.listen(HOST, PORT); });
  11719. auto se = detail::scope_exit([&] {
  11720. svr.stop();
  11721. t.join();
  11722. ASSERT_FALSE(svr.is_running());
  11723. ASSERT_TRUE(handled);
  11724. });
  11725. svr.wait_until_ready();
  11726. auto req = "POST /test HTTP/1.1\r\n"
  11727. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11728. "Content-Length: 167\r\n"
  11729. "\r\n----------\r\n"
  11730. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11731. "Content-Length: 5\r\n"
  11732. "\r\n"
  11733. "text1"
  11734. "\r\n----------\r\n"
  11735. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11736. "\r\n"
  11737. "text2"
  11738. "\r\n------------\r\n";
  11739. std::string response;
  11740. ASSERT_TRUE(send_request(1, req, &response));
  11741. ASSERT_EQ("200", response.substr(9, 3));
  11742. }
  11743. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11744. auto handled = false;
  11745. Server svr;
  11746. svr.Post("/test", [&](const Request &req, Response &) {
  11747. ASSERT_EQ(2u, req.form.fields.size());
  11748. const auto &text1 = req.form.get_field("text1");
  11749. ASSERT_EQ("text1", text1);
  11750. // TODO: Add header access for text fields if needed
  11751. const auto &text2 = req.form.get_field("text2");
  11752. ASSERT_EQ("text2", text2);
  11753. // TODO: Header access for text fields needs to be implemented
  11754. // auto &headers = it->second.headers;
  11755. // ASSERT_EQ(3U, headers.size());
  11756. // auto custom_header = headers.find("x-whatever");
  11757. // ASSERT_TRUE(custom_header != headers.end());
  11758. // ASSERT_NE("customvalue", custom_header->second);
  11759. // ASSERT_EQ("CustomValue", custom_header->second);
  11760. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11761. handled = true;
  11762. });
  11763. thread t = thread([&] { svr.listen(HOST, PORT); });
  11764. auto se = detail::scope_exit([&] {
  11765. svr.stop();
  11766. t.join();
  11767. ASSERT_FALSE(svr.is_running());
  11768. ASSERT_TRUE(handled);
  11769. });
  11770. svr.wait_until_ready();
  11771. auto req = "POST /test HTTP/1.1\r\n"
  11772. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11773. "Content-Length: 232\r\n"
  11774. "\r\n----------\r\n"
  11775. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11776. "Content-Length: 5\r\n"
  11777. "X-Test: 1\r\n"
  11778. "\r\n"
  11779. "text1"
  11780. "\r\n----------\r\n"
  11781. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11782. "Content-Type: text/plain\r\n"
  11783. "X-Whatever: CustomValue\r\n"
  11784. "\r\n"
  11785. "text2"
  11786. "\r\n------------\r\n"
  11787. "That should be disregarded. Not even read";
  11788. std::string response;
  11789. ASSERT_TRUE(send_request(1, req, &response));
  11790. ASSERT_EQ("200", response.substr(9, 3));
  11791. }
  11792. TEST(MultipartFormDataTest, LargeHeader) {
  11793. auto handled = false;
  11794. Server svr;
  11795. svr.Post("/test", [&](const Request &req, Response &) {
  11796. ASSERT_EQ(1u, req.form.fields.size());
  11797. const auto &text = req.form.get_field("name1");
  11798. ASSERT_EQ("text1", text);
  11799. handled = true;
  11800. });
  11801. thread t = thread([&] { svr.listen(HOST, PORT); });
  11802. auto se = detail::scope_exit([&] {
  11803. svr.stop();
  11804. t.join();
  11805. ASSERT_FALSE(svr.is_running());
  11806. ASSERT_TRUE(handled);
  11807. });
  11808. svr.wait_until_ready();
  11809. auto boundary = std::string("cpp-httplib-multipart-data");
  11810. std::string content = "--" + boundary +
  11811. "\r\n"
  11812. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11813. "\r\n"
  11814. "text1\r\n"
  11815. "--" +
  11816. boundary + "--\r\n";
  11817. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11818. "Content-Type: multipart/form-data;boundary=" +
  11819. boundary +
  11820. "\r\n"
  11821. "Content-Length: " +
  11822. std::to_string(content.size()) +
  11823. "\r\n"
  11824. "Dummy-Header: ";
  11825. std::string header_suffix = "\r\n"
  11826. "\r\n";
  11827. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11828. size_t header_dummy_size =
  11829. read_buff_size -
  11830. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11831. auto header_dummy = std::string(header_dummy_size, '@');
  11832. auto req = header_prefix + header_dummy + header_suffix + content;
  11833. std::string response;
  11834. ASSERT_TRUE(send_request(1, req, &response));
  11835. ASSERT_EQ("200", response.substr(9, 3));
  11836. }
  11837. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11838. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11839. // (not chunked Transfer-Encoding) after the streaming refactor.
  11840. auto handled = false;
  11841. Server svr;
  11842. svr.Post("/upload", [&](const Request &req, Response &res) {
  11843. auto cl_it = req.headers.find("Content-Length");
  11844. EXPECT_TRUE(cl_it != req.headers.end());
  11845. auto te_it = req.headers.find("Transfer-Encoding");
  11846. EXPECT_TRUE(te_it == req.headers.end());
  11847. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11848. res.set_content("ok", "text/plain");
  11849. handled = true;
  11850. });
  11851. auto port = svr.bind_to_any_port(HOST);
  11852. auto t = thread([&] { svr.listen_after_bind(); });
  11853. auto se = detail::scope_exit([&] {
  11854. svr.stop();
  11855. t.join();
  11856. ASSERT_FALSE(svr.is_running());
  11857. ASSERT_TRUE(handled);
  11858. });
  11859. svr.wait_until_ready();
  11860. UploadFormDataItems items = {
  11861. {"field1", "hello", "", "text/plain"},
  11862. {"file1", "world", "test.txt", "application/octet-stream"},
  11863. };
  11864. Client cli(HOST, port);
  11865. auto res = cli.Post("/upload", {}, items);
  11866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11867. EXPECT_EQ(StatusCode::OK_200, res->status);
  11868. }
  11869. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11870. // Verify that make_multipart_content_provider coalesces many small segments
  11871. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11872. constexpr size_t kItemCount = 1000;
  11873. UploadFormDataItems items;
  11874. items.reserve(kItemCount);
  11875. for (size_t i = 0; i < kItemCount; i++) {
  11876. items.push_back(
  11877. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11878. }
  11879. const std::string boundary = "----test-boundary";
  11880. auto content_length = detail::get_multipart_content_length(items, boundary);
  11881. auto provider = detail::make_multipart_content_provider(items, boundary);
  11882. // Drive the provider the same way write_content_with_progress does
  11883. size_t write_count = 0;
  11884. size_t total_bytes = 0;
  11885. DataSink sink;
  11886. size_t offset = 0;
  11887. sink.write = [&](const char *d, size_t l) -> bool {
  11888. (void)d;
  11889. write_count++;
  11890. total_bytes += l;
  11891. offset += l;
  11892. return true;
  11893. };
  11894. sink.is_writable = []() -> bool { return true; };
  11895. while (offset < content_length) {
  11896. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11897. }
  11898. EXPECT_EQ(content_length, total_bytes);
  11899. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11900. // With buffering into 64KB blocks, write_count should be much smaller.
  11901. auto segment_count = 3 * kItemCount + 1;
  11902. EXPECT_LT(write_count, segment_count / 10);
  11903. }
  11904. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11905. // Integration test: send many UploadFormDataItems and verify the server
  11906. // receives all of them correctly (#2410).
  11907. constexpr size_t kItemCount = 500;
  11908. auto handled = false;
  11909. Server svr;
  11910. svr.Post("/upload", [&](const Request &req, Response &res) {
  11911. EXPECT_EQ(kItemCount, req.form.fields.size());
  11912. for (size_t i = 0; i < kItemCount; i++) {
  11913. auto key = "field" + std::to_string(i);
  11914. auto val = "value" + std::to_string(i);
  11915. auto it = req.form.fields.find(key);
  11916. if (it != req.form.fields.end()) {
  11917. EXPECT_EQ(val, it->second.content);
  11918. } else {
  11919. ADD_FAILURE() << "Missing field: " << key;
  11920. }
  11921. }
  11922. res.set_content("ok", "text/plain");
  11923. handled = true;
  11924. });
  11925. auto port = svr.bind_to_any_port(HOST);
  11926. auto t = thread([&] { svr.listen_after_bind(); });
  11927. auto se = detail::scope_exit([&] {
  11928. svr.stop();
  11929. t.join();
  11930. ASSERT_FALSE(svr.is_running());
  11931. ASSERT_TRUE(handled);
  11932. });
  11933. svr.wait_until_ready();
  11934. UploadFormDataItems items;
  11935. items.reserve(kItemCount);
  11936. for (size_t i = 0; i < kItemCount; i++) {
  11937. items.push_back(
  11938. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11939. }
  11940. Client cli(HOST, port);
  11941. auto res = cli.Post("/upload", items);
  11942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11943. EXPECT_EQ(StatusCode::OK_200, res->status);
  11944. }
  11945. TEST(MultipartFormDataTest, MakeFileProvider) {
  11946. // Verify make_file_provider sends a file's contents correctly.
  11947. const std::string file_content(4096, 'Z');
  11948. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11949. {
  11950. std::ofstream ofs(tmp_path, std::ios::binary);
  11951. ofs.write(file_content.data(),
  11952. static_cast<std::streamsize>(file_content.size()));
  11953. }
  11954. auto handled = false;
  11955. Server svr;
  11956. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11957. const ContentReader &content_reader) {
  11958. ASSERT_TRUE(req.is_multipart_form_data());
  11959. std::vector<FormData> items;
  11960. content_reader(
  11961. [&](const FormData &file) {
  11962. items.push_back(file);
  11963. return true;
  11964. },
  11965. [&](const char *data, size_t data_length) {
  11966. items.back().content.append(data, data_length);
  11967. return true;
  11968. });
  11969. ASSERT_EQ(1u, items.size());
  11970. EXPECT_EQ("myfile", items[0].name);
  11971. EXPECT_EQ("data.bin", items[0].filename);
  11972. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11973. EXPECT_EQ(file_content, items[0].content);
  11974. handled = true;
  11975. });
  11976. auto port = svr.bind_to_any_port(HOST);
  11977. auto t = thread([&] { svr.listen_after_bind(); });
  11978. auto se = detail::scope_exit([&] {
  11979. svr.stop();
  11980. t.join();
  11981. ASSERT_FALSE(svr.is_running());
  11982. ASSERT_TRUE(handled);
  11983. std::remove(tmp_path.c_str());
  11984. });
  11985. svr.wait_until_ready();
  11986. FormDataProviderItems providers;
  11987. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11988. "application/octet-stream"));
  11989. Client cli(HOST, port);
  11990. auto res = cli.Post("/upload", {}, {}, providers);
  11991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11992. EXPECT_EQ(StatusCode::OK_200, res->status);
  11993. }
  11994. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11995. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11996. // (100) headers is rejected with a 400 Bad Request response.
  11997. Server svr;
  11998. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11999. res.set_content("ok", "text/plain");
  12000. });
  12001. thread t = thread([&] { svr.listen(HOST, PORT); });
  12002. auto se = detail::scope_exit([&] {
  12003. svr.stop();
  12004. t.join();
  12005. ASSERT_FALSE(svr.is_running());
  12006. });
  12007. svr.wait_until_ready();
  12008. // Build a multipart part with 101 custom headers (exceeding
  12009. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12010. std::stringstream body;
  12011. body << "--simpleboundary\r\n"
  12012. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12013. for (int i = 0; i < 101; i++) {
  12014. body << "X-Custom-Header-" << i << ": value\r\n";
  12015. }
  12016. body << "\r\n"
  12017. << "value1\r\n"
  12018. << "--simpleboundary--\r\n";
  12019. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12020. Client cli(HOST, PORT);
  12021. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12023. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12024. }
  12025. TEST(MakeFileBodyTest, Basic) {
  12026. const std::string file_content(4096, 'Z');
  12027. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12028. {
  12029. std::ofstream ofs(tmp_path, std::ios::binary);
  12030. ofs.write(file_content.data(),
  12031. static_cast<std::streamsize>(file_content.size()));
  12032. }
  12033. auto handled = false;
  12034. Server svr;
  12035. svr.Post("/upload", [&](const Request &req, Response &res) {
  12036. EXPECT_EQ(file_content, req.body);
  12037. handled = true;
  12038. res.status = StatusCode::OK_200;
  12039. });
  12040. auto port = svr.bind_to_any_port(HOST);
  12041. auto t = thread([&] { svr.listen_after_bind(); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. t.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. ASSERT_TRUE(handled);
  12047. std::remove(tmp_path.c_str());
  12048. });
  12049. svr.wait_until_ready();
  12050. auto fb = make_file_body(tmp_path);
  12051. ASSERT_GT(fb.first, 0u);
  12052. Client cli(HOST, port);
  12053. auto res =
  12054. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12056. EXPECT_EQ(StatusCode::OK_200, res->status);
  12057. }
  12058. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12059. static constexpr unsigned int number_of_tasks{1000000};
  12060. std::atomic_uint count{0};
  12061. std::unique_ptr<TaskQueue> task_queue{
  12062. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12063. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12064. auto queued = task_queue->enqueue(
  12065. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12066. EXPECT_TRUE(queued);
  12067. }
  12068. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12069. task_queue->shutdown();
  12070. #else
  12071. EXPECT_NO_THROW(task_queue->shutdown());
  12072. #endif
  12073. EXPECT_EQ(number_of_tasks, count.load());
  12074. }
  12075. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12076. static constexpr unsigned int number_of_tasks{1000000};
  12077. static constexpr unsigned int qlimit{2};
  12078. unsigned int queued_count{0};
  12079. std::atomic_uint count{0};
  12080. std::unique_ptr<TaskQueue> task_queue{
  12081. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12082. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12083. if (task_queue->enqueue(
  12084. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12085. queued_count++;
  12086. }
  12087. }
  12088. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12089. task_queue->shutdown();
  12090. #else
  12091. EXPECT_NO_THROW(task_queue->shutdown());
  12092. #endif
  12093. EXPECT_EQ(queued_count, count.load());
  12094. EXPECT_TRUE(queued_count <= number_of_tasks);
  12095. EXPECT_TRUE(queued_count >= qlimit);
  12096. }
  12097. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12098. // Use a short idle timeout so a dynamic thread spawns, times out and
  12099. // exits during the test, and the pool keeps working afterwards.
  12100. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12101. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12102. /*idle_timeout_sec=*/1}};
  12103. std::atomic_uint count{0};
  12104. std::condition_variable cv;
  12105. std::mutex mtx;
  12106. bool release = false;
  12107. // Block the base thread so the second task spawns a dynamic thread.
  12108. EXPECT_TRUE(task_queue->enqueue([&] {
  12109. std::unique_lock<std::mutex> lock(mtx);
  12110. while (!release) {
  12111. cv.wait(lock);
  12112. }
  12113. count++;
  12114. }));
  12115. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12116. // Let the dynamic thread finish its task and exceed the idle timeout.
  12117. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12118. {
  12119. std::unique_lock<std::mutex> lock(mtx);
  12120. release = true;
  12121. }
  12122. cv.notify_all();
  12123. // The pool must still accept and run tasks after the dynamic thread exited.
  12124. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12125. task_queue->shutdown();
  12126. EXPECT_EQ(3u, count.load());
  12127. }
  12128. TEST(TaskQueueTest, MaxQueuedRequests) {
  12129. static constexpr unsigned int qlimit{3};
  12130. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12131. std::condition_variable sem_cv;
  12132. std::mutex sem_mtx;
  12133. int credits = 0;
  12134. bool queued;
  12135. /* Fill up the queue with tasks that will block until we give them credits to
  12136. * complete. */
  12137. for (unsigned int n = 0; n <= qlimit;) {
  12138. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12139. std::unique_lock<std::mutex> lock(sem_mtx);
  12140. while (credits <= 0) {
  12141. sem_cv.wait(lock);
  12142. }
  12143. /* Consume the credit and signal the test code if they are all gone. */
  12144. if (--credits == 0) { sem_cv.notify_one(); }
  12145. });
  12146. if (n < qlimit) {
  12147. /* The first qlimit enqueues must succeed. */
  12148. EXPECT_TRUE(queued);
  12149. } else {
  12150. /* The last one will succeed only when the worker thread
  12151. * starts and dequeues the first blocking task. Although
  12152. * not necessary for the correctness of this test, we sleep for
  12153. * a short while to avoid busy waiting. */
  12154. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12155. }
  12156. if (queued) { n++; }
  12157. }
  12158. /* Further enqueues must fail since the queue is full. */
  12159. for (auto i = 0; i < 4; i++) {
  12160. queued = task_queue->enqueue([] {});
  12161. EXPECT_FALSE(queued);
  12162. }
  12163. /* Give the credits to allow the previous tasks to complete. */
  12164. {
  12165. std::unique_lock<std::mutex> lock(sem_mtx);
  12166. credits += qlimit + 1;
  12167. }
  12168. sem_cv.notify_all();
  12169. /* Wait for all the credits to be consumed. */
  12170. {
  12171. std::unique_lock<std::mutex> lock(sem_mtx);
  12172. while (credits > 0) {
  12173. sem_cv.wait(lock);
  12174. }
  12175. }
  12176. /* Check that we are able again to enqueue at least qlimit tasks. */
  12177. for (unsigned int i = 0; i < qlimit; i++) {
  12178. queued = task_queue->enqueue([] {});
  12179. EXPECT_TRUE(queued);
  12180. }
  12181. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12182. task_queue->shutdown();
  12183. #else
  12184. EXPECT_NO_THROW(task_queue->shutdown());
  12185. #endif
  12186. }
  12187. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12188. Server svr;
  12189. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12190. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12191. });
  12192. svr.Get("/hello", [](const Request &req, Response &res) {
  12193. res.set_content(req.get_param_value("key"), "text/plain");
  12194. });
  12195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12196. auto se = detail::scope_exit([&] {
  12197. svr.stop();
  12198. thread.join();
  12199. ASSERT_FALSE(svr.is_running());
  12200. });
  12201. svr.wait_until_ready();
  12202. {
  12203. Client cli(HOST, PORT);
  12204. cli.set_follow_location(true);
  12205. auto res = cli.Get("/");
  12206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12207. EXPECT_EQ(StatusCode::OK_200, res->status);
  12208. EXPECT_EQ("val&key2=val2", res->body);
  12209. }
  12210. }
  12211. #endif
  12212. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12213. Server svr;
  12214. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12215. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12216. });
  12217. svr.Get("/hello", [](const Request &req, Response &res) {
  12218. res.set_content(req.get_param_value("key"), "text/plain");
  12219. });
  12220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12221. auto se = detail::scope_exit([&] {
  12222. svr.stop();
  12223. thread.join();
  12224. ASSERT_FALSE(svr.is_running());
  12225. });
  12226. svr.wait_until_ready();
  12227. {
  12228. Client cli(HOST, PORT);
  12229. cli.set_follow_location(true);
  12230. auto res = cli.Get("/");
  12231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12232. EXPECT_EQ(StatusCode::OK_200, res->status);
  12233. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12234. }
  12235. }
  12236. TEST(RedirectTest, RedirectWithPlusInPath) {
  12237. Server svr;
  12238. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12239. res.set_redirect("/a+b");
  12240. });
  12241. // Route pattern uses regex; escape + as \\+
  12242. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12243. res.set_content(req.path, "text/plain");
  12244. });
  12245. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12246. auto se = detail::scope_exit([&] {
  12247. svr.stop();
  12248. thread.join();
  12249. ASSERT_FALSE(svr.is_running());
  12250. });
  12251. svr.wait_until_ready();
  12252. {
  12253. Client cli(HOST, PORT);
  12254. cli.set_follow_location(true);
  12255. auto res = cli.Get("/");
  12256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12257. EXPECT_EQ(StatusCode::OK_200, res->status);
  12258. EXPECT_EQ("/a+b", res->body);
  12259. }
  12260. }
  12261. #ifdef CPPHTTPLIB_SSL_ENABLED
  12262. TEST(RedirectTest, Issue2185_Online) {
  12263. SSLClient client("github.com");
  12264. client.set_follow_location(true);
  12265. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12266. "Coollab-Windows.zip");
  12267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12268. EXPECT_EQ(StatusCode::OK_200, res->status);
  12269. EXPECT_EQ(9920427U, res->body.size());
  12270. }
  12271. #endif
  12272. TEST(VulnerabilityTest, CRLFInjection) {
  12273. Server svr;
  12274. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12275. res.set_content("Hello 1", "text/plain");
  12276. });
  12277. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12278. res.set_content("Hello 2", "text/plain");
  12279. });
  12280. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12281. res.set_content("Hello 3", "text/plain");
  12282. });
  12283. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12284. res.set_content("Hello 4", "text/plain");
  12285. });
  12286. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12287. for (const auto &x : req.headers) {
  12288. auto key = x.first;
  12289. EXPECT_STRNE("evil", key.c_str());
  12290. }
  12291. });
  12292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12293. auto se = detail::scope_exit([&] {
  12294. svr.stop();
  12295. thread.join();
  12296. ASSERT_FALSE(svr.is_running());
  12297. });
  12298. svr.wait_until_ready();
  12299. {
  12300. Client cli(HOST, PORT);
  12301. cli.Post("/test1", "A=B",
  12302. "application/x-www-form-urlencoded\r\nevil: hello1");
  12303. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12304. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12305. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12306. }
  12307. }
  12308. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12309. auto server_thread = std::thread([] {
  12310. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12311. default_socket_options(srv);
  12312. sockaddr_in addr{};
  12313. addr.sin_family = AF_INET;
  12314. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12315. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12316. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12317. ::listen(srv, 1);
  12318. sockaddr_in cli_addr{};
  12319. socklen_t cli_len = sizeof(cli_addr);
  12320. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12321. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12322. std::string buf_all;
  12323. char buf[2048];
  12324. ssize_t n;
  12325. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12326. buf_all.append(buf, static_cast<size_t>(n));
  12327. size_t pos;
  12328. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12329. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12330. auto e = request_block.find("\r\n");
  12331. if (e != std::string::npos) {
  12332. auto request_line = request_block.substr(0, e);
  12333. std::string msg =
  12334. "CRLF injection detected in request line: '" + request_line + "'";
  12335. EXPECT_FALSE(true) << msg;
  12336. }
  12337. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12338. ::send(cli,
  12339. #ifdef _WIN32
  12340. static_cast<const char *>(resp.c_str()),
  12341. static_cast<int>(resp.size()),
  12342. #else
  12343. resp.c_str(), resp.size(),
  12344. #endif
  12345. 0);
  12346. buf_all.erase(0, pos + 4);
  12347. }
  12348. }
  12349. detail::close_socket(cli);
  12350. detail::close_socket(srv);
  12351. });
  12352. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12353. auto cli = Client("127.0.0.1", PORT + 1);
  12354. auto headers = Headers{
  12355. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12356. {"Connection", "keep-alive"}};
  12357. auto res = cli.Get("/hi", headers);
  12358. EXPECT_FALSE(res);
  12359. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12360. server_thread.join();
  12361. }
  12362. TEST(PathParamsTest, StaticMatch) {
  12363. const auto pattern = "/users/all";
  12364. detail::PathParamsMatcher matcher(pattern);
  12365. Request request;
  12366. request.path = "/users/all";
  12367. ASSERT_TRUE(matcher.match(request));
  12368. std::unordered_map<std::string, std::string> expected_params = {};
  12369. EXPECT_EQ(request.path_params, expected_params);
  12370. }
  12371. TEST(PathParamsTest, StaticMismatch) {
  12372. const auto pattern = "/users/all";
  12373. detail::PathParamsMatcher matcher(pattern);
  12374. Request request;
  12375. request.path = "/users/1";
  12376. ASSERT_FALSE(matcher.match(request));
  12377. }
  12378. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12379. const auto pattern = "/users/:id/subscriptions";
  12380. detail::PathParamsMatcher matcher(pattern);
  12381. Request request;
  12382. request.path = "/users/42/subscriptions";
  12383. ASSERT_TRUE(matcher.match(request));
  12384. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12385. EXPECT_EQ(request.path_params, expected_params);
  12386. }
  12387. TEST(PathParamsTest, SingleParamInTheEnd) {
  12388. const auto pattern = "/users/:id";
  12389. detail::PathParamsMatcher matcher(pattern);
  12390. Request request;
  12391. request.path = "/users/24";
  12392. ASSERT_TRUE(matcher.match(request));
  12393. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12394. EXPECT_EQ(request.path_params, expected_params);
  12395. }
  12396. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12397. const auto pattern = "/users/:id/";
  12398. detail::PathParamsMatcher matcher(pattern);
  12399. Request request;
  12400. request.path = "/users/42/";
  12401. ASSERT_TRUE(matcher.match(request));
  12402. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12403. EXPECT_EQ(request.path_params, expected_params);
  12404. }
  12405. TEST(PathParamsTest, EmptyParam) {
  12406. const auto pattern = "/users/:id/";
  12407. detail::PathParamsMatcher matcher(pattern);
  12408. Request request;
  12409. request.path = "/users//";
  12410. ASSERT_TRUE(matcher.match(request));
  12411. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12412. EXPECT_EQ(request.path_params, expected_params);
  12413. }
  12414. TEST(PathParamsTest, FragmentMismatch) {
  12415. const auto pattern = "/users/:id/";
  12416. detail::PathParamsMatcher matcher(pattern);
  12417. Request request;
  12418. request.path = "/admins/24/";
  12419. ASSERT_FALSE(matcher.match(request));
  12420. }
  12421. TEST(PathParamsTest, ExtraFragments) {
  12422. const auto pattern = "/users/:id";
  12423. detail::PathParamsMatcher matcher(pattern);
  12424. Request request;
  12425. request.path = "/users/42/subscriptions";
  12426. ASSERT_FALSE(matcher.match(request));
  12427. }
  12428. TEST(PathParamsTest, MissingTrailingParam) {
  12429. const auto pattern = "/users/:id";
  12430. detail::PathParamsMatcher matcher(pattern);
  12431. Request request;
  12432. request.path = "/users";
  12433. ASSERT_FALSE(matcher.match(request));
  12434. }
  12435. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12436. const auto pattern = "/users/:id/subscriptions";
  12437. detail::PathParamsMatcher matcher(pattern);
  12438. Request request;
  12439. request.path = "/users/subscriptions";
  12440. ASSERT_FALSE(matcher.match(request));
  12441. }
  12442. TEST(PathParamsTest, MultipleParams) {
  12443. const auto pattern = "/users/:userid/subscriptions/:subid";
  12444. detail::PathParamsMatcher matcher(pattern);
  12445. Request request;
  12446. request.path = "/users/42/subscriptions/2";
  12447. ASSERT_TRUE(matcher.match(request));
  12448. std::unordered_map<std::string, std::string> expected_params = {
  12449. {"userid", "42"}, {"subid", "2"}};
  12450. EXPECT_EQ(request.path_params, expected_params);
  12451. }
  12452. TEST(PathParamsTest, SequenceOfParams) {
  12453. const auto pattern = "/values/:x/:y/:z";
  12454. detail::PathParamsMatcher matcher(pattern);
  12455. Request request;
  12456. request.path = "/values/1/2/3";
  12457. ASSERT_TRUE(matcher.match(request));
  12458. std::unordered_map<std::string, std::string> expected_params = {
  12459. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12460. EXPECT_EQ(request.path_params, expected_params);
  12461. }
  12462. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12463. const auto pattern = "/prefix:suffix";
  12464. detail::PathParamsMatcher matcher(pattern);
  12465. Request request;
  12466. request.path = "/prefix:suffix";
  12467. ASSERT_TRUE(matcher.match(request));
  12468. const std::unordered_map<std::string, std::string> expected_params = {};
  12469. EXPECT_EQ(request.path_params, expected_params);
  12470. }
  12471. TEST(ParseUrlTest, VariousPatterns) {
  12472. {
  12473. detail::UrlComponents uc;
  12474. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12475. EXPECT_EQ("http", uc.scheme);
  12476. EXPECT_EQ("example.com", uc.host);
  12477. EXPECT_EQ("8080", uc.port);
  12478. EXPECT_EQ("/path", uc.path);
  12479. EXPECT_EQ("?q=1", uc.query);
  12480. }
  12481. {
  12482. detail::UrlComponents uc;
  12483. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12484. EXPECT_EQ("https", uc.scheme);
  12485. EXPECT_EQ("example.com", uc.host);
  12486. EXPECT_TRUE(uc.port.empty());
  12487. EXPECT_EQ("/path", uc.path);
  12488. }
  12489. {
  12490. detail::UrlComponents uc;
  12491. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12492. EXPECT_EQ("::1", uc.host);
  12493. EXPECT_EQ("8080", uc.port);
  12494. EXPECT_EQ("/path", uc.path);
  12495. }
  12496. {
  12497. detail::UrlComponents uc;
  12498. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12499. }
  12500. {
  12501. detail::UrlComponents uc;
  12502. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12503. EXPECT_TRUE(uc.scheme.empty());
  12504. EXPECT_EQ("example.com", uc.host);
  12505. EXPECT_EQ("/path", uc.path);
  12506. EXPECT_EQ("?q=1", uc.query);
  12507. }
  12508. {
  12509. detail::UrlComponents uc;
  12510. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12511. EXPECT_TRUE(uc.host.empty());
  12512. EXPECT_EQ("/path", uc.path);
  12513. EXPECT_EQ("?q=1", uc.query);
  12514. }
  12515. {
  12516. detail::UrlComponents uc;
  12517. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12518. EXPECT_EQ("example.com", uc.host);
  12519. EXPECT_EQ("8080", uc.port);
  12520. }
  12521. {
  12522. // Unix socket path — must not be parsed as host
  12523. detail::UrlComponents uc;
  12524. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12525. EXPECT_TRUE(uc.host.empty());
  12526. }
  12527. {
  12528. detail::UrlComponents uc;
  12529. ASSERT_TRUE(detail::parse_url("", uc));
  12530. EXPECT_TRUE(uc.host.empty());
  12531. EXPECT_TRUE(uc.path.empty());
  12532. }
  12533. {
  12534. detail::UrlComponents uc;
  12535. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12536. }
  12537. {
  12538. detail::UrlComponents uc;
  12539. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12540. }
  12541. {
  12542. // Accepted by parse_url; callers restrict to http/https
  12543. detail::UrlComponents uc;
  12544. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12545. EXPECT_EQ("ftp", uc.scheme);
  12546. }
  12547. {
  12548. detail::UrlComponents uc;
  12549. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12550. }
  12551. {
  12552. detail::UrlComponents uc;
  12553. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12554. }
  12555. }
  12556. TEST(ParseUrlTest, FragmentHandling) {
  12557. {
  12558. detail::UrlComponents uc;
  12559. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12560. EXPECT_EQ("/path", uc.path);
  12561. EXPECT_TRUE(uc.query.empty());
  12562. }
  12563. {
  12564. detail::UrlComponents uc;
  12565. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12566. EXPECT_TRUE(uc.path.empty());
  12567. EXPECT_TRUE(uc.query.empty());
  12568. }
  12569. }
  12570. TEST(ParseUrlTest, UserinfoHandling) {
  12571. // Userinfo with @ but no colon — host includes @
  12572. detail::UrlComponents uc;
  12573. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12574. EXPECT_EQ("user@host.com", uc.host);
  12575. EXPECT_EQ("/path", uc.path);
  12576. }
  12577. TEST(ParseUrlTest, IPv6EdgeCases) {
  12578. {
  12579. detail::UrlComponents uc;
  12580. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12581. EXPECT_TRUE(uc.scheme.empty());
  12582. EXPECT_EQ("::1", uc.host);
  12583. EXPECT_EQ("8080", uc.port);
  12584. }
  12585. {
  12586. // Zone ID '%25' is not in [a-fA-F0-9:]
  12587. detail::UrlComponents uc;
  12588. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12589. }
  12590. }
  12591. TEST(ParseUrlTest, SchemeEdgeCases) {
  12592. {
  12593. detail::UrlComponents uc;
  12594. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12595. }
  12596. {
  12597. detail::UrlComponents uc;
  12598. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12599. }
  12600. {
  12601. detail::UrlComponents uc;
  12602. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12603. }
  12604. }
  12605. TEST(ParseUrlTest, PortEdgeCases) {
  12606. {
  12607. detail::UrlComponents uc;
  12608. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12609. EXPECT_TRUE(uc.port.empty());
  12610. EXPECT_EQ("/path", uc.path);
  12611. }
  12612. {
  12613. // parse_url accepts any port string; validation is done by parse_port
  12614. detail::UrlComponents uc;
  12615. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12616. EXPECT_EQ("abc", uc.port);
  12617. }
  12618. }
  12619. TEST(ParseUrlTest, WebSocketPatterns) {
  12620. {
  12621. detail::UrlComponents uc;
  12622. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12623. EXPECT_EQ("ws", uc.scheme);
  12624. EXPECT_EQ("echo.example.com", uc.host);
  12625. EXPECT_EQ("8080", uc.port);
  12626. EXPECT_EQ("/ws", uc.path);
  12627. }
  12628. {
  12629. detail::UrlComponents uc;
  12630. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12631. EXPECT_EQ("wss", uc.scheme);
  12632. EXPECT_EQ("echo.example.com", uc.host);
  12633. EXPECT_TRUE(uc.port.empty());
  12634. EXPECT_EQ("/ws", uc.path);
  12635. }
  12636. }
  12637. TEST(ParseUrlTest, QueryOnly) {
  12638. detail::UrlComponents uc;
  12639. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12640. EXPECT_TRUE(uc.host.empty());
  12641. EXPECT_TRUE(uc.path.empty());
  12642. EXPECT_EQ("?q=1&r=2", uc.query);
  12643. }
  12644. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12645. detail::UrlComponents uc;
  12646. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12647. EXPECT_TRUE(uc.scheme.empty());
  12648. EXPECT_EQ("example.com", uc.host);
  12649. EXPECT_EQ("443", uc.port);
  12650. EXPECT_EQ("/path", uc.path);
  12651. }
  12652. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12653. // If ipv6 regex working, regex match codepath is taken.
  12654. // else port will default to 80 in Client impl
  12655. int clientImplMagicPort = 80;
  12656. int port = 4321;
  12657. // above ports must be different to avoid false negative
  12658. EXPECT_NE(clientImplMagicPort, port);
  12659. std::string ipV6TestURL = "http://[ff06::c3]";
  12660. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12661. CLIENT_PRIVATE_KEY_FILE);
  12662. EXPECT_EQ(cli.port(), port);
  12663. }
  12664. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12665. auto file_path = "./www/dir/index.html";
  12666. auto dir_path = "./www/dir";
  12667. detail::FileStat stat_file(file_path);
  12668. EXPECT_TRUE(stat_file.is_file());
  12669. EXPECT_FALSE(stat_file.is_dir());
  12670. detail::FileStat stat_dir(dir_path);
  12671. EXPECT_FALSE(stat_dir.is_file());
  12672. EXPECT_TRUE(stat_dir.is_dir());
  12673. }
  12674. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12675. // IPv4 with default HTTP port (80)
  12676. EXPECT_EQ("example.com",
  12677. detail::make_host_and_port_string("example.com", 80, false));
  12678. // IPv4 with default HTTPS port (443)
  12679. EXPECT_EQ("example.com",
  12680. detail::make_host_and_port_string("example.com", 443, true));
  12681. // IPv4 with non-default HTTP port
  12682. EXPECT_EQ("example.com:8080",
  12683. detail::make_host_and_port_string("example.com", 8080, false));
  12684. // IPv4 with non-default HTTPS port
  12685. EXPECT_EQ("example.com:8443",
  12686. detail::make_host_and_port_string("example.com", 8443, true));
  12687. // IPv6 with default HTTP port (80)
  12688. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12689. // IPv6 with default HTTPS port (443)
  12690. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12691. // IPv6 with non-default HTTP port
  12692. EXPECT_EQ("[::1]:8080",
  12693. detail::make_host_and_port_string("::1", 8080, false));
  12694. // IPv6 with non-default HTTPS port
  12695. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12696. // IPv6 full address with default port
  12697. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12698. detail::make_host_and_port_string(
  12699. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12700. // IPv6 full address with non-default port
  12701. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12702. detail::make_host_and_port_string(
  12703. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12704. // IPv6 localhost with non-default port
  12705. EXPECT_EQ("[::1]:3000",
  12706. detail::make_host_and_port_string("::1", 3000, false));
  12707. // IPv6 with zone ID (link-local address) with default port
  12708. EXPECT_EQ("[fe80::1%eth0]",
  12709. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12710. // IPv6 with zone ID (link-local address) with non-default port
  12711. EXPECT_EQ("[fe80::1%eth0]:8080",
  12712. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12713. // Edge case: Port 443 with is_ssl=false (should add port)
  12714. EXPECT_EQ("example.com:443",
  12715. detail::make_host_and_port_string("example.com", 443, false));
  12716. // Edge case: Port 80 with is_ssl=true (should add port)
  12717. EXPECT_EQ("example.com:80",
  12718. detail::make_host_and_port_string("example.com", 80, true));
  12719. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12720. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12721. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12722. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12723. // Security fix: Already bracketed IPv6 should not get double brackets
  12724. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12725. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12726. EXPECT_EQ("[::1]:8080",
  12727. detail::make_host_and_port_string("[::1]", 8080, false));
  12728. EXPECT_EQ("[2001:db8::1]:8080",
  12729. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12730. EXPECT_EQ("[fe80::1%eth0]",
  12731. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12732. EXPECT_EQ("[fe80::1%eth0]:8080",
  12733. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12734. // Edge case: Empty host (should return as-is)
  12735. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12736. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12737. // This is a known limitation but shouldn't crash
  12738. EXPECT_EQ("[host:name]",
  12739. detail::make_host_and_port_string("host:name", 80, false));
  12740. // Port number edge cases (no validation, but should not crash)
  12741. EXPECT_EQ("example.com:0",
  12742. detail::make_host_and_port_string("example.com", 0, false));
  12743. EXPECT_EQ("example.com:-1",
  12744. detail::make_host_and_port_string("example.com", -1, false));
  12745. EXPECT_EQ("example.com:65535",
  12746. detail::make_host_and_port_string("example.com", 65535, false));
  12747. EXPECT_EQ("example.com:65536",
  12748. detail::make_host_and_port_string("example.com", 65536, false));
  12749. }
  12750. #ifdef CPPHTTPLIB_SSL_ENABLED
  12751. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12752. httplib::SSLClient cli("roblox.com", 443);
  12753. cli.set_follow_location(true);
  12754. auto res = cli.Get("/");
  12755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12756. EXPECT_EQ(StatusCode::OK_200, res->status);
  12757. }
  12758. #endif
  12759. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12760. Server svr;
  12761. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12762. EXPECT_EQ(res.status, 400);
  12763. });
  12764. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12765. auto se = detail::scope_exit([&] {
  12766. svr.stop();
  12767. thread.join();
  12768. ASSERT_FALSE(svr.is_running());
  12769. });
  12770. svr.wait_until_ready();
  12771. Client cli(HOST, PORT);
  12772. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12773. }
  12774. TEST(InvalidHeaderCharsTest, is_field_name) {
  12775. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12776. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12777. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12778. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12779. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12780. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12781. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12782. EXPECT_FALSE(detail::fields::is_field_name(""));
  12783. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12784. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12785. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12786. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12787. }
  12788. TEST(InvalidHeaderCharsTest, is_field_value) {
  12789. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12790. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12791. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12792. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12793. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12794. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12795. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12796. EXPECT_TRUE(detail::fields::is_field_value(""));
  12797. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12798. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12799. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12800. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12801. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12802. }
  12803. TEST(InvalidHeaderCharsTest, OnServer) {
  12804. Server svr;
  12805. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12806. std::string header = "Not Set";
  12807. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12808. res.set_header(header, "value");
  12809. res.set_content("Page Content Page Content", "text/plain");
  12810. });
  12811. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12812. std::string header = "Not Set";
  12813. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12814. res.set_header("X-Test", header);
  12815. res.set_content("Page Content Page Content", "text/plain");
  12816. });
  12817. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12818. auto se = detail::scope_exit([&] {
  12819. svr.stop();
  12820. thread.join();
  12821. ASSERT_FALSE(svr.is_running());
  12822. });
  12823. svr.wait_until_ready();
  12824. Client cli(HOST, PORT);
  12825. {
  12826. auto res = cli.Get(
  12827. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12829. EXPECT_EQ("Page Content Page Content", res->body);
  12830. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12831. }
  12832. {
  12833. auto res = cli.Get(
  12834. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12836. EXPECT_EQ("Page Content Page Content", res->body);
  12837. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12838. }
  12839. }
  12840. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12841. auto handled = false;
  12842. Server svr;
  12843. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12844. thread t = thread([&] { svr.listen(HOST, PORT); });
  12845. auto se = detail::scope_exit([&] {
  12846. svr.stop();
  12847. t.join();
  12848. ASSERT_FALSE(svr.is_running());
  12849. ASSERT_FALSE(handled);
  12850. });
  12851. svr.wait_until_ready();
  12852. auto req = "POST /test HTTP/1.1\r\n"
  12853. "Content-Length: x\r\n"
  12854. "\r\n";
  12855. std::string response;
  12856. ASSERT_TRUE(send_request(1, req, &response));
  12857. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12858. response.substr(0, response.find("\r\n")));
  12859. }
  12860. #ifndef _WIN32
  12861. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12862. static constexpr char reject[] = "Unauthorized";
  12863. static constexpr char accept[] = "Upload accepted";
  12864. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12865. Server svr;
  12866. svr.set_expect_100_continue_handler(
  12867. [](const Request & /*req*/, Response &res) {
  12868. res.status = StatusCode::Unauthorized_401;
  12869. res.set_content(reject, "text/plain");
  12870. return res.status;
  12871. });
  12872. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12873. res.set_content(accept, "text/plain");
  12874. });
  12875. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12876. auto se = detail::scope_exit([&] {
  12877. svr.stop();
  12878. thread.join();
  12879. ASSERT_FALSE(svr.is_running());
  12880. });
  12881. svr.wait_until_ready();
  12882. {
  12883. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12884. curl_easy_init(), &curl_easy_cleanup};
  12885. ASSERT_NE(curl, nullptr);
  12886. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12887. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12888. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12889. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12890. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12891. &curl_slist_free_all};
  12892. ASSERT_NE(list, nullptr);
  12893. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12894. struct read_data {
  12895. size_t read_size;
  12896. size_t total_size;
  12897. } data = {0, total_size};
  12898. using read_callback_t =
  12899. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12900. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12901. void *userdata) -> size_t {
  12902. read_data *d = (read_data *)userdata;
  12903. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12904. std::fill_n(ptr, size * nmemb, 'A');
  12905. d->read_size += size * nmemb;
  12906. return size * nmemb;
  12907. };
  12908. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12909. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12910. std::vector<char> buffer;
  12911. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12912. using write_callback_t =
  12913. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12914. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12915. void *userdata) -> size_t {
  12916. std::vector<char> *buf = (std::vector<char> *)userdata;
  12917. buf->reserve(buf->size() + size * nmemb + 1);
  12918. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12919. return size * nmemb;
  12920. };
  12921. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12922. {
  12923. const auto res = curl_easy_perform(curl.get());
  12924. ASSERT_EQ(res, CURLE_OK);
  12925. }
  12926. {
  12927. auto response_code = long{};
  12928. const auto res =
  12929. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12930. ASSERT_EQ(res, CURLE_OK);
  12931. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12932. }
  12933. {
  12934. auto dl = curl_off_t{};
  12935. const auto res =
  12936. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12937. ASSERT_EQ(res, CURLE_OK);
  12938. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12939. }
  12940. {
  12941. buffer.push_back('\0');
  12942. ASSERT_STRCASEEQ(buffer.data(), reject);
  12943. }
  12944. }
  12945. }
  12946. #endif
  12947. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12948. // Regression test for #2458.
  12949. //
  12950. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12951. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12952. // ticket can make the client socket spuriously readable during the
  12953. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12954. // the client withholds the body and then blocks reading a response that never
  12955. // comes, failing with `Failed to read connection`.
  12956. //
  12957. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12958. // within the timeout. This raw OpenSSL server deliberately never sends
  12959. // `100 Continue`; the client must still deliver the body and receive 200.
  12960. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12961. signal(SIGPIPE, SIG_IGN);
  12962. const auto port = PORT + 4;
  12963. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12964. ASSERT_NE(srv, INVALID_SOCKET);
  12965. int opt = 1;
  12966. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12967. sockaddr_in addr{};
  12968. addr.sin_family = AF_INET;
  12969. addr.sin_port = htons(static_cast<uint16_t>(port));
  12970. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12971. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12972. ASSERT_EQ(0, ::listen(srv, 1));
  12973. std::atomic<size_t> server_body_bytes{0};
  12974. auto server_thread = std::thread([&] {
  12975. sockaddr_in cli_addr{};
  12976. socklen_t cli_len = sizeof(cli_addr);
  12977. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12978. if (cli == INVALID_SOCKET) { return; }
  12979. // Bound the lifetime of the server side so a buggy client (which never
  12980. // sends the body) cannot make this thread block forever on join.
  12981. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12982. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12983. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12984. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12985. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12986. SSL *ssl = SSL_new(ctx);
  12987. SSL_set_fd(ssl, static_cast<int>(cli));
  12988. if (SSL_accept(ssl) > 0) {
  12989. // Read the request headers. Reading here also flushes the TLS 1.3
  12990. // session tickets to the client. Deliberately do NOT send
  12991. // `100 Continue`.
  12992. std::string buf;
  12993. char tmp[1024];
  12994. while (buf.find("\r\n\r\n") == std::string::npos) {
  12995. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12996. if (n <= 0) { break; }
  12997. buf.append(tmp, static_cast<size_t>(n));
  12998. }
  12999. // A correct client sends the body now; count what arrives.
  13000. auto pos = buf.find("\r\n\r\n");
  13001. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  13002. while (body < 4096) {
  13003. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13004. if (n <= 0) { break; }
  13005. body += static_cast<size_t>(n);
  13006. }
  13007. server_body_bytes = body;
  13008. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13009. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13010. SSL_shutdown(ssl);
  13011. }
  13012. SSL_free(ssl);
  13013. detail::close_socket(cli);
  13014. SSL_CTX_free(ctx);
  13015. });
  13016. auto se = detail::scope_exit([&] {
  13017. server_thread.join();
  13018. detail::close_socket(srv);
  13019. });
  13020. SSLClient cli("127.0.0.1", port);
  13021. cli.enable_server_certificate_verification(false);
  13022. cli.set_connection_timeout(5, 0);
  13023. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13024. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13025. std::string body(4096, 'A');
  13026. auto res = cli.Put("/api/test", body, "application/json");
  13027. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13028. EXPECT_EQ(StatusCode::OK_200, res->status);
  13029. EXPECT_EQ(body.size(), server_body_bytes.load());
  13030. }
  13031. #endif
  13032. template <typename S, typename C>
  13033. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13034. svr.Get("/stream", [&](const Request &, Response &res) {
  13035. auto data = new std::string("01234567890123456789");
  13036. res.set_content_provider(
  13037. data->size(), "text/plain",
  13038. [&, data](size_t offset, size_t length, DataSink &sink) {
  13039. const size_t DATA_CHUNK_SIZE = 4;
  13040. const auto &d = *data;
  13041. std::this_thread::sleep_for(std::chrono::seconds(1));
  13042. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13043. return true;
  13044. },
  13045. [data](bool success) {
  13046. EXPECT_FALSE(success);
  13047. delete data;
  13048. });
  13049. });
  13050. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13051. auto i = new size_t(0);
  13052. res.set_content_provider(
  13053. "text/plain",
  13054. [i](size_t, DataSink &sink) {
  13055. if (*i < 5) {
  13056. std::this_thread::sleep_for(std::chrono::seconds(1));
  13057. sink.write("abcd", 4);
  13058. (*i)++;
  13059. } else {
  13060. sink.done();
  13061. }
  13062. return true;
  13063. },
  13064. [i](bool success) {
  13065. EXPECT_FALSE(success);
  13066. delete i;
  13067. });
  13068. });
  13069. svr.Get("/chunked", [&](const Request &, Response &res) {
  13070. auto i = new size_t(0);
  13071. res.set_chunked_content_provider(
  13072. "text/plain",
  13073. [i](size_t, DataSink &sink) {
  13074. if (*i < 5) {
  13075. std::this_thread::sleep_for(std::chrono::seconds(1));
  13076. sink.os << "abcd";
  13077. (*i)++;
  13078. } else {
  13079. sink.done();
  13080. }
  13081. return true;
  13082. },
  13083. [i](bool success) {
  13084. EXPECT_FALSE(success);
  13085. delete i;
  13086. });
  13087. });
  13088. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13089. auto se = detail::scope_exit([&] {
  13090. svr.stop();
  13091. listen_thread.join();
  13092. ASSERT_FALSE(svr.is_running());
  13093. });
  13094. svr.wait_until_ready();
  13095. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13096. {
  13097. auto start = std::chrono::steady_clock::now();
  13098. auto res = cli.Get("/stream");
  13099. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13100. std::chrono::steady_clock::now() - start)
  13101. .count();
  13102. ASSERT_FALSE(res);
  13103. EXPECT_EQ(Error::Read, res.error());
  13104. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13105. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13106. }
  13107. {
  13108. auto start = std::chrono::steady_clock::now();
  13109. auto res = cli.Get("/stream_without_length");
  13110. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13111. std::chrono::steady_clock::now() - start)
  13112. .count();
  13113. ASSERT_FALSE(res);
  13114. EXPECT_EQ(Error::Read, res.error());
  13115. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13116. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13117. }
  13118. {
  13119. auto start = std::chrono::steady_clock::now();
  13120. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13121. EXPECT_EQ("abcd", string(data, data_length));
  13122. return true;
  13123. });
  13124. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13125. std::chrono::steady_clock::now() - start)
  13126. .count();
  13127. ASSERT_FALSE(res);
  13128. EXPECT_EQ(Error::Read, res.error());
  13129. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13130. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13131. }
  13132. }
  13133. TEST(MaxTimeoutTest, ContentStream) {
  13134. time_t timeout = 2000;
  13135. time_t threshold = 200;
  13136. Server svr;
  13137. Client cli("localhost", PORT);
  13138. max_timeout_test(svr, cli, timeout, threshold);
  13139. }
  13140. #ifdef CPPHTTPLIB_SSL_ENABLED
  13141. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13142. time_t timeout = 2000;
  13143. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13145. SSLClient cli("localhost", PORT);
  13146. cli.enable_server_certificate_verification(false);
  13147. max_timeout_test(svr, cli, timeout, threshold);
  13148. }
  13149. #endif
  13150. class EventDispatcher {
  13151. public:
  13152. EventDispatcher() {}
  13153. bool wait_event(DataSink *sink) {
  13154. unique_lock<mutex> lk(m_);
  13155. int id = id_;
  13156. // Wait with timeout to prevent hanging if client disconnects
  13157. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13158. [&] { return cid_ == id; })) {
  13159. return false; // Timeout occurred
  13160. }
  13161. sink->write(message_.data(), message_.size());
  13162. return true;
  13163. }
  13164. void send_event(const string &message) {
  13165. lock_guard<mutex> lk(m_);
  13166. cid_ = id_++;
  13167. message_ = message;
  13168. cv_.notify_all();
  13169. }
  13170. private:
  13171. mutex m_;
  13172. condition_variable cv_;
  13173. atomic_int id_{0};
  13174. atomic_int cid_{-1};
  13175. string message_;
  13176. };
  13177. TEST(ClientInThreadTest, Issue2068) {
  13178. EventDispatcher ed;
  13179. Server svr;
  13180. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13181. res.set_chunked_content_provider("text/event-stream",
  13182. [&](size_t /*offset*/, DataSink &sink) {
  13183. return ed.wait_event(&sink);
  13184. });
  13185. });
  13186. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13187. svr.wait_until_ready();
  13188. thread event_thread([&] {
  13189. int id = 0;
  13190. while (svr.is_running()) {
  13191. this_thread::sleep_for(chrono::milliseconds(500));
  13192. std::stringstream ss;
  13193. ss << "data: " << id << "\n\n";
  13194. ed.send_event(ss.str());
  13195. id++;
  13196. }
  13197. });
  13198. auto se = detail::scope_exit([&] {
  13199. svr.stop();
  13200. listen_thread.join();
  13201. event_thread.join();
  13202. ASSERT_FALSE(svr.is_running());
  13203. });
  13204. {
  13205. auto client = detail::make_unique<Client>(HOST, PORT);
  13206. client->set_read_timeout(std::chrono::minutes(10));
  13207. std::atomic<bool> stop{false};
  13208. std::thread t([&] {
  13209. client->Get("/event1",
  13210. [&](const char *, size_t) -> bool { return !stop; });
  13211. });
  13212. std::this_thread::sleep_for(std::chrono::seconds(2));
  13213. stop = true;
  13214. client->stop();
  13215. t.join();
  13216. // Reset client after thread has finished
  13217. client.reset();
  13218. }
  13219. }
  13220. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13221. auto handled = false;
  13222. Server svr;
  13223. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13225. auto se = detail::scope_exit([&] {
  13226. svr.stop();
  13227. t.join();
  13228. ASSERT_FALSE(svr.is_running());
  13229. ASSERT_FALSE(handled);
  13230. });
  13231. svr.wait_until_ready();
  13232. // Two Content-Length headers with different values — must be rejected
  13233. auto req = "POST /test HTTP/1.1\r\n"
  13234. "Content-Length: 5\r\n"
  13235. "Content-Length: 10\r\n"
  13236. "\r\n"
  13237. "hello";
  13238. std::string response;
  13239. ASSERT_TRUE(send_request(1, req, &response));
  13240. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13241. response.substr(0, response.find("\r\n")));
  13242. }
  13243. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13244. auto handled = false;
  13245. Server svr;
  13246. svr.Post("/test", [&](const Request &, Response &res) {
  13247. handled = true;
  13248. res.set_content("ok", "text/plain");
  13249. });
  13250. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13251. auto se = detail::scope_exit([&] {
  13252. svr.stop();
  13253. t.join();
  13254. ASSERT_FALSE(svr.is_running());
  13255. ASSERT_TRUE(handled);
  13256. });
  13257. svr.wait_until_ready();
  13258. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13259. auto req = "POST /test HTTP/1.1\r\n"
  13260. "Content-Length: 5\r\n"
  13261. "Content-Length: 5\r\n"
  13262. "\r\n"
  13263. "hello";
  13264. std::string response;
  13265. ASSERT_TRUE(send_request(1, req, &response));
  13266. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13267. }
  13268. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13269. Server svr;
  13270. svr.Get("/", [](const Request &req, Response &res) {
  13271. EXPECT_EQ(2U, req.trailers.size());
  13272. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13273. // Denied
  13274. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13275. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13276. // Accepted
  13277. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13278. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13279. EXPECT_TRUE(req.has_trailer("X-World"));
  13280. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13281. res.set_content("ok", "text/plain");
  13282. });
  13283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13284. auto se = detail::scope_exit([&] {
  13285. svr.stop();
  13286. t.join();
  13287. ASSERT_FALSE(svr.is_running());
  13288. });
  13289. svr.wait_until_ready();
  13290. const std::string req = "GET / HTTP/1.1\r\n"
  13291. "Transfer-Encoding: chunked\r\n"
  13292. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13293. "\r\n"
  13294. "0\r\n"
  13295. "Content-Length: 10\r\n"
  13296. "Host: internal.local\r\n"
  13297. "Content-Type: malicious/content\r\n"
  13298. "Cookie: any\r\n"
  13299. "Set-Cookie: any\r\n"
  13300. "X-Forwarded-For: attacker.com\r\n"
  13301. "X-Real-Ip: 1.1.1.1\r\n"
  13302. "X-Hello: hello\r\n"
  13303. "X-World: world\r\n"
  13304. "\r\n";
  13305. std::string res;
  13306. ASSERT_TRUE(send_request(1, req, &res));
  13307. }
  13308. // A direct client that is not listed in trusted_proxies must not be able to
  13309. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13310. // the peer address on the actual TCP connection determines whether the
  13311. // header is honored.
  13312. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13313. Server svr;
  13314. // Deliberately does NOT include the loopback address the test client
  13315. // actually connects from, so the direct connection is not a trusted proxy.
  13316. svr.set_trusted_proxies({"203.0.113.66"});
  13317. std::string observed_remote_addr;
  13318. svr.Get("/ip", [&](const Request &req, Response &res) {
  13319. observed_remote_addr = req.remote_addr;
  13320. res.set_content("ok", "text/plain");
  13321. });
  13322. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13323. auto se = detail::scope_exit([&] {
  13324. svr.stop();
  13325. t.join();
  13326. ASSERT_FALSE(svr.is_running());
  13327. });
  13328. svr.wait_until_ready();
  13329. Client cli(HOST, PORT);
  13330. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13332. EXPECT_EQ(StatusCode::OK_200, res->status);
  13333. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13334. // ignored entirely and the real connection-level address retained.
  13335. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13336. observed_remote_addr == "127.0.0.1");
  13337. }
  13338. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13339. Server svr;
  13340. std::string observed_remote_addr;
  13341. std::string observed_xff;
  13342. svr.Get("/ip", [&](const Request &req, Response &res) {
  13343. observed_remote_addr = req.remote_addr;
  13344. observed_xff = req.get_header_value("X-Forwarded-For");
  13345. res.set_content("ok", "text/plain");
  13346. });
  13347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13348. auto se = detail::scope_exit([&] {
  13349. svr.stop();
  13350. t.join();
  13351. ASSERT_FALSE(svr.is_running());
  13352. });
  13353. svr.wait_until_ready();
  13354. Client cli(HOST, PORT);
  13355. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13357. EXPECT_EQ(StatusCode::OK_200, res->status);
  13358. EXPECT_EQ(observed_xff, "203.0.113.66");
  13359. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13360. observed_remote_addr == "127.0.0.1");
  13361. }
  13362. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13363. Server svr;
  13364. svr.set_trusted_proxies({"203.0.113.66"});
  13365. std::string observed_remote_addr;
  13366. std::string observed_xff;
  13367. svr.Get("/ip", [&](const Request &req, Response &res) {
  13368. observed_remote_addr = req.remote_addr;
  13369. observed_xff = req.get_header_value("X-Forwarded-For");
  13370. res.set_content("ok", "text/plain");
  13371. });
  13372. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13373. auto se = detail::scope_exit([&] {
  13374. svr.stop();
  13375. t.join();
  13376. ASSERT_FALSE(svr.is_running());
  13377. });
  13378. svr.wait_until_ready();
  13379. Client cli(HOST, PORT);
  13380. auto res = cli.Get("/ip");
  13381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13382. EXPECT_EQ(StatusCode::OK_200, res->status);
  13383. EXPECT_EQ(observed_xff, "");
  13384. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13385. observed_remote_addr == "127.0.0.1");
  13386. }
  13387. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13388. Server svr;
  13389. // Include the loopback address the test client actually connects from, so
  13390. // the direct connection itself is recognized as the trusted proxy hop.
  13391. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13392. std::string observed_remote_addr;
  13393. std::string observed_xff;
  13394. svr.Get("/ip", [&](const Request &req, Response &res) {
  13395. observed_remote_addr = req.remote_addr;
  13396. observed_xff = req.get_header_value("X-Forwarded-For");
  13397. res.set_content("ok", "text/plain");
  13398. });
  13399. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13400. auto se = detail::scope_exit([&] {
  13401. svr.stop();
  13402. t.join();
  13403. ASSERT_FALSE(svr.is_running());
  13404. });
  13405. svr.wait_until_ready();
  13406. Client cli(HOST, PORT);
  13407. auto res = cli.Get(
  13408. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13410. EXPECT_EQ(StatusCode::OK_200, res->status);
  13411. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13412. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13413. }
  13414. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13415. Server svr;
  13416. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13417. std::string observed_remote_addr;
  13418. std::string observed_xff;
  13419. svr.Get("/ip", [&](const Request &req, Response &res) {
  13420. observed_remote_addr = req.remote_addr;
  13421. observed_xff = req.get_header_value("X-Forwarded-For");
  13422. res.set_content("ok", "text/plain");
  13423. });
  13424. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13425. auto se = detail::scope_exit([&] {
  13426. svr.stop();
  13427. t.join();
  13428. ASSERT_FALSE(svr.is_running());
  13429. });
  13430. svr.wait_until_ready();
  13431. Client cli(HOST, PORT);
  13432. auto res = cli.Get(
  13433. "/ip",
  13434. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. EXPECT_EQ(StatusCode::OK_200, res->status);
  13437. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13438. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13439. }
  13440. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13441. Server svr;
  13442. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13443. std::string observed_remote_addr;
  13444. std::string observed_xff;
  13445. svr.Get("/ip", [&](const Request &req, Response &res) {
  13446. observed_remote_addr = req.remote_addr;
  13447. observed_xff = req.get_header_value("X-Forwarded-For");
  13448. res.set_content("ok", "text/plain");
  13449. });
  13450. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13451. auto se = detail::scope_exit([&] {
  13452. svr.stop();
  13453. t.join();
  13454. ASSERT_FALSE(svr.is_running());
  13455. });
  13456. svr.wait_until_ready();
  13457. Client cli(HOST, PORT);
  13458. auto res = cli.Get(
  13459. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. EXPECT_EQ(StatusCode::OK_200, res->status);
  13462. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13463. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13464. // and must not be selected.
  13465. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13466. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13467. }
  13468. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13469. Server svr;
  13470. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13471. std::string observed_remote_addr;
  13472. svr.Get("/ip", [&](const Request &req, Response &res) {
  13473. observed_remote_addr = req.remote_addr;
  13474. res.set_content("ok", "text/plain");
  13475. });
  13476. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13477. auto se = detail::scope_exit([&] {
  13478. svr.stop();
  13479. t.join();
  13480. ASSERT_FALSE(svr.is_running());
  13481. });
  13482. svr.wait_until_ready();
  13483. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13484. // a forged address and the trusted proxy's own address; the forged value must
  13485. // not win over the address the trusted proxy actually recorded.
  13486. Client cli(HOST, PORT);
  13487. auto res = cli.Get(
  13488. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13490. EXPECT_EQ(StatusCode::OK_200, res->status);
  13491. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13492. }
  13493. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13494. Server svr;
  13495. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13496. std::string observed_remote_addr;
  13497. std::string observed_xff;
  13498. svr.Get("/ip", [&](const Request &req, Response &res) {
  13499. observed_remote_addr = req.remote_addr;
  13500. observed_xff = req.get_header_value("X-Forwarded-For");
  13501. res.set_content("ok", "text/plain");
  13502. });
  13503. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13504. auto se = detail::scope_exit([&] {
  13505. svr.stop();
  13506. t.join();
  13507. ASSERT_FALSE(svr.is_running());
  13508. });
  13509. svr.wait_until_ready();
  13510. Client cli(HOST, PORT);
  13511. auto res = cli.Get(
  13512. "/ip",
  13513. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13515. EXPECT_EQ(StatusCode::OK_200, res->status);
  13516. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13517. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13518. }
  13519. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13520. Server svr;
  13521. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13522. std::string observed_remote_addr;
  13523. std::string observed_xff;
  13524. svr.Get("/ip", [&](const Request &req, Response &res) {
  13525. observed_remote_addr = req.remote_addr;
  13526. observed_xff = req.get_header_value("X-Forwarded-For");
  13527. res.set_content("ok", "text/plain");
  13528. });
  13529. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13530. auto se = detail::scope_exit([&] {
  13531. svr.stop();
  13532. t.join();
  13533. ASSERT_FALSE(svr.is_running());
  13534. });
  13535. svr.wait_until_ready();
  13536. std::string raw_req =
  13537. "GET /ip HTTP/1.1\r\n"
  13538. "Host: localhost\r\n"
  13539. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13540. "Connection: close\r\n"
  13541. "\r\n";
  13542. std::string out;
  13543. ASSERT_TRUE(send_request(5, raw_req, &out));
  13544. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13545. // Header parser trims surrounding whitespace of the header value
  13546. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13547. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13548. }
  13549. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13550. // crash the server (it used to call front() on an empty vector inside
  13551. // get_client_ip). The connection-level remote address must be retained instead.
  13552. static void run_malformed_xff_test(const std::string &xff_value) {
  13553. Server svr;
  13554. svr.set_trusted_proxies({"192.0.2.45"});
  13555. std::string observed_remote_addr;
  13556. svr.Get("/ip", [&](const Request &req, Response &res) {
  13557. observed_remote_addr = req.remote_addr;
  13558. res.set_content("ok", "text/plain");
  13559. });
  13560. int port = 0;
  13561. thread t = thread([&]() {
  13562. port = svr.bind_to_any_port(HOST);
  13563. svr.listen_after_bind();
  13564. });
  13565. auto se = detail::scope_exit([&] {
  13566. svr.stop();
  13567. t.join();
  13568. ASSERT_FALSE(svr.is_running());
  13569. });
  13570. svr.wait_until_ready();
  13571. Client cli(HOST, port);
  13572. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13574. EXPECT_EQ(StatusCode::OK_200, res->status);
  13575. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13576. observed_remote_addr == "127.0.0.1");
  13577. }
  13578. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13579. run_malformed_xff_test("");
  13580. }
  13581. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13582. run_malformed_xff_test(",");
  13583. }
  13584. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13585. run_malformed_xff_test(", , ,");
  13586. }
  13587. #ifndef _WIN32
  13588. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13589. Server svr;
  13590. svr.Post("/post", [&](const Request &req, Response &res) {
  13591. res.set_content(req.body, "text/plain");
  13592. });
  13593. svr.Put("/put", [&](const Request &req, Response &res) {
  13594. res.set_content(req.body, "text/plain");
  13595. });
  13596. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13597. res.set_content(req.body, "text/plain");
  13598. });
  13599. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13600. res.set_content(req.body, "text/plain");
  13601. });
  13602. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13603. auto se = detail::scope_exit([&] {
  13604. svr.stop();
  13605. t.join();
  13606. ASSERT_FALSE(svr.is_running());
  13607. });
  13608. svr.wait_until_ready();
  13609. std::string resp;
  13610. // POST without Content-Length
  13611. ASSERT_TRUE(send_request(5,
  13612. "POST /post HTTP/1.1\r\n"
  13613. "Host: localhost\r\n"
  13614. "Connection: close\r\n"
  13615. "\r\n",
  13616. &resp));
  13617. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13618. // PUT without Content-Length
  13619. resp.clear();
  13620. ASSERT_TRUE(send_request(5,
  13621. "PUT /put HTTP/1.1\r\n"
  13622. "Host: localhost\r\n"
  13623. "Connection: close\r\n"
  13624. "\r\n",
  13625. &resp));
  13626. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13627. // PATCH without Content-Length
  13628. resp.clear();
  13629. ASSERT_TRUE(send_request(5,
  13630. "PATCH /patch HTTP/1.1\r\n"
  13631. "Host: localhost\r\n"
  13632. "Connection: close\r\n"
  13633. "\r\n",
  13634. &resp));
  13635. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13636. // DELETE without Content-Length
  13637. resp.clear();
  13638. ASSERT_TRUE(send_request(5,
  13639. "DELETE /delete HTTP/1.1\r\n"
  13640. "Host: localhost\r\n"
  13641. "Connection: close\r\n"
  13642. "\r\n",
  13643. &resp));
  13644. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13645. }
  13646. #endif
  13647. //==============================================================================
  13648. // open_stream() Tests
  13649. //==============================================================================
  13650. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13651. std::string result;
  13652. char buf[8192];
  13653. ssize_t n;
  13654. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13655. result.append(buf, static_cast<size_t>(n));
  13656. }
  13657. return result;
  13658. }
  13659. // Mock stream for unit tests
  13660. class MockStream : public Stream {
  13661. public:
  13662. std::string data;
  13663. size_t pos = 0;
  13664. ssize_t error_after = -1; // -1 = no error
  13665. explicit MockStream(const std::string &d, ssize_t err = -1)
  13666. : data(d), error_after(err) {}
  13667. bool is_readable() const override { return true; }
  13668. bool wait_readable() const override { return true; }
  13669. bool wait_writable() const override { return true; }
  13670. ssize_t read(char *ptr, size_t size) override {
  13671. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13672. if (pos >= data.size()) return 0;
  13673. size_t limit =
  13674. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13675. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13676. std::memcpy(ptr, data.data() + pos, to_read);
  13677. pos += to_read;
  13678. return static_cast<ssize_t>(to_read);
  13679. }
  13680. ssize_t write(const char *, size_t) override { return -1; }
  13681. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13682. ip = "127.0.0.1";
  13683. port = 0;
  13684. }
  13685. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13686. ip = "127.0.0.1";
  13687. port = 0;
  13688. }
  13689. socket_t socket() const override { return INVALID_SOCKET; }
  13690. time_t duration() const override { return 0; }
  13691. };
  13692. TEST(StreamHandleTest, Basic) {
  13693. ClientImpl::StreamHandle handle;
  13694. EXPECT_FALSE(handle.is_valid());
  13695. handle.response = detail::make_unique<Response>();
  13696. handle.error = Error::Connection;
  13697. EXPECT_FALSE(handle.is_valid());
  13698. handle.error = Error::Success;
  13699. EXPECT_TRUE(handle.is_valid());
  13700. }
  13701. TEST(BodyReaderTest, Basic) {
  13702. MockStream stream("Hello, World!");
  13703. detail::BodyReader reader;
  13704. reader.stream = &stream;
  13705. reader.content_length = 13;
  13706. char buf[32];
  13707. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13708. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13709. EXPECT_TRUE(reader.eof);
  13710. }
  13711. TEST(BodyReaderTest, NoStream) {
  13712. detail::BodyReader reader;
  13713. char buf[32];
  13714. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13715. EXPECT_EQ(Error::Connection, reader.last_error);
  13716. }
  13717. TEST(BodyReaderTest, Error) {
  13718. MockStream stream("Hello, World!", 5);
  13719. detail::BodyReader reader;
  13720. reader.stream = &stream;
  13721. reader.content_length = 13;
  13722. char buf[32];
  13723. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13724. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13725. EXPECT_EQ(Error::Read, reader.last_error);
  13726. }
  13727. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13728. // Mock-based StreamHandle tests relying on private internals are removed.
  13729. class OpenStreamTest : public ::testing::Test {
  13730. protected:
  13731. void SetUp() override {
  13732. svr_.Get("/hello", [](const Request &, Response &res) {
  13733. res.set_content("Hello World!", "text/plain");
  13734. });
  13735. svr_.Get("/large", [](const Request &, Response &res) {
  13736. res.set_content(std::string(10000, 'X'), "text/plain");
  13737. });
  13738. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  13739. res.set_content("Hello World!", "image/jpeg");
  13740. res.set_header("Content-Encoding", "UTF-8");
  13741. });
  13742. svr_.Get("/chunked", [](const Request &, Response &res) {
  13743. res.set_chunked_content_provider("text/plain",
  13744. [](size_t offset, DataSink &sink) {
  13745. if (offset < 15) {
  13746. sink.write("chunk", 5);
  13747. return true;
  13748. }
  13749. sink.done();
  13750. return true;
  13751. });
  13752. });
  13753. svr_.Get("/compressible", [](const Request &, Response &res) {
  13754. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13755. DataSink &sink) {
  13756. if (offset < 100 * 1024) {
  13757. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13758. sink.write(chunk.data(), chunk.size());
  13759. return true;
  13760. }
  13761. sink.done();
  13762. return true;
  13763. });
  13764. });
  13765. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13766. [](const Request & /*req*/, Response &res) {
  13767. auto i = new int(0);
  13768. res.set_header("Trailer", "Content-Length, X-Allowed");
  13769. res.set_chunked_content_provider(
  13770. "text/plain",
  13771. [i](size_t /*offset*/, DataSink &sink) {
  13772. switch (*i) {
  13773. case 0: sink.os << "123"; break;
  13774. case 1: sink.os << "456"; break;
  13775. case 2: sink.os << "789"; break;
  13776. case 3: {
  13777. sink.done_with_trailer(
  13778. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13779. } break;
  13780. }
  13781. (*i)++;
  13782. return true;
  13783. },
  13784. [i](bool success) {
  13785. EXPECT_TRUE(success);
  13786. delete i;
  13787. });
  13788. });
  13789. // Echo headers endpoint for header-related tests
  13790. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13791. std::string body;
  13792. for (const auto &h : req.headers) {
  13793. body.append(h.first);
  13794. body.push_back(':');
  13795. body.append(h.second);
  13796. body.push_back('\n');
  13797. }
  13798. res.set_content(body, "text/plain");
  13799. });
  13800. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13801. std::string body;
  13802. for (const auto &h : req.headers) {
  13803. body.append(h.first);
  13804. body.push_back(':');
  13805. body.append(h.second);
  13806. body.push_back('\n');
  13807. }
  13808. res.set_content(body, "text/plain");
  13809. });
  13810. port_ = svr_.bind_to_any_port("127.0.0.1");
  13811. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13812. svr_.wait_until_ready();
  13813. }
  13814. void TearDown() override {
  13815. svr_.stop();
  13816. if (thread_.joinable()) thread_.join();
  13817. }
  13818. Server svr_;
  13819. std::thread thread_;
  13820. int port_ = 0;
  13821. };
  13822. TEST_F(OpenStreamTest, Basic) {
  13823. Client cli("127.0.0.1", port_);
  13824. auto handle = cli.open_stream("GET", "/hello");
  13825. EXPECT_TRUE(handle.is_valid());
  13826. EXPECT_EQ("Hello World!", read_all(handle));
  13827. }
  13828. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  13829. Client cli("127.0.0.1", port_);
  13830. auto handle = cli.open_stream("GET", "/unknown-encoding");
  13831. ASSERT_TRUE(handle.is_valid());
  13832. EXPECT_EQ("Hello World!", read_all(handle));
  13833. }
  13834. TEST_F(OpenStreamTest, SmallBuffer) {
  13835. Client cli("127.0.0.1", port_);
  13836. auto handle = cli.open_stream("GET", "/hello");
  13837. std::string result;
  13838. char buf[4];
  13839. ssize_t n;
  13840. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13841. result.append(buf, static_cast<size_t>(n));
  13842. EXPECT_EQ("Hello World!", result);
  13843. }
  13844. TEST_F(OpenStreamTest, DefaultHeaders) {
  13845. Client cli("127.0.0.1", port_);
  13846. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13847. {
  13848. auto handle = cli.open_stream("GET", "/echo-headers");
  13849. ASSERT_TRUE(handle.is_valid());
  13850. auto body = read_all(handle);
  13851. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13852. std::string::npos);
  13853. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13854. std::string::npos);
  13855. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13856. }
  13857. // open_stream POST with body and no explicit content_type should NOT add
  13858. // text/plain Content-Type (behavior differs from non-streaming path), but
  13859. // should include Content-Length
  13860. {
  13861. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13862. ASSERT_TRUE(handle.is_valid());
  13863. auto body = read_all(handle);
  13864. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13865. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13866. }
  13867. // open_stream POST with explicit Content-Type should preserve it
  13868. {
  13869. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13870. {{"Content-Type", "application/custom"}},
  13871. "{}", "application/custom");
  13872. ASSERT_TRUE(handle.is_valid());
  13873. auto body = read_all(handle);
  13874. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13875. }
  13876. // User-specified User-Agent must not be overwritten for stream API
  13877. {
  13878. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13879. {{"User-Agent", "MyAgent/1.2"}});
  13880. ASSERT_TRUE(handle.is_valid());
  13881. auto body = read_all(handle);
  13882. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13883. }
  13884. }
  13885. TEST_F(OpenStreamTest, Large) {
  13886. Client cli("127.0.0.1", port_);
  13887. auto handle = cli.open_stream("GET", "/large");
  13888. EXPECT_EQ(10000u, read_all(handle).size());
  13889. }
  13890. TEST_F(OpenStreamTest, ConnectionError) {
  13891. Client cli("127.0.0.1", 9999);
  13892. auto handle = cli.open_stream("GET", "/hello");
  13893. EXPECT_FALSE(handle.is_valid());
  13894. }
  13895. TEST_F(OpenStreamTest, Chunked) {
  13896. Client cli("127.0.0.1", port_);
  13897. auto handle = cli.open_stream("GET", "/chunked");
  13898. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13899. "Transfer-Encoding") == "chunked");
  13900. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13901. }
  13902. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13903. Client cli("127.0.0.1", port_);
  13904. auto handle =
  13905. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13906. ASSERT_TRUE(handle.is_valid());
  13907. // Consume body to allow trailers to be received/parsed
  13908. auto body = read_all(handle);
  13909. // Explicitly parse trailers (ensure trailers are available for assertion)
  13910. handle.parse_trailers_if_needed();
  13911. EXPECT_EQ(std::string("123456789"), body);
  13912. // The response should include a Trailer header declaring both names
  13913. ASSERT_TRUE(handle.response);
  13914. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13915. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13916. handle.response->get_header_value("Trailer"));
  13917. // Prohibited trailer must not be present
  13918. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13919. // Allowed trailer should be present
  13920. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13921. EXPECT_EQ(std::string("yes"),
  13922. handle.response->get_trailer_value("X-Allowed"));
  13923. // Verify trailers are NOT present as regular headers
  13924. EXPECT_EQ(std::string(""),
  13925. handle.response->get_header_value("Content-Length"));
  13926. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13927. }
  13928. static std::thread serve_single_response(std::promise<int> &port_promise,
  13929. const std::string &response) {
  13930. return std::thread([&port_promise, response] {
  13931. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13932. default_socket_options(srv);
  13933. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13934. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13935. sockaddr_in addr{};
  13936. addr.sin_family = AF_INET;
  13937. addr.sin_port = htons(0); // Let OS assign a free port
  13938. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13939. int opt = 1;
  13940. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13941. #ifdef _WIN32
  13942. reinterpret_cast<const char *>(&opt),
  13943. #else
  13944. &opt,
  13945. #endif
  13946. sizeof(opt));
  13947. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13948. ::listen(srv, 1) != 0) {
  13949. port_promise.set_value(-1);
  13950. detail::close_socket(srv);
  13951. return;
  13952. }
  13953. socklen_t addr_len = sizeof(addr);
  13954. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13955. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13956. sockaddr_in cli_addr{};
  13957. socklen_t cli_len = sizeof(cli_addr);
  13958. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13959. if (cli != INVALID_SOCKET) {
  13960. // Read the complete HTTP request (until the blank line that terminates
  13961. // headers) before sending the response. If the server closes the socket
  13962. // while the client's request data is still unread in the kernel receive
  13963. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13964. // connection on both sides: it discards the client's receive buffer
  13965. // (which already holds our response) and causes any in-progress write on
  13966. // the client to fail with ECONNRESET. Reading all request data first
  13967. // ensures close() emits a graceful FIN.
  13968. {
  13969. char rbuf[256];
  13970. std::string req;
  13971. while (req.find("\r\n\r\n") == std::string::npos) {
  13972. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13973. if (n <= 0) { break; }
  13974. req.append(rbuf, static_cast<size_t>(n));
  13975. }
  13976. }
  13977. ::send(cli,
  13978. #ifdef _WIN32
  13979. static_cast<const char *>(response.c_str()),
  13980. static_cast<int>(response.size()),
  13981. #else
  13982. response.c_str(), response.size(),
  13983. #endif
  13984. 0);
  13985. detail::close_socket(cli);
  13986. }
  13987. detail::close_socket(srv);
  13988. });
  13989. }
  13990. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13991. #ifndef _WIN32
  13992. signal(SIGPIPE, SIG_IGN);
  13993. #endif
  13994. std::promise<int> port_promise;
  13995. auto port_future = port_promise.get_future();
  13996. auto server_thread =
  13997. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13998. "Content-Type: text/plain\r\n"
  13999. "Content-Length: not-a-number\r\n"
  14000. "Connection: close\r\n"
  14001. "\r\n"
  14002. "hello");
  14003. auto port = port_future.get();
  14004. ASSERT_GT(port, 0);
  14005. Client cli("127.0.0.1", port);
  14006. auto handle = cli.open_stream("GET", "/");
  14007. EXPECT_FALSE(handle.is_valid());
  14008. server_thread.join();
  14009. }
  14010. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14011. #ifndef _WIN32
  14012. signal(SIGPIPE, SIG_IGN);
  14013. #endif
  14014. std::promise<int> port_promise;
  14015. auto port_future = port_promise.get_future();
  14016. auto server_thread = serve_single_response(
  14017. port_promise, "HTTP/1.1 200 OK\r\n"
  14018. "Content-Type: text/plain\r\n"
  14019. "Content-Length: 99999999999999999999999999\r\n"
  14020. "Connection: close\r\n"
  14021. "\r\n"
  14022. "hello");
  14023. auto port = port_future.get();
  14024. ASSERT_GT(port, 0);
  14025. // Historically std::stoull would throw std::out_of_range here and crash
  14026. // the process, then parsing silently clamped to a bogus framing length and
  14027. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14028. // so the stream fails to open, matching the not-a-number case above. The
  14029. // process still must NOT terminate.
  14030. Client cli("127.0.0.1", port);
  14031. auto handle = cli.open_stream("GET", "/");
  14032. EXPECT_FALSE(handle.is_valid());
  14033. server_thread.join();
  14034. }
  14035. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14036. TEST_F(OpenStreamTest, Gzip) {
  14037. Client cli("127.0.0.1", port_);
  14038. auto handle = cli.open_stream("GET", "/compressible", {},
  14039. {{"Accept-Encoding", "gzip"}});
  14040. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14041. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14042. }
  14043. #endif
  14044. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14045. TEST_F(OpenStreamTest, Brotli) {
  14046. Client cli("127.0.0.1", port_);
  14047. auto handle =
  14048. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14049. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14050. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14051. }
  14052. #endif
  14053. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14054. TEST_F(OpenStreamTest, Zstd) {
  14055. Client cli("127.0.0.1", port_);
  14056. auto handle = cli.open_stream("GET", "/compressible", {},
  14057. {{"Accept-Encoding", "zstd"}});
  14058. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14059. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14060. }
  14061. #endif
  14062. #ifdef CPPHTTPLIB_SSL_ENABLED
  14063. class SSLOpenStreamTest : public ::testing::Test {
  14064. protected:
  14065. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14066. void SetUp() override {
  14067. svr_.Get("/hello", [](const Request &, Response &res) {
  14068. res.set_content("Hello SSL World!", "text/plain");
  14069. });
  14070. svr_.Get("/chunked", [](const Request &, Response &res) {
  14071. res.set_chunked_content_provider("text/plain",
  14072. [](size_t offset, DataSink &sink) {
  14073. if (offset < 15) {
  14074. sink.write("chunk", 5);
  14075. return true;
  14076. }
  14077. sink.done();
  14078. return true;
  14079. });
  14080. });
  14081. svr_.Post("/echo", [](const Request &req, Response &res) {
  14082. res.set_content(req.body, req.get_header_value("Content-Type"));
  14083. });
  14084. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14085. std::string body = req.body;
  14086. res.set_chunked_content_provider(
  14087. "text/plain", [body](size_t offset, DataSink &sink) {
  14088. if (offset < body.size()) {
  14089. sink.write(body.data() + offset, body.size() - offset);
  14090. }
  14091. sink.done();
  14092. return true;
  14093. });
  14094. });
  14095. port_ = svr_.bind_to_any_port("127.0.0.1");
  14096. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14097. svr_.wait_until_ready();
  14098. }
  14099. void TearDown() override {
  14100. svr_.stop();
  14101. if (thread_.joinable()) thread_.join();
  14102. }
  14103. SSLServer svr_;
  14104. std::thread thread_;
  14105. int port_ = 0;
  14106. };
  14107. TEST_F(SSLOpenStreamTest, Basic) {
  14108. SSLClient cli("127.0.0.1", port_);
  14109. cli.enable_server_certificate_verification(false);
  14110. auto handle = cli.open_stream("GET", "/hello");
  14111. ASSERT_TRUE(handle.is_valid());
  14112. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14113. }
  14114. TEST_F(SSLOpenStreamTest, Chunked) {
  14115. SSLClient cli("127.0.0.1", port_);
  14116. cli.enable_server_certificate_verification(false);
  14117. auto handle = cli.open_stream("GET", "/chunked");
  14118. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14119. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14120. "Transfer-Encoding") == "chunked");
  14121. auto body = read_all(handle);
  14122. EXPECT_EQ("chunkchunkchunk", body);
  14123. }
  14124. TEST_F(SSLOpenStreamTest, Post) {
  14125. SSLClient cli("127.0.0.1", port_);
  14126. cli.enable_server_certificate_verification(false);
  14127. auto handle =
  14128. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14129. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14130. EXPECT_EQ(200, handle.response->status);
  14131. auto body = read_all(handle);
  14132. EXPECT_EQ("Hello SSL POST", body);
  14133. }
  14134. TEST_F(SSLOpenStreamTest, PostChunked) {
  14135. SSLClient cli("127.0.0.1", port_);
  14136. cli.enable_server_certificate_verification(false);
  14137. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14138. "Chunked SSL Data", "text/plain");
  14139. ASSERT_TRUE(handle.is_valid());
  14140. EXPECT_EQ(200, handle.response->status);
  14141. auto body = read_all(handle);
  14142. EXPECT_EQ("Chunked SSL Data", body);
  14143. }
  14144. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14145. // Content-Length is terminated by the server closing the connection. When the
  14146. // SSL peer sends a close_notify after the body, the client must treat it as a
  14147. // clean EOF and return a successful response rather than an error.
  14148. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14150. ASSERT_TRUE(svr.is_valid());
  14151. svr.set_keep_alive_max_count(1);
  14152. const std::string expected_body = "Hello from connection-close response!";
  14153. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14154. res.set_content_provider("text/plain",
  14155. [&](size_t offset, DataSink &sink) -> bool {
  14156. if (offset < expected_body.size()) {
  14157. sink.write(expected_body.data() + offset,
  14158. expected_body.size() - offset);
  14159. }
  14160. sink.done();
  14161. return true;
  14162. });
  14163. });
  14164. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14165. auto se = detail::scope_exit([&] {
  14166. svr.stop();
  14167. listen_thread.join();
  14168. ASSERT_FALSE(svr.is_running());
  14169. });
  14170. svr.wait_until_ready();
  14171. SSLClient cli(HOST, PORT);
  14172. cli.enable_server_certificate_verification(false);
  14173. auto res = cli.Get("/no-content-length");
  14174. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14175. EXPECT_EQ(StatusCode::OK_200, res->status);
  14176. EXPECT_EQ(expected_body, res->body);
  14177. }
  14178. #endif // CPPHTTPLIB_SSL_ENABLED
  14179. //==============================================================================
  14180. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14181. // results for various scenarios.
  14182. //==============================================================================
  14183. TEST(ParityTest, GetVsOpenStream) {
  14184. Server svr;
  14185. const std::string path = "/parity";
  14186. const std::string content = "Parity test content: hello world";
  14187. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14188. res.set_content(content, "text/plain");
  14189. });
  14190. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14191. auto se = detail::scope_exit([&] {
  14192. svr.stop();
  14193. t.join();
  14194. ASSERT_FALSE(svr.is_running());
  14195. });
  14196. svr.wait_until_ready();
  14197. Client cli(HOST, PORT);
  14198. // Non-stream path
  14199. auto r1 = cli.Get(path);
  14200. ASSERT_TRUE(r1);
  14201. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14202. // Stream path
  14203. auto h = cli.open_stream("GET", path);
  14204. ASSERT_TRUE(h.is_valid());
  14205. EXPECT_EQ(r1->body, read_all(h));
  14206. }
  14207. // Helper to compress data with provided compressor type T
  14208. template <typename Compressor>
  14209. static std::string compress_payload_for_parity(const std::string &in) {
  14210. std::string out;
  14211. Compressor compressor;
  14212. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14213. [&](const char *data, size_t n) {
  14214. out.append(data, n);
  14215. return true;
  14216. });
  14217. EXPECT_TRUE(ok);
  14218. return out;
  14219. }
  14220. // Helper function for compression parity tests
  14221. template <typename Compressor>
  14222. static void test_compression_parity(const std::string &original,
  14223. const std::string &path,
  14224. const std::string &encoding) {
  14225. const std::string compressed =
  14226. compress_payload_for_parity<Compressor>(original);
  14227. Server svr;
  14228. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14229. res.set_content(compressed, "application/octet-stream");
  14230. res.set_header("Content-Encoding", encoding);
  14231. });
  14232. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14233. auto se = detail::scope_exit([&] {
  14234. svr.stop();
  14235. t.join();
  14236. ASSERT_FALSE(svr.is_running());
  14237. });
  14238. svr.wait_until_ready();
  14239. Client cli(HOST, PORT);
  14240. // Non-streaming
  14241. {
  14242. auto res = cli.Get(path);
  14243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14244. EXPECT_EQ(StatusCode::OK_200, res->status);
  14245. EXPECT_EQ(original, res->body);
  14246. }
  14247. // Streaming
  14248. {
  14249. auto h = cli.open_stream("GET", path);
  14250. ASSERT_TRUE(h.is_valid());
  14251. EXPECT_EQ(original, read_all(h));
  14252. }
  14253. }
  14254. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14255. TEST(ParityTest, Gzip) {
  14256. test_compression_parity<detail::gzip_compressor>(
  14257. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14258. }
  14259. #endif
  14260. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14261. TEST(ParityTest, Brotli) {
  14262. test_compression_parity<detail::brotli_compressor>(
  14263. "Hello, brotli parity test payload", "/parity-br", "br");
  14264. }
  14265. #endif
  14266. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14267. TEST(ParityTest, Zstd) {
  14268. test_compression_parity<detail::zstd_compressor>(
  14269. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14270. }
  14271. #endif
  14272. //==============================================================================
  14273. // New Stream API Tests
  14274. //==============================================================================
  14275. inline std::string read_body(httplib::stream::Result &result) {
  14276. std::string body;
  14277. while (result.next()) {
  14278. body.append(result.data(), result.size());
  14279. }
  14280. return body;
  14281. }
  14282. TEST(ClientConnectionTest, Basic) {
  14283. httplib::ClientConnection conn;
  14284. EXPECT_FALSE(conn.is_open());
  14285. conn.sock = 1;
  14286. EXPECT_TRUE(conn.is_open());
  14287. httplib::ClientConnection conn2(std::move(conn));
  14288. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14289. conn2.sock = INVALID_SOCKET;
  14290. }
  14291. // Unified test server for all stream::* tests
  14292. class StreamApiTest : public ::testing::Test {
  14293. protected:
  14294. void SetUp() override {
  14295. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14296. res.set_content("Hello World!", "text/plain");
  14297. });
  14298. svr_.Get("/echo-params",
  14299. [](const httplib::Request &req, httplib::Response &res) {
  14300. std::string r;
  14301. for (const auto &p : req.params) {
  14302. if (!r.empty()) r += "&";
  14303. r += p.first + "=" + p.second;
  14304. }
  14305. res.set_content(r, "text/plain");
  14306. });
  14307. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14308. res.set_content(req.body, req.get_header_value("Content-Type"));
  14309. });
  14310. svr_.Post("/echo-headers",
  14311. [](const httplib::Request &req, httplib::Response &res) {
  14312. std::string r;
  14313. for (const auto &h : req.headers)
  14314. r += h.first + ": " + h.second + "\n";
  14315. res.set_content(r, "text/plain");
  14316. });
  14317. svr_.Post("/echo-params",
  14318. [](const httplib::Request &req, httplib::Response &res) {
  14319. std::string r = "params:";
  14320. for (const auto &p : req.params)
  14321. r += p.first + "=" + p.second + ";";
  14322. res.set_content(r + " body:" + req.body, "text/plain");
  14323. });
  14324. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14325. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14326. });
  14327. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14328. res.set_content("PUT:" + req.body, "text/plain");
  14329. });
  14330. svr_.Patch("/echo",
  14331. [](const httplib::Request &req, httplib::Response &res) {
  14332. res.set_content("PATCH:" + req.body, "text/plain");
  14333. });
  14334. svr_.Delete(
  14335. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14336. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14337. "text/plain");
  14338. });
  14339. svr_.Get("/head-test",
  14340. [](const httplib::Request &, httplib::Response &res) {
  14341. res.set_content("body for HEAD", "text/plain");
  14342. });
  14343. svr_.Options("/options",
  14344. [](const httplib::Request &, httplib::Response &res) {
  14345. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14346. });
  14347. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14348. svr_.wait_until_ready();
  14349. }
  14350. void TearDown() override {
  14351. svr_.stop();
  14352. if (thread_.joinable()) thread_.join();
  14353. }
  14354. httplib::Server svr_;
  14355. std::thread thread_;
  14356. };
  14357. // stream::Get tests
  14358. TEST_F(StreamApiTest, GetBasic) {
  14359. httplib::Client cli(HOST, PORT);
  14360. auto result = httplib::stream::Get(cli, "/hello");
  14361. ASSERT_TRUE(result.is_valid());
  14362. EXPECT_EQ(200, result.status());
  14363. EXPECT_EQ("Hello World!", read_body(result));
  14364. }
  14365. TEST_F(StreamApiTest, GetWithParams) {
  14366. httplib::Client cli(HOST, PORT);
  14367. httplib::Params params{{"foo", "bar"}};
  14368. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14369. ASSERT_TRUE(result.is_valid());
  14370. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14371. }
  14372. TEST_F(StreamApiTest, GetConnectionError) {
  14373. httplib::Client cli(HOST, 9999);
  14374. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14375. }
  14376. TEST_F(StreamApiTest, Get404) {
  14377. httplib::Client cli(HOST, PORT);
  14378. auto result = httplib::stream::Get(cli, "/nonexistent");
  14379. EXPECT_TRUE(result.is_valid());
  14380. EXPECT_EQ(404, result.status());
  14381. }
  14382. // stream::Post tests
  14383. TEST_F(StreamApiTest, PostBasic) {
  14384. httplib::Client cli(HOST, PORT);
  14385. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14386. "application/json");
  14387. ASSERT_TRUE(result.is_valid());
  14388. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14389. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14390. }
  14391. TEST_F(StreamApiTest, PostWithHeaders) {
  14392. httplib::Client cli(HOST, PORT);
  14393. httplib::Headers headers{{"X-Custom", "value"}};
  14394. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14395. "text/plain");
  14396. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14397. }
  14398. TEST_F(StreamApiTest, PostWithParams) {
  14399. httplib::Client cli(HOST, PORT);
  14400. httplib::Params params{{"k", "v"}};
  14401. auto result =
  14402. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14403. auto body = read_body(result);
  14404. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14405. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14406. }
  14407. TEST_F(StreamApiTest, PostLarge) {
  14408. httplib::Client cli(HOST, PORT);
  14409. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14410. size_t total = 0;
  14411. while (result.next()) {
  14412. total += result.size();
  14413. }
  14414. EXPECT_EQ(100u * 1024u, total);
  14415. }
  14416. // stream::Put/Patch tests
  14417. TEST_F(StreamApiTest, PutAndPatch) {
  14418. httplib::Client cli(HOST, PORT);
  14419. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14420. EXPECT_EQ("PUT:test", read_body(put));
  14421. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14422. EXPECT_EQ("PATCH:test", read_body(patch));
  14423. }
  14424. // stream::Delete tests
  14425. TEST_F(StreamApiTest, Delete) {
  14426. httplib::Client cli(HOST, PORT);
  14427. auto del1 = httplib::stream::Delete(cli, "/resource");
  14428. EXPECT_EQ("Deleted", read_body(del1));
  14429. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14430. EXPECT_EQ("Deleted:data", read_body(del2));
  14431. }
  14432. // stream::Head/Options tests
  14433. TEST_F(StreamApiTest, HeadAndOptions) {
  14434. httplib::Client cli(HOST, PORT);
  14435. auto head = httplib::stream::Head(cli, "/head-test");
  14436. EXPECT_TRUE(head.is_valid());
  14437. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14438. auto opts = httplib::stream::Options(cli, "/options");
  14439. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14440. }
  14441. // SSL stream::* tests
  14442. #ifdef CPPHTTPLIB_SSL_ENABLED
  14443. class SSLStreamApiTest : public ::testing::Test {
  14444. protected:
  14445. void SetUp() override {
  14446. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14447. res.set_content("Hello SSL!", "text/plain");
  14448. });
  14449. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14450. res.set_content(req.body, "text/plain");
  14451. });
  14452. port_ = svr_.bind_to_any_port("127.0.0.1");
  14453. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14454. svr_.wait_until_ready();
  14455. }
  14456. void TearDown() override {
  14457. svr_.stop();
  14458. if (thread_.joinable()) thread_.join();
  14459. }
  14460. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14461. std::thread thread_;
  14462. int port_ = 0;
  14463. };
  14464. TEST_F(SSLStreamApiTest, GetAndPost) {
  14465. httplib::SSLClient cli("127.0.0.1", port_);
  14466. cli.enable_server_certificate_verification(false);
  14467. auto get = httplib::stream::Get(cli, "/hello");
  14468. EXPECT_EQ("Hello SSL!", read_body(get));
  14469. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14470. EXPECT_EQ("test", read_body(post));
  14471. }
  14472. #endif
  14473. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14474. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14475. // BodyReader
  14476. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14477. // Test that read timeout during streaming is detected
  14478. // Use a large content-length response where server delays mid-stream
  14479. Server svr;
  14480. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14481. // Send a large response with delay in the middle
  14482. res.set_content_provider(
  14483. 1000, // content_length
  14484. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14485. if (offset < 100) {
  14486. // Send first 100 bytes immediately
  14487. std::string data(100, 'A');
  14488. sink.write(data.c_str(), data.size());
  14489. return true;
  14490. }
  14491. // Then delay longer than client timeout
  14492. std::this_thread::sleep_for(std::chrono::seconds(3));
  14493. std::string data(900, 'B');
  14494. sink.write(data.c_str(), data.size());
  14495. return true;
  14496. });
  14497. });
  14498. auto port = 8091;
  14499. std::thread t([&]() { svr.listen("localhost", port); });
  14500. svr.wait_until_ready();
  14501. Client cli("localhost", port);
  14502. cli.set_read_timeout(1, 0); // 1 second timeout
  14503. auto handle = cli.open_stream("GET", "/slow-stream");
  14504. ASSERT_TRUE(handle.is_valid());
  14505. char buf[256];
  14506. ssize_t total = 0;
  14507. ssize_t n;
  14508. bool got_error = false;
  14509. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14510. total += n;
  14511. }
  14512. if (n < 0) {
  14513. got_error = true;
  14514. // Should be timeout or read error
  14515. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14516. handle.get_read_error() == Error::Read)
  14517. << "Actual error: " << to_string(handle.get_read_error());
  14518. }
  14519. // Either we got an error, or we got less data than expected
  14520. EXPECT_TRUE(got_error || total < 1000)
  14521. << "Expected timeout but got all " << total << " bytes";
  14522. svr.stop();
  14523. t.join();
  14524. }
  14525. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14526. // Test connection closed detection via BodyReader
  14527. Server svr;
  14528. std::atomic<bool> close_now{false};
  14529. svr.Get("/will-close", [&](const Request &, Response &res) {
  14530. res.set_content_provider(
  14531. 10000, // Large content_length that we won't fully send
  14532. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14533. if (offset < 100) {
  14534. std::string data(100, 'X');
  14535. sink.write(data.c_str(), data.size());
  14536. return true;
  14537. }
  14538. // Wait for signal then abort
  14539. while (!close_now) {
  14540. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14541. }
  14542. return false; // Abort - server will close connection
  14543. });
  14544. });
  14545. auto port = 8092;
  14546. std::thread t([&]() { svr.listen("localhost", port); });
  14547. svr.wait_until_ready();
  14548. Client cli("localhost", port);
  14549. auto handle = cli.open_stream("GET", "/will-close");
  14550. ASSERT_TRUE(handle.is_valid());
  14551. char buf[256];
  14552. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14553. EXPECT_GT(n, 0) << "First read should succeed";
  14554. // Signal server to close
  14555. close_now = true;
  14556. // Keep reading until error or EOF
  14557. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14558. // Keep reading
  14559. }
  14560. // Should get an error since content_length wasn't satisfied
  14561. if (n < 0) {
  14562. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14563. handle.get_read_error() == Error::Read)
  14564. << "Actual error: " << to_string(handle.get_read_error());
  14565. }
  14566. svr.stop();
  14567. t.join();
  14568. }
  14569. #ifdef CPPHTTPLIB_SSL_ENABLED
  14570. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14571. // Test that read timeout during SSL streaming is detected
  14572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14573. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14574. res.set_content_provider(
  14575. 1000, "text/plain",
  14576. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14577. if (offset < 100) {
  14578. std::string data(100, 'A');
  14579. sink.write(data.c_str(), data.size());
  14580. return true;
  14581. }
  14582. std::this_thread::sleep_for(std::chrono::seconds(3));
  14583. std::string data(900, 'B');
  14584. sink.write(data.c_str(), data.size());
  14585. return true;
  14586. });
  14587. });
  14588. auto port = 8093;
  14589. std::thread t([&]() { svr.listen("localhost", port); });
  14590. svr.wait_until_ready();
  14591. SSLClient cli("localhost", port);
  14592. cli.enable_server_certificate_verification(false);
  14593. cli.set_read_timeout(1, 0); // 1 second timeout
  14594. auto handle = cli.open_stream("GET", "/slow-stream");
  14595. ASSERT_TRUE(handle.is_valid());
  14596. char buf[256];
  14597. ssize_t total = 0;
  14598. ssize_t n;
  14599. bool got_error = false;
  14600. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14601. total += n;
  14602. }
  14603. if (n < 0) {
  14604. got_error = true;
  14605. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14606. handle.get_read_error() == Error::Read)
  14607. << "Actual error: " << to_string(handle.get_read_error());
  14608. }
  14609. EXPECT_TRUE(got_error || total < 1000)
  14610. << "Expected timeout but got all " << total << " bytes";
  14611. svr.stop();
  14612. t.join();
  14613. }
  14614. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14615. // Test SSL connection closed detection
  14616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14617. std::atomic<bool> close_now{false};
  14618. svr.Get("/will-close", [&](const Request &, Response &res) {
  14619. res.set_content_provider(
  14620. 10000, "text/plain",
  14621. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14622. if (offset < 100) {
  14623. std::string data(100, 'X');
  14624. sink.write(data.c_str(), data.size());
  14625. return true;
  14626. }
  14627. while (!close_now) {
  14628. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14629. }
  14630. return false;
  14631. });
  14632. });
  14633. auto port = 8094;
  14634. std::thread t([&]() { svr.listen("localhost", port); });
  14635. svr.wait_until_ready();
  14636. SSLClient cli("localhost", port);
  14637. cli.enable_server_certificate_verification(false);
  14638. auto handle = cli.open_stream("GET", "/will-close");
  14639. ASSERT_TRUE(handle.is_valid());
  14640. char buf[256];
  14641. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14642. EXPECT_GT(n, 0);
  14643. // Signal server to close
  14644. close_now = true;
  14645. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14646. // Keep reading
  14647. }
  14648. if (n < 0) {
  14649. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14650. handle.get_read_error() == Error::Read)
  14651. << "Actual error: " << to_string(handle.get_read_error());
  14652. }
  14653. svr.stop();
  14654. t.join();
  14655. }
  14656. #endif
  14657. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14658. using namespace httplib;
  14659. // Create a test file
  14660. const char *fname = "etag_testfile.txt";
  14661. const char *content = "etag-content";
  14662. {
  14663. std::ofstream ofs(fname);
  14664. ofs << content;
  14665. ASSERT_TRUE(ofs.good());
  14666. }
  14667. Server svr;
  14668. svr.set_mount_point("/static", ".");
  14669. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14670. svr.wait_until_ready();
  14671. Client cli(HOST, PORT);
  14672. // First request: should get 200 with ETag header
  14673. auto res1 = cli.Get("/static/etag_testfile.txt");
  14674. ASSERT_TRUE(res1);
  14675. ASSERT_EQ(200, res1->status);
  14676. ASSERT_TRUE(res1->has_header("ETag"));
  14677. std::string etag = res1->get_header_value("ETag");
  14678. EXPECT_FALSE(etag.empty());
  14679. // Verify ETag format: W/"hex-hex"
  14680. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14681. EXPECT_EQ('W', etag[0]);
  14682. EXPECT_EQ('/', etag[1]);
  14683. EXPECT_EQ('"', etag[2]);
  14684. EXPECT_EQ('"', etag.back());
  14685. // Exact match: expect 304 Not Modified
  14686. Headers h2 = {{"If-None-Match", etag}};
  14687. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14688. ASSERT_TRUE(res2);
  14689. EXPECT_EQ(304, res2->status);
  14690. // Wildcard match: expect 304 Not Modified
  14691. Headers h3 = {{"If-None-Match", "*"}};
  14692. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14693. ASSERT_TRUE(res3);
  14694. EXPECT_EQ(304, res3->status);
  14695. // Non-matching ETag: expect 200
  14696. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14697. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14698. ASSERT_TRUE(res4);
  14699. EXPECT_EQ(200, res4->status);
  14700. // Multiple ETags with one matching: expect 304
  14701. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14702. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14703. ASSERT_TRUE(res5);
  14704. EXPECT_EQ(304, res5->status);
  14705. svr.stop();
  14706. t.join();
  14707. std::remove(fname);
  14708. }
  14709. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14710. using namespace httplib;
  14711. Server svr;
  14712. svr.set_mount_point("/static", ".");
  14713. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14714. svr.wait_until_ready();
  14715. Client cli(HOST, PORT);
  14716. // Send If-None-Match: * to a non-existent file
  14717. Headers h = {{"If-None-Match", "*"}};
  14718. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14720. EXPECT_EQ(404, res->status);
  14721. svr.stop();
  14722. t.join();
  14723. }
  14724. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14725. using namespace httplib;
  14726. // Create a test file
  14727. const char *fname = "etag_boundary_testfile.txt";
  14728. const char *content = "boundary-test";
  14729. {
  14730. std::ofstream ofs(fname);
  14731. ofs << content;
  14732. ASSERT_TRUE(ofs.good());
  14733. }
  14734. Server svr;
  14735. svr.set_mount_point("/static", ".");
  14736. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14737. svr.wait_until_ready();
  14738. Client cli(HOST, PORT);
  14739. // Get the actual ETag
  14740. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14741. ASSERT_TRUE(res1);
  14742. ASSERT_EQ(200, res1->status);
  14743. ASSERT_TRUE(res1->has_header("ETag"));
  14744. std::string etag = res1->get_header_value("ETag");
  14745. // Test 1: Very long ETag value (longer than actual ETag)
  14746. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14747. Headers h1 = {{"If-None-Match", "W/"
  14748. "\"very-long-etag-value-that-is-much-longer-"
  14749. "than-the-actual-etag-value\""}};
  14750. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14751. ASSERT_TRUE(res2);
  14752. EXPECT_EQ(200, res2->status); // Should not match
  14753. // Test 2: Long string followed by wildcard
  14754. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14755. // string)
  14756. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14757. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14758. ASSERT_TRUE(res3);
  14759. EXPECT_EQ(304, res3->status); // Should match on "*"
  14760. // Test 3: Wildcard followed by long string
  14761. // Should match on "*" immediately and return 304
  14762. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14763. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14764. ASSERT_TRUE(res4);
  14765. EXPECT_EQ(304, res4->status); // Should match on "*"
  14766. // Test 4: Multiple long non-matching values
  14767. // Should NOT match and return 200 (test that all comparisons are safe)
  14768. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14769. "W/\"second-long-non-matching-value\", "
  14770. "W/\"third-long-non-matching-value\""}};
  14771. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14772. ASSERT_TRUE(res5);
  14773. EXPECT_EQ(200, res5->status); // Should not match
  14774. // Test 5: Single character that is not "*" (edge case)
  14775. Headers h5 = {{"If-None-Match", "X"}};
  14776. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14777. ASSERT_TRUE(res6);
  14778. EXPECT_EQ(200, res6->status); // Should not match
  14779. svr.stop();
  14780. t.join();
  14781. std::remove(fname);
  14782. }
  14783. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14784. using namespace httplib;
  14785. // Create a test file
  14786. const char *fname = "ims_testfile.txt";
  14787. const char *content = "if-modified-since-test";
  14788. {
  14789. std::ofstream ofs(fname);
  14790. ofs << content;
  14791. ASSERT_TRUE(ofs.good());
  14792. }
  14793. Server svr;
  14794. svr.set_mount_point("/static", ".");
  14795. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14796. svr.wait_until_ready();
  14797. Client cli(HOST, PORT);
  14798. // First request: should get 200 with Last-Modified header
  14799. auto res1 = cli.Get("/static/ims_testfile.txt");
  14800. ASSERT_TRUE(res1);
  14801. ASSERT_EQ(200, res1->status);
  14802. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14803. std::string last_modified = res1->get_header_value("Last-Modified");
  14804. EXPECT_FALSE(last_modified.empty());
  14805. // If-Modified-Since with same time: expect 304
  14806. Headers h2 = {{"If-Modified-Since", last_modified}};
  14807. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14808. ASSERT_TRUE(res2);
  14809. EXPECT_EQ(304, res2->status);
  14810. // If-Modified-Since with future time: expect 304
  14811. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14812. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14813. ASSERT_TRUE(res3);
  14814. EXPECT_EQ(304, res3->status);
  14815. // If-Modified-Since with past time: expect 200
  14816. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14817. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14818. ASSERT_TRUE(res4);
  14819. EXPECT_EQ(200, res4->status);
  14820. // If-None-Match takes precedence over If-Modified-Since
  14821. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14822. ASSERT_TRUE(res1->has_header("ETag"));
  14823. std::string etag = res1->get_header_value("ETag");
  14824. Headers h5 = {{"If-None-Match", etag},
  14825. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14826. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14827. ASSERT_TRUE(res5);
  14828. EXPECT_EQ(304, res5->status);
  14829. svr.stop();
  14830. t.join();
  14831. std::remove(fname);
  14832. }
  14833. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14834. using namespace httplib;
  14835. Server svr;
  14836. // Endpoint that returns compressible content
  14837. svr.Get("/compressible", [](const Request &, Response &res) {
  14838. // Return a large enough body to trigger compression
  14839. std::string body(1000, 'a');
  14840. res.set_content(body, "text/plain");
  14841. });
  14842. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14843. svr.wait_until_ready();
  14844. Client cli(HOST, PORT);
  14845. // Request with gzip support: should get Vary header when compressed
  14846. cli.set_compress(true);
  14847. auto res1 = cli.Get("/compressible");
  14848. ASSERT_TRUE(res1);
  14849. EXPECT_EQ(200, res1->status);
  14850. // If Content-Encoding is set, Vary should also be set
  14851. if (res1->has_header("Content-Encoding")) {
  14852. EXPECT_TRUE(res1->has_header("Vary"));
  14853. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14854. }
  14855. // Request without Accept-Encoding header: should not have compression
  14856. Headers h_no_compress;
  14857. auto res2 = cli.Get("/compressible", h_no_compress);
  14858. ASSERT_TRUE(res2);
  14859. EXPECT_EQ(200, res2->status);
  14860. // Verify Vary header is present when compression is applied
  14861. // (the exact behavior depends on server configuration)
  14862. svr.stop();
  14863. t.join();
  14864. }
  14865. TEST(ETagTest, IfRangeWithETag) {
  14866. using namespace httplib;
  14867. // Create a test file with known content
  14868. const char *fname = "if_range_testfile.txt";
  14869. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14870. {
  14871. std::ofstream ofs(fname);
  14872. ofs << content;
  14873. ASSERT_TRUE(ofs.good());
  14874. }
  14875. Server svr;
  14876. svr.set_mount_point("/static", ".");
  14877. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14878. svr.wait_until_ready();
  14879. Client cli(HOST, PORT);
  14880. // First request: get ETag
  14881. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14882. ASSERT_TRUE(res1);
  14883. ASSERT_EQ(200, res1->status);
  14884. ASSERT_TRUE(res1->has_header("ETag"));
  14885. std::string etag = res1->get_header_value("ETag");
  14886. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14887. // Since our server generates weak ETags (W/"..."), If-Range with our
  14888. // ETag should NOT result in partial content - it should return full content.
  14889. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14890. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14891. ASSERT_TRUE(res2);
  14892. // Weak ETag in If-Range -> full content (200), not partial (206)
  14893. EXPECT_EQ(200, res2->status);
  14894. EXPECT_EQ(content, res2->body);
  14895. EXPECT_FALSE(res2->has_header("Content-Range"));
  14896. // Range request with non-matching If-Range (ETag): should get 200 (full
  14897. // content)
  14898. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14899. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14900. ASSERT_TRUE(res3);
  14901. EXPECT_EQ(200, res3->status);
  14902. EXPECT_EQ(content, res3->body);
  14903. EXPECT_FALSE(res3->has_header("Content-Range"));
  14904. // Range request with strong ETag (hypothetical - our server doesn't generate
  14905. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14906. // should return full content)
  14907. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14908. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14909. ASSERT_TRUE(res4);
  14910. EXPECT_EQ(200, res4->status);
  14911. EXPECT_EQ(content, res4->body);
  14912. EXPECT_FALSE(res4->has_header("Content-Range"));
  14913. svr.stop();
  14914. t.join();
  14915. std::remove(fname);
  14916. }
  14917. TEST(ETagTest, IfRangeWithDate) {
  14918. using namespace httplib;
  14919. // Create a test file
  14920. const char *fname = "if_range_date_testfile.txt";
  14921. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14922. {
  14923. std::ofstream ofs(fname);
  14924. ofs << content;
  14925. ASSERT_TRUE(ofs.good());
  14926. }
  14927. Server svr;
  14928. svr.set_mount_point("/static", ".");
  14929. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14930. svr.wait_until_ready();
  14931. Client cli(HOST, PORT);
  14932. // First request: get Last-Modified
  14933. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14934. ASSERT_TRUE(res1);
  14935. ASSERT_EQ(200, res1->status);
  14936. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14937. std::string last_modified = res1->get_header_value("Last-Modified");
  14938. // Range request with matching If-Range (date): should get 206
  14939. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14940. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14941. ASSERT_TRUE(res2);
  14942. EXPECT_EQ(206, res2->status);
  14943. EXPECT_EQ("FGHIJ", res2->body);
  14944. // Range request with old If-Range date: should get 200 (full content)
  14945. Headers h3 = {{"Range", "bytes=5-9"},
  14946. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14947. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14948. ASSERT_TRUE(res3);
  14949. EXPECT_EQ(200, res3->status);
  14950. EXPECT_EQ(content, res3->body);
  14951. // Range request with future If-Range date: should get 206
  14952. Headers h4 = {{"Range", "bytes=0-4"},
  14953. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14954. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14955. ASSERT_TRUE(res4);
  14956. EXPECT_EQ(206, res4->status);
  14957. EXPECT_EQ("ABCDE", res4->body);
  14958. svr.stop();
  14959. t.join();
  14960. std::remove(fname);
  14961. }
  14962. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14963. using namespace httplib;
  14964. const char *fname = "etag_malformed.txt";
  14965. const char *content = "malformed-etag";
  14966. {
  14967. std::ofstream ofs(fname);
  14968. ofs << content;
  14969. ASSERT_TRUE(ofs.good());
  14970. }
  14971. Server svr;
  14972. svr.set_mount_point("/static", ".");
  14973. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14974. svr.wait_until_ready();
  14975. Client cli(HOST, PORT);
  14976. // baseline: should get 200 and an ETag
  14977. auto res1 = cli.Get("/static/etag_malformed.txt");
  14978. ASSERT_TRUE(res1);
  14979. ASSERT_EQ(200, res1->status);
  14980. ASSERT_TRUE(res1->has_header("ETag"));
  14981. // Malformed ETag value (missing quotes) should be treated as non-matching
  14982. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14983. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14984. ASSERT_TRUE(res_bad);
  14985. EXPECT_EQ(200, res_bad->status);
  14986. // Whitespace-only header value should be considered invalid / non-matching
  14987. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14988. "Host: localhost\r\n"
  14989. "If-None-Match: \r\n"
  14990. "Connection: close\r\n"
  14991. "\r\n";
  14992. std::string out;
  14993. ASSERT_TRUE(send_request(5, raw_req, &out));
  14994. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14995. svr.stop();
  14996. t.join();
  14997. std::remove(fname);
  14998. }
  14999. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  15000. using namespace httplib;
  15001. const char *fname = "ims_invalid_format.txt";
  15002. const char *content = "ims-bad-format";
  15003. {
  15004. std::ofstream ofs(fname);
  15005. ofs << content;
  15006. ASSERT_TRUE(ofs.good());
  15007. }
  15008. Server svr;
  15009. svr.set_mount_point("/static", ".");
  15010. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15011. svr.wait_until_ready();
  15012. Client cli(HOST, PORT);
  15013. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15014. ASSERT_TRUE(res1);
  15015. ASSERT_EQ(200, res1->status);
  15016. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15017. // If-Modified-Since with invalid format should not result in 304
  15018. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15019. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15020. ASSERT_TRUE(res_bad);
  15021. EXPECT_EQ(200, res_bad->status);
  15022. // If-Range with invalid date format should be treated as mismatch -> full
  15023. // content (200)
  15024. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15025. {"If-Range", "invalid-date"}};
  15026. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15027. ASSERT_TRUE(res_ifrange);
  15028. EXPECT_EQ(200, res_ifrange->status);
  15029. svr.stop();
  15030. t.join();
  15031. std::remove(fname);
  15032. }
  15033. TEST(ETagTest, IfRangeWithMalformedETag) {
  15034. using namespace httplib;
  15035. const char *fname = "ifrange_malformed.txt";
  15036. const std::string content = "0123456789";
  15037. {
  15038. std::ofstream ofs(fname);
  15039. ofs << content;
  15040. ASSERT_TRUE(ofs.good());
  15041. }
  15042. Server svr;
  15043. svr.set_mount_point("/static", ".");
  15044. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15045. svr.wait_until_ready();
  15046. Client cli(HOST, PORT);
  15047. // First request: get ETag
  15048. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15049. ASSERT_TRUE(res1);
  15050. ASSERT_EQ(200, res1->status);
  15051. ASSERT_TRUE(res1->has_header("ETag"));
  15052. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15053. // full content (200)
  15054. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15055. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15056. ASSERT_TRUE(res2);
  15057. EXPECT_EQ(200, res2->status);
  15058. EXPECT_EQ(content, res2->body);
  15059. svr.stop();
  15060. t.join();
  15061. std::remove(fname);
  15062. }
  15063. TEST(ETagTest, ExtremeLargeDateValues) {
  15064. using namespace httplib;
  15065. const char *fname = "ims_extreme_date.txt";
  15066. const char *content = "ims-extreme-date";
  15067. {
  15068. std::ofstream ofs(fname);
  15069. ofs << content;
  15070. ASSERT_TRUE(ofs.good());
  15071. }
  15072. Server svr;
  15073. svr.set_mount_point("/static", ".");
  15074. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15075. svr.wait_until_ready();
  15076. Client cli(HOST, PORT);
  15077. auto res1 = cli.Get(std::string("/static/") + fname);
  15078. ASSERT_TRUE(res1);
  15079. ASSERT_EQ(200, res1->status);
  15080. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15081. // Extremely large year that may overflow date parsing routines.
  15082. Headers h_large_date = {
  15083. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15084. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15085. ASSERT_TRUE(res_bad);
  15086. // Expect server to treat this as invalid/mismatch and return full content
  15087. EXPECT_EQ(200, res_bad->status);
  15088. // If-Range with extremely large date should be treated as mismatch -> full
  15089. // content (200)
  15090. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15091. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15092. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15093. ASSERT_TRUE(res_ifrange);
  15094. EXPECT_EQ(200, res_ifrange->status);
  15095. svr.stop();
  15096. t.join();
  15097. std::remove(fname);
  15098. }
  15099. TEST(ETagTest, NegativeFileModificationTime) {
  15100. using namespace httplib;
  15101. const char *fname = "ims_negative_mtime.txt";
  15102. const std::string content = "negative-mtime";
  15103. {
  15104. std::ofstream ofs(fname);
  15105. ofs << content;
  15106. ASSERT_TRUE(ofs.good());
  15107. }
  15108. // Try to set file mtime to a negative value. This may fail on some
  15109. // platforms/filesystems; if it fails, the test will still verify server
  15110. // behaves safely by performing a regular conditional request.
  15111. #if defined(__APPLE__) || defined(__linux__)
  15112. bool set_negative = false;
  15113. do {
  15114. struct timeval times[2];
  15115. // access time: now
  15116. times[0].tv_sec = time(nullptr);
  15117. times[0].tv_usec = 0;
  15118. // modification time: negative (e.g., -1)
  15119. times[1].tv_sec = -1;
  15120. times[1].tv_usec = 0;
  15121. if (utimes(fname, times) == 0) { set_negative = true; }
  15122. } while (0);
  15123. #else
  15124. bool set_negative = false;
  15125. #endif
  15126. Server svr;
  15127. svr.set_mount_point("/static", ".");
  15128. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15129. svr.wait_until_ready();
  15130. Client cli(HOST, PORT);
  15131. auto res1 = cli.Get(std::string("/static/") + fname);
  15132. ASSERT_TRUE(res1);
  15133. ASSERT_EQ(200, res1->status);
  15134. bool has_last_modified = res1->has_header("Last-Modified");
  15135. std::string last_modified;
  15136. if (has_last_modified) {
  15137. last_modified = res1->get_header_value("Last-Modified");
  15138. }
  15139. if (set_negative) {
  15140. // If we successfully set a negative mtime, ensure server returns a
  15141. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15142. // with an old date and ensure server handles it without crash.
  15143. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15144. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15145. ASSERT_TRUE(res2);
  15146. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15147. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15148. } else {
  15149. // Could not set negative mtime on this platform; fall back to verifying
  15150. // that normal invalid/malformed dates are treated safely (non-304).
  15151. Headers h_bad_date = {
  15152. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15153. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15154. ASSERT_TRUE(res_bad);
  15155. EXPECT_EQ(200, res_bad->status);
  15156. }
  15157. svr.stop();
  15158. t.join();
  15159. std::remove(fname);
  15160. }
  15161. //==============================================================================
  15162. // SSE Parsing Tests
  15163. //==============================================================================
  15164. class SSEParsingTest : public ::testing::Test {
  15165. protected:
  15166. // Test helper that mimics SSE parsing behavior
  15167. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15168. int &retry_ms) {
  15169. // Blank line signals end of event
  15170. if (line.empty() || line == "\r") { return true; }
  15171. // Lines starting with ':' are comments (ignored)
  15172. if (!line.empty() && line[0] == ':') { return false; }
  15173. // Find the colon separator
  15174. auto colon_pos = line.find(':');
  15175. if (colon_pos == std::string::npos) {
  15176. // Line with no colon is treated as field name with empty value
  15177. return false;
  15178. }
  15179. std::string field = line.substr(0, colon_pos);
  15180. std::string value;
  15181. // Value starts after colon, skip optional single space
  15182. if (colon_pos + 1 < line.size()) {
  15183. size_t value_start = colon_pos + 1;
  15184. if (line[value_start] == ' ') { value_start++; }
  15185. value = line.substr(value_start);
  15186. // Remove trailing \r if present
  15187. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15188. }
  15189. // Handle known fields
  15190. if (field == "event") {
  15191. msg.event = value;
  15192. } else if (field == "data") {
  15193. // Multiple data lines are concatenated with newlines
  15194. if (!msg.data.empty()) { msg.data += "\n"; }
  15195. msg.data += value;
  15196. } else if (field == "id") {
  15197. // Empty id is valid (clears the last event ID)
  15198. msg.id = value;
  15199. } else if (field == "retry") {
  15200. // Parse retry interval in milliseconds
  15201. {
  15202. int v = 0;
  15203. auto res =
  15204. detail::from_chars(value.data(), value.data() + value.size(), v);
  15205. if (res.ec == std::errc{}) { retry_ms = v; }
  15206. }
  15207. }
  15208. // Unknown fields are ignored per SSE spec
  15209. return false;
  15210. }
  15211. };
  15212. // Test: Single-line data
  15213. TEST_F(SSEParsingTest, SingleLineData) {
  15214. sse::SSEMessage msg;
  15215. int retry_ms = 3000;
  15216. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15217. EXPECT_EQ(msg.data, "hello");
  15218. EXPECT_EQ(msg.event, "message");
  15219. // Blank line ends event
  15220. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15221. }
  15222. // Test: Multi-line data
  15223. TEST_F(SSEParsingTest, MultiLineData) {
  15224. sse::SSEMessage msg;
  15225. int retry_ms = 3000;
  15226. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15227. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15228. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15229. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15230. }
  15231. // Test: Custom event types
  15232. TEST_F(SSEParsingTest, CustomEventType) {
  15233. sse::SSEMessage msg;
  15234. int retry_ms = 3000;
  15235. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15236. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15237. EXPECT_EQ(msg.event, "update");
  15238. EXPECT_EQ(msg.data, "payload");
  15239. }
  15240. // Test: Event ID handling
  15241. TEST_F(SSEParsingTest, EventIdHandling) {
  15242. sse::SSEMessage msg;
  15243. int retry_ms = 3000;
  15244. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15245. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15246. EXPECT_EQ(msg.id, "12345");
  15247. }
  15248. // Test: Empty event ID (clears last event ID)
  15249. TEST_F(SSEParsingTest, EmptyEventId) {
  15250. sse::SSEMessage msg;
  15251. msg.id = "previous";
  15252. int retry_ms = 3000;
  15253. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15254. EXPECT_EQ(msg.id, "");
  15255. }
  15256. // Test: Retry field parsing
  15257. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15258. sse::SSEMessage msg;
  15259. int retry_ms = 3000;
  15260. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15261. EXPECT_EQ(retry_ms, 5000);
  15262. }
  15263. // Test: Invalid retry value
  15264. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15265. sse::SSEMessage msg;
  15266. int retry_ms = 3000;
  15267. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15268. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15269. }
  15270. // Test: Comments (lines starting with :)
  15271. TEST_F(SSEParsingTest, CommentsIgnored) {
  15272. sse::SSEMessage msg;
  15273. int retry_ms = 3000;
  15274. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15275. EXPECT_EQ(msg.data, "");
  15276. EXPECT_EQ(msg.event, "message");
  15277. }
  15278. // Test: Colon in value
  15279. TEST_F(SSEParsingTest, ColonInValue) {
  15280. sse::SSEMessage msg;
  15281. int retry_ms = 3000;
  15282. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15283. EXPECT_EQ(msg.data, "hello:world:test");
  15284. }
  15285. // Test: Line with no colon (field name only)
  15286. TEST_F(SSEParsingTest, FieldNameOnly) {
  15287. sse::SSEMessage msg;
  15288. int retry_ms = 3000;
  15289. // According to SSE spec, this is treated as field name with empty value
  15290. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15291. // Since we don't recognize "data" without colon, data should be empty
  15292. EXPECT_EQ(msg.data, "");
  15293. }
  15294. // Test: Trailing \r handling
  15295. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15296. sse::SSEMessage msg;
  15297. int retry_ms = 3000;
  15298. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15299. EXPECT_EQ(msg.data, "hello");
  15300. }
  15301. // Test: Unknown fields ignored
  15302. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15303. sse::SSEMessage msg;
  15304. int retry_ms = 3000;
  15305. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15306. EXPECT_EQ(msg.data, "");
  15307. EXPECT_EQ(msg.event, "message");
  15308. }
  15309. // Test: Space after colon is optional
  15310. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15311. sse::SSEMessage msg1, msg2;
  15312. int retry_ms = 3000;
  15313. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15314. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15315. EXPECT_EQ(msg1.data, "hello");
  15316. EXPECT_EQ(msg2.data, "hello");
  15317. }
  15318. // Test: SSEMessage clear
  15319. TEST_F(SSEParsingTest, MessageClear) {
  15320. sse::SSEMessage msg;
  15321. msg.event = "custom";
  15322. msg.data = "some data";
  15323. msg.id = "123";
  15324. msg.clear();
  15325. EXPECT_EQ(msg.event, "message");
  15326. EXPECT_EQ(msg.data, "");
  15327. EXPECT_EQ(msg.id, "");
  15328. }
  15329. // Test: Complete event parsing
  15330. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15331. sse::SSEMessage msg;
  15332. int retry_ms = 3000;
  15333. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15334. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15335. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15336. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15337. // Blank line ends event
  15338. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15339. EXPECT_EQ(msg.event, "notification");
  15340. EXPECT_EQ(msg.id, "evt-42");
  15341. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15342. EXPECT_EQ(retry_ms, 1000);
  15343. }
  15344. //==============================================================================
  15345. // Integration Tests with Server
  15346. //==============================================================================
  15347. class SSEIntegrationTest : public ::testing::Test {
  15348. protected:
  15349. void SetUp() override {
  15350. stop_server_.store(false);
  15351. events_.clear();
  15352. server_ = httplib::detail::make_unique<Server>();
  15353. setup_server();
  15354. start_server();
  15355. }
  15356. void TearDown() override {
  15357. stop_server_.store(true);
  15358. event_cv_.notify_all();
  15359. server_->stop();
  15360. if (server_thread_.joinable()) { server_thread_.join(); }
  15361. }
  15362. void setup_server() {
  15363. // Simple SSE endpoint
  15364. server_->Get("/events", [this](const Request &req, Response &res) {
  15365. auto last_id = req.get_header_value("Last-Event-ID");
  15366. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15367. res.set_chunked_content_provider(
  15368. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15369. std::unique_lock<std::mutex> lock(event_mutex_);
  15370. if (event_cv_.wait_for(
  15371. lock, std::chrono::milliseconds(200), [this] {
  15372. return !events_.empty() || stop_server_.load();
  15373. })) {
  15374. if (stop_server_.load()) { return false; }
  15375. if (!events_.empty()) {
  15376. std::string event = events_.front();
  15377. events_.erase(events_.begin());
  15378. sink.write(event.data(), event.size());
  15379. return true;
  15380. }
  15381. }
  15382. return !stop_server_.load();
  15383. });
  15384. });
  15385. // Endpoint that returns error
  15386. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15387. res.status = 500;
  15388. res.set_content("Internal Server Error", "text/plain");
  15389. });
  15390. // Endpoint for custom event types
  15391. server_->Get("/custom-events", [](const Request &, Response &res) {
  15392. res.set_chunked_content_provider(
  15393. "text/event-stream", [](size_t offset, DataSink &sink) {
  15394. if (offset == 0) {
  15395. std::string event = "event: update\ndata: updated\n\n"
  15396. "event: delete\ndata: deleted\n\n";
  15397. sink.write(event.data(), event.size());
  15398. }
  15399. return false; // End stream after sending
  15400. });
  15401. });
  15402. }
  15403. void start_server() {
  15404. port_ = server_->bind_to_any_port(HOST);
  15405. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15406. // Wait for server to start
  15407. while (!server_->is_running()) {
  15408. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15409. }
  15410. }
  15411. int get_port() const { return port_; }
  15412. void send_event(const std::string &event) {
  15413. std::lock_guard<std::mutex> lock(event_mutex_);
  15414. events_.push_back(event);
  15415. event_cv_.notify_all();
  15416. }
  15417. std::unique_ptr<Server> server_;
  15418. std::thread server_thread_;
  15419. std::mutex event_mutex_;
  15420. std::condition_variable event_cv_;
  15421. std::vector<std::string> events_;
  15422. std::atomic<bool> stop_server_{false};
  15423. std::string last_received_event_id_;
  15424. int port_ = 0;
  15425. };
  15426. // Test: Successful connection and on_open callback
  15427. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15428. // Add a simple endpoint that sends one event and closes
  15429. server_->Get("/simple-event", [](const Request &, Response &res) {
  15430. res.set_chunked_content_provider(
  15431. "text/event-stream", [](size_t offset, DataSink &sink) {
  15432. if (offset == 0) {
  15433. std::string event = "data: hello\n\n";
  15434. sink.write(event.data(), event.size());
  15435. }
  15436. return false; // Close stream after sending
  15437. });
  15438. });
  15439. Client client("localhost", get_port());
  15440. sse::SSEClient sse(client, "/simple-event");
  15441. std::atomic<bool> open_called{false};
  15442. std::atomic<bool> message_received{false};
  15443. sse.on_open([&open_called]() { open_called.store(true); });
  15444. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15445. if (msg.data == "hello") { message_received.store(true); }
  15446. });
  15447. sse.set_reconnect_interval(100);
  15448. sse.set_max_reconnect_attempts(1);
  15449. // Start async
  15450. sse.start_async();
  15451. // Wait for message to be processed
  15452. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15453. sse.stop();
  15454. EXPECT_TRUE(open_called.load());
  15455. EXPECT_TRUE(message_received.load());
  15456. }
  15457. // Test: on_message callback
  15458. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15459. // Endpoint that sends multiple events then closes
  15460. server_->Get("/multi-event", [](const Request &, Response &res) {
  15461. res.set_chunked_content_provider(
  15462. "text/event-stream", [](size_t offset, DataSink &sink) {
  15463. if (offset == 0) {
  15464. std::string events = "data: message1\n\ndata: message2\n\n";
  15465. sink.write(events.data(), events.size());
  15466. }
  15467. return false;
  15468. });
  15469. });
  15470. Client client("localhost", get_port());
  15471. sse::SSEClient sse(client, "/multi-event");
  15472. std::vector<std::string> received_messages;
  15473. std::mutex messages_mutex;
  15474. sse.on_message([&](const sse::SSEMessage &msg) {
  15475. std::lock_guard<std::mutex> lock(messages_mutex);
  15476. received_messages.push_back(msg.data);
  15477. });
  15478. sse.set_reconnect_interval(100);
  15479. sse.set_max_reconnect_attempts(1);
  15480. sse.start_async();
  15481. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15482. sse.stop();
  15483. std::lock_guard<std::mutex> lock(messages_mutex);
  15484. EXPECT_GE(received_messages.size(), 2u);
  15485. if (received_messages.size() >= 2) {
  15486. EXPECT_EQ(received_messages[0], "message1");
  15487. EXPECT_EQ(received_messages[1], "message2");
  15488. }
  15489. }
  15490. // Test: on_event for specific types
  15491. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15492. Client client("localhost", get_port());
  15493. sse::SSEClient sse(client, "/custom-events");
  15494. std::atomic<bool> update_received{false};
  15495. std::atomic<bool> delete_received{false};
  15496. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15497. if (msg.data == "updated") { update_received.store(true); }
  15498. });
  15499. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15500. if (msg.data == "deleted") { delete_received.store(true); }
  15501. });
  15502. sse.set_max_reconnect_attempts(1);
  15503. sse.start_async();
  15504. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15505. sse.stop();
  15506. EXPECT_TRUE(update_received.load());
  15507. EXPECT_TRUE(delete_received.load());
  15508. }
  15509. // Test: on_error callback on connection failure
  15510. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15511. // Connect to a non-existent port
  15512. Client client("localhost", 59999);
  15513. sse::SSEClient sse(client, "/events");
  15514. std::atomic<bool> error_called{false};
  15515. Error received_error = Error::Success;
  15516. sse.on_error([&](Error err) {
  15517. error_called.store(true);
  15518. received_error = err;
  15519. });
  15520. sse.set_reconnect_interval(50);
  15521. sse.set_max_reconnect_attempts(1);
  15522. sse.start_async();
  15523. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15524. sse.stop();
  15525. EXPECT_TRUE(error_called.load());
  15526. EXPECT_NE(received_error, Error::Success);
  15527. }
  15528. // Test: Last-Event-ID header sent on reconnect
  15529. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15530. // Endpoint that sends event with ID
  15531. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15532. res.set_chunked_content_provider(
  15533. "text/event-stream", [](size_t offset, DataSink &sink) {
  15534. if (offset == 0) {
  15535. std::string event = "id: evt-123\ndata: test\n\n";
  15536. sink.write(event.data(), event.size());
  15537. }
  15538. return false;
  15539. });
  15540. });
  15541. Client client("localhost", get_port());
  15542. sse::SSEClient sse(client, "/event-with-id");
  15543. std::atomic<bool> id_received{false};
  15544. sse.on_message([&](const sse::SSEMessage &msg) {
  15545. if (!msg.id.empty()) { id_received.store(true); }
  15546. });
  15547. sse.set_reconnect_interval(100);
  15548. sse.set_max_reconnect_attempts(1);
  15549. sse.start_async();
  15550. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15551. sse.stop();
  15552. EXPECT_TRUE(id_received.load());
  15553. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15554. }
  15555. // Test: Manual stop
  15556. TEST_F(SSEIntegrationTest, ManualStop) {
  15557. // Endpoint that sends one event and stays open briefly
  15558. std::atomic<bool> handler_running{true};
  15559. server_->Get("/stay-open", [&handler_running](const Request &,
  15560. Response &res) {
  15561. res.set_chunked_content_provider(
  15562. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15563. if (offset == 0) {
  15564. std::string event = "data: connected\n\n";
  15565. sink.write(event.data(), event.size());
  15566. }
  15567. // Keep connection open while handler_running is true
  15568. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15569. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15570. }
  15571. return false;
  15572. });
  15573. });
  15574. Client client("localhost", get_port());
  15575. sse::SSEClient sse(client, "/stay-open");
  15576. std::atomic<bool> connected{false};
  15577. sse.on_open([&connected]() { connected.store(true); });
  15578. sse.set_reconnect_interval(100);
  15579. sse.set_max_reconnect_attempts(1);
  15580. sse.start_async();
  15581. // Wait for connection to establish
  15582. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15583. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15584. }
  15585. EXPECT_TRUE(connected.load());
  15586. EXPECT_TRUE(sse.is_connected());
  15587. // Signal handler to stop
  15588. handler_running.store(false);
  15589. // Stop SSE client
  15590. sse.stop();
  15591. EXPECT_FALSE(sse.is_connected());
  15592. }
  15593. // Test: SSEClient with custom headers
  15594. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15595. // Setup a server endpoint that checks for custom header
  15596. std::atomic<bool> header_received{false};
  15597. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15598. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15599. header_received.store(true);
  15600. }
  15601. res.set_chunked_content_provider("text/event-stream",
  15602. [](size_t, DataSink &) { return false; });
  15603. });
  15604. Client client("localhost", get_port());
  15605. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15606. sse::SSEClient sse(client, "/header-check", headers);
  15607. sse.set_max_reconnect_attempts(1);
  15608. sse.start_async();
  15609. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15610. sse.stop();
  15611. EXPECT_TRUE(header_received.load());
  15612. }
  15613. // Test: Reconnect interval configuration
  15614. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15615. Client client("localhost", get_port());
  15616. sse::SSEClient sse(client, "/events");
  15617. auto &result = sse.set_reconnect_interval(500);
  15618. // Builder pattern should return reference to self
  15619. EXPECT_EQ(&result, &sse);
  15620. }
  15621. // Test: Max reconnect attempts
  15622. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15623. // Connect to non-existent port to force reconnects
  15624. Client client("localhost", 59998);
  15625. sse::SSEClient sse(client, "/events");
  15626. std::atomic<int> error_count{0};
  15627. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15628. sse.set_reconnect_interval(50);
  15629. sse.set_max_reconnect_attempts(2);
  15630. auto start = std::chrono::steady_clock::now();
  15631. sse.start(); // Blocking call
  15632. auto end = std::chrono::steady_clock::now();
  15633. // Should have stopped after 2 failed attempts
  15634. EXPECT_GE(error_count.load(), 2);
  15635. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15636. auto duration =
  15637. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15638. #ifdef _WIN32
  15639. // Windows is much slower for socket connection failures
  15640. EXPECT_LT(duration.count(), 7000);
  15641. #else
  15642. EXPECT_LT(duration.count(), 1000);
  15643. #endif
  15644. }
  15645. // Test: Multi-line data in integration
  15646. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15647. // Endpoint with multi-line data
  15648. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15649. res.set_chunked_content_provider(
  15650. "text/event-stream", [](size_t offset, DataSink &sink) {
  15651. if (offset == 0) {
  15652. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15653. sink.write(event.data(), event.size());
  15654. }
  15655. return false;
  15656. });
  15657. });
  15658. Client client("localhost", get_port());
  15659. sse::SSEClient sse(client, "/multiline-data");
  15660. std::string received_data;
  15661. std::mutex data_mutex;
  15662. sse.on_message([&](const sse::SSEMessage &msg) {
  15663. std::lock_guard<std::mutex> lock(data_mutex);
  15664. received_data = msg.data;
  15665. });
  15666. sse.set_reconnect_interval(100);
  15667. sse.set_max_reconnect_attempts(1);
  15668. sse.start_async();
  15669. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15670. sse.stop();
  15671. std::lock_guard<std::mutex> lock(data_mutex);
  15672. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15673. }
  15674. // Test: Auto-reconnect after server disconnection
  15675. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15676. std::atomic<int> connection_count{0};
  15677. std::atomic<int> message_count{0};
  15678. // Endpoint that sends one event and closes, forcing reconnect
  15679. server_->Get("/reconnect-test",
  15680. [&connection_count](const Request &, Response &res) {
  15681. connection_count.fetch_add(1);
  15682. res.set_chunked_content_provider(
  15683. "text/event-stream", [](size_t offset, DataSink &sink) {
  15684. if (offset == 0) {
  15685. std::string event = "data: hello\n\n";
  15686. sink.write(event.data(), event.size());
  15687. }
  15688. return false; // Close connection after sending
  15689. });
  15690. });
  15691. Client client("localhost", get_port());
  15692. sse::SSEClient sse(client, "/reconnect-test");
  15693. sse.on_message([&message_count](const sse::SSEMessage &) {
  15694. message_count.fetch_add(1);
  15695. });
  15696. sse.set_reconnect_interval(100);
  15697. sse.set_max_reconnect_attempts(3);
  15698. sse.start_async();
  15699. // Wait long enough for multiple reconnects
  15700. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15701. sse.stop();
  15702. // Should have connected multiple times (initial + reconnects)
  15703. EXPECT_GE(connection_count.load(), 2);
  15704. // Should have received messages from multiple connections
  15705. EXPECT_GE(message_count.load(), 2);
  15706. }
  15707. // Test: Last-Event-ID sent on reconnect
  15708. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15709. std::atomic<int> connection_count{0};
  15710. std::vector<std::string> received_last_event_ids;
  15711. std::mutex id_mutex;
  15712. // Endpoint that checks Last-Event-ID header and sends event with ID
  15713. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15714. int conn = connection_count.fetch_add(1);
  15715. // Capture the Last-Event-ID header from each connection
  15716. {
  15717. std::lock_guard<std::mutex> lock(id_mutex);
  15718. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15719. }
  15720. res.set_chunked_content_provider(
  15721. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15722. if (offset == 0) {
  15723. std::string event =
  15724. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15725. sink.write(event.data(), event.size());
  15726. }
  15727. return false;
  15728. });
  15729. });
  15730. Client client("localhost", get_port());
  15731. sse::SSEClient sse(client, "/reconnect-with-id");
  15732. sse.set_reconnect_interval(100);
  15733. sse.set_max_reconnect_attempts(3);
  15734. sse.start_async();
  15735. // Wait for at least 2 connections
  15736. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15737. sse.stop();
  15738. // Verify behavior
  15739. std::lock_guard<std::mutex> lock(id_mutex);
  15740. EXPECT_GE(received_last_event_ids.size(), 2u);
  15741. // First connection should have no Last-Event-ID
  15742. if (!received_last_event_ids.empty()) {
  15743. EXPECT_EQ(received_last_event_ids[0], "");
  15744. }
  15745. // Second connection should have Last-Event-ID from first connection
  15746. if (received_last_event_ids.size() >= 2) {
  15747. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15748. }
  15749. }
  15750. // Test: set_headers updates headers used on reconnect
  15751. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15752. std::vector<std::string> received_tokens;
  15753. std::mutex token_mutex;
  15754. // Endpoint that captures Authorization header
  15755. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15756. {
  15757. std::lock_guard<std::mutex> lock(token_mutex);
  15758. received_tokens.push_back(req.get_header_value("Authorization"));
  15759. }
  15760. res.set_chunked_content_provider(
  15761. "text/event-stream", [](size_t offset, DataSink &sink) {
  15762. if (offset == 0) {
  15763. std::string event = "data: hello\n\n";
  15764. sink.write(event.data(), event.size());
  15765. }
  15766. return false; // Close connection to trigger reconnect
  15767. });
  15768. });
  15769. Client client("localhost", get_port());
  15770. Headers headers = {{"Authorization", "Bearer old-token"}};
  15771. sse::SSEClient sse(client, "/auth-check", headers);
  15772. // Update headers on each successful connection
  15773. sse.on_open(
  15774. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15775. sse.set_reconnect_interval(100);
  15776. sse.set_max_reconnect_attempts(3);
  15777. sse.start_async();
  15778. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15779. sse.stop();
  15780. std::lock_guard<std::mutex> lock(token_mutex);
  15781. ASSERT_GE(received_tokens.size(), 2u);
  15782. // First connection uses original header
  15783. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15784. // Second connection uses updated header from set_headers
  15785. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15786. }
  15787. // Test: 401 allows reconnection (so on_error can refresh headers)
  15788. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15789. std::atomic<int> connection_count{0};
  15790. // Endpoint: returns 401 on first attempt, 200 on second
  15791. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15792. int conn = connection_count.fetch_add(1);
  15793. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15794. res.status = StatusCode::Unauthorized_401;
  15795. res.set_content("Unauthorized", "text/plain");
  15796. return;
  15797. }
  15798. res.set_chunked_content_provider(
  15799. "text/event-stream", [](size_t offset, DataSink &sink) {
  15800. if (offset == 0) {
  15801. std::string event = "data: authenticated\n\n";
  15802. sink.write(event.data(), event.size());
  15803. }
  15804. return false;
  15805. });
  15806. });
  15807. Client client("localhost", get_port());
  15808. Headers headers = {{"Authorization", "Bearer expired"}};
  15809. sse::SSEClient sse(client, "/auth-retry", headers);
  15810. std::atomic<bool> message_received{false};
  15811. // Refresh token on error
  15812. sse.on_error(
  15813. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15814. sse.on_message([&](const sse::SSEMessage &msg) {
  15815. if (msg.data == "authenticated") { message_received.store(true); }
  15816. });
  15817. sse.set_reconnect_interval(100);
  15818. sse.set_max_reconnect_attempts(3);
  15819. sse.start_async();
  15820. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15821. sse.stop();
  15822. // Should have reconnected after 401 and succeeded with new token
  15823. EXPECT_GE(connection_count.load(), 2);
  15824. EXPECT_TRUE(message_received.load());
  15825. }
  15826. TEST(Issue2318Test, EmptyHostString) {
  15827. {
  15828. httplib::Client cli_empty("", PORT);
  15829. auto res = cli_empty.Get("/");
  15830. ASSERT_FALSE(res);
  15831. EXPECT_EQ(httplib::Error::Connection, res.error());
  15832. }
  15833. {
  15834. httplib::Client cli(" ", PORT);
  15835. auto res = cli.Get("/");
  15836. ASSERT_FALSE(res);
  15837. EXPECT_EQ(httplib::Error::Connection, res.error());
  15838. }
  15839. }
  15840. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15841. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15842. Server svr;
  15843. // Set a small payload limit (1KB)
  15844. svr.set_payload_max_length(1024);
  15845. svr.Post("/test", [&](const Request &req, Response &res) {
  15846. res.set_content("Body size: " + std::to_string(req.body.size()),
  15847. "text/plain");
  15848. });
  15849. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15850. auto se = detail::scope_exit([&] {
  15851. svr.stop();
  15852. listen_thread.join();
  15853. });
  15854. svr.wait_until_ready();
  15855. // Create data that compresses well but exceeds limit when decompressed
  15856. // 8KB of repeated null bytes compresses to a very small size
  15857. std::string original_data(8 * 1024, '\0');
  15858. // Compress the data using gzip
  15859. std::string compressed_data;
  15860. detail::gzip_compressor compressor;
  15861. compressor.compress(original_data.data(), original_data.size(), true,
  15862. [&](const char *data, size_t size) {
  15863. compressed_data.append(data, size);
  15864. return true;
  15865. });
  15866. // Verify compression worked (compressed should be much smaller)
  15867. ASSERT_LT(compressed_data.size(), original_data.size());
  15868. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15869. // Send compressed data with Content-Encoding: gzip
  15870. Client cli(HOST, PORT);
  15871. Headers headers = {{"Content-Encoding", "gzip"}};
  15872. auto res =
  15873. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15874. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15876. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15877. }
  15878. #endif
  15879. // ============================================================================
  15880. // OpenSSL-Specific Tests
  15881. // ============================================================================
  15882. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15883. X509 *readCertificate(const std::string &strFileName) {
  15884. std::ifstream inStream(strFileName);
  15885. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15886. std::istreambuf_iterator<char>());
  15887. if (strCertPEM.empty()) return (nullptr);
  15888. BIO *pbCert = BIO_new(BIO_s_mem());
  15889. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15890. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15891. BIO_free(pbCert);
  15892. return (pCert);
  15893. }
  15894. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15895. std::ifstream inStream(strFileName);
  15896. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15897. std::istreambuf_iterator<char>());
  15898. if (strPrivateKeyPEM.empty()) return (nullptr);
  15899. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15900. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15901. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15902. BIO_free(pbPrivKey);
  15903. return (pPrivateKey);
  15904. }
  15905. TEST(BindServerTest, UpdateCerts) {
  15906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15907. int port = svr.bind_to_any_port("0.0.0.0");
  15908. ASSERT_TRUE(svr.is_valid());
  15909. ASSERT_TRUE(port > 0);
  15910. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15911. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15912. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15913. ASSERT_TRUE(cert != nullptr);
  15914. ASSERT_TRUE(ca_cert != nullptr);
  15915. ASSERT_TRUE(key != nullptr);
  15916. X509_STORE *cert_store = X509_STORE_new();
  15917. X509_STORE_add_cert(cert_store, ca_cert);
  15918. // svr.update_certs(cert, key, cert_store); // deprecated
  15919. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15920. CLIENT_CA_CERT_FILE);
  15921. ASSERT_TRUE(svr.is_valid());
  15922. svr.stop();
  15923. X509_STORE_free(cert_store);
  15924. X509_free(cert);
  15925. X509_free(ca_cert);
  15926. EVP_PKEY_free(key);
  15927. }
  15928. // Test that update_certs() updates client CA list correctly
  15929. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15930. // Start with file-based constructor
  15931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15932. ASSERT_TRUE(svr.is_valid());
  15933. // Initially no client CA list should be set
  15934. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15935. ASSERT_TRUE(ssl_ctx != nullptr);
  15936. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15937. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15938. EXPECT_EQ(0, count_before);
  15939. // Now update with client CA (PEM string)
  15940. std::string cert_pem, key_pem, ca_pem;
  15941. read_file(SERVER_CERT_FILE, cert_pem);
  15942. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15943. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15944. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15945. ASSERT_TRUE(svr.is_valid());
  15946. // Now client CA list should be set
  15947. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15948. ASSERT_TRUE(ca_list_after != nullptr);
  15949. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15950. }
  15951. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15952. // Test that the file-path SSLServer constructor properly sets the client CA
  15953. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15955. ASSERT_TRUE(svr.is_valid());
  15956. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15957. ASSERT_TRUE(ssl_ctx != nullptr);
  15958. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15959. ASSERT_TRUE(ca_list != nullptr);
  15960. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15961. }
  15962. #endif
  15963. // ============================================================================
  15964. // MbedTLS-Specific Tests
  15965. // ============================================================================
  15966. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15967. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15968. using namespace httplib::tls;
  15969. // Track if callback was invoked
  15970. bool callback_invoked = false;
  15971. // The callback receives void* ctx which is actually MbedTlsContext*
  15972. // We can access the mbedtls_ssl_config via the context
  15973. auto setup_callback = [&callback_invoked](void *ctx) {
  15974. callback_invoked = true;
  15975. // Cast to MbedTlsContext* to access the ssl config
  15976. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15977. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15978. // Use static variables to hold certificate data (simplified for test)
  15979. static mbedtls_x509_crt own_cert;
  15980. static mbedtls_pk_context own_key;
  15981. static mbedtls_x509_crt ca_chain;
  15982. static bool initialized = false;
  15983. if (!initialized) {
  15984. mbedtls_x509_crt_init(&own_cert);
  15985. mbedtls_pk_init(&own_key);
  15986. mbedtls_x509_crt_init(&ca_chain);
  15987. // Load server certificate
  15988. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15989. return false;
  15990. }
  15991. // Load server private key.
  15992. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15993. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15994. #if MBEDTLS_VERSION_MAJOR == 3
  15995. ,
  15996. mbedtls_ctr_drbg_random, nullptr
  15997. #endif
  15998. ) != 0) {
  15999. return false;
  16000. }
  16001. // Load CA chain for client verification
  16002. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  16003. return false;
  16004. }
  16005. initialized = true;
  16006. }
  16007. // Configure the SSL config
  16008. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16009. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16010. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16011. // Set minimum TLS version using mbedTLS native API
  16012. #if MBEDTLS_VERSION_MAJOR >= 3
  16013. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16014. #else
  16015. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16016. MBEDTLS_SSL_MINOR_VERSION_3);
  16017. #endif
  16018. return true;
  16019. };
  16020. SSLServer svr(setup_callback);
  16021. ASSERT_TRUE(svr.is_valid());
  16022. ASSERT_TRUE(callback_invoked);
  16023. svr.Get("/test", [&](const Request &req, Response &res) {
  16024. res.set_content("test", "text/plain");
  16025. auto cert = req.peer_cert();
  16026. ASSERT_TRUE(static_cast<bool>(cert));
  16027. auto common_name = cert.subject_cn();
  16028. EXPECT_EQ("Common Name", common_name);
  16029. });
  16030. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16031. auto se = detail::scope_exit([&] {
  16032. svr.stop();
  16033. t.join();
  16034. ASSERT_FALSE(svr.is_running());
  16035. });
  16036. svr.wait_until_ready();
  16037. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16038. cli.enable_server_certificate_verification(false);
  16039. cli.set_connection_timeout(30);
  16040. auto res = cli.Get("/test");
  16041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16042. ASSERT_EQ(StatusCode::OK_200, res->status);
  16043. }
  16044. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16045. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16046. // keep-alive SSL session, which reads through that config in
  16047. // mbedtls_ssl_close_notify.
  16048. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16050. ASSERT_TRUE(svr.is_valid());
  16051. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16052. res.set_content("test", "text/plain");
  16053. });
  16054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16055. auto se = detail::scope_exit([&] {
  16056. svr.stop();
  16057. t.join();
  16058. ASSERT_FALSE(svr.is_running());
  16059. });
  16060. svr.wait_until_ready();
  16061. {
  16062. SSLClient cli(HOST, PORT);
  16063. cli.enable_server_certificate_verification(false);
  16064. cli.set_keep_alive(true);
  16065. auto res = cli.Get("/test");
  16066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16067. ASSERT_EQ(StatusCode::OK_200, res->status);
  16068. // cli is destructed here with the keep-alive SSL session still open.
  16069. }
  16070. }
  16071. #endif
  16072. // WebSocket Tests
  16073. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16074. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16075. // defining the meaning of these bits has been negotiated.
  16076. auto make_frame = [](uint8_t first_byte) {
  16077. std::string frame;
  16078. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16079. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16080. frame += "Hello";
  16081. return frame;
  16082. };
  16083. // RSV1 set (0x40)
  16084. {
  16085. detail::BufferStream strm;
  16086. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16087. ws::Opcode opcode;
  16088. std::string payload;
  16089. bool fin;
  16090. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16091. false, 1024));
  16092. }
  16093. // RSV2 set (0x20)
  16094. {
  16095. detail::BufferStream strm;
  16096. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16097. ws::Opcode opcode;
  16098. std::string payload;
  16099. bool fin;
  16100. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16101. false, 1024));
  16102. }
  16103. // RSV3 set (0x10)
  16104. {
  16105. detail::BufferStream strm;
  16106. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16107. ws::Opcode opcode;
  16108. std::string payload;
  16109. bool fin;
  16110. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16111. false, 1024));
  16112. }
  16113. // No RSV bits set - should succeed
  16114. {
  16115. detail::BufferStream strm;
  16116. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16117. ws::Opcode opcode;
  16118. std::string payload;
  16119. bool fin;
  16120. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16121. false, 1024));
  16122. EXPECT_EQ(ws::Opcode::Text, opcode);
  16123. EXPECT_EQ("Hello", payload);
  16124. EXPECT_TRUE(fin);
  16125. }
  16126. }
  16127. TEST(WebSocketTest, ControlFrameValidation) {
  16128. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16129. // payload length <= 125.
  16130. // Ping with FIN=0 - must be rejected
  16131. {
  16132. detail::BufferStream strm;
  16133. std::string frame;
  16134. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16135. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16136. strm.write(frame.data(), frame.size());
  16137. ws::Opcode opcode;
  16138. std::string payload;
  16139. bool fin;
  16140. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16141. false, 1024));
  16142. }
  16143. // Close with FIN=0 - must be rejected
  16144. {
  16145. detail::BufferStream strm;
  16146. std::string frame;
  16147. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16148. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16149. strm.write(frame.data(), frame.size());
  16150. ws::Opcode opcode;
  16151. std::string payload;
  16152. bool fin;
  16153. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16154. false, 1024));
  16155. }
  16156. // Ping with payload_len=126 (extended length) - must be rejected
  16157. {
  16158. detail::BufferStream strm;
  16159. std::string frame;
  16160. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16161. frame += static_cast<char>(126); // payload_len=126 (>125)
  16162. frame += static_cast<char>(0x00); // extended length high byte
  16163. frame += static_cast<char>(126); // extended length low byte
  16164. frame += std::string(126, 'x');
  16165. strm.write(frame.data(), frame.size());
  16166. ws::Opcode opcode;
  16167. std::string payload;
  16168. bool fin;
  16169. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16170. false, 1024));
  16171. }
  16172. // Ping with FIN=1 and payload_len=125 - should succeed
  16173. {
  16174. detail::BufferStream strm;
  16175. std::string frame;
  16176. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16177. frame += static_cast<char>(125); // payload_len=125
  16178. frame += std::string(125, 'x');
  16179. strm.write(frame.data(), frame.size());
  16180. ws::Opcode opcode;
  16181. std::string payload;
  16182. bool fin;
  16183. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16184. false, 1024));
  16185. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16186. EXPECT_EQ(125u, payload.size());
  16187. EXPECT_TRUE(fin);
  16188. }
  16189. }
  16190. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16191. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16192. // length MUST be 0.
  16193. // MSB set - must be rejected
  16194. {
  16195. detail::BufferStream strm;
  16196. std::string frame;
  16197. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16198. frame += static_cast<char>(127); // 64-bit extended length
  16199. frame += static_cast<char>(0x80); // MSB set (invalid)
  16200. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16201. strm.write(frame.data(), frame.size());
  16202. ws::Opcode opcode;
  16203. std::string payload;
  16204. bool fin;
  16205. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16206. false, 1024));
  16207. }
  16208. // MSB clear - should pass length parsing (will be rejected by max_len,
  16209. // but that's a different check; use a small length to verify)
  16210. {
  16211. detail::BufferStream strm;
  16212. std::string frame;
  16213. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16214. frame += static_cast<char>(127); // 64-bit extended length
  16215. frame += std::string(7, '\0'); // high bytes = 0
  16216. frame += static_cast<char>(0x03); // length = 3
  16217. frame += "abc";
  16218. strm.write(frame.data(), frame.size());
  16219. ws::Opcode opcode;
  16220. std::string payload;
  16221. bool fin;
  16222. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16223. false, 1024));
  16224. EXPECT_EQ(ws::Opcode::Text, opcode);
  16225. EXPECT_EQ("abc", payload);
  16226. }
  16227. }
  16228. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16229. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16230. // Valid UTF-8
  16231. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16232. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16233. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16234. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16235. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16236. // Invalid UTF-8
  16237. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16238. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16239. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16240. EXPECT_FALSE(
  16241. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16242. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16243. }
  16244. TEST(WebSocketTest, ConnectAndDisconnect) {
  16245. Server svr;
  16246. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16247. std::string msg;
  16248. while (ws.read(msg)) {}
  16249. });
  16250. auto port = svr.bind_to_any_port(HOST);
  16251. std::thread t([&]() { svr.listen_after_bind(); });
  16252. svr.wait_until_ready();
  16253. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16254. ASSERT_TRUE(client.connect());
  16255. EXPECT_TRUE(client.is_open());
  16256. client.close();
  16257. EXPECT_FALSE(client.is_open());
  16258. svr.stop();
  16259. t.join();
  16260. }
  16261. TEST(WebSocketTest, ValidURL) {
  16262. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16263. EXPECT_TRUE(ws1.is_valid());
  16264. ws::WebSocketClient ws2("ws://example.com/path");
  16265. EXPECT_TRUE(ws2.is_valid());
  16266. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16267. EXPECT_TRUE(ws3.is_valid());
  16268. #ifdef CPPHTTPLIB_SSL_ENABLED
  16269. ws::WebSocketClient wss1("wss://example.com/path");
  16270. EXPECT_TRUE(wss1.is_valid());
  16271. ws::WebSocketClient wss2("wss://example.com:443/path");
  16272. EXPECT_TRUE(wss2.is_valid());
  16273. #endif
  16274. }
  16275. TEST(WebSocketTest, InvalidURL) {
  16276. // No scheme
  16277. ws::WebSocketClient ws1("localhost:8080/path");
  16278. EXPECT_FALSE(ws1.is_valid());
  16279. // No path
  16280. ws::WebSocketClient ws2("ws://localhost:8080");
  16281. EXPECT_FALSE(ws2.is_valid());
  16282. // Empty string
  16283. ws::WebSocketClient ws3("");
  16284. EXPECT_FALSE(ws3.is_valid());
  16285. // Missing host
  16286. ws::WebSocketClient ws4("ws://:8080/path");
  16287. EXPECT_FALSE(ws4.is_valid());
  16288. // Port number overflow — should not crash
  16289. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16290. EXPECT_FALSE(ws5.is_valid());
  16291. // Port out of range
  16292. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16293. EXPECT_FALSE(ws6.is_valid());
  16294. }
  16295. TEST(WebSocketTest, UnsupportedScheme) {
  16296. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16297. ws::WebSocketClient ws1("http://localhost:8080/path");
  16298. EXPECT_FALSE(ws1.is_valid());
  16299. ws::WebSocketClient ws2("https://localhost:8080/path");
  16300. EXPECT_FALSE(ws2.is_valid());
  16301. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16302. EXPECT_FALSE(ws3.is_valid());
  16303. #else
  16304. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16305. std::invalid_argument);
  16306. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16307. std::invalid_argument);
  16308. #endif
  16309. }
  16310. TEST(WebSocketTest, ConnectWhenInvalid) {
  16311. ws::WebSocketClient ws("not a valid url");
  16312. EXPECT_FALSE(ws.is_valid());
  16313. EXPECT_FALSE(ws.connect());
  16314. }
  16315. TEST(WebSocketTest, DefaultPort) {
  16316. ws::WebSocketClient ws1("ws://example.com/path");
  16317. EXPECT_TRUE(ws1.is_valid());
  16318. // ws:// defaults to port 80 (verified by successful parse)
  16319. #ifdef CPPHTTPLIB_SSL_ENABLED
  16320. ws::WebSocketClient ws2("wss://example.com/path");
  16321. EXPECT_TRUE(ws2.is_valid());
  16322. // wss:// defaults to port 443 (verified by successful parse)
  16323. #endif
  16324. }
  16325. TEST(WebSocketTest, IPv6LiteralAddress) {
  16326. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16327. EXPECT_TRUE(ws1.is_valid());
  16328. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16329. EXPECT_TRUE(ws2.is_valid());
  16330. }
  16331. TEST(WebSocketTest, ComplexPath) {
  16332. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16333. EXPECT_TRUE(ws1.is_valid());
  16334. ws::WebSocketClient ws2("ws://localhost:8080/");
  16335. EXPECT_TRUE(ws2.is_valid());
  16336. }
  16337. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16338. Server svr;
  16339. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16340. std::string msg;
  16341. while (ws.read(msg)) {}
  16342. });
  16343. auto port = svr.bind_to_any_port(HOST);
  16344. std::thread t([&]() { svr.listen_after_bind(); });
  16345. svr.wait_until_ready();
  16346. auto another_host = "example.com";
  16347. auto wrong_ip = "192.0.2.1";
  16348. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16349. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16350. ASSERT_TRUE(client.connect());
  16351. EXPECT_TRUE(client.is_open());
  16352. client.close();
  16353. svr.stop();
  16354. t.join();
  16355. }
  16356. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16357. Server svr;
  16358. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16359. std::string msg;
  16360. while (ws.read(msg)) {}
  16361. });
  16362. auto port = svr.bind_to_any_port(HOST);
  16363. std::thread t([&]() { svr.listen_after_bind(); });
  16364. svr.wait_until_ready();
  16365. auto wrong_ip = "192.0.2.1";
  16366. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16367. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16368. client.set_connection_timeout(1);
  16369. client.set_read_timeout(1);
  16370. client.set_write_timeout(1);
  16371. EXPECT_FALSE(client.connect());
  16372. EXPECT_FALSE(client.is_open());
  16373. svr.stop();
  16374. t.join();
  16375. }
  16376. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16377. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16378. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16379. // (RFC 6761) is only a map key and the Host header value.
  16380. auto host = "target.invalid";
  16381. Server svr;
  16382. std::string received_host;
  16383. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16384. received_host = req.get_header_value("Host");
  16385. std::string msg;
  16386. while (ws.read(msg)) {}
  16387. });
  16388. auto port = svr.bind_to_any_port(HOST);
  16389. std::thread t([&]() { svr.listen_after_bind(); });
  16390. // ASSERT_* below returns from the test body, which would leave t joinable
  16391. // and make ~thread call std::terminate.
  16392. auto se = detail::scope_exit([&] {
  16393. svr.stop();
  16394. if (t.joinable()) { t.join(); }
  16395. });
  16396. svr.wait_until_ready();
  16397. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16398. std::to_string(port) + "/ws");
  16399. client.set_hostname_addr_map({{host, HOST}});
  16400. ASSERT_TRUE(client.connect());
  16401. EXPECT_TRUE(client.is_open());
  16402. client.close();
  16403. svr.stop();
  16404. t.join();
  16405. // The mapping only redirects the connection; the identity stays host_.
  16406. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16407. }
  16408. class WebSocketIntegrationTest : public ::testing::Test {
  16409. protected:
  16410. void SetUp() override {
  16411. server_ = httplib::detail::make_unique<Server>();
  16412. setup_server();
  16413. start_server();
  16414. }
  16415. void TearDown() override {
  16416. server_->stop();
  16417. if (server_thread_.joinable()) { server_thread_.join(); }
  16418. }
  16419. void setup_server() {
  16420. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16421. std::string msg;
  16422. ws::ReadResult ret;
  16423. while ((ret = ws.read(msg))) {
  16424. if (ret == ws::Binary) {
  16425. ws.send(msg.data(), msg.size());
  16426. } else {
  16427. ws.send(msg);
  16428. }
  16429. }
  16430. });
  16431. server_->WebSocket("/ws-echo-string",
  16432. [](const Request &, ws::WebSocket &ws) {
  16433. std::string msg;
  16434. while (ws.read(msg)) {
  16435. ws.send("echo: " + msg);
  16436. }
  16437. });
  16438. server_->WebSocket(
  16439. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16440. // Echo back request metadata
  16441. ws.send("path:" + req.path);
  16442. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16443. std::string msg;
  16444. while (ws.read(msg)) {}
  16445. });
  16446. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16447. std::string msg;
  16448. ws.read(msg); // wait for a message
  16449. ws.close();
  16450. });
  16451. server_->WebSocket("/ws-close-status",
  16452. [](const Request &, ws::WebSocket &ws) {
  16453. std::string msg;
  16454. ws.read(msg); // wait for a message
  16455. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16456. });
  16457. server_->WebSocket(
  16458. "/ws-subprotocol",
  16459. [](const Request &, ws::WebSocket &ws) {
  16460. std::string msg;
  16461. while (ws.read(msg)) {
  16462. ws.send(msg);
  16463. }
  16464. },
  16465. [](const std::vector<std::string> &protocols) -> std::string {
  16466. for (const auto &p : protocols) {
  16467. if (p == "graphql-ws") { return p; }
  16468. }
  16469. return "";
  16470. });
  16471. }
  16472. void start_server() {
  16473. port_ = server_->bind_to_any_port(HOST);
  16474. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16475. server_->wait_until_ready();
  16476. }
  16477. std::unique_ptr<Server> server_;
  16478. std::thread server_thread_;
  16479. int port_ = 0;
  16480. };
  16481. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16482. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16483. "/ws-echo");
  16484. ASSERT_TRUE(client.connect());
  16485. ASSERT_TRUE(client.is_open());
  16486. ASSERT_TRUE(client.send("Hello WebSocket"));
  16487. std::string msg;
  16488. EXPECT_EQ(ws::Text, client.read(msg));
  16489. EXPECT_EQ("Hello WebSocket", msg);
  16490. client.close();
  16491. }
  16492. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16493. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16494. "/ws-echo");
  16495. ASSERT_TRUE(client.connect());
  16496. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16497. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16498. std::string msg;
  16499. EXPECT_EQ(ws::Binary, client.read(msg));
  16500. EXPECT_EQ(binary_data, msg);
  16501. client.close();
  16502. }
  16503. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16504. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16505. "/ws-echo");
  16506. ASSERT_TRUE(client.connect());
  16507. for (int i = 0; i < 10; i++) {
  16508. auto text = "message " + std::to_string(i);
  16509. ASSERT_TRUE(client.send(text));
  16510. std::string msg;
  16511. ASSERT_TRUE(client.read(msg));
  16512. EXPECT_EQ(text, msg);
  16513. }
  16514. client.close();
  16515. }
  16516. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16517. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16518. "/ws-close");
  16519. ASSERT_TRUE(client.connect());
  16520. // Send a message to trigger the server to close
  16521. ASSERT_TRUE(client.send("trigger close"));
  16522. // The server will close, so read should return false
  16523. std::string msg;
  16524. EXPECT_FALSE(client.read(msg));
  16525. EXPECT_FALSE(client.is_open());
  16526. }
  16527. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16528. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16529. "/ws-echo");
  16530. ASSERT_TRUE(client.connect());
  16531. // 128KB message
  16532. std::string large_data(128 * 1024, 'X');
  16533. ASSERT_TRUE(client.send(large_data));
  16534. std::string msg;
  16535. ASSERT_TRUE(client.read(msg));
  16536. EXPECT_EQ(large_data, msg);
  16537. client.close();
  16538. }
  16539. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16541. "/ws-echo");
  16542. ASSERT_TRUE(client.connect());
  16543. const int num_threads = 4;
  16544. std::vector<std::thread> threads;
  16545. std::atomic<int> send_count{0};
  16546. for (int t = 0; t < num_threads; t++) {
  16547. threads.emplace_back([&client, &send_count, t]() {
  16548. for (int i = 0; i < 5; i++) {
  16549. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16550. if (client.send(text)) { send_count++; }
  16551. }
  16552. });
  16553. }
  16554. for (auto &th : threads) {
  16555. th.join();
  16556. }
  16557. int received = 0;
  16558. std::string msg;
  16559. while (received < send_count.load()) {
  16560. if (!client.read(msg)) { break; }
  16561. received++;
  16562. }
  16563. EXPECT_EQ(send_count.load(), received);
  16564. client.close();
  16565. }
  16566. TEST_F(WebSocketIntegrationTest, ReadString) {
  16567. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16568. "/ws-echo-string");
  16569. ASSERT_TRUE(client.connect());
  16570. ASSERT_TRUE(client.send("hello"));
  16571. std::string msg;
  16572. ASSERT_TRUE(client.read(msg));
  16573. EXPECT_EQ("echo: hello", msg);
  16574. ASSERT_TRUE(client.send("world"));
  16575. ASSERT_TRUE(client.read(msg));
  16576. EXPECT_EQ("echo: world", msg);
  16577. client.close();
  16578. }
  16579. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16580. Headers headers = {{"X-Test-Header", "test-value"}};
  16581. ws::WebSocketClient client(
  16582. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16583. ASSERT_TRUE(client.connect());
  16584. std::string msg;
  16585. ASSERT_TRUE(client.read(msg));
  16586. EXPECT_EQ("path:/ws-request-info", msg);
  16587. ASSERT_TRUE(client.read(msg));
  16588. EXPECT_EQ("header:test-value", msg);
  16589. client.close();
  16590. }
  16591. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16593. "/ws-echo");
  16594. client.set_read_timeout(1, 0); // 1 second
  16595. ASSERT_TRUE(client.connect());
  16596. // Don't send anything — server echo handler waits for a message,
  16597. // so read() should time out and return false.
  16598. std::string msg;
  16599. EXPECT_FALSE(client.read(msg));
  16600. }
  16601. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16602. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16603. "/ws-echo");
  16604. client.set_read_timeout(5, 0);
  16605. ASSERT_TRUE(client.connect());
  16606. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16607. // The server should reject it and close the connection.
  16608. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16609. client.send(oversized);
  16610. // The server's read() should have failed due to payload limit,
  16611. // so our read() should return false (connection closed).
  16612. std::string msg;
  16613. EXPECT_FALSE(client.read(msg));
  16614. }
  16615. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16616. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16617. "/ws-echo");
  16618. client.set_read_timeout(10, 0);
  16619. ASSERT_TRUE(client.connect());
  16620. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16621. // This should succeed.
  16622. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16623. ASSERT_TRUE(client.send(at_limit));
  16624. std::string msg;
  16625. ASSERT_TRUE(client.read(msg));
  16626. EXPECT_EQ(at_limit.size(), msg.size());
  16627. client.close();
  16628. }
  16629. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16630. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16631. "/nonexistent");
  16632. EXPECT_FALSE(client.connect());
  16633. EXPECT_FALSE(client.is_open());
  16634. }
  16635. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16636. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16637. "/ws-echo");
  16638. ASSERT_TRUE(client.connect());
  16639. ASSERT_TRUE(client.send(""));
  16640. std::string msg;
  16641. EXPECT_EQ(ws::Text, client.read(msg));
  16642. EXPECT_EQ("", msg);
  16643. client.close();
  16644. }
  16645. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16646. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16647. "/ws-echo");
  16648. // First connection
  16649. ASSERT_TRUE(client.connect());
  16650. ASSERT_TRUE(client.send("first"));
  16651. std::string msg;
  16652. ASSERT_TRUE(client.read(msg));
  16653. EXPECT_EQ("first", msg);
  16654. client.close();
  16655. EXPECT_FALSE(client.is_open());
  16656. // Reconnect using the same client object
  16657. ASSERT_TRUE(client.connect());
  16658. ASSERT_TRUE(client.is_open());
  16659. ASSERT_TRUE(client.send("second"));
  16660. ASSERT_TRUE(client.read(msg));
  16661. EXPECT_EQ("second", msg);
  16662. client.close();
  16663. }
  16664. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16665. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16666. "/ws-close-status");
  16667. ASSERT_TRUE(client.connect());
  16668. // Trigger the server to close with GoingAway status
  16669. ASSERT_TRUE(client.send("trigger"));
  16670. // read() should return false after receiving the close frame
  16671. std::string msg;
  16672. EXPECT_FALSE(client.read(msg));
  16673. EXPECT_FALSE(client.is_open());
  16674. }
  16675. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16676. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16677. "/ws-echo");
  16678. ASSERT_TRUE(client.connect());
  16679. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16680. EXPECT_FALSE(client.is_open());
  16681. }
  16682. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16683. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16684. ws::WebSocketClient client(
  16685. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16686. ASSERT_TRUE(client.connect());
  16687. // Server should have selected graphql-ws
  16688. EXPECT_EQ("graphql-ws", client.subprotocol());
  16689. client.close();
  16690. }
  16691. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16692. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16693. ws::WebSocketClient client(
  16694. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16695. ASSERT_TRUE(client.connect());
  16696. // Server should not have selected any subprotocol
  16697. EXPECT_TRUE(client.subprotocol().empty());
  16698. client.close();
  16699. }
  16700. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16701. // Connect without requesting any subprotocol
  16702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16703. "/ws-subprotocol");
  16704. ASSERT_TRUE(client.connect());
  16705. EXPECT_TRUE(client.subprotocol().empty());
  16706. client.close();
  16707. }
  16708. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16709. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16710. "/ws-echo");
  16711. client.set_tcp_nodelay(true);
  16712. client.set_connection_timeout(3, 0);
  16713. bool socket_options_called = false;
  16714. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16715. ASSERT_TRUE(client.connect());
  16716. ASSERT_TRUE(client.is_open());
  16717. EXPECT_TRUE(socket_options_called);
  16718. ASSERT_TRUE(client.send("hello"));
  16719. std::string msg;
  16720. auto result = client.read(msg);
  16721. EXPECT_EQ(result, ws::ReadResult::Text);
  16722. EXPECT_EQ(msg, "hello");
  16723. client.close();
  16724. }
  16725. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16726. Server svr;
  16727. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16728. if (!req.has_header("Authorization")) {
  16729. res.status = StatusCode::Unauthorized_401;
  16730. res.set_content("Unauthorized", "text/plain");
  16731. return Server::HandlerResponse::Handled;
  16732. }
  16733. return Server::HandlerResponse::Unhandled;
  16734. });
  16735. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16736. std::string msg;
  16737. while (ws.read(msg)) {
  16738. ws.send(msg);
  16739. }
  16740. });
  16741. auto port = svr.bind_to_any_port("localhost");
  16742. std::thread t([&]() { svr.listen_after_bind(); });
  16743. svr.wait_until_ready();
  16744. // Without Authorization header - should be rejected before upgrade
  16745. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16746. EXPECT_FALSE(client1.connect());
  16747. // With Authorization header - should succeed
  16748. Headers headers = {{"Authorization", "Bearer token123"}};
  16749. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16750. headers);
  16751. ASSERT_TRUE(client2.connect());
  16752. ASSERT_TRUE(client2.send("hello"));
  16753. std::string msg;
  16754. ASSERT_TRUE(client2.read(msg));
  16755. EXPECT_EQ("hello", msg);
  16756. client2.close();
  16757. svr.stop();
  16758. t.join();
  16759. }
  16760. TEST(WebSocketTest, QueryStringInHandshake) {
  16761. Server svr;
  16762. std::mutex mtx;
  16763. std::string received_target;
  16764. std::string received_token;
  16765. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16766. {
  16767. std::lock_guard<std::mutex> lock(mtx);
  16768. received_target = req.target;
  16769. if (req.has_param("token")) {
  16770. received_token = req.get_param_value("token");
  16771. }
  16772. }
  16773. std::string msg;
  16774. while (ws.read(msg)) {
  16775. ws.send(msg);
  16776. }
  16777. });
  16778. auto port = svr.bind_to_any_port("localhost");
  16779. std::thread t([&]() { svr.listen_after_bind(); });
  16780. svr.wait_until_ready();
  16781. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16782. "/ws?token=ABC&session=123");
  16783. ASSERT_TRUE(client.connect());
  16784. // Round-trip ensures the handler has run and captured the request.
  16785. ASSERT_TRUE(client.send("hello"));
  16786. std::string msg;
  16787. ASSERT_TRUE(client.read(msg));
  16788. EXPECT_EQ("hello", msg);
  16789. client.close();
  16790. {
  16791. std::lock_guard<std::mutex> lock(mtx);
  16792. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16793. EXPECT_EQ("ABC", received_token);
  16794. }
  16795. svr.stop();
  16796. t.join();
  16797. }
  16798. // Run a handshake against a throwaway server and hand the request the server
  16799. // received back to the caller, so tests can assert on the headers the client
  16800. // actually put on the wire.
  16801. static void capture_websocket_handshake_request(
  16802. const Headers &client_headers,
  16803. std::function<void(const Request &, int port)> verify) {
  16804. Server svr;
  16805. std::mutex mtx;
  16806. Request received;
  16807. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16808. {
  16809. std::lock_guard<std::mutex> lock(mtx);
  16810. received = req;
  16811. }
  16812. std::string msg;
  16813. while (ws.read(msg)) {
  16814. ws.send(msg);
  16815. }
  16816. });
  16817. auto port = svr.bind_to_any_port("localhost");
  16818. std::thread t([&]() { svr.listen_after_bind(); });
  16819. auto se = detail::scope_exit([&] {
  16820. svr.stop();
  16821. t.join();
  16822. });
  16823. svr.wait_until_ready();
  16824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  16825. client_headers);
  16826. ASSERT_TRUE(client.connect());
  16827. ASSERT_TRUE(client.send("hello"));
  16828. std::string msg;
  16829. ASSERT_TRUE(client.read(msg));
  16830. client.close();
  16831. {
  16832. std::lock_guard<std::mutex> lock(mtx);
  16833. verify(received, port);
  16834. }
  16835. }
  16836. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  16837. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  16838. // Non-default port must be present in the Host header. Default ports
  16839. // (80/443) are omitted; that logic is covered by
  16840. // MakeHostAndPortStringTest.
  16841. EXPECT_EQ("localhost:" + std::to_string(port),
  16842. req.get_header_value("Host"));
  16843. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  16844. req.get_header_value("User-Agent"));
  16845. EXPECT_FALSE(req.has_header("Accept"));
  16846. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  16847. EXPECT_FALSE(req.has_header("Content-Length"));
  16848. });
  16849. }
  16850. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  16851. capture_websocket_handshake_request(
  16852. {{"Host", "example.com"},
  16853. {"User-Agent", "custom-agent"},
  16854. {"X-Custom", "value"}},
  16855. [](const Request &req, int) {
  16856. EXPECT_EQ("example.com", req.get_header_value("Host"));
  16857. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  16858. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  16859. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  16860. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  16861. });
  16862. }
  16863. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  16864. capture_websocket_handshake_request(
  16865. {{"Upgrade", "bogus"},
  16866. {"Connection", "close"},
  16867. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  16868. {"Sec-WebSocket-Version", "8"}},
  16869. [](const Request &req, int) {
  16870. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  16871. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  16872. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  16873. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  16874. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  16875. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  16876. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  16877. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  16878. req.get_header_value("Sec-WebSocket-Key"));
  16879. });
  16880. }
  16881. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  16882. // A header the client refuses to send must abort the handshake before any
  16883. // part of it reaches the wire; a lone request line would otherwise sit in
  16884. // the peer's buffer as a truncated request.
  16885. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16886. ASSERT_NE(INVALID_SOCKET, srv);
  16887. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  16888. sockaddr_in addr{};
  16889. addr.sin_family = AF_INET;
  16890. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  16891. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16892. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16893. ASSERT_EQ(0, ::listen(srv, 1));
  16894. sockaddr_in bound{};
  16895. socklen_t bound_len = sizeof(bound);
  16896. ASSERT_EQ(
  16897. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  16898. auto port = ntohs(bound.sin_port);
  16899. ssize_t received = -1;
  16900. std::thread t([&] {
  16901. // Bound every blocking call so a regression fails the test with a bad
  16902. // value instead of hanging the suite.
  16903. fd_set rfds;
  16904. FD_ZERO(&rfds);
  16905. FD_SET(srv, &rfds);
  16906. timeval tv{5, 0};
  16907. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  16908. 0) {
  16909. return;
  16910. }
  16911. sockaddr_in cli_addr{};
  16912. socklen_t cli_len = sizeof(cli_addr);
  16913. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16914. if (cli == INVALID_SOCKET) { return; }
  16915. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  16916. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16917. char buf[4096];
  16918. received = ::recv(cli, buf, sizeof(buf), 0);
  16919. });
  16920. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  16921. // connect() has already shut the socket down by the time it returns false,
  16922. // so the peer sees EOF without waiting for the client to be destroyed.
  16923. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  16924. {{"X-Bad", "a\r\nInjected: 1"}});
  16925. EXPECT_FALSE(client.connect());
  16926. t.join();
  16927. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  16928. EXPECT_EQ(0, received);
  16929. }
  16930. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  16931. // The socket path doubles as the URL host, so it must not contain '/'.
  16932. const char *shard = getenv("GTEST_SHARD_INDEX");
  16933. const std::string sock_path =
  16934. shard ? std::string("httplib-ws-") + shard + ".sock"
  16935. : std::string("httplib-ws.sock");
  16936. std::remove(sock_path.c_str());
  16937. Server svr;
  16938. std::mutex mtx;
  16939. std::string received_host;
  16940. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16941. {
  16942. std::lock_guard<std::mutex> lock(mtx);
  16943. received_host = req.get_header_value("Host");
  16944. }
  16945. std::string msg;
  16946. while (ws.read(msg)) {
  16947. ws.send(msg);
  16948. }
  16949. });
  16950. svr.set_address_family(AF_UNIX);
  16951. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  16952. auto se = detail::scope_exit([&] {
  16953. svr.stop();
  16954. t.join();
  16955. std::remove(sock_path.c_str());
  16956. });
  16957. svr.wait_until_ready();
  16958. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  16959. client.set_address_family(AF_UNIX);
  16960. ASSERT_TRUE(client.connect());
  16961. ASSERT_TRUE(client.send("hello"));
  16962. std::string msg;
  16963. ASSERT_TRUE(client.read(msg));
  16964. client.close();
  16965. {
  16966. std::lock_guard<std::mutex> lock(mtx);
  16967. // There is no host:port for a Unix socket, so the same "localhost"
  16968. // placeholder the HTTP client uses is expected.
  16969. EXPECT_EQ("localhost", received_host);
  16970. }
  16971. }
  16972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16973. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16974. protected:
  16975. void SetUp() override {
  16976. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16977. SERVER_PRIVATE_KEY_FILE);
  16978. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16979. std::string msg;
  16980. ws::ReadResult ret;
  16981. while ((ret = ws.read(msg))) {
  16982. if (ret == ws::Binary) {
  16983. ws.send(msg.data(), msg.size());
  16984. } else {
  16985. ws.send(msg);
  16986. }
  16987. }
  16988. });
  16989. port_ = server_->bind_to_any_port(HOST);
  16990. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16991. server_->wait_until_ready();
  16992. }
  16993. void TearDown() override {
  16994. server_->stop();
  16995. if (server_thread_.joinable()) { server_thread_.join(); }
  16996. }
  16997. std::unique_ptr<SSLServer> server_;
  16998. std::thread server_thread_;
  16999. int port_ = 0;
  17000. };
  17001. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  17002. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17003. "/ws-echo");
  17004. client.enable_server_certificate_verification(false);
  17005. ASSERT_TRUE(client.connect());
  17006. ASSERT_TRUE(client.is_open());
  17007. ASSERT_TRUE(client.send("Hello WSS"));
  17008. std::string msg;
  17009. EXPECT_EQ(ws::Text, client.read(msg));
  17010. EXPECT_EQ("Hello WSS", msg);
  17011. client.close();
  17012. }
  17013. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17014. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17015. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17016. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17017. // client (without calling close() first) is the only path that runs
  17018. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17019. // bug exactly.
  17020. //
  17021. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17022. // when linked against an instrumented libssl; run under Valgrind to catch it
  17023. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17024. // suite (the freed session otherwise stalls on the close handshake) — this test
  17025. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17026. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17027. {
  17028. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17029. "/ws-echo");
  17030. client.enable_server_certificate_verification(false);
  17031. client.set_read_timeout(2, 0);
  17032. client.set_write_timeout(2, 0);
  17033. ASSERT_TRUE(client.connect());
  17034. ASSERT_TRUE(client.is_open());
  17035. ASSERT_TRUE(client.send("still open"));
  17036. // Intentionally do NOT call client.close(): leaving scope runs
  17037. // shutdown_and_close() with the WebSocket still open, which must send the
  17038. // close frame while the TLS session is still alive.
  17039. }
  17040. }
  17041. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17042. // shutdown_and_close() at the start of connect(), reproducing the same
  17043. // use-after-free within the test body rather than at scope exit. The second
  17044. // connect must succeed and echo, proving the close handshake ran over a live
  17045. // session. See the note above about memory-tool requirements.
  17046. TEST_F(WebSocketSSLIntegrationTest,
  17047. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17048. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17049. "/ws-echo");
  17050. client.enable_server_certificate_verification(false);
  17051. client.set_read_timeout(2, 0);
  17052. client.set_write_timeout(2, 0);
  17053. ASSERT_TRUE(client.connect());
  17054. ASSERT_TRUE(client.is_open());
  17055. ASSERT_TRUE(client.send("still open"));
  17056. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17057. // the still-open connection, which must not touch a freed TLS session.
  17058. ASSERT_TRUE(client.connect());
  17059. ASSERT_TRUE(client.is_open());
  17060. ASSERT_TRUE(client.send("after reconnect"));
  17061. std::string msg;
  17062. EXPECT_EQ(ws::Text, client.read(msg));
  17063. EXPECT_EQ("after reconnect", msg);
  17064. client.close();
  17065. }
  17066. #endif
  17067. #ifdef CPPHTTPLIB_SSL_ENABLED
  17068. class WebSocketSSLCATest : public ::testing::Test {
  17069. protected:
  17070. void SetUp() override {
  17071. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17072. SERVER_PRIVATE_KEY_FILE);
  17073. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17074. std::string msg;
  17075. while (ws.read(msg)) {
  17076. ws.send(msg);
  17077. }
  17078. });
  17079. port_ = server_->bind_to_any_port("127.0.0.1");
  17080. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17081. server_->wait_until_ready();
  17082. }
  17083. void TearDown() override {
  17084. server_->stop();
  17085. if (server_thread_.joinable()) { server_thread_.join(); }
  17086. }
  17087. std::string url() const {
  17088. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17089. }
  17090. std::unique_ptr<SSLServer> server_;
  17091. std::thread server_thread_;
  17092. int port_ = 0;
  17093. };
  17094. // A custom CA loaded as PEM verifies the server with full certificate
  17095. // verification enabled
  17096. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17097. ws::WebSocketClient client(url());
  17098. std::string cert;
  17099. read_file(SERVER_CERT2_FILE, cert);
  17100. client.load_ca_cert_store(cert.c_str(), cert.size());
  17101. ASSERT_TRUE(client.connect());
  17102. ASSERT_TRUE(client.send("hello"));
  17103. std::string msg;
  17104. EXPECT_EQ(ws::Text, client.read(msg));
  17105. EXPECT_EQ("hello", msg);
  17106. client.close();
  17107. }
  17108. // A custom CA that does not cover the server must fail verification (the
  17109. // custom CA is exclusive; system certs are not loaded alongside it)
  17110. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17111. ws::WebSocketClient client(url());
  17112. std::string cert;
  17113. read_file(CLIENT_CA_CERT_FILE, cert);
  17114. client.load_ca_cert_store(cert.c_str(), cert.size());
  17115. ASSERT_FALSE(client.connect());
  17116. }
  17117. // Regression test: reconnecting with a native custom CA store used to reuse
  17118. // a store handle the previous TLS context had already freed (use-after-free
  17119. // under the OpenSSL backend). The context now lives as long as the client.
  17120. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17121. ws::WebSocketClient client(url());
  17122. std::string cert;
  17123. read_file(SERVER_CERT2_FILE, cert);
  17124. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17125. ASSERT_TRUE(client.connect());
  17126. client.close();
  17127. ASSERT_TRUE(client.connect());
  17128. ASSERT_TRUE(client.send("again"));
  17129. std::string msg;
  17130. EXPECT_EQ(ws::Text, client.read(msg));
  17131. EXPECT_EQ("again", msg);
  17132. client.close();
  17133. }
  17134. // Regression test: a certificate with a trusted chain but no identity match
  17135. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17136. // verification entirely for IP hosts, so this connection succeeded there.
  17137. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17138. // chain verification while the identity check must still fail.
  17139. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17141. ASSERT_TRUE(svr.is_valid());
  17142. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17143. std::string msg;
  17144. while (ws.read(msg)) {
  17145. ws.send(msg);
  17146. }
  17147. });
  17148. auto port = svr.bind_to_any_port("127.0.0.1");
  17149. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17150. auto se = detail::scope_exit([&] {
  17151. svr.stop();
  17152. t.join();
  17153. });
  17154. svr.wait_until_ready();
  17155. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17156. "/echo");
  17157. std::string cert;
  17158. read_file(SERVER_CERT_FILE, cert);
  17159. client.load_ca_cert_store(cert.c_str(), cert.size());
  17160. ASSERT_FALSE(client.connect());
  17161. }
  17162. #endif
  17163. #if !defined(_WIN32)
  17164. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17165. auto secret_dir = std::string("./symlink_test_secret");
  17166. auto served_dir = std::string("./symlink_test_served");
  17167. auto secret_file = secret_dir + "/secret.txt";
  17168. auto symlink_path = served_dir + "/escape";
  17169. // Setup: create directories and files
  17170. mkdir(secret_dir.c_str(), 0755);
  17171. mkdir(served_dir.c_str(), 0755);
  17172. {
  17173. std::ofstream ofs(secret_file);
  17174. ofs << "SECRET_DATA";
  17175. }
  17176. // Create symlink using absolute path so it resolves correctly
  17177. #ifdef PATH_MAX
  17178. char abs_secret[PATH_MAX];
  17179. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17180. #else
  17181. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17182. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17183. ASSERT_NE(nullptr, abs_secret);
  17184. #endif
  17185. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17186. auto se = detail::scope_exit([&] {
  17187. unlink(symlink_path.c_str());
  17188. unlink(secret_file.c_str());
  17189. rmdir(served_dir.c_str());
  17190. rmdir(secret_dir.c_str());
  17191. });
  17192. Server svr;
  17193. svr.set_mount_point("/", served_dir);
  17194. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17195. auto se2 = detail::scope_exit([&] {
  17196. svr.stop();
  17197. listen_thread.join();
  17198. });
  17199. svr.wait_until_ready();
  17200. Client cli("localhost", PORT);
  17201. // Symlink pointing outside base dir should be blocked
  17202. auto res = cli.Get("/escape/secret.txt");
  17203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17204. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17205. }
  17206. #endif
  17207. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17208. // A GET request with Content-Length to a static file handler must have its
  17209. // body drained before the keep-alive connection is reused. Otherwise the
  17210. // unread body bytes are interpreted as the next HTTP request.
  17211. //
  17212. // The body is sent AFTER receiving the first response (as in the original
  17213. // PoC) so that the stream_line_reader cannot buffer it together with the
  17214. // headers of the first request.
  17215. Server svr;
  17216. svr.set_mount_point("/", "./www");
  17217. std::atomic<int> smuggled_count(0);
  17218. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17219. smuggled_count++;
  17220. res.set_content("oops", "text/plain");
  17221. });
  17222. auto port = svr.bind_to_any_port("localhost");
  17223. thread t = thread([&] { svr.listen_after_bind(); });
  17224. auto se = detail::scope_exit([&] {
  17225. svr.stop();
  17226. t.join();
  17227. });
  17228. svr.wait_until_ready();
  17229. auto error = Error::Success;
  17230. auto sock = detail::create_client_socket(
  17231. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17232. /*connection_timeout_sec=*/2, 0,
  17233. /*read_timeout_sec=*/2, 0,
  17234. /*write_timeout_sec=*/2, 0, std::string(), error);
  17235. ASSERT_NE(INVALID_SOCKET, sock);
  17236. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17237. // The "smuggled" request will be sent as the body of the outer GET
  17238. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17239. "Host: localhost\r\n"
  17240. "Connection: close\r\n"
  17241. "\r\n";
  17242. // Step 1: Send only the outer request headers (no body yet)
  17243. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17244. "Host: localhost\r\n"
  17245. "Content-Length: " +
  17246. std::to_string(smuggled.size()) +
  17247. "\r\n"
  17248. "\r\n";
  17249. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17250. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17251. // Step 2: Read the first response (server serves file without reading body)
  17252. std::string first_response;
  17253. char buf[4096];
  17254. for (;;) {
  17255. auto n = recv(sock, buf, sizeof(buf), 0);
  17256. if (n <= 0) break;
  17257. first_response.append(buf, static_cast<size_t>(n));
  17258. // Stop once we have a complete response (headers + body)
  17259. auto hdr_end = first_response.find("\r\n\r\n");
  17260. if (hdr_end != std::string::npos) {
  17261. // Check for Content-Length to know when the body is complete
  17262. auto cl_pos = first_response.find("Content-Length:");
  17263. if (cl_pos != std::string::npos) {
  17264. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17265. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17266. auto cl = std::stoul(
  17267. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17268. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17269. } else {
  17270. break; // No Content-Length, assume headers-only response
  17271. }
  17272. }
  17273. }
  17274. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17275. // Step 3: Now send the body, which looks like a new HTTP request.
  17276. // On a vulnerable server the keep-alive loop reads this as a second request.
  17277. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17278. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17279. // Step 4: Try to read a second response (should NOT exist after fix)
  17280. std::string second_response;
  17281. for (;;) {
  17282. auto n = recv(sock, buf, sizeof(buf), 0);
  17283. if (n <= 0) break;
  17284. second_response.append(buf, static_cast<size_t>(n));
  17285. }
  17286. // The smuggled request must NOT have been processed
  17287. EXPECT_EQ(0, smuggled_count.load());
  17288. }
  17289. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17290. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17291. // must be rejected with 400 Bad Request.
  17292. Server svr;
  17293. svr.Post("/test", [&](const Request &, Response &res) {
  17294. res.set_content("ok", "text/plain");
  17295. });
  17296. thread t = thread([&] { svr.listen(HOST, PORT); });
  17297. auto se = detail::scope_exit([&] {
  17298. svr.stop();
  17299. t.join();
  17300. ASSERT_FALSE(svr.is_running());
  17301. });
  17302. svr.wait_until_ready();
  17303. // Exact "chunked"
  17304. {
  17305. auto req = "POST /test HTTP/1.1\r\n"
  17306. "Host: localhost\r\n"
  17307. "Content-Length: 5\r\n"
  17308. "Transfer-Encoding: chunked\r\n"
  17309. "Connection: close\r\n"
  17310. "\r\n"
  17311. "hello";
  17312. std::string response;
  17313. ASSERT_TRUE(send_request(1, req, &response));
  17314. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17315. response.substr(0, response.find("\r\n")));
  17316. }
  17317. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17318. {
  17319. auto req = "POST /test HTTP/1.1\r\n"
  17320. "Host: localhost\r\n"
  17321. "Content-Length: 5\r\n"
  17322. "Transfer-Encoding: gzip, chunked\r\n"
  17323. "Connection: close\r\n"
  17324. "\r\n"
  17325. "hello";
  17326. std::string response;
  17327. ASSERT_TRUE(send_request(1, req, &response));
  17328. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17329. response.substr(0, response.find("\r\n")));
  17330. }
  17331. }
  17332. // Regression for issue #2450: a DELETE without Content-Length on a
  17333. // keep-alive connection must not let the post-response drain consume the
  17334. // next request's bytes.
  17335. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17336. Server svr;
  17337. std::atomic<int> delete_count(0);
  17338. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17339. delete_count++;
  17340. res.status = StatusCode::NoContent_204;
  17341. });
  17342. auto port = svr.bind_to_any_port(HOST);
  17343. thread t = thread([&] { svr.listen_after_bind(); });
  17344. auto se = detail::scope_exit([&] {
  17345. svr.stop();
  17346. t.join();
  17347. });
  17348. svr.wait_until_ready();
  17349. auto error = Error::Success;
  17350. auto sock = detail::create_client_socket(
  17351. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17352. /*connection_timeout_sec=*/2, 0,
  17353. /*read_timeout_sec=*/2, 0,
  17354. /*write_timeout_sec=*/2, 0, std::string(), error);
  17355. ASSERT_NE(INVALID_SOCKET, sock);
  17356. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17357. auto send_request_and_read_response = [&](const std::string &req,
  17358. std::string &out) -> bool {
  17359. auto sent = send(sock, req.data(), req.size(), 0);
  17360. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17361. char buf[4096];
  17362. for (;;) {
  17363. auto n = recv(sock, buf, sizeof(buf), 0);
  17364. if (n <= 0) { return !out.empty(); }
  17365. out.append(buf, static_cast<size_t>(n));
  17366. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17367. }
  17368. };
  17369. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17370. "Host: localhost\r\n"
  17371. "\r\n";
  17372. std::string resp1;
  17373. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17374. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17375. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17376. "Host: localhost\r\n"
  17377. "Connection: close\r\n"
  17378. "\r\n";
  17379. std::string resp2;
  17380. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17381. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17382. EXPECT_EQ(2, delete_count.load());
  17383. }
  17384. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17385. Server svr;
  17386. svr.Post("/ingest", [&](const Request &, Response &res,
  17387. const ContentReader &content_reader) {
  17388. auto consumed = content_reader([](const char *, size_t) { return false; });
  17389. EXPECT_FALSE(consumed);
  17390. res.status = StatusCode::Conflict_409;
  17391. res.set_header("Connection", "close");
  17392. });
  17393. auto port = svr.bind_to_any_port(HOST);
  17394. thread t = thread([&] { svr.listen_after_bind(); });
  17395. auto se = detail::scope_exit([&] {
  17396. svr.stop();
  17397. t.join();
  17398. });
  17399. svr.wait_until_ready();
  17400. auto error = Error::Success;
  17401. auto sock = detail::create_client_socket(
  17402. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17403. /*connection_timeout_sec=*/2, 0,
  17404. /*read_timeout_sec=*/1, 0,
  17405. /*write_timeout_sec=*/2, 0, std::string(), error);
  17406. ASSERT_NE(INVALID_SOCKET, sock);
  17407. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17408. std::string request = "POST /ingest HTTP/1.1\r\n"
  17409. "Host: localhost\r\n"
  17410. "Transfer-Encoding: chunked\r\n"
  17411. "\r\n"
  17412. "4\r\n"
  17413. "data\r\n";
  17414. auto sent = send(sock, request.data(), request.size(), 0);
  17415. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17416. std::string response;
  17417. ssize_t received = 0;
  17418. do {
  17419. char buf[4096];
  17420. received = recv(sock, buf, sizeof(buf), 0);
  17421. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17422. } while (received > 0);
  17423. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17424. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17425. EXPECT_EQ(0, received);
  17426. }
  17427. namespace no_proxy_test {
  17428. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17429. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17430. // calling listen().
  17431. class ScopedServer {
  17432. public:
  17433. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17434. ~ScopedServer() {
  17435. svr_.stop();
  17436. if (th_.joinable()) { th_.join(); }
  17437. }
  17438. Server &svr() { return svr_; }
  17439. int port() const { return port_; }
  17440. void listen() {
  17441. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17442. svr_.wait_until_ready();
  17443. }
  17444. private:
  17445. Server svr_;
  17446. std::thread th_;
  17447. int port_ = 0;
  17448. };
  17449. class ProxyAndTargetServers {
  17450. public:
  17451. ProxyAndTargetServers() {
  17452. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17453. proxy_hits_++;
  17454. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17455. res.set_content("via-proxy", "text/plain");
  17456. });
  17457. target_.Get(".*", [this](const Request &req, Response &res) {
  17458. target_hits_++;
  17459. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17460. res.set_content("direct", "text/plain");
  17461. });
  17462. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17463. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17464. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17465. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17466. proxy_mock_.wait_until_ready();
  17467. target_.wait_until_ready();
  17468. }
  17469. ~ProxyAndTargetServers() {
  17470. proxy_mock_.stop();
  17471. target_.stop();
  17472. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17473. if (target_thread_.joinable()) { target_thread_.join(); }
  17474. }
  17475. Server &proxy_mock() { return proxy_mock_; }
  17476. Server &target() { return target_; }
  17477. int proxy_port() const { return proxy_port_; }
  17478. int target_port() const { return target_port_; }
  17479. int proxy_hits() const { return proxy_hits_.load(); }
  17480. int target_hits() const { return target_hits_.load(); }
  17481. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17482. void reset_counters() {
  17483. proxy_hits_ = 0;
  17484. target_hits_ = 0;
  17485. last_had_proxy_authz_ = false;
  17486. }
  17487. private:
  17488. Server proxy_mock_;
  17489. Server target_;
  17490. std::thread proxy_thread_;
  17491. std::thread target_thread_;
  17492. int proxy_port_ = 0;
  17493. int target_port_ = 0;
  17494. std::atomic<int> proxy_hits_{0};
  17495. std::atomic<int> target_hits_{0};
  17496. std::atomic<bool> last_had_proxy_authz_{false};
  17497. };
  17498. inline std::unique_ptr<Client> make_client(const std::string &host,
  17499. ProxyAndTargetServers &s) {
  17500. auto cli = detail::make_unique<Client>(host, s.target_port());
  17501. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17502. cli->set_proxy("127.0.0.1", s.proxy_port());
  17503. return cli;
  17504. }
  17505. } // namespace no_proxy_test
  17506. using no_proxy_test::make_client;
  17507. using no_proxy_test::ProxyAndTargetServers;
  17508. TEST(NoProxyTest, ExactHostnameBypasses) {
  17509. ProxyAndTargetServers s;
  17510. auto cli = make_client("example.com", s);
  17511. cli->set_no_proxy({"example.com"});
  17512. auto res = cli->Get("/");
  17513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17514. EXPECT_EQ(0, s.proxy_hits());
  17515. EXPECT_EQ(1, s.target_hits());
  17516. }
  17517. TEST(NoProxyTest, SubdomainBypasses) {
  17518. ProxyAndTargetServers s;
  17519. auto cli = make_client("foo.example.com", s);
  17520. cli->set_no_proxy({"example.com"});
  17521. auto res = cli->Get("/");
  17522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17523. EXPECT_EQ(0, s.proxy_hits());
  17524. EXPECT_EQ(1, s.target_hits());
  17525. }
  17526. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17527. // Regression guard: "evilexample.com" must not be considered a subdomain
  17528. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17529. // check would let traffic bypass the proxy and leak credentials direct
  17530. // to the attacker host.
  17531. ProxyAndTargetServers s;
  17532. auto cli = make_client("evilexample.com", s);
  17533. cli->set_no_proxy({"example.com"});
  17534. auto res = cli->Get("/");
  17535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17536. EXPECT_GE(s.proxy_hits(), 1);
  17537. EXPECT_EQ(0, s.target_hits());
  17538. }
  17539. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17540. ProxyAndTargetServers s;
  17541. auto cli = make_client("example.com.evil.com", s);
  17542. cli->set_no_proxy({"example.com"});
  17543. auto res = cli->Get("/");
  17544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17545. EXPECT_GE(s.proxy_hits(), 1);
  17546. EXPECT_EQ(0, s.target_hits());
  17547. }
  17548. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17549. ProxyAndTargetServers s;
  17550. auto cli = make_client("example.com", s);
  17551. cli->set_no_proxy({".example.com"});
  17552. auto res = cli->Get("/");
  17553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17554. EXPECT_EQ(0, s.proxy_hits());
  17555. EXPECT_EQ(1, s.target_hits());
  17556. }
  17557. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17558. ProxyAndTargetServers s;
  17559. auto cli = make_client("Example.COM", s);
  17560. cli->set_no_proxy({"EXAMPLE.com"});
  17561. auto res = cli->Get("/");
  17562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17563. EXPECT_EQ(0, s.proxy_hits());
  17564. EXPECT_EQ(1, s.target_hits());
  17565. }
  17566. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17567. ProxyAndTargetServers s;
  17568. auto cli = make_client("example.com.", s);
  17569. cli->set_no_proxy({"example.com"});
  17570. auto res = cli->Get("/");
  17571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17572. EXPECT_EQ(0, s.proxy_hits());
  17573. EXPECT_EQ(1, s.target_hits());
  17574. }
  17575. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17576. // Trailing dots must be normalized on BOTH sides — host and entry.
  17577. // An implementation that only strips the host-side trailing dot would
  17578. // fail to match host "example.com" against entry "example.com." because
  17579. // a literal substring search would compare 11 chars against 12.
  17580. ProxyAndTargetServers s;
  17581. auto cli = make_client("example.com", s);
  17582. cli->set_no_proxy({"example.com."});
  17583. auto res = cli->Get("/");
  17584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17585. EXPECT_EQ(0, s.proxy_hits());
  17586. EXPECT_EQ(1, s.target_hits());
  17587. }
  17588. TEST(NoProxyTest, WildcardBypassesEverything) {
  17589. ProxyAndTargetServers s;
  17590. auto cli = make_client("anything.invalid.test", s);
  17591. cli->set_no_proxy({"*"});
  17592. auto res = cli->Get("/");
  17593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17594. EXPECT_EQ(0, s.proxy_hits());
  17595. EXPECT_EQ(1, s.target_hits());
  17596. }
  17597. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17598. ProxyAndTargetServers s;
  17599. Client cli("127.0.0.1", s.target_port());
  17600. cli.set_proxy("127.0.0.1", s.proxy_port());
  17601. cli.set_no_proxy({"127.0.0.1"});
  17602. auto res = cli.Get("/");
  17603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17604. EXPECT_EQ(0, s.proxy_hits());
  17605. EXPECT_EQ(1, s.target_hits());
  17606. }
  17607. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17608. ProxyAndTargetServers s;
  17609. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17610. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17611. cli.set_proxy("127.0.0.1", s.proxy_port());
  17612. cli.set_no_proxy({"::1"});
  17613. auto res = cli.Get("/");
  17614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17615. EXPECT_EQ(0, s.proxy_hits());
  17616. EXPECT_EQ(1, s.target_hits());
  17617. }
  17618. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17619. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17620. // must still be recognized as IPv6 for CIDR matching. Implementations
  17621. // that detect IPv6 only when the host begins with '[' would parse the
  17622. // host as a hostname and miss the match.
  17623. ProxyAndTargetServers s;
  17624. Client cli("fe80::1", s.target_port());
  17625. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17626. cli.set_proxy("127.0.0.1", s.proxy_port());
  17627. cli.set_no_proxy({"fe80::/10"});
  17628. auto res = cli.Get("/");
  17629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17630. EXPECT_EQ(0, s.proxy_hits());
  17631. EXPECT_EQ(1, s.target_hits());
  17632. }
  17633. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17634. ProxyAndTargetServers s;
  17635. Client cli("::1", s.target_port());
  17636. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17637. cli.set_proxy("127.0.0.1", s.proxy_port());
  17638. cli.set_no_proxy({"[::1]"});
  17639. auto res = cli.Get("/");
  17640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17641. EXPECT_EQ(0, s.proxy_hits());
  17642. EXPECT_EQ(1, s.target_hits());
  17643. }
  17644. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17645. ProxyAndTargetServers s;
  17646. Client cli("fe80::1", s.target_port());
  17647. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17648. cli.set_proxy("127.0.0.1", s.proxy_port());
  17649. cli.set_no_proxy({"[fe80::]/10"});
  17650. auto res = cli.Get("/");
  17651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17652. EXPECT_EQ(0, s.proxy_hits());
  17653. EXPECT_EQ(1, s.target_hits());
  17654. }
  17655. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17656. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17657. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17658. // tricks via address-family conversion.
  17659. ProxyAndTargetServers s;
  17660. Client cli("::ffff:127.0.0.1", s.target_port());
  17661. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17662. cli.set_proxy("127.0.0.1", s.proxy_port());
  17663. cli.set_no_proxy({"127.0.0.1"});
  17664. auto res = cli.Get("/");
  17665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17666. EXPECT_GE(s.proxy_hits(), 1);
  17667. EXPECT_EQ(0, s.target_hits());
  17668. }
  17669. TEST(NoProxyTest, IPv4CidrMatch) {
  17670. ProxyAndTargetServers s;
  17671. Client cli("127.0.0.1", s.target_port());
  17672. cli.set_proxy("127.0.0.1", s.proxy_port());
  17673. cli.set_no_proxy({"127.0.0.0/8"});
  17674. auto res = cli.Get("/");
  17675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17676. EXPECT_EQ(0, s.proxy_hits());
  17677. EXPECT_EQ(1, s.target_hits());
  17678. }
  17679. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17680. ProxyAndTargetServers s;
  17681. Client cli("127.0.0.1", s.target_port());
  17682. cli.set_proxy("127.0.0.1", s.proxy_port());
  17683. cli.set_no_proxy({"10.0.0.0/8"});
  17684. auto res = cli.Get("/");
  17685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17686. EXPECT_GE(s.proxy_hits(), 1);
  17687. EXPECT_EQ(0, s.target_hits());
  17688. }
  17689. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17690. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17691. // IPv4 target matches.
  17692. ProxyAndTargetServers s;
  17693. Client cli("127.0.0.1", s.target_port());
  17694. cli.set_proxy("127.0.0.1", s.proxy_port());
  17695. cli.set_no_proxy({"0.0.0.0/0"});
  17696. auto res = cli.Get("/");
  17697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17698. EXPECT_EQ(0, s.proxy_hits());
  17699. EXPECT_EQ(1, s.target_hits());
  17700. }
  17701. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17702. ProxyAndTargetServers s;
  17703. Client cli("127.0.0.1", s.target_port());
  17704. cli.set_proxy("127.0.0.1", s.proxy_port());
  17705. cli.set_no_proxy({"127.0.0.1"});
  17706. auto res = cli.Get("/");
  17707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17708. EXPECT_EQ(0, s.proxy_hits());
  17709. EXPECT_EQ(1, s.target_hits());
  17710. }
  17711. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17712. ProxyAndTargetServers s;
  17713. Client cli("127.0.0.1", s.target_port());
  17714. cli.set_proxy("127.0.0.1", s.proxy_port());
  17715. cli.set_no_proxy({"127.0.0.0/33"});
  17716. auto res = cli.Get("/");
  17717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17718. EXPECT_GE(s.proxy_hits(), 1);
  17719. EXPECT_EQ(0, s.target_hits());
  17720. }
  17721. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17722. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17723. ProxyAndTargetServers s;
  17724. Client cli("127.0.0.1", s.target_port());
  17725. cli.set_proxy("127.0.0.1", s.proxy_port());
  17726. cli.set_no_proxy({"127.0.0.1/"});
  17727. auto res = cli.Get("/");
  17728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17729. EXPECT_GE(s.proxy_hits(), 1);
  17730. EXPECT_EQ(0, s.target_hits());
  17731. }
  17732. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17733. ProxyAndTargetServers s;
  17734. auto cli = make_client("internal.corp", s);
  17735. cli->set_proxy_basic_auth("u", "p");
  17736. cli->set_no_proxy({"internal.corp"});
  17737. auto res = cli->Get("/");
  17738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17739. EXPECT_EQ(1, s.target_hits());
  17740. EXPECT_EQ(0, s.proxy_hits());
  17741. EXPECT_FALSE(s.last_had_proxy_authz())
  17742. << "Proxy-Authorization must not be sent direct to the target";
  17743. }
  17744. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17745. ProxyAndTargetServers s;
  17746. auto cli = make_client("public.example", s);
  17747. cli->set_proxy_basic_auth("u", "p");
  17748. cli->set_no_proxy({"internal.corp"}); // does not match
  17749. auto res = cli->Get("/");
  17750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17751. EXPECT_GE(s.proxy_hits(), 1);
  17752. EXPECT_TRUE(s.last_had_proxy_authz());
  17753. }
  17754. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17755. ProxyAndTargetServers s;
  17756. auto cli = make_client("anything.test", s);
  17757. auto res = cli->Get("/");
  17758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17759. EXPECT_GE(s.proxy_hits(), 1);
  17760. EXPECT_EQ(0, s.target_hits());
  17761. }
  17762. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17763. ProxyAndTargetServers s;
  17764. auto cli = make_client("example.com", s);
  17765. cli->set_no_proxy({"example.com:8080"});
  17766. auto res = cli->Get("/");
  17767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17768. EXPECT_GE(s.proxy_hits(), 1);
  17769. EXPECT_EQ(0, s.target_hits());
  17770. }
  17771. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17772. ProxyAndTargetServers s;
  17773. auto cli = make_client("anything.test", s);
  17774. cli->set_no_proxy({"", " ", "\t"});
  17775. auto res = cli->Get("/");
  17776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17777. EXPECT_GE(s.proxy_hits(), 1);
  17778. EXPECT_EQ(0, s.target_hits());
  17779. }
  17780. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17781. // An entry with leading/trailing whitespace must still match — env-style
  17782. // values are commonly pasted with stray spaces and an implementation
  17783. // that feeds the raw token directly to inet_pton would fail to match
  17784. // valid CIDRs because of the spaces.
  17785. ProxyAndTargetServers s;
  17786. Client cli("127.0.0.1", s.target_port());
  17787. cli.set_proxy("127.0.0.1", s.proxy_port());
  17788. cli.set_no_proxy({" 127.0.0.0/8 "});
  17789. auto res = cli.Get("/");
  17790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17791. EXPECT_EQ(0, s.proxy_hits());
  17792. EXPECT_EQ(1, s.target_hits());
  17793. }
  17794. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17795. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17796. // go direct and must NOT carry Proxy-Authorization.
  17797. std::atomic<int> proxy_hits{0};
  17798. std::atomic<int> target_hits{0};
  17799. std::atomic<bool> target_saw_authz{false};
  17800. no_proxy_test::ScopedServer proxy_mock, target;
  17801. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17802. proxy_hits++;
  17803. res.status = 302;
  17804. res.set_header("Location", "http://127.0.0.1:" +
  17805. std::to_string(target.port()) + "/landed");
  17806. });
  17807. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17808. target_hits++;
  17809. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17810. res.set_content("direct", "text/plain");
  17811. });
  17812. proxy_mock.listen();
  17813. target.listen();
  17814. Client cli("public.example", target.port());
  17815. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17816. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17817. cli.set_proxy_basic_auth("u", "p");
  17818. cli.set_no_proxy({"127.0.0.1"});
  17819. cli.set_follow_location(true);
  17820. auto res = cli.Get("/redir");
  17821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17822. EXPECT_GE(proxy_hits.load(), 1);
  17823. EXPECT_GE(target_hits.load(), 1);
  17824. EXPECT_FALSE(target_saw_authz.load());
  17825. }
  17826. #ifdef CPPHTTPLIB_SSL_ENABLED
  17827. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17828. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17829. // proxy creds would be sent to the (possibly hostile) origin.
  17830. std::atomic<int> target_hits{0};
  17831. std::atomic<bool> target_saw_proxy_authz{false};
  17832. no_proxy_test::ScopedServer target;
  17833. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17834. target_hits++;
  17835. if (req.has_header("Proxy-Authorization")) {
  17836. target_saw_proxy_authz = true;
  17837. }
  17838. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17839. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17840. "nonce=\"abc\", algorithm=MD5");
  17841. });
  17842. target.listen();
  17843. // The proxy address is set to the target's port: the bypass MUST kick in;
  17844. // if it doesn't, the test still routes "via proxy" to the same server and
  17845. // the Proxy-Authorization assertion below catches the leak.
  17846. Client cli("evil.example", target.port());
  17847. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17848. cli.set_proxy("127.0.0.1", target.port());
  17849. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17850. cli.set_no_proxy({"evil.example"});
  17851. auto res = cli.Get("/x");
  17852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17853. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17854. EXPECT_EQ(1, target_hits.load());
  17855. EXPECT_FALSE(target_saw_proxy_authz.load());
  17856. }
  17857. #endif
  17858. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17859. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17860. std::atomic<int> proxy_hits{0};
  17861. std::atomic<int> bypass_hits{0};
  17862. std::atomic<bool> proxy_saw_c_url{false};
  17863. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17864. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17865. proxy_hits++;
  17866. if (req.path.find("/start") != std::string::npos) {
  17867. res.status = 302;
  17868. res.set_header("Location", "http://127.0.0.1:" +
  17869. std::to_string(bypass_server.port()) +
  17870. "/middle");
  17871. return;
  17872. }
  17873. if (req.path.find("/end") != std::string::npos) {
  17874. proxy_saw_c_url = true;
  17875. res.set_content("c-via-proxy", "text/plain");
  17876. return;
  17877. }
  17878. res.set_content("unexpected", "text/plain");
  17879. });
  17880. // public.example's "advertised" port is arbitrary (the request never lands
  17881. // there — it goes through the proxy), but use a dynamic value to stay
  17882. // friendly with sharded parallel runs.
  17883. int public_port = bypass_server.port();
  17884. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17885. bypass_hits++;
  17886. res.status = 302;
  17887. res.set_header("Location", "http://public.example:" +
  17888. std::to_string(public_port) + "/end");
  17889. });
  17890. proxy_mock.listen();
  17891. bypass_server.listen();
  17892. Client cli("public.example", public_port);
  17893. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17894. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17895. cli.set_no_proxy({"127.0.0.1"});
  17896. cli.set_follow_location(true);
  17897. auto res = cli.Get("/start");
  17898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17899. EXPECT_EQ(StatusCode::OK_200, res->status);
  17900. EXPECT_EQ("c-via-proxy", res->body);
  17901. EXPECT_GE(proxy_hits.load(), 2);
  17902. EXPECT_GE(bypass_hits.load(), 1);
  17903. EXPECT_TRUE(proxy_saw_c_url.load());
  17904. }
  17905. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17906. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17907. // request reconnects to the correct endpoint.
  17908. std::atomic<int> proxy_hits{0};
  17909. std::atomic<int> target_hits{0};
  17910. no_proxy_test::ScopedServer proxy_mock, target;
  17911. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17912. proxy_hits++;
  17913. res.set_content("via-proxy", "text/plain");
  17914. });
  17915. target.svr().Get(".*", [&](const Request &, Response &res) {
  17916. target_hits++;
  17917. res.set_content("direct", "text/plain");
  17918. });
  17919. proxy_mock.listen();
  17920. target.listen();
  17921. Client cli("public.example", target.port());
  17922. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17923. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17924. cli.set_keep_alive(true);
  17925. auto res1 = cli.Get("/a");
  17926. ASSERT_TRUE(res1);
  17927. EXPECT_EQ("via-proxy", res1->body);
  17928. EXPECT_EQ(1, proxy_hits.load());
  17929. EXPECT_EQ(0, target_hits.load());
  17930. cli.set_no_proxy({"public.example"});
  17931. auto res2 = cli.Get("/b");
  17932. ASSERT_TRUE(res2);
  17933. EXPECT_EQ("direct", res2->body);
  17934. EXPECT_EQ(1, proxy_hits.load());
  17935. EXPECT_EQ(1, target_hits.load());
  17936. }
  17937. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17938. namespace proxy_tunnel_test {
  17939. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17940. class ScopedSSLServer {
  17941. public:
  17942. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17943. port_ = svr_.bind_to_any_port("127.0.0.1");
  17944. }
  17945. ~ScopedSSLServer() {
  17946. svr_.stop();
  17947. if (th_.joinable()) { th_.join(); }
  17948. }
  17949. SSLServer &svr() { return svr_; }
  17950. int port() const { return port_; }
  17951. void listen() {
  17952. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17953. svr_.wait_until_ready();
  17954. }
  17955. private:
  17956. SSLServer svr_;
  17957. std::thread th_;
  17958. int port_ = 0;
  17959. };
  17960. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17961. class ScopedConnectProxy {
  17962. public:
  17963. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17964. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17965. if (listen_fd_ < 0) { return; }
  17966. int yes = 1;
  17967. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17968. sockaddr_in a{};
  17969. a.sin_family = AF_INET;
  17970. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17971. a.sin_port = 0;
  17972. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17973. return;
  17974. }
  17975. socklen_t alen = sizeof(a);
  17976. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17977. 0) {
  17978. return;
  17979. }
  17980. port_ = ntohs(a.sin_port);
  17981. if (::listen(listen_fd_, 1) != 0) { return; }
  17982. th_ = std::thread([this] { run(); });
  17983. }
  17984. ~ScopedConnectProxy() {
  17985. stop_ = true;
  17986. if (listen_fd_ >= 0) {
  17987. ::shutdown(listen_fd_, SHUT_RDWR);
  17988. ::close(listen_fd_);
  17989. }
  17990. if (th_.joinable()) { th_.join(); }
  17991. }
  17992. int port() const { return port_; }
  17993. int connect_hits() const { return connect_hits_.load(); }
  17994. private:
  17995. void run() {
  17996. while (!stop_.load()) {
  17997. fd_set rfds;
  17998. FD_ZERO(&rfds);
  17999. FD_SET(listen_fd_, &rfds);
  18000. timeval tv{0, 100 * 1000};
  18001. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  18002. if (sel <= 0) { continue; }
  18003. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18004. if (client_fd < 0) { continue; }
  18005. std::string req;
  18006. char buf[2048];
  18007. while (req.find("\r\n\r\n") == std::string::npos) {
  18008. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18009. if (n <= 0) { break; }
  18010. req.append(buf, static_cast<size_t>(n));
  18011. }
  18012. if (req.compare(0, 7, "CONNECT") != 0) {
  18013. ::close(client_fd);
  18014. continue;
  18015. }
  18016. connect_hits_++;
  18017. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18018. ::send(client_fd, ok, std::strlen(ok), 0);
  18019. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18020. sockaddr_in o{};
  18021. o.sin_family = AF_INET;
  18022. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18023. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18024. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18025. 0) {
  18026. ::close(client_fd);
  18027. ::close(origin_fd);
  18028. continue;
  18029. }
  18030. auto forward = [](int from, int to) {
  18031. char b[8192];
  18032. for (;;) {
  18033. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18034. if (n <= 0) { break; }
  18035. ssize_t off = 0;
  18036. while (off < n) {
  18037. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18038. if (s <= 0) {
  18039. off = n;
  18040. break;
  18041. }
  18042. off += s;
  18043. }
  18044. }
  18045. ::shutdown(to, SHUT_WR);
  18046. };
  18047. std::thread t1([&] { forward(client_fd, origin_fd); });
  18048. std::thread t2([&] { forward(origin_fd, client_fd); });
  18049. t1.join();
  18050. t2.join();
  18051. ::close(client_fd);
  18052. ::close(origin_fd);
  18053. }
  18054. }
  18055. int forward_port_ = -1;
  18056. int listen_fd_ = -1;
  18057. int port_ = 0;
  18058. std::thread th_;
  18059. std::atomic<bool> stop_{false};
  18060. std::atomic<int> connect_hits_{0};
  18061. };
  18062. } // namespace proxy_tunnel_test
  18063. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18064. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18065. // retry; otherwise proxy creds would be sent to the origin.
  18066. std::atomic<int> origin_hits{0};
  18067. std::atomic<bool> origin_saw_proxy_authz{false};
  18068. proxy_tunnel_test::ScopedSSLServer origin;
  18069. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18070. origin_hits++;
  18071. if (req.has_header("Proxy-Authorization")) {
  18072. origin_saw_proxy_authz = true;
  18073. }
  18074. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18075. res.set_header("Proxy-Authenticate",
  18076. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18077. "algorithm=MD5");
  18078. });
  18079. origin.listen();
  18080. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18081. ASSERT_NE(0, proxy.port());
  18082. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18083. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18084. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18085. // and answer with its own status, making this test flaky.
  18086. SSLClient cli("127.0.0.1", origin.port());
  18087. cli.enable_server_certificate_verification(false);
  18088. cli.set_proxy("127.0.0.1", proxy.port());
  18089. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18090. auto res = cli.Get("/x");
  18091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18092. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18093. EXPECT_EQ(1, origin_hits.load());
  18094. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18095. EXPECT_EQ(1, proxy.connect_hits());
  18096. }
  18097. #endif