test.cc 689 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643
  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. res.set_content_provider(
  3777. data->size(), "text/plain",
  3778. [data](size_t offset, size_t length, DataSink &sink) {
  3779. size_t DATA_CHUNK_SIZE = 4;
  3780. const auto &d = *data;
  3781. auto out_len =
  3782. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3783. auto ret =
  3784. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3785. EXPECT_TRUE(ret);
  3786. return true;
  3787. },
  3788. [data, &req](bool success) {
  3789. EXPECT_EQ(success, !req.has_param("error"));
  3790. delete data;
  3791. });
  3792. })
  3793. .Get("/streamed-with-range-and-error-status",
  3794. [&](const Request & /*req*/, Response &res) {
  3795. auto data = new std::string("abcdefg");
  3796. res.status = StatusCode::Forbidden_403;
  3797. res.set_content_provider(
  3798. data->size(), "text/plain",
  3799. [data](size_t offset, size_t length, DataSink &sink) {
  3800. size_t DATA_CHUNK_SIZE = 4;
  3801. const auto &d = *data;
  3802. auto out_len =
  3803. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3804. auto ret =
  3805. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3806. EXPECT_TRUE(ret);
  3807. return true;
  3808. },
  3809. [data](bool /*success*/) { delete data; });
  3810. })
  3811. .Get("/streamed-cancel",
  3812. [&](const Request & /*req*/, Response &res) {
  3813. res.set_content_provider(
  3814. size_t(-1), "text/plain",
  3815. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3816. sink.os << "data_chunk";
  3817. return true;
  3818. });
  3819. })
  3820. .Get("/regex-with-delimiter",
  3821. [&](const Request &req, Response & /*res*/) {
  3822. ASSERT_TRUE(req.has_param("key"));
  3823. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3824. })
  3825. .Get("/with-range",
  3826. [&](const Request & /*req*/, Response &res) {
  3827. res.set_content("abcdefg", "text/plain");
  3828. })
  3829. .Get("/test-start-time",
  3830. [&](const Request &req, Response & /*res*/) {
  3831. EXPECT_NE(req.start_time_,
  3832. std::chrono::steady_clock::time_point::min());
  3833. })
  3834. .Get("/with-range-customized-response",
  3835. [&](const Request & /*req*/, Response &res) {
  3836. res.status = StatusCode::BadRequest_400;
  3837. res.set_content(JSON_DATA, "application/json");
  3838. })
  3839. .Post("/chunked",
  3840. [&](const Request &req, Response & /*res*/) {
  3841. EXPECT_EQ(req.body, "dechunked post body");
  3842. })
  3843. .Post("/large-chunked",
  3844. [&](const Request &req, Response & /*res*/) {
  3845. std::string expected(6 * 30 * 1024u, 'a');
  3846. EXPECT_EQ(req.body, expected);
  3847. })
  3848. .Post("/multipart",
  3849. [&](const Request &req, Response & /*res*/) {
  3850. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3851. req.form.get_field_count("text2") +
  3852. req.form.get_field_count("file3") +
  3853. req.form.get_field_count("file4"));
  3854. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3855. req.form.get_file_count("file2"));
  3856. ASSERT_TRUE(!req.form.has_file("???"));
  3857. ASSERT_TRUE(!req.form.has_field("???"));
  3858. ASSERT_TRUE(req.body.empty());
  3859. {
  3860. const auto &text = req.form.get_field("text1");
  3861. EXPECT_EQ("text default", text);
  3862. }
  3863. {
  3864. const auto &text = req.form.get_field("text2");
  3865. EXPECT_EQ("aωb", text);
  3866. }
  3867. {
  3868. const auto &file = req.form.get_file("file1");
  3869. EXPECT_EQ("hello.txt", file.filename);
  3870. EXPECT_EQ("text/plain", file.content_type);
  3871. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3872. }
  3873. {
  3874. const auto &file = req.form.get_file("file2");
  3875. EXPECT_EQ("world.json", file.filename);
  3876. EXPECT_EQ("application/json", file.content_type);
  3877. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3878. }
  3879. {
  3880. const auto &text = req.form.get_field("file3");
  3881. EXPECT_EQ(0u, text.size());
  3882. }
  3883. {
  3884. const auto &text = req.form.get_field("file4");
  3885. EXPECT_EQ(0u, text.size());
  3886. }
  3887. })
  3888. .Post("/multipart/multi_file_values",
  3889. [&](const Request &req, Response & /*res*/) {
  3890. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3891. req.form.get_field_count("multi_text1"));
  3892. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3893. ASSERT_TRUE(!req.form.has_file("???"));
  3894. ASSERT_TRUE(!req.form.has_field("???"));
  3895. ASSERT_TRUE(req.body.empty());
  3896. {
  3897. const auto &text = req.form.get_field("text");
  3898. EXPECT_EQ("default text", text);
  3899. }
  3900. {
  3901. const auto &text1_values = req.form.get_fields("multi_text1");
  3902. EXPECT_EQ(2u, text1_values.size());
  3903. EXPECT_EQ("aaaaa", text1_values[0]);
  3904. EXPECT_EQ("bbbbb", text1_values[1]);
  3905. }
  3906. {
  3907. const auto &file1_values = req.form.get_files("multi_file1");
  3908. EXPECT_EQ(2u, file1_values.size());
  3909. auto file1 = file1_values[0];
  3910. EXPECT_EQ(file1.filename, "hello.txt");
  3911. EXPECT_EQ(file1.content_type, "text/plain");
  3912. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3913. auto file2 = file1_values[1];
  3914. EXPECT_EQ(file2.filename, "world.json");
  3915. EXPECT_EQ(file2.content_type, "application/json");
  3916. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3917. }
  3918. })
  3919. .Post("/empty",
  3920. [&](const Request &req, Response &res) {
  3921. EXPECT_EQ(req.body, "");
  3922. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3923. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3924. res.set_content("empty", "text/plain");
  3925. })
  3926. .Post("/empty-no-content-type",
  3927. [&](const Request &req, Response &res) {
  3928. EXPECT_EQ(req.body, "");
  3929. EXPECT_FALSE(req.has_header("Content-Type"));
  3930. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3931. res.set_content("empty-no-content-type", "text/plain");
  3932. })
  3933. .Post("/path-only",
  3934. [&](const Request &req, Response &res) {
  3935. EXPECT_EQ(req.body, "");
  3936. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3937. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3938. res.set_content("path-only", "text/plain");
  3939. })
  3940. .Post("/path-headers-only",
  3941. [&](const Request &req, Response &res) {
  3942. EXPECT_EQ(req.body, "");
  3943. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3944. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3945. EXPECT_EQ("world", req.get_header_value("hello"));
  3946. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3947. res.set_content("path-headers-only", "text/plain");
  3948. })
  3949. .Post("/post-large",
  3950. [&](const Request &req, Response &res) {
  3951. EXPECT_EQ(req.body, LARGE_DATA);
  3952. res.set_content(req.body, "text/plain");
  3953. })
  3954. .Post("/post-loopback",
  3955. [&](const Request &, Response &res,
  3956. ContentReader const &content_reader) {
  3957. std::string body;
  3958. content_reader([&](const char *data, size_t data_length) {
  3959. body.append(data, data_length);
  3960. return true;
  3961. });
  3962. res.set_content(body, "text/plain");
  3963. })
  3964. .Put("/put-loopback",
  3965. [&](const Request &, Response &res,
  3966. ContentReader const &content_reader) {
  3967. std::string body;
  3968. content_reader([&](const char *data, size_t data_length) {
  3969. body.append(data, data_length);
  3970. return true;
  3971. });
  3972. res.set_content(body, "text/plain");
  3973. })
  3974. .Patch("/patch-loopback",
  3975. [&](const Request &, Response &res,
  3976. ContentReader const &content_reader) {
  3977. std::string body;
  3978. content_reader([&](const char *data, size_t data_length) {
  3979. body.append(data, data_length);
  3980. return true;
  3981. });
  3982. res.set_content(body, "text/plain");
  3983. })
  3984. .Put("/empty-no-content-type",
  3985. [&](const Request &req, Response &res) {
  3986. EXPECT_EQ(req.body, "");
  3987. EXPECT_FALSE(req.has_header("Content-Type"));
  3988. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3989. res.set_content("empty-no-content-type", "text/plain");
  3990. })
  3991. .Put("/put",
  3992. [&](const Request &req, Response &res) {
  3993. EXPECT_EQ(req.body, "PUT");
  3994. res.set_content(req.body, "text/plain");
  3995. })
  3996. .Put("/put-large",
  3997. [&](const Request &req, Response &res) {
  3998. EXPECT_EQ(req.body, LARGE_DATA);
  3999. res.set_content(req.body, "text/plain");
  4000. })
  4001. .Patch("/patch",
  4002. [&](const Request &req, Response &res) {
  4003. EXPECT_EQ(req.body, "PATCH");
  4004. res.set_content(req.body, "text/plain");
  4005. })
  4006. .Delete("/delete",
  4007. [&](const Request & /*req*/, Response &res) {
  4008. res.set_content("DELETE", "text/plain");
  4009. })
  4010. .Delete("/delete-body",
  4011. [&](const Request &req, Response &res) {
  4012. EXPECT_EQ(req.body, "content");
  4013. res.set_content(req.body, "text/plain");
  4014. })
  4015. .Options(R"(\*)",
  4016. [&](const Request & /*req*/, Response &res) {
  4017. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4018. })
  4019. .Get("/request-target",
  4020. [&](const Request &req, Response & /*res*/) {
  4021. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4022. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4023. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4024. })
  4025. .Get("/long-query-value",
  4026. [&](const Request &req, Response & /*res*/) {
  4027. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4028. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4029. })
  4030. .Get("/too-long-query-value",
  4031. [&](const Request &req, Response & /*res*/) {
  4032. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4033. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4034. })
  4035. .Get("/array-param",
  4036. [&](const Request &req, Response & /*res*/) {
  4037. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4038. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4039. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4040. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4041. })
  4042. .Get("/array-param-values",
  4043. [&](const Request &req, Response & /*res*/) {
  4044. auto values = req.get_param_values("array");
  4045. EXPECT_EQ(3u, values.size());
  4046. EXPECT_EQ("value1", values[0]);
  4047. EXPECT_EQ("value2", values[1]);
  4048. EXPECT_EQ("value3", values[2]);
  4049. auto empty = req.get_param_values("nonexistent");
  4050. EXPECT_TRUE(empty.empty());
  4051. })
  4052. .Post("/validate-no-multiple-headers",
  4053. [&](const Request &req, Response & /*res*/) {
  4054. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4055. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4056. })
  4057. .Post("/content_receiver",
  4058. [&](const Request &req, Response &res,
  4059. const ContentReader &content_reader) {
  4060. if (req.is_multipart_form_data()) {
  4061. std::vector<FormData> items;
  4062. content_reader(
  4063. [&](const FormData &file) {
  4064. items.push_back(file);
  4065. return true;
  4066. },
  4067. [&](const char *data, size_t data_length) {
  4068. items.back().content.append(data, data_length);
  4069. return true;
  4070. });
  4071. EXPECT_EQ(5u, items.size());
  4072. {
  4073. const auto &file = get_file_value(items, "text1");
  4074. EXPECT_TRUE(file.filename.empty());
  4075. EXPECT_EQ("text default", file.content);
  4076. }
  4077. {
  4078. const auto &file = get_file_value(items, "text2");
  4079. EXPECT_TRUE(file.filename.empty());
  4080. EXPECT_EQ("aωb", file.content);
  4081. }
  4082. {
  4083. const auto &file = get_file_value(items, "file1");
  4084. EXPECT_EQ("hello.txt", file.filename);
  4085. EXPECT_EQ("text/plain", file.content_type);
  4086. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4087. }
  4088. {
  4089. const auto &file = get_file_value(items, "file2");
  4090. EXPECT_EQ("world.json", file.filename);
  4091. EXPECT_EQ("application/json", file.content_type);
  4092. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4093. }
  4094. {
  4095. const auto &file = get_file_value(items, "file3");
  4096. EXPECT_TRUE(file.filename.empty());
  4097. EXPECT_EQ("application/octet-stream", file.content_type);
  4098. EXPECT_EQ(0u, file.content.size());
  4099. }
  4100. } else {
  4101. std::string body;
  4102. content_reader([&](const char *data, size_t data_length) {
  4103. EXPECT_EQ(7U, data_length);
  4104. body.append(data, data_length);
  4105. return true;
  4106. });
  4107. EXPECT_EQ(body, "content");
  4108. res.set_content(body, "text/plain");
  4109. }
  4110. })
  4111. .Put("/content_receiver",
  4112. [&](const Request & /*req*/, Response &res,
  4113. const ContentReader &content_reader) {
  4114. std::string body;
  4115. content_reader([&](const char *data, size_t data_length) {
  4116. body.append(data, data_length);
  4117. return true;
  4118. });
  4119. EXPECT_EQ(body, "content");
  4120. res.set_content(body, "text/plain");
  4121. })
  4122. .Patch("/content_receiver",
  4123. [&](const Request & /*req*/, Response &res,
  4124. const ContentReader &content_reader) {
  4125. std::string body;
  4126. content_reader([&](const char *data, size_t data_length) {
  4127. body.append(data, data_length);
  4128. return true;
  4129. });
  4130. EXPECT_EQ(body, "content");
  4131. res.set_content(body, "text/plain");
  4132. })
  4133. .Post("/query-string-and-body",
  4134. [&](const Request &req, Response & /*res*/) {
  4135. ASSERT_TRUE(req.has_param("key"));
  4136. EXPECT_EQ(req.get_param_value("key"), "value");
  4137. EXPECT_EQ(req.body, "content");
  4138. })
  4139. .Get("/last-request",
  4140. [&](const Request &req, Response & /*res*/) {
  4141. EXPECT_EQ("close", req.get_header_value("Connection"));
  4142. })
  4143. .Get(R"(/redirect/(\d+))",
  4144. [&](const Request &req, Response &res) {
  4145. auto num = std::stoi(req.matches[1]) + 1;
  4146. std::string url = "/redirect/" + std::to_string(num);
  4147. res.set_redirect(url);
  4148. })
  4149. .Post("/binary",
  4150. [&](const Request &req, Response &res) {
  4151. EXPECT_EQ(4U, req.body.size());
  4152. EXPECT_EQ("application/octet-stream",
  4153. req.get_header_value("Content-Type"));
  4154. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4155. res.set_content(req.body, "application/octet-stream");
  4156. })
  4157. .Put("/binary",
  4158. [&](const Request &req, Response &res) {
  4159. EXPECT_EQ(4U, req.body.size());
  4160. EXPECT_EQ("application/octet-stream",
  4161. req.get_header_value("Content-Type"));
  4162. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4163. res.set_content(req.body, "application/octet-stream");
  4164. })
  4165. .Patch("/binary",
  4166. [&](const Request &req, Response &res) {
  4167. EXPECT_EQ(4U, req.body.size());
  4168. EXPECT_EQ("application/octet-stream",
  4169. req.get_header_value("Content-Type"));
  4170. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4171. res.set_content(req.body, "application/octet-stream");
  4172. })
  4173. .Delete("/binary",
  4174. [&](const Request &req, Response &res) {
  4175. EXPECT_EQ(4U, req.body.size());
  4176. EXPECT_EQ("application/octet-stream",
  4177. req.get_header_value("Content-Type"));
  4178. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4179. res.set_content(req.body, "application/octet-stream");
  4180. })
  4181. .Get("/issue1772",
  4182. [&](const Request & /*req*/, Response &res) {
  4183. res.status = 401;
  4184. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4185. })
  4186. .Delete("/issue609",
  4187. [](const httplib::Request &, httplib::Response &res,
  4188. const httplib::ContentReader &) {
  4189. res.set_content("ok", "text/plain");
  4190. })
  4191. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4192. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4193. .Get("/compress",
  4194. [&](const Request & /*req*/, Response &res) {
  4195. res.set_content(
  4196. "12345678901234567890123456789012345678901234567890123456789"
  4197. "01234567890123456789012345678901234567890",
  4198. "text/plain");
  4199. })
  4200. .Get("/compress-with-charset",
  4201. [&](const Request & /*req*/, Response &res) {
  4202. res.set_content(
  4203. "12345678901234567890123456789012345678901234567890123456789"
  4204. "01234567890123456789012345678901234567890",
  4205. "application/json; charset=utf-8");
  4206. })
  4207. .Get("/nocompress",
  4208. [&](const Request & /*req*/, Response &res) {
  4209. res.set_content(
  4210. "12345678901234567890123456789012345678901234567890123456789"
  4211. "01234567890123456789012345678901234567890",
  4212. "application/octet-stream");
  4213. })
  4214. .Post("/compress-multipart",
  4215. [&](const Request &req, Response & /*res*/) {
  4216. EXPECT_EQ(2u, req.form.fields.size());
  4217. ASSERT_TRUE(!req.form.has_field("???"));
  4218. {
  4219. const auto &text = req.form.get_field("key1");
  4220. EXPECT_EQ("test", text);
  4221. }
  4222. {
  4223. const auto &text = req.form.get_field("key2");
  4224. EXPECT_EQ("--abcdefg123", text);
  4225. }
  4226. })
  4227. #endif
  4228. ;
  4229. persons_["john"] = "programmer";
  4230. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4231. svr_.wait_until_ready();
  4232. }
  4233. virtual void TearDown() {
  4234. svr_.stop();
  4235. if (!request_threads_.empty()) {
  4236. std::this_thread::sleep_for(std::chrono::seconds(1));
  4237. for (auto &t : request_threads_) {
  4238. t.join();
  4239. }
  4240. }
  4241. t_.join();
  4242. }
  4243. map<string, string> persons_;
  4244. #ifdef CPPHTTPLIB_SSL_ENABLED
  4245. SSLClient cli_;
  4246. SSLServer svr_;
  4247. #else
  4248. Client cli_;
  4249. Server svr_;
  4250. #endif
  4251. thread t_;
  4252. std::vector<thread> request_threads_;
  4253. };
  4254. TEST_F(ServerTest, GetMethod200) {
  4255. auto res = cli_.Get("/hi");
  4256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4257. EXPECT_EQ("HTTP/1.1", res->version);
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("OK", res->reason);
  4260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4261. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4262. EXPECT_EQ("Hello World!", res->body);
  4263. }
  4264. TEST_F(ServerTest, GetEmptyFile) {
  4265. auto res = cli_.Get("/empty_file");
  4266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4267. EXPECT_EQ(StatusCode::OK_200, res->status);
  4268. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4269. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4270. EXPECT_EQ("", res->body);
  4271. }
  4272. TEST_F(ServerTest, GetFileContent) {
  4273. auto res = cli_.Get("/file_content");
  4274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4275. EXPECT_EQ(StatusCode::OK_200, res->status);
  4276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4277. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4278. EXPECT_EQ("test.html", res->body);
  4279. }
  4280. TEST_F(ServerTest, GetFileContentWithRange) {
  4281. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4283. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4284. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4285. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4286. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4287. EXPECT_EQ("est", res->body);
  4288. }
  4289. TEST_F(ServerTest, GetFileContentWithContentType) {
  4290. auto res = cli_.Get("/file_content_with_content_type");
  4291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4292. EXPECT_EQ(StatusCode::OK_200, res->status);
  4293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4294. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4295. EXPECT_EQ("file\n", res->body);
  4296. }
  4297. TEST_F(ServerTest, GetInvalidFileContent) {
  4298. auto res = cli_.Get("/invalid_file_content");
  4299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4300. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4301. }
  4302. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4303. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4305. EXPECT_EQ("HTTP/1.1", res->version);
  4306. EXPECT_EQ(StatusCode::OK_200, res->status);
  4307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4308. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4309. EXPECT_EQ("Hello World!", res->body);
  4310. }
  4311. TEST_F(ServerTest, GetMethod302) {
  4312. auto res = cli_.Get("/");
  4313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4314. EXPECT_EQ(StatusCode::Found_302, res->status);
  4315. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4316. }
  4317. TEST_F(ServerTest, GetMethod302Redirect) {
  4318. cli_.set_follow_location(true);
  4319. auto res = cli_.Get("/");
  4320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4321. EXPECT_EQ(StatusCode::OK_200, res->status);
  4322. EXPECT_EQ("Hello World!", res->body);
  4323. EXPECT_EQ("/hi", res->location);
  4324. }
  4325. TEST_F(ServerTest, GetMethod404) {
  4326. auto res = cli_.Get("/invalid");
  4327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4329. }
  4330. TEST_F(ServerTest, HeadMethod200) {
  4331. auto res = cli_.Head("/hi");
  4332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4335. EXPECT_TRUE(res->body.empty());
  4336. }
  4337. TEST_F(ServerTest, HeadMethod200Static) {
  4338. auto res = cli_.Head("/mount/dir/index.html");
  4339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4342. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4343. EXPECT_TRUE(res->body.empty());
  4344. }
  4345. TEST_F(ServerTest, HeadMethod404) {
  4346. auto res = cli_.Head("/invalid");
  4347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4349. EXPECT_TRUE(res->body.empty());
  4350. }
  4351. TEST_F(ServerTest, GetMethodPersonJohn) {
  4352. auto res = cli_.Get("/person/john");
  4353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4354. EXPECT_EQ(StatusCode::OK_200, res->status);
  4355. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4356. EXPECT_EQ("programmer", res->body);
  4357. }
  4358. TEST_F(ServerTest, PostMethod1) {
  4359. auto res = cli_.Get("/person/john1");
  4360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4361. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4362. res = cli_.Post("/person", "name=john1&note=coder",
  4363. "application/x-www-form-urlencoded");
  4364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4365. ASSERT_EQ(StatusCode::OK_200, res->status);
  4366. res = cli_.Get("/person/john1");
  4367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4368. ASSERT_EQ(StatusCode::OK_200, res->status);
  4369. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4370. ASSERT_EQ("coder", res->body);
  4371. }
  4372. TEST_F(ServerTest, PostMethod2) {
  4373. auto res = cli_.Get("/person/john2");
  4374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4375. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4376. Params params;
  4377. params.emplace("name", "john2");
  4378. params.emplace("note", "coder");
  4379. res = cli_.Post("/person", params);
  4380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4381. ASSERT_EQ(StatusCode::OK_200, res->status);
  4382. res = cli_.Get("/person/john2");
  4383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4384. ASSERT_EQ(StatusCode::OK_200, res->status);
  4385. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4386. ASSERT_EQ("coder", res->body);
  4387. }
  4388. TEST_F(ServerTest, PutMethod3) {
  4389. auto res = cli_.Get("/person/john3");
  4390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4391. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4392. Params params;
  4393. params.emplace("name", "john3");
  4394. params.emplace("note", "coder");
  4395. res = cli_.Put("/person", params);
  4396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4397. ASSERT_EQ(StatusCode::OK_200, res->status);
  4398. res = cli_.Get("/person/john3");
  4399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4400. ASSERT_EQ(StatusCode::OK_200, res->status);
  4401. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4402. ASSERT_EQ("coder", res->body);
  4403. }
  4404. TEST_F(ServerTest, DeleteMethod1) {
  4405. auto res = cli_.Get("/person/john4");
  4406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4407. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4408. Params params;
  4409. params.emplace("name", "john4");
  4410. params.emplace("note", "coder");
  4411. res = cli_.Post("/person", params);
  4412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4413. ASSERT_EQ(StatusCode::OK_200, res->status);
  4414. res = cli_.Get("/person/john4");
  4415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4416. ASSERT_EQ(StatusCode::OK_200, res->status);
  4417. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4418. ASSERT_EQ("coder", res->body);
  4419. Params delete_params;
  4420. delete_params.emplace("name", "john4");
  4421. res = cli_.Delete("/person", delete_params);
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. ASSERT_EQ(StatusCode::OK_200, res->status);
  4424. ASSERT_EQ("DELETED", res->body);
  4425. res = cli_.Get("/person/john4");
  4426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4427. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4428. }
  4429. TEST_F(ServerTest, DeleteMethod2) {
  4430. auto res = cli_.Get("/person/john5");
  4431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4432. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4433. Params params;
  4434. params.emplace("name", "john5");
  4435. params.emplace("note", "developer");
  4436. res = cli_.Post("/person", params);
  4437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4438. ASSERT_EQ(StatusCode::OK_200, res->status);
  4439. res = cli_.Get("/person/john5");
  4440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4441. ASSERT_EQ(StatusCode::OK_200, res->status);
  4442. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4443. ASSERT_EQ("developer", res->body);
  4444. Params delete_params;
  4445. delete_params.emplace("name", "john5");
  4446. Headers headers;
  4447. headers.emplace("Custom-Header", "test-value");
  4448. res = cli_.Delete("/person", headers, delete_params);
  4449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4450. ASSERT_EQ(StatusCode::OK_200, res->status);
  4451. ASSERT_EQ("DELETED", res->body);
  4452. res = cli_.Get("/person/john5");
  4453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4454. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4455. }
  4456. TEST_F(ServerTest, DeleteMethod3) {
  4457. auto res = cli_.Get("/person/john6");
  4458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4459. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4460. Params params;
  4461. params.emplace("name", "john6");
  4462. params.emplace("note", "tester");
  4463. res = cli_.Post("/person", params);
  4464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4465. ASSERT_EQ(StatusCode::OK_200, res->status);
  4466. res = cli_.Get("/person/john6");
  4467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4468. ASSERT_EQ(StatusCode::OK_200, res->status);
  4469. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4470. ASSERT_EQ("tester", res->body);
  4471. Params delete_params;
  4472. delete_params.emplace("name", "john6");
  4473. Headers headers;
  4474. headers.emplace("Custom-Header", "test-value");
  4475. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4477. ASSERT_EQ(StatusCode::OK_200, res->status);
  4478. ASSERT_EQ("DELETED", res->body);
  4479. res = cli_.Get("/person/john6");
  4480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4481. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4482. }
  4483. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4484. Params params;
  4485. params.emplace("json", JSON_DATA);
  4486. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4488. ASSERT_EQ(StatusCode::OK_200, res->status);
  4489. ASSERT_EQ(JSON_DATA, res->body);
  4490. }
  4491. TEST_F(ServerTest, PostEmptyContent) {
  4492. auto res = cli_.Post("/empty", "", "text/plain");
  4493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4494. ASSERT_EQ(StatusCode::OK_200, res->status);
  4495. ASSERT_EQ("empty", res->body);
  4496. }
  4497. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4498. auto res = cli_.Post("/empty-no-content-type");
  4499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4500. ASSERT_EQ(StatusCode::OK_200, res->status);
  4501. ASSERT_EQ("empty-no-content-type", res->body);
  4502. }
  4503. TEST_F(ServerTest, PostPathOnly) {
  4504. auto res = cli_.Post("/path-only");
  4505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4506. ASSERT_EQ(StatusCode::OK_200, res->status);
  4507. ASSERT_EQ("path-only", res->body);
  4508. }
  4509. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4510. auto res = cli_.Post("/path-headers-only",
  4511. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4513. ASSERT_EQ(StatusCode::OK_200, res->status);
  4514. ASSERT_EQ("path-headers-only", res->body);
  4515. }
  4516. TEST_F(ServerTest, PostLarge) {
  4517. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4519. ASSERT_EQ(StatusCode::OK_200, res->status);
  4520. EXPECT_EQ(LARGE_DATA, res->body);
  4521. }
  4522. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4523. auto res = cli_.Put("/empty-no-content-type");
  4524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4525. ASSERT_EQ(StatusCode::OK_200, res->status);
  4526. ASSERT_EQ("empty-no-content-type", res->body);
  4527. }
  4528. TEST_F(ServerTest, GetMethodDir) {
  4529. auto res = cli_.Get("/dir/");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4533. auto body = R"(<html>
  4534. <head>
  4535. </head>
  4536. <body>
  4537. <a href="/dir/test.html">Test</a>
  4538. <a href="/hi">hi</a>
  4539. </body>
  4540. </html>
  4541. )";
  4542. EXPECT_EQ(body, res->body);
  4543. }
  4544. TEST_F(ServerTest, GetMethodDirTest) {
  4545. auto res = cli_.Get("/dir/test.html");
  4546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4549. EXPECT_EQ("test.html", res->body);
  4550. }
  4551. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4552. auto res = cli_.Get("/dir/../dir/test.html");
  4553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4556. EXPECT_EQ("test.html", res->body);
  4557. }
  4558. TEST_F(ServerTest, GetMethodInvalidPath) {
  4559. auto res = cli_.Get("/dir/../test.html");
  4560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4562. }
  4563. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4564. auto res = cli_.Get("/../www/dir/test.html");
  4565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4566. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4567. }
  4568. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4569. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4571. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4572. }
  4573. TEST_F(ServerTest, GetMethodDirMountTest) {
  4574. auto res = cli_.Get("/mount/dir/test.html");
  4575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4576. EXPECT_EQ(StatusCode::OK_200, res->status);
  4577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4578. EXPECT_EQ("test.html", res->body);
  4579. }
  4580. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4581. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4585. EXPECT_EQ("test.html", res->body);
  4586. }
  4587. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4588. auto res = cli_.Get("/mount/dir/../test.html");
  4589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4590. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4591. }
  4592. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4593. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4596. }
  4597. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4598. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4601. }
  4602. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4603. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4606. }
  4607. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4608. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4611. }
  4612. TEST_F(ServerTest, PostMethod303) {
  4613. auto res = cli_.Post("/1", "body", "text/plain");
  4614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4615. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4616. EXPECT_EQ("/2", res->get_header_value("Location"));
  4617. }
  4618. TEST_F(ServerTest, PostMethod303Redirect) {
  4619. cli_.set_follow_location(true);
  4620. auto res = cli_.Post("/1", "body", "text/plain");
  4621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4622. EXPECT_EQ(StatusCode::OK_200, res->status);
  4623. EXPECT_EQ("redirected.", res->body);
  4624. EXPECT_EQ("/2", res->location);
  4625. }
  4626. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4627. auto res = cli_.Get("/dir/test.abcde");
  4628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4631. EXPECT_EQ("abcde", res->body);
  4632. }
  4633. TEST_F(ServerTest, StaticFileRange) {
  4634. auto res =
  4635. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4638. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4639. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4640. EXPECT_EQ(true, res->has_header("Content-Range"));
  4641. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4642. EXPECT_EQ(std::string("cd"), res->body);
  4643. }
  4644. TEST_F(ServerTest, StaticFileRanges) {
  4645. auto res = cli_.Get("/dir/test.abcde",
  4646. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4648. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4649. EXPECT_TRUE(
  4650. res->get_header_value("Content-Type")
  4651. .find(
  4652. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4653. 0);
  4654. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4655. }
  4656. TEST_F(ServerTest, StaticFileRangeHead) {
  4657. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4660. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4661. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4662. EXPECT_EQ(true, res->has_header("Content-Range"));
  4663. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4664. }
  4665. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4666. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4668. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4669. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4670. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4671. EXPECT_EQ(true, res->has_header("Content-Range"));
  4672. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4673. res->get_header_value("Content-Range"));
  4674. EXPECT_EQ("LAST\n", res->body);
  4675. }
  4676. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4677. auto res =
  4678. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4680. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4681. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4682. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4683. EXPECT_EQ(true, res->has_header("Content-Range"));
  4684. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4685. }
  4686. TEST_F(ServerTest, StaticFileBigFile) {
  4687. auto res = cli_.Get("/dir/1MB.txt");
  4688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4689. EXPECT_EQ(StatusCode::OK_200, res->status);
  4690. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4691. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4692. }
  4693. TEST_F(ServerTest, InvalidBaseDirMount) {
  4694. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4695. }
  4696. TEST_F(ServerTest, Binary) {
  4697. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4698. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4699. "application/octet-stream");
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. ASSERT_EQ(StatusCode::OK_200, res->status);
  4702. ASSERT_EQ(4U, res->body.size());
  4703. res = cli_.Put("/binary", binary.data(), binary.size(),
  4704. "application/octet-stream");
  4705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4706. ASSERT_EQ(StatusCode::OK_200, res->status);
  4707. ASSERT_EQ(4U, res->body.size());
  4708. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4709. "application/octet-stream");
  4710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4711. ASSERT_EQ(StatusCode::OK_200, res->status);
  4712. ASSERT_EQ(4U, res->body.size());
  4713. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4714. "application/octet-stream");
  4715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4716. ASSERT_EQ(StatusCode::OK_200, res->status);
  4717. ASSERT_EQ(4U, res->body.size());
  4718. }
  4719. TEST_F(ServerTest, BinaryString) {
  4720. auto binary = std::string("\x00\x01\x02\x03", 4);
  4721. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4723. ASSERT_EQ(StatusCode::OK_200, res->status);
  4724. ASSERT_EQ(4U, res->body.size());
  4725. res = cli_.Put("/binary", binary, "application/octet-stream");
  4726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4727. ASSERT_EQ(StatusCode::OK_200, res->status);
  4728. ASSERT_EQ(4U, res->body.size());
  4729. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4731. ASSERT_EQ(StatusCode::OK_200, res->status);
  4732. ASSERT_EQ(4U, res->body.size());
  4733. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4735. ASSERT_EQ(StatusCode::OK_200, res->status);
  4736. ASSERT_EQ(4U, res->body.size());
  4737. }
  4738. TEST_F(ServerTest, EmptyRequest) {
  4739. auto res = cli_.Get("");
  4740. ASSERT_TRUE(!res);
  4741. EXPECT_EQ(Error::Connection, res.error());
  4742. }
  4743. TEST_F(ServerTest, LongRequest) {
  4744. std::string request;
  4745. for (size_t i = 0; i < 545; i++) {
  4746. request += "/TooLongRequest";
  4747. }
  4748. request += "OK";
  4749. auto res = cli_.Get(request.c_str());
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4752. }
  4753. TEST_F(ServerTest, TooLongRequest) {
  4754. std::string request;
  4755. for (size_t i = 0; i < 546; i++) {
  4756. request += "/TooLongRequest";
  4757. }
  4758. request += "_NG";
  4759. auto start = std::chrono::high_resolution_clock::now();
  4760. cli_.set_keep_alive(true);
  4761. auto res = cli_.Get(request.c_str());
  4762. auto end = std::chrono::high_resolution_clock::now();
  4763. auto elapsed =
  4764. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4765. .count();
  4766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4767. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4768. EXPECT_LE(elapsed, 1000);
  4769. EXPECT_EQ("close", res->get_header_value("Connection"));
  4770. EXPECT_FALSE(cli_.is_socket_open());
  4771. }
  4772. TEST_F(ServerTest, AlmostTooLongRequest) {
  4773. // test for #2046 - URI length check shouldn't include other content on req
  4774. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4775. // leading /, space, HTTP/1.1)
  4776. std::string request =
  4777. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4778. auto res = cli_.Get(request.c_str());
  4779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4781. }
  4782. TEST_F(ServerTest, LongHeader) {
  4783. Request req;
  4784. req.method = "GET";
  4785. req.path = "/hi";
  4786. std::string host_and_port;
  4787. host_and_port += HOST;
  4788. host_and_port += ":";
  4789. host_and_port += std::to_string(PORT);
  4790. req.headers.emplace("Host", host_and_port.c_str());
  4791. req.headers.emplace("Accept", "*/*");
  4792. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4793. req.headers.emplace(
  4794. "Header-Name",
  4795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4823. "@@@@@@@@@@@@@@@@");
  4824. auto res = std::make_shared<Response>();
  4825. auto error = Error::Success;
  4826. auto ret = cli_.send(req, *res, error);
  4827. ASSERT_TRUE(ret);
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. }
  4830. TEST_F(ServerTest, LongQueryValue) {
  4831. auto start = std::chrono::high_resolution_clock::now();
  4832. cli_.set_keep_alive(true);
  4833. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4834. auto end = std::chrono::high_resolution_clock::now();
  4835. auto elapsed =
  4836. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4837. .count();
  4838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4839. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4840. EXPECT_LE(elapsed, 1000);
  4841. EXPECT_EQ("close", res->get_header_value("Connection"));
  4842. EXPECT_FALSE(cli_.is_socket_open());
  4843. }
  4844. TEST_F(ServerTest, TooLongQueryValue) {
  4845. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4846. ASSERT_FALSE(res);
  4847. EXPECT_EQ(Error::Read, res.error());
  4848. }
  4849. TEST_F(ServerTest, TooLongHeader) {
  4850. Request req;
  4851. req.method = "GET";
  4852. req.path = "/hi";
  4853. std::string host_and_port;
  4854. host_and_port += HOST;
  4855. host_and_port += ":";
  4856. host_and_port += std::to_string(PORT);
  4857. req.headers.emplace("Host", host_and_port.c_str());
  4858. req.headers.emplace("Accept", "*/*");
  4859. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4860. req.headers.emplace(
  4861. "Header-Name",
  4862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4888. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4889. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4890. "@@@@@@@@@@@@@@@@@");
  4891. auto res = std::make_shared<Response>();
  4892. auto error = Error::Success;
  4893. auto ret = cli_.send(req, *res, error);
  4894. ASSERT_TRUE(ret);
  4895. EXPECT_EQ(StatusCode::OK_200, res->status);
  4896. }
  4897. TEST_F(ServerTest, HeaderCountAtLimit) {
  4898. // Test with headers just under the 100 limit
  4899. httplib::Headers headers;
  4900. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4901. // This should keep us just under the 100 header limit
  4902. for (int i = 0; i < 95; i++) {
  4903. std::string name = "X-Test-Header-" + std::to_string(i);
  4904. std::string value = "value" + std::to_string(i);
  4905. headers.emplace(name, value);
  4906. }
  4907. // This should work fine as we're under the limit
  4908. auto res = cli_.Get("/hi", headers);
  4909. EXPECT_TRUE(res);
  4910. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4911. }
  4912. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4913. // Test with many headers to exceed the 100 limit
  4914. httplib::Headers headers;
  4915. // Add 150 headers to definitely exceed the 100 limit
  4916. for (int i = 0; i < 150; i++) {
  4917. std::string name = "X-Test-Header-" + std::to_string(i);
  4918. std::string value = "value" + std::to_string(i);
  4919. headers.emplace(name, value);
  4920. }
  4921. // This should fail due to exceeding header count limit
  4922. cli_.set_keep_alive(true);
  4923. auto res = cli_.Get("/hi", headers);
  4924. // The server should respond with 400 Bad Request
  4925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4926. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4927. EXPECT_EQ("close", res->get_header_value("Connection"));
  4928. EXPECT_FALSE(cli_.is_socket_open());
  4929. }
  4930. TEST_F(ServerTest, PercentEncoding) {
  4931. auto res = cli_.Get("/e%6edwith%");
  4932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4933. EXPECT_EQ(StatusCode::OK_200, res->status);
  4934. }
  4935. TEST_F(ServerTest, PercentEncodingUnicode) {
  4936. auto res = cli_.Get("/e%u006edwith%");
  4937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4938. EXPECT_EQ(StatusCode::OK_200, res->status);
  4939. }
  4940. TEST_F(ServerTest, InvalidPercentEncoding) {
  4941. auto res = cli_.Get("/%endwith%");
  4942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4944. }
  4945. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4946. auto res = cli_.Get("/%uendwith%");
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4949. }
  4950. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4951. auto res = cli_.Get("/hello?aaa=bbb%");
  4952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4953. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4954. }
  4955. TEST_F(ServerTest, PlusSignEncoding) {
  4956. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4958. EXPECT_EQ(StatusCode::OK_200, res->status);
  4959. EXPECT_EQ("a +b", res->body);
  4960. }
  4961. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4962. // This test simulates a potential DoS attack using many headers
  4963. // to verify our security fix prevents memory exhaustion
  4964. httplib::Headers attack_headers;
  4965. // Attempt to add many headers like an attacker would (200 headers to far
  4966. // exceed limit)
  4967. for (int i = 0; i < 200; i++) {
  4968. std::string name = "X-Attack-Header-" + std::to_string(i);
  4969. std::string value = "attack_payload_" + std::to_string(i);
  4970. attack_headers.emplace(name, value);
  4971. }
  4972. // Try to POST with excessive headers
  4973. cli_.set_keep_alive(true);
  4974. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4975. // Should either fail or return 400 Bad Request due to security limit
  4976. if (res) {
  4977. // If we get a response, it should be 400 Bad Request
  4978. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4979. EXPECT_EQ("close", res->get_header_value("Connection"));
  4980. }
  4981. EXPECT_FALSE(cli_.is_socket_open());
  4982. }
  4983. TEST_F(ServerTest, MultipartFormData) {
  4984. UploadFormDataItems items = {
  4985. {"text1", "text default", "", ""},
  4986. {"text2", "aωb", "", ""},
  4987. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4988. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4989. {"file3", "", "", "application/octet-stream"},
  4990. {"file4", "", "", " application/json tmp-string "}};
  4991. auto res = cli_.Post("/multipart", items);
  4992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4993. EXPECT_EQ(StatusCode::OK_200, res->status);
  4994. }
  4995. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4996. UploadFormDataItems items = {
  4997. {"text", "default text", "", ""},
  4998. {"multi_text1", "aaaaa", "", ""},
  4999. {"multi_text1", "bbbbb", "", ""},
  5000. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5001. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5002. "application/json"},
  5003. };
  5004. auto res = cli_.Post("/multipart/multi_file_values", items);
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. }
  5008. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5009. auto res = cli_.Get("/hi");
  5010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5011. EXPECT_EQ(StatusCode::OK_200, res->status);
  5012. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5013. EXPECT_EQ("Hello World!", res->body);
  5014. }
  5015. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5016. Request req;
  5017. req.method = "POST";
  5018. req.path = "/chunked";
  5019. std::string host_and_port;
  5020. host_and_port += HOST;
  5021. host_and_port += ":";
  5022. host_and_port += std::to_string(PORT);
  5023. req.headers.emplace("Host", host_and_port.c_str());
  5024. req.headers.emplace("Accept", "*/*");
  5025. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5026. req.headers.emplace("Content-Type", "text/plain");
  5027. req.headers.emplace("Content-Length", "0");
  5028. req.headers.emplace(
  5029. "Transfer-Encoding",
  5030. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5031. // Client does not chunk, so make a chunked body manually.
  5032. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5033. auto res = std::make_shared<Response>();
  5034. auto error = Error::Success;
  5035. auto ret = cli_.send(req, *res, error);
  5036. ASSERT_TRUE(ret);
  5037. EXPECT_EQ(StatusCode::OK_200, res->status);
  5038. }
  5039. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5040. // rather than treat them as valid lengths.
  5041. template <typename ClientT>
  5042. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5043. Request req;
  5044. req.method = "POST";
  5045. req.path = "/chunked";
  5046. std::string host_and_port;
  5047. host_and_port += HOST;
  5048. host_and_port += ":";
  5049. host_and_port += std::to_string(PORT);
  5050. req.headers.emplace("Host", host_and_port.c_str());
  5051. req.headers.emplace("Content-Length", "0");
  5052. req.headers.emplace("Transfer-Encoding", "chunked");
  5053. req.body = body;
  5054. auto res = std::make_shared<Response>();
  5055. auto error = Error::Success;
  5056. ASSERT_TRUE(cli.send(req, *res, error));
  5057. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5058. }
  5059. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5060. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5061. }
  5062. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5063. expect_chunked_body_rejected(
  5064. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5065. }
  5066. TEST_F(ServerTest, GetStreamed2) {
  5067. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5070. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5071. EXPECT_EQ(true, res->has_header("Content-Range"));
  5072. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5073. EXPECT_EQ(std::string("ab"), res->body);
  5074. }
  5075. TEST_F(ServerTest, GetStreamed) {
  5076. auto res = cli_.Get("/streamed");
  5077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5078. EXPECT_EQ(StatusCode::OK_200, res->status);
  5079. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5080. EXPECT_EQ(std::string("aaabbb"), res->body);
  5081. }
  5082. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5083. auto res = cli_.Get("/streamed-without-length",
  5084. Headers{make_range_header({{0, -1}})});
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. EXPECT_EQ(false, res->has_header("Content-Length"));
  5088. EXPECT_EQ(false, res->has_header("Content-Range"));
  5089. EXPECT_EQ(std::string("abcdefg"), res->body);
  5090. }
  5091. TEST_F(ServerTest, GetStreamedWithRange1) {
  5092. auto res =
  5093. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5095. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5096. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5097. EXPECT_EQ(true, res->has_header("Content-Range"));
  5098. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5099. EXPECT_EQ(std::string("def"), res->body);
  5100. }
  5101. TEST_F(ServerTest, GetStreamedWithRange2) {
  5102. auto res =
  5103. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5106. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5107. EXPECT_EQ(true, res->has_header("Content-Range"));
  5108. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5109. EXPECT_EQ(std::string("bcdefg"), res->body);
  5110. }
  5111. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5112. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5114. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5115. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5116. EXPECT_EQ(true, res->has_header("Content-Range"));
  5117. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5118. EXPECT_EQ(std::string("efg"), res->body);
  5119. }
  5120. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5121. auto res =
  5122. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5125. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5126. EXPECT_EQ(false, res->has_header("Content-Range"));
  5127. EXPECT_EQ(0U, res->body.size());
  5128. }
  5129. TEST_F(ServerTest, GetStreamedWithRangeAndErrorStatus) {
  5130. // The handler answers with a non-2xx status, so `detail::range_error()`
  5131. // never validated the ranges and `apply_ranges()` reported the full
  5132. // content length. The body must match that header and the content provider
  5133. // must not be asked for an offset outside the representation.
  5134. auto res = cli_.Get("/streamed-with-range-and-error-status",
  5135. Headers{{make_range_header({{3, 5}})}});
  5136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5137. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5138. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5139. EXPECT_EQ(false, res->has_header("Content-Range"));
  5140. EXPECT_EQ(std::string("abcdefg"), res->body);
  5141. auto res2 = cli_.Get("/streamed-with-range-and-error-status",
  5142. Headers{{"Range", "bytes=100000-100200"}});
  5143. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  5144. EXPECT_EQ(StatusCode::Forbidden_403, res2->status);
  5145. EXPECT_EQ("7", res2->get_header_value("Content-Length"));
  5146. EXPECT_EQ(std::string("abcdefg"), res2->body);
  5147. }
  5148. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5149. auto res =
  5150. cli_.Get("/streamed-with-range",
  5151. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5152. "92233720368547758079223372036854775807"}});
  5153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5154. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5155. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5156. EXPECT_EQ(false, res->has_header("Content-Range"));
  5157. EXPECT_EQ(0U, res->body.size());
  5158. }
  5159. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5160. auto res = cli_.Get(
  5161. "/with-range",
  5162. Headers{{"Range",
  5163. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5164. {"Accept-Encoding", ""}});
  5165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5167. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ(true, res->has_header("Content-Range"));
  5169. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5170. EXPECT_EQ(std::string("abcdefg"), res->body);
  5171. }
  5172. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5173. auto res = cli_.Get("/with-range", Headers{
  5174. {"Range", "bytes=0-"},
  5175. {"Accept-Encoding", ""},
  5176. });
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5179. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5180. EXPECT_EQ(true, res->has_header("Content-Range"));
  5181. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5182. EXPECT_EQ(std::string("abcdefg"), res->body);
  5183. }
  5184. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5185. auto res = cli_.Get("/streamed-with-range",
  5186. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5189. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5190. EXPECT_EQ(false, res->has_header("Content-Range"));
  5191. EXPECT_EQ(267U, res->body.size());
  5192. // Check that both range contents are present
  5193. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5194. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5195. // Check that Content-Range headers are present for both ranges
  5196. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5197. std::string::npos);
  5198. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5199. std::string::npos);
  5200. }
  5201. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5202. Ranges ranges;
  5203. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5204. ranges.emplace_back(0, -1);
  5205. }
  5206. auto res = cli_.Get("/streamed-with-range?error",
  5207. Headers{{make_range_header(ranges)}});
  5208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5209. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5210. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5211. EXPECT_EQ(false, res->has_header("Content-Range"));
  5212. EXPECT_EQ(0U, res->body.size());
  5213. }
  5214. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5215. auto res = cli_.Get("/streamed-with-range",
  5216. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5219. EXPECT_EQ(5U, res->body.size());
  5220. // Check that overlapping ranges are coalesced into a single range
  5221. EXPECT_EQ("bcdef", res->body);
  5222. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5223. // Should be single range, not multipart
  5224. EXPECT_TRUE(res->has_header("Content-Range"));
  5225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5226. }
  5227. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5228. auto res = cli_.Get("/streamed-with-range",
  5229. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5232. EXPECT_EQ(268U, res->body.size());
  5233. // Check that both range contents are present
  5234. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5235. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5236. // Check that Content-Range headers are present for both ranges
  5237. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5238. std::string::npos);
  5239. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5240. std::string::npos);
  5241. }
  5242. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5243. auto res = cli_.Get("/streamed-with-range",
  5244. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5247. EXPECT_EQ(269U, res->body.size());
  5248. // Check that both duplicate range contents are present
  5249. size_t first_abc = res->body.find("abc\r\n");
  5250. EXPECT_TRUE(first_abc != std::string::npos);
  5251. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5252. EXPECT_TRUE(second_abc != std::string::npos);
  5253. // Check that Content-Range headers are present for both ranges
  5254. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5255. EXPECT_TRUE(first_range != std::string::npos);
  5256. size_t second_range =
  5257. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5258. EXPECT_TRUE(second_range != std::string::npos);
  5259. }
  5260. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5261. auto res =
  5262. cli_.Get("/streamed-with-range?error",
  5263. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5266. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5267. EXPECT_EQ(false, res->has_header("Content-Range"));
  5268. EXPECT_EQ(0U, res->body.size());
  5269. }
  5270. TEST_F(ServerTest, GetStreamedEndless) {
  5271. uint64_t offset = 0;
  5272. auto res = cli_.Get("/streamed-cancel",
  5273. [&](const char * /*data*/, uint64_t data_length) {
  5274. if (offset < 100) {
  5275. offset += data_length;
  5276. return true;
  5277. }
  5278. return false;
  5279. });
  5280. ASSERT_TRUE(!res);
  5281. EXPECT_EQ(Error::Canceled, res.error());
  5282. }
  5283. TEST_F(ServerTest, ClientStop) {
  5284. std::atomic_size_t count{4};
  5285. std::vector<std::thread> threads;
  5286. for (auto i = count.load(); i != 0; --i) {
  5287. threads.emplace_back([&]() {
  5288. auto res = cli_.Get("/streamed-cancel",
  5289. [&](const char *, uint64_t) { return true; });
  5290. --count;
  5291. ASSERT_TRUE(!res);
  5292. EXPECT_TRUE(res.error() == Error::Canceled ||
  5293. res.error() == Error::Read || res.error() == Error::Write);
  5294. });
  5295. }
  5296. std::this_thread::sleep_for(std::chrono::seconds(2));
  5297. while (count != 0) {
  5298. cli_.stop();
  5299. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5300. }
  5301. for (auto &t : threads) {
  5302. t.join();
  5303. }
  5304. }
  5305. TEST_F(ServerTest, GetWithRange1) {
  5306. auto res = cli_.Get("/with-range", Headers{
  5307. make_range_header({{3, 5}}),
  5308. {"Accept-Encoding", ""},
  5309. });
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5312. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5313. EXPECT_EQ(true, res->has_header("Content-Range"));
  5314. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5315. EXPECT_EQ(std::string("def"), res->body);
  5316. }
  5317. TEST_F(ServerTest, GetWithRange2) {
  5318. auto res = cli_.Get("/with-range", Headers{
  5319. make_range_header({{1, -1}}),
  5320. {"Accept-Encoding", ""},
  5321. });
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5324. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5325. EXPECT_EQ(true, res->has_header("Content-Range"));
  5326. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5327. EXPECT_EQ(std::string("bcdefg"), res->body);
  5328. }
  5329. TEST_F(ServerTest, GetWithRange3) {
  5330. auto res = cli_.Get("/with-range", Headers{
  5331. make_range_header({{0, 0}}),
  5332. {"Accept-Encoding", ""},
  5333. });
  5334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5336. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5337. EXPECT_EQ(true, res->has_header("Content-Range"));
  5338. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5339. EXPECT_EQ(std::string("a"), res->body);
  5340. }
  5341. TEST_F(ServerTest, GetWithRange4) {
  5342. auto res = cli_.Get("/with-range", Headers{
  5343. make_range_header({{-1, 2}}),
  5344. {"Accept-Encoding", ""},
  5345. });
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5348. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5349. EXPECT_EQ(true, res->has_header("Content-Range"));
  5350. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5351. EXPECT_EQ(std::string("fg"), res->body);
  5352. }
  5353. TEST_F(ServerTest, GetWithRange5) {
  5354. auto res = cli_.Get("/with-range", Headers{
  5355. make_range_header({{0, 5}}),
  5356. {"Accept-Encoding", ""},
  5357. });
  5358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5359. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5360. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5361. EXPECT_EQ(true, res->has_header("Content-Range"));
  5362. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5363. EXPECT_EQ(std::string("abcdef"), res->body);
  5364. }
  5365. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5366. auto res =
  5367. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5369. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5370. }
  5371. TEST_F(ServerTest, GetWithRangeMultipart) {
  5372. auto res =
  5373. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5375. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5376. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5377. EXPECT_EQ(false, res->has_header("Content-Range"));
  5378. EXPECT_EQ(267U, res->body.size());
  5379. }
  5380. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5381. auto res = cli_.Get("/with-range",
  5382. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5384. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5385. }
  5386. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5387. auto res = cli_.Get("/with-range-customized-response",
  5388. Headers{{make_range_header({{1, 2}})}});
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5391. EXPECT_EQ(true, res->has_header("Content-Length"));
  5392. EXPECT_EQ(false, res->has_header("Content-Range"));
  5393. EXPECT_EQ(JSON_DATA, res->body);
  5394. }
  5395. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5396. auto res = cli_.Get("/with-range-customized-response",
  5397. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5399. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5400. EXPECT_EQ(true, res->has_header("Content-Length"));
  5401. EXPECT_EQ(false, res->has_header("Content-Range"));
  5402. EXPECT_EQ(JSON_DATA, res->body);
  5403. }
  5404. TEST_F(ServerTest, Issue1772) {
  5405. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5408. }
  5409. TEST_F(ServerTest, Issue609) {
  5410. auto res = cli_.Delete("/issue609");
  5411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. EXPECT_EQ(std::string("ok"), res->body);
  5414. }
  5415. TEST_F(ServerTest, GetStreamedChunked) {
  5416. auto res = cli_.Get("/streamed-chunked");
  5417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5418. EXPECT_EQ(StatusCode::OK_200, res->status);
  5419. EXPECT_EQ(std::string("123456789"), res->body);
  5420. }
  5421. TEST_F(ServerTest, GetStreamedChunked2) {
  5422. auto res = cli_.Get("/streamed-chunked2");
  5423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5424. EXPECT_EQ(StatusCode::OK_200, res->status);
  5425. EXPECT_EQ(std::string("123456789"), res->body);
  5426. }
  5427. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5428. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5430. EXPECT_EQ(StatusCode::OK_200, res->status);
  5431. EXPECT_EQ(std::string("123456789"), res->body);
  5432. EXPECT_TRUE(res->has_header("Trailer"));
  5433. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5434. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5435. // Trailers are now stored separately from headers (security fix)
  5436. EXPECT_EQ(2U, res->trailers.size());
  5437. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5438. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5439. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5440. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5441. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5442. // Verify trailers are NOT in headers (security verification)
  5443. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5444. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5445. }
  5446. TEST_F(ServerTest, LargeChunkedPost) {
  5447. Request req;
  5448. req.method = "POST";
  5449. req.path = "/large-chunked";
  5450. std::string host_and_port;
  5451. host_and_port += HOST;
  5452. host_and_port += ":";
  5453. host_and_port += std::to_string(PORT);
  5454. req.headers.emplace("Host", host_and_port.c_str());
  5455. req.headers.emplace("Accept", "*/*");
  5456. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5457. req.headers.emplace("Content-Type", "text/plain");
  5458. req.headers.emplace("Content-Length", "0");
  5459. req.headers.emplace("Transfer-Encoding", "chunked");
  5460. std::string long_string(30 * 1024u, 'a');
  5461. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5462. // Attempt to make a large enough post to exceed OS buffers, to test that
  5463. // the server handles short reads if the full chunk data isn't available.
  5464. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5465. auto res = std::make_shared<Response>();
  5466. auto error = Error::Success;
  5467. auto ret = cli_.send(req, *res, error);
  5468. ASSERT_TRUE(ret);
  5469. EXPECT_EQ(StatusCode::OK_200, res->status);
  5470. }
  5471. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5472. auto res = cli_.Get("/remote_addr");
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. EXPECT_EQ(StatusCode::OK_200, res->status);
  5475. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5476. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5477. }
  5478. TEST_F(ServerTest, GetMethodLocalAddr) {
  5479. auto res = cli_.Get("/local_addr");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5483. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5484. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5485. }
  5486. TEST_F(ServerTest, HTTPResponseSplitting) {
  5487. auto res = cli_.Get("/http_response_splitting");
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. EXPECT_EQ(StatusCode::OK_200, res->status);
  5490. }
  5491. TEST_F(ServerTest, SlowRequest) {
  5492. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5493. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5494. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5495. }
  5496. #if 0
  5497. TEST_F(ServerTest, SlowPost) {
  5498. char buffer[64 * 1024];
  5499. memset(buffer, 0x42, sizeof(buffer));
  5500. auto res = cli_.Post(
  5501. "/slowpost", 64 * 1024 * 1024,
  5502. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5503. auto ret = sink.write(buffer, sizeof(buffer));
  5504. EXPECT_TRUE(ret);
  5505. return true;
  5506. },
  5507. "text/plain");
  5508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5509. EXPECT_EQ(StatusCode::OK_200, res->status);
  5510. }
  5511. TEST_F(ServerTest, SlowPostFail) {
  5512. char buffer[64 * 1024];
  5513. memset(buffer, 0x42, sizeof(buffer));
  5514. cli_.set_write_timeout(std::chrono::seconds(0));
  5515. auto res = cli_.Post(
  5516. "/slowpost", 64 * 1024 * 1024,
  5517. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5518. sink.write(buffer, sizeof(buffer));
  5519. return true;
  5520. },
  5521. "text/plain");
  5522. ASSERT_TRUE(!res);
  5523. EXPECT_EQ(Error::Write, res.error());
  5524. }
  5525. #endif
  5526. TEST_F(ServerTest, Put) {
  5527. auto res = cli_.Put("/put", "PUT", "text/plain");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(StatusCode::OK_200, res->status);
  5530. EXPECT_EQ("PUT", res->body);
  5531. }
  5532. TEST_F(ServerTest, PutWithContentProvider) {
  5533. auto res = cli_.Put(
  5534. "/put", 3,
  5535. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5536. sink.os << "PUT";
  5537. return true;
  5538. },
  5539. "text/plain");
  5540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5541. EXPECT_EQ(StatusCode::OK_200, res->status);
  5542. EXPECT_EQ("PUT", res->body);
  5543. }
  5544. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5545. auto res = cli_.Post(
  5546. "/post", 42,
  5547. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5548. return false;
  5549. },
  5550. "text/plain");
  5551. ASSERT_TRUE(!res);
  5552. EXPECT_EQ(Error::Canceled, res.error());
  5553. }
  5554. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5555. auto res = cli_.Put(
  5556. "/put",
  5557. [](size_t /*offset*/, DataSink &sink) {
  5558. sink.os << "PUT";
  5559. sink.done();
  5560. return true;
  5561. },
  5562. "text/plain");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. EXPECT_EQ(StatusCode::OK_200, res->status);
  5565. EXPECT_EQ("PUT", res->body);
  5566. }
  5567. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5568. auto res = cli_.Post(
  5569. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5570. "text/plain");
  5571. ASSERT_TRUE(!res);
  5572. EXPECT_EQ(Error::Canceled, res.error());
  5573. }
  5574. TEST_F(ServerTest, PostLoopBack) {
  5575. std::string body;
  5576. auto res = cli_.Post(
  5577. "/post-loopback", 9,
  5578. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5579. EXPECT_EQ(9u, length);
  5580. sink.write("123", 3);
  5581. sink.write("456", 3);
  5582. sink.write("789", 3);
  5583. return true;
  5584. },
  5585. "text/plain",
  5586. [&body](const char *data, size_t data_length) {
  5587. body.append(data, data_length);
  5588. return true;
  5589. });
  5590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5591. EXPECT_EQ(StatusCode::OK_200, res->status);
  5592. EXPECT_EQ("123456789", body);
  5593. }
  5594. TEST_F(ServerTest, PutLoopBack) {
  5595. std::string body;
  5596. auto res = cli_.Put(
  5597. "/put-loopback", 9,
  5598. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5599. EXPECT_EQ(9u, length);
  5600. sink.write("123", 3);
  5601. sink.write("456", 3);
  5602. sink.write("789", 3);
  5603. return true;
  5604. },
  5605. "text/plain",
  5606. [&body](const char *data, size_t data_length) {
  5607. body.append(data, data_length);
  5608. return true;
  5609. });
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. EXPECT_EQ("123456789", body);
  5613. }
  5614. TEST_F(ServerTest, PatchLoopBack) {
  5615. std::string body;
  5616. auto res = cli_.Patch(
  5617. "/patch-loopback", 9,
  5618. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5619. EXPECT_EQ(9u, length);
  5620. sink.write("123", 3);
  5621. sink.write("456", 3);
  5622. sink.write("789", 3);
  5623. return true;
  5624. },
  5625. "text/plain",
  5626. [&body](const char *data, size_t data_length) {
  5627. body.append(data, data_length);
  5628. return true;
  5629. });
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::OK_200, res->status);
  5632. EXPECT_EQ("123456789", body);
  5633. }
  5634. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5635. std::string body;
  5636. auto res = cli_.Post(
  5637. "/post-loopback",
  5638. [](size_t /*offset*/, DataSink &sink) {
  5639. sink.write("123", 3);
  5640. sink.write("456", 3);
  5641. sink.write("789", 3);
  5642. sink.done();
  5643. return true;
  5644. },
  5645. "text/plain",
  5646. [&body](const char *data, size_t data_length) {
  5647. body.append(data, data_length);
  5648. return true;
  5649. });
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. EXPECT_EQ(StatusCode::OK_200, res->status);
  5652. EXPECT_EQ("123456789", body);
  5653. }
  5654. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5655. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5656. cli_.set_compress(true);
  5657. auto res = cli_.Put(
  5658. "/put", 3,
  5659. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5660. sink.os << "PUT";
  5661. return true;
  5662. },
  5663. "text/plain");
  5664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5665. EXPECT_EQ(StatusCode::OK_200, res->status);
  5666. EXPECT_EQ("PUT", res->body);
  5667. }
  5668. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5669. cli_.set_compress(true);
  5670. auto res = cli_.Post(
  5671. "/post", 42,
  5672. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5673. return false;
  5674. },
  5675. "text/plain");
  5676. ASSERT_TRUE(!res);
  5677. EXPECT_EQ(Error::Canceled, res.error());
  5678. }
  5679. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5680. cli_.set_compress(true);
  5681. auto res = cli_.Put(
  5682. "/put",
  5683. [](size_t /*offset*/, DataSink &sink) {
  5684. sink.os << "PUT";
  5685. sink.done();
  5686. return true;
  5687. },
  5688. "text/plain");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ("PUT", res->body);
  5692. }
  5693. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5694. cli_.set_compress(true);
  5695. auto res = cli_.Post(
  5696. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5697. "text/plain");
  5698. ASSERT_TRUE(!res);
  5699. EXPECT_EQ(Error::Canceled, res.error());
  5700. }
  5701. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5702. cli_.set_compress(true);
  5703. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ(LARGE_DATA, res->body);
  5707. }
  5708. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5709. #ifdef CPPHTTPLIB_SSL_ENABLED
  5710. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5711. Client cli(s.c_str());
  5712. cli.enable_server_certificate_verification(false);
  5713. #else
  5714. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5715. Client cli(s.c_str());
  5716. #endif
  5717. cli.set_compress(true);
  5718. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5720. EXPECT_EQ(StatusCode::OK_200, res->status);
  5721. EXPECT_EQ(LARGE_DATA, res->body);
  5722. // The compressed size should be less than a 10th of the original. May vary
  5723. // depending on the zlib library.
  5724. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5725. static_cast<uint64_t>(10 * 1024 * 1024));
  5726. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5727. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5728. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5729. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5730. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5731. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5732. #endif
  5733. }
  5734. TEST_F(ServerTest, PutContentWithDeflate) {
  5735. cli_.set_compress(false);
  5736. Headers headers;
  5737. headers.emplace("Content-Encoding", "deflate");
  5738. // PUT in deflate format:
  5739. auto res = cli_.Put("/put", headers,
  5740. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. EXPECT_EQ("PUT", res->body);
  5744. }
  5745. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5746. Headers headers;
  5747. headers.emplace("Accept-Encoding", "gzip, deflate");
  5748. auto res = cli_.Get("/streamed-chunked", headers);
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. EXPECT_EQ(std::string("123456789"), res->body);
  5752. }
  5753. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5754. Headers headers;
  5755. headers.emplace("Accept-Encoding", "gzip, deflate");
  5756. auto res = cli_.Get("/streamed-chunked2", headers);
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. EXPECT_EQ(StatusCode::OK_200, res->status);
  5759. EXPECT_EQ(std::string("123456789"), res->body);
  5760. }
  5761. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5762. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. }
  5766. TEST(GzipDecompressor, ChunkedDecompression) {
  5767. std::string data;
  5768. for (size_t i = 0; i < 32 * 1024; ++i) {
  5769. data.push_back(static_cast<char>('a' + i % 26));
  5770. }
  5771. std::string compressed_data;
  5772. {
  5773. httplib::detail::gzip_compressor compressor;
  5774. bool result = compressor.compress(
  5775. data.data(), data.size(),
  5776. /*last=*/true,
  5777. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5778. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5779. compressed_data_size);
  5780. return true;
  5781. });
  5782. ASSERT_TRUE(result);
  5783. }
  5784. std::string decompressed_data;
  5785. {
  5786. httplib::detail::gzip_decompressor decompressor;
  5787. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5788. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5789. size_t chunk_size = 130;
  5790. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5791. chunk_begin += chunk_size) {
  5792. size_t current_chunk_size =
  5793. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5794. bool result = decompressor.decompress(
  5795. compressed_data.data() + chunk_begin, current_chunk_size,
  5796. [&](const char *decompressed_data_chunk,
  5797. size_t decompressed_data_chunk_size) {
  5798. decompressed_data.insert(decompressed_data.size(),
  5799. decompressed_data_chunk,
  5800. decompressed_data_chunk_size);
  5801. return true;
  5802. });
  5803. ASSERT_TRUE(result);
  5804. }
  5805. }
  5806. ASSERT_EQ(data, decompressed_data);
  5807. }
  5808. TEST(GzipDecompressor, DeflateDecompression) {
  5809. std::string original_text = "Raw deflate without gzip";
  5810. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5811. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5812. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5813. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5814. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5815. std::string decompressed_data;
  5816. {
  5817. httplib::detail::gzip_decompressor decompressor;
  5818. bool result = decompressor.decompress(
  5819. compressed_data.data(), compressed_data.size(),
  5820. [&](const char *decompressed_data_chunk,
  5821. size_t decompressed_data_chunk_size) {
  5822. decompressed_data.insert(decompressed_data.size(),
  5823. decompressed_data_chunk,
  5824. decompressed_data_chunk_size);
  5825. return true;
  5826. });
  5827. ASSERT_TRUE(result);
  5828. }
  5829. ASSERT_EQ(original_text, decompressed_data);
  5830. }
  5831. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5832. std::string original_text = "Raw deflate without gzip";
  5833. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5834. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5835. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5836. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5837. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5838. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5839. std::string decompressed_data;
  5840. {
  5841. httplib::detail::gzip_decompressor decompressor;
  5842. bool result = decompressor.decompress(
  5843. compressed_data.data(), compressed_data.size(),
  5844. [&](const char *decompressed_data_chunk,
  5845. size_t decompressed_data_chunk_size) {
  5846. decompressed_data.insert(decompressed_data.size(),
  5847. decompressed_data_chunk,
  5848. decompressed_data_chunk_size);
  5849. return true;
  5850. });
  5851. ASSERT_TRUE(result);
  5852. }
  5853. ASSERT_EQ(original_text, decompressed_data);
  5854. }
  5855. #endif
  5856. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5857. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5858. Headers headers;
  5859. headers.emplace("Accept-Encoding", "br");
  5860. auto res = cli_.Get("/streamed-chunked", headers);
  5861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5862. EXPECT_EQ(StatusCode::OK_200, res->status);
  5863. EXPECT_EQ(std::string("123456789"), res->body);
  5864. }
  5865. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5866. Headers headers;
  5867. headers.emplace("Accept-Encoding", "br");
  5868. auto res = cli_.Get("/streamed-chunked2", headers);
  5869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5870. EXPECT_EQ(StatusCode::OK_200, res->status);
  5871. EXPECT_EQ(std::string("123456789"), res->body);
  5872. }
  5873. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5874. cli_.set_compress(true);
  5875. auto res = cli_.Put(
  5876. "/put", 3,
  5877. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5878. sink.os << "PUT";
  5879. return true;
  5880. },
  5881. "text/plain");
  5882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5883. EXPECT_EQ(StatusCode::OK_200, res->status);
  5884. EXPECT_EQ("PUT", res->body);
  5885. }
  5886. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5887. cli_.set_compress(true);
  5888. auto res = cli_.Put(
  5889. "/put",
  5890. [](size_t /*offset*/, DataSink &sink) {
  5891. sink.os << "PUT";
  5892. sink.done();
  5893. return true;
  5894. },
  5895. "text/plain");
  5896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5897. EXPECT_EQ(StatusCode::OK_200, res->status);
  5898. EXPECT_EQ("PUT", res->body);
  5899. }
  5900. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5901. cli_.set_compress(true);
  5902. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. EXPECT_EQ(StatusCode::OK_200, res->status);
  5905. EXPECT_EQ(LARGE_DATA, res->body);
  5906. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5907. }
  5908. #endif
  5909. TEST_F(ServerTest, Patch) {
  5910. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. EXPECT_EQ(StatusCode::OK_200, res->status);
  5913. EXPECT_EQ("PATCH", res->body);
  5914. }
  5915. TEST_F(ServerTest, Delete) {
  5916. auto res = cli_.Delete("/delete");
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::OK_200, res->status);
  5919. EXPECT_EQ("DELETE", res->body);
  5920. }
  5921. TEST_F(ServerTest, DeleteContentReceiver) {
  5922. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5924. EXPECT_EQ(StatusCode::OK_200, res->status);
  5925. EXPECT_EQ("content", res->body);
  5926. }
  5927. TEST_F(ServerTest, Options) {
  5928. auto res = cli_.Options("*");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. EXPECT_EQ(StatusCode::OK_200, res->status);
  5931. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5932. EXPECT_TRUE(res->body.empty());
  5933. }
  5934. TEST_F(ServerTest, URL) {
  5935. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. EXPECT_EQ(StatusCode::OK_200, res->status);
  5938. }
  5939. TEST_F(ServerTest, ArrayParam) {
  5940. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5942. EXPECT_EQ(StatusCode::OK_200, res->status);
  5943. }
  5944. TEST_F(ServerTest, ArrayParamValues) {
  5945. auto res =
  5946. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5948. EXPECT_EQ(StatusCode::OK_200, res->status);
  5949. }
  5950. TEST_F(ServerTest, NoMultipleHeaders) {
  5951. Headers headers = {{"Content-Length", "5"}};
  5952. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5953. "text/plain");
  5954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5955. EXPECT_EQ(StatusCode::OK_200, res->status);
  5956. }
  5957. TEST_F(ServerTest, PostContentReceiver) {
  5958. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. ASSERT_EQ(StatusCode::OK_200, res->status);
  5961. ASSERT_EQ("content", res->body);
  5962. }
  5963. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5964. UploadFormDataItems items = {
  5965. {"text1", "text default", "", ""},
  5966. {"text2", "aωb", "", ""},
  5967. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5968. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5969. {"file3", "", "", "application/octet-stream"},
  5970. };
  5971. auto res = cli_.Post("/content_receiver", items);
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. }
  5975. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5976. UploadFormDataItems items = {
  5977. {"text1", "text default", "", ""},
  5978. {"text2", "aωb", "", ""},
  5979. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5980. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5981. {"file3", "", "", "application/octet-stream"},
  5982. };
  5983. auto boundary = std::string("+++++");
  5984. std::string body;
  5985. for (const auto &item : items) {
  5986. body += "--" + boundary + "\r\n";
  5987. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5988. if (!item.filename.empty()) {
  5989. body += "; filename=\"" + item.filename + "\"";
  5990. }
  5991. body += "\r\n";
  5992. if (!item.content_type.empty()) {
  5993. body += "Content-Type: " + item.content_type + "\r\n";
  5994. }
  5995. body += "\r\n";
  5996. body += item.content + "\r\n";
  5997. }
  5998. body += "--" + boundary + "--\r\n";
  5999. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6000. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. }
  6004. TEST(MultipartFormDataTest, FieldEscaping) {
  6005. Server svr;
  6006. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6007. const ContentReader &content_reader) {
  6008. ASSERT_TRUE(req.is_multipart_form_data());
  6009. std::vector<FormData> received;
  6010. content_reader(
  6011. [&](const FormData &file) {
  6012. received.push_back(file);
  6013. return true;
  6014. },
  6015. [&](const char *data, size_t data_length) {
  6016. received.back().content.append(data, data_length);
  6017. return true;
  6018. });
  6019. // '"', CR and LF in names and filenames are escaped following the
  6020. // WHATWG HTML standard, so each part still parses as a single part
  6021. // with no injected headers. Content types get CR/LF escaped too,
  6022. // while '"' (legal there, e.g. quoted charset) is preserved.
  6023. ASSERT_EQ(4U, received.size());
  6024. EXPECT_EQ("na%22me", received[0].name);
  6025. EXPECT_EQ("quoted name", received[0].content);
  6026. EXPECT_EQ("file", received[1].name);
  6027. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6028. received[1].filename);
  6029. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6030. EXPECT_EQ("injected", received[1].content);
  6031. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6032. EXPECT_EQ("my%22file.txt", received[2].filename);
  6033. EXPECT_EQ("cr lf name", received[2].content);
  6034. EXPECT_EQ("typed", received[3].name);
  6035. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6036. received[3].content_type);
  6037. EXPECT_EQ("typed content", received[3].content);
  6038. });
  6039. auto port = svr.bind_to_any_port("localhost");
  6040. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6041. auto se = detail::scope_exit([&] {
  6042. svr.stop();
  6043. t.join();
  6044. ASSERT_FALSE(svr.is_running());
  6045. });
  6046. svr.wait_until_ready();
  6047. Client cli("localhost", port);
  6048. UploadFormDataItems items = {
  6049. {"na\"me", "quoted name", "", ""},
  6050. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6051. "application/octet-stream"},
  6052. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6053. {"typed", "typed content", "",
  6054. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6055. };
  6056. auto res = cli.Post("/post", items);
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::OK_200, res->status);
  6059. }
  6060. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6061. const UploadFormDataItems items = {
  6062. {"name1", "Content 1", "", ""},
  6063. {"name2", "Content 2", "file2.txt", "text/plain"},
  6064. };
  6065. Server svr;
  6066. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6067. const ContentReader &content_reader) {
  6068. ASSERT_TRUE(req.is_multipart_form_data());
  6069. std::vector<FormData> received;
  6070. content_reader(
  6071. [&](const FormData &file) {
  6072. received.push_back(file);
  6073. return true;
  6074. },
  6075. [&](const char *data, size_t data_length) {
  6076. received.back().content.append(data, data_length);
  6077. return true;
  6078. });
  6079. ASSERT_EQ(2U, received.size());
  6080. EXPECT_EQ("name1", received[0].name);
  6081. EXPECT_EQ("Content 1", received[0].content);
  6082. EXPECT_EQ("name2", received[1].name);
  6083. EXPECT_EQ("Content 2", received[1].content);
  6084. EXPECT_EQ("file2.txt", received[1].filename);
  6085. EXPECT_EQ("text/plain", received[1].content_type);
  6086. });
  6087. auto port = svr.bind_to_any_port("localhost");
  6088. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6089. auto se = detail::scope_exit([&] {
  6090. svr.stop();
  6091. t.join();
  6092. ASSERT_FALSE(svr.is_running());
  6093. });
  6094. svr.wait_until_ready();
  6095. Client cli("localhost", port);
  6096. // Whole-body serialization with a generated boundary
  6097. {
  6098. MultipartFormDataWriter writer;
  6099. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6100. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6101. writer.content_type());
  6102. auto body = writer.serialize(items);
  6103. EXPECT_EQ(body.size(), writer.content_length(items));
  6104. auto res = cli.Post("/post", body, writer.content_type());
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. }
  6108. // Per-part framing with a custom boundary via a content provider
  6109. {
  6110. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6111. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6112. MultipartFormDataWriter writer("custom-boundary_123");
  6113. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6114. std::string body;
  6115. for (const auto &item : items) {
  6116. body += writer.item_begin(item);
  6117. body += item.content;
  6118. body += MultipartFormDataWriter::item_end();
  6119. }
  6120. body += writer.finish();
  6121. EXPECT_EQ(body.size(), writer.content_length(items));
  6122. auto res = cli.Post(
  6123. "/post", body.size(),
  6124. [&](size_t offset, size_t length, DataSink &sink) {
  6125. sink.write(body.data() + offset, length);
  6126. return true;
  6127. },
  6128. writer.content_type());
  6129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6130. EXPECT_EQ(StatusCode::OK_200, res->status);
  6131. }
  6132. }
  6133. TEST_F(ServerTest, PostContentReceiverGzip) {
  6134. cli_.set_compress(true);
  6135. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. ASSERT_EQ(StatusCode::OK_200, res->status);
  6138. ASSERT_EQ("content", res->body);
  6139. }
  6140. TEST_F(ServerTest, PutContentReceiver) {
  6141. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. ASSERT_EQ(StatusCode::OK_200, res->status);
  6144. ASSERT_EQ("content", res->body);
  6145. }
  6146. TEST_F(ServerTest, PatchContentReceiver) {
  6147. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. ASSERT_EQ(StatusCode::OK_200, res->status);
  6150. ASSERT_EQ("content", res->body);
  6151. }
  6152. template <typename ClientType>
  6153. void TestWithHeadersAndContentReceiver(
  6154. ClientType &cli,
  6155. std::function<Result(ClientType &, const std::string &, const Headers &,
  6156. const std::string &, const std::string &,
  6157. ContentReceiver, DownloadProgress)>
  6158. request_func) {
  6159. Headers headers;
  6160. headers.emplace("X-Custom-Header", "test-value");
  6161. std::string received_body;
  6162. auto res = request_func(
  6163. cli, "/content_receiver", headers, "content", "application/json",
  6164. [&](const char *data, size_t data_length) {
  6165. received_body.append(data, data_length);
  6166. return true;
  6167. },
  6168. nullptr);
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. EXPECT_EQ(StatusCode::OK_200, res->status);
  6171. EXPECT_EQ("content", received_body);
  6172. }
  6173. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6174. #ifdef CPPHTTPLIB_SSL_ENABLED
  6175. using ClientT = SSLClient;
  6176. #else
  6177. using ClientT = Client;
  6178. #endif
  6179. TestWithHeadersAndContentReceiver<ClientT>(
  6180. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6181. const std::string &body, const std::string &content_type,
  6182. ContentReceiver receiver, DownloadProgress progress) {
  6183. return cli.Post(path, headers, body, content_type, receiver, progress);
  6184. });
  6185. }
  6186. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6187. #ifdef CPPHTTPLIB_SSL_ENABLED
  6188. using ClientT = SSLClient;
  6189. #else
  6190. using ClientT = Client;
  6191. #endif
  6192. TestWithHeadersAndContentReceiver<ClientT>(
  6193. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6194. const std::string &body, const std::string &content_type,
  6195. ContentReceiver receiver, DownloadProgress progress) {
  6196. return cli.Put(path, headers, body, content_type, receiver, progress);
  6197. });
  6198. }
  6199. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6200. #ifdef CPPHTTPLIB_SSL_ENABLED
  6201. using ClientT = SSLClient;
  6202. #else
  6203. using ClientT = Client;
  6204. #endif
  6205. TestWithHeadersAndContentReceiver<ClientT>(
  6206. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6207. const std::string &body, const std::string &content_type,
  6208. ContentReceiver receiver, DownloadProgress progress) {
  6209. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6210. });
  6211. }
  6212. template <typename ClientType>
  6213. void TestWithHeadersAndContentReceiverWithProgress(
  6214. ClientType &cli,
  6215. std::function<Result(ClientType &, const std::string &, const Headers &,
  6216. const std::string &, const std::string &,
  6217. ContentReceiver, DownloadProgress)>
  6218. request_func) {
  6219. Headers headers;
  6220. headers.emplace("X-Test-Header", "progress-test");
  6221. std::string received_body;
  6222. auto progress_called = false;
  6223. auto res = request_func(
  6224. cli, "/content_receiver", headers, "content", "text/plain",
  6225. [&](const char *data, size_t data_length) {
  6226. received_body.append(data, data_length);
  6227. return true;
  6228. },
  6229. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6230. progress_called = true;
  6231. return true;
  6232. });
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. EXPECT_EQ(StatusCode::OK_200, res->status);
  6235. EXPECT_EQ("content", received_body);
  6236. EXPECT_TRUE(progress_called);
  6237. }
  6238. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6239. #ifdef CPPHTTPLIB_SSL_ENABLED
  6240. using ClientT = SSLClient;
  6241. #else
  6242. using ClientT = Client;
  6243. #endif
  6244. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6245. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6246. const std::string &body, const std::string &content_type,
  6247. ContentReceiver receiver, DownloadProgress progress) {
  6248. return cli.Post(path, headers, body, content_type, receiver, progress);
  6249. });
  6250. }
  6251. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6252. #ifdef CPPHTTPLIB_SSL_ENABLED
  6253. using ClientT = SSLClient;
  6254. #else
  6255. using ClientT = Client;
  6256. #endif
  6257. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6258. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6259. const std::string &body, const std::string &content_type,
  6260. ContentReceiver receiver, DownloadProgress progress) {
  6261. return cli.Put(path, headers, body, content_type, receiver, progress);
  6262. });
  6263. }
  6264. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6265. #ifdef CPPHTTPLIB_SSL_ENABLED
  6266. using ClientT = SSLClient;
  6267. #else
  6268. using ClientT = Client;
  6269. #endif
  6270. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6271. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6272. const std::string &body, const std::string &content_type,
  6273. ContentReceiver receiver, DownloadProgress progress) {
  6274. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6275. });
  6276. }
  6277. template <typename ClientType>
  6278. void TestWithHeadersAndContentReceiverError(
  6279. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6280. const Headers &, const std::string &,
  6281. const std::string &, ContentReceiver)>
  6282. request_func) {
  6283. Headers headers;
  6284. headers.emplace("X-Error-Test", "true");
  6285. std::string received_body;
  6286. auto receiver_failed = false;
  6287. auto res =
  6288. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6289. [&](const char *data, size_t data_length) {
  6290. received_body.append(data, data_length);
  6291. receiver_failed = true;
  6292. return false;
  6293. });
  6294. ASSERT_FALSE(res);
  6295. EXPECT_TRUE(receiver_failed);
  6296. }
  6297. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6298. #ifdef CPPHTTPLIB_SSL_ENABLED
  6299. using ClientT = SSLClient;
  6300. #else
  6301. using ClientT = Client;
  6302. #endif
  6303. TestWithHeadersAndContentReceiverError<ClientT>(
  6304. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6305. const std::string &body, const std::string &content_type,
  6306. ContentReceiver receiver) {
  6307. return cli.Post(path, headers, body, content_type, receiver);
  6308. });
  6309. }
  6310. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6311. #ifdef CPPHTTPLIB_SSL_ENABLED
  6312. using ClientT = SSLClient;
  6313. #else
  6314. using ClientT = Client;
  6315. #endif
  6316. TestWithHeadersAndContentReceiverError<ClientT>(
  6317. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6318. const std::string &body, const std::string &content_type,
  6319. ContentReceiver receiver) {
  6320. return cli.Put(path, headers, body, content_type, receiver);
  6321. });
  6322. }
  6323. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6324. #ifdef CPPHTTPLIB_SSL_ENABLED
  6325. using ClientT = SSLClient;
  6326. #else
  6327. using ClientT = Client;
  6328. #endif
  6329. TestWithHeadersAndContentReceiverError<ClientT>(
  6330. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6331. const std::string &body, const std::string &content_type,
  6332. ContentReceiver receiver) {
  6333. return cli.Patch(path, headers, body, content_type, receiver);
  6334. });
  6335. }
  6336. TEST_F(ServerTest, PostQueryStringAndBody) {
  6337. auto res =
  6338. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. ASSERT_EQ(StatusCode::OK_200, res->status);
  6341. }
  6342. TEST_F(ServerTest, HTTP2Magic) {
  6343. Request req;
  6344. req.method = "PRI";
  6345. req.path = "*";
  6346. req.body = "SM";
  6347. auto res = std::make_shared<Response>();
  6348. auto error = Error::Success;
  6349. auto ret = cli_.send(req, *res, error);
  6350. ASSERT_TRUE(ret);
  6351. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6352. }
  6353. TEST_F(ServerTest, KeepAlive) {
  6354. auto res = cli_.Get("/hi");
  6355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6356. EXPECT_EQ(StatusCode::OK_200, res->status);
  6357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6358. EXPECT_EQ("Hello World!", res->body);
  6359. res = cli_.Get("/hi");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. EXPECT_EQ(StatusCode::OK_200, res->status);
  6362. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6363. EXPECT_EQ("Hello World!", res->body);
  6364. res = cli_.Get("/hi");
  6365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6366. EXPECT_EQ(StatusCode::OK_200, res->status);
  6367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6368. EXPECT_EQ("Hello World!", res->body);
  6369. res = cli_.Get("/not-exist");
  6370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6371. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6372. res = cli_.Post("/empty", "", "text/plain");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6376. EXPECT_EQ("empty", res->body);
  6377. EXPECT_EQ("close", res->get_header_value("Connection"));
  6378. res = cli_.Post(
  6379. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6380. "text/plain");
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6384. EXPECT_EQ("empty", res->body);
  6385. cli_.set_keep_alive(false);
  6386. res = cli_.Get("/last-request");
  6387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6388. EXPECT_EQ(StatusCode::OK_200, res->status);
  6389. EXPECT_EQ("close", res->get_header_value("Connection"));
  6390. }
  6391. TEST_F(ServerTest, TooManyRedirect) {
  6392. cli_.set_follow_location(true);
  6393. auto res = cli_.Get("/redirect/0");
  6394. ASSERT_TRUE(!res);
  6395. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6396. }
  6397. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6398. Request req;
  6399. req.method = "FOOBAR";
  6400. req.path = "/hi";
  6401. cli_.set_keep_alive(true);
  6402. auto res = cli_.send(req);
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6405. EXPECT_EQ("close", res->get_header_value("Connection"));
  6406. EXPECT_FALSE(cli_.is_socket_open());
  6407. }
  6408. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6409. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6410. TEST_F(ServerTest, Gzip) {
  6411. Headers headers;
  6412. headers.emplace("Accept-Encoding", "gzip, deflate");
  6413. auto res = cli_.Get("/compress", headers);
  6414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6415. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6416. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6417. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6418. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6419. "7890123456789012345678901234567890",
  6420. res->body);
  6421. EXPECT_EQ(StatusCode::OK_200, res->status);
  6422. }
  6423. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6424. Headers headers;
  6425. headers.emplace("Accept-Encoding", "gzip, deflate");
  6426. auto res = cli_.Get("/compress-with-charset", headers);
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6429. EXPECT_EQ("application/json; charset=utf-8",
  6430. res->get_header_value("Content-Type"));
  6431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6432. "7890123456789012345678901234567890",
  6433. res->body);
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. }
  6436. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6437. Headers headers;
  6438. headers.emplace("Accept-Encoding", "");
  6439. auto res = cli_.Get("/compress", headers);
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6443. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6445. "7890123456789012345678901234567890",
  6446. res->body);
  6447. EXPECT_EQ(StatusCode::OK_200, res->status);
  6448. }
  6449. TEST_F(ServerTest, GzipWithContentReceiver) {
  6450. Headers headers;
  6451. headers.emplace("Accept-Encoding", "gzip, deflate");
  6452. std::string body;
  6453. auto res = cli_.Get("/compress", headers,
  6454. [&](const char *data, uint64_t data_length) {
  6455. EXPECT_EQ(100U, data_length);
  6456. body.append(data, data_length);
  6457. return true;
  6458. });
  6459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6460. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6462. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6464. "7890123456789012345678901234567890",
  6465. body);
  6466. EXPECT_EQ(StatusCode::OK_200, res->status);
  6467. }
  6468. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6469. Headers headers;
  6470. headers.emplace("Accept-Encoding", "gzip, deflate");
  6471. cli_.set_decompress(false);
  6472. auto res = cli_.Get("/compress", headers);
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6475. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6476. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6477. EXPECT_EQ(33U, res->body.size());
  6478. EXPECT_EQ(StatusCode::OK_200, res->status);
  6479. }
  6480. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6481. Headers headers;
  6482. headers.emplace("Accept-Encoding", "");
  6483. std::string body;
  6484. auto res = cli_.Get("/compress", headers,
  6485. [&](const char *data, uint64_t data_length) {
  6486. EXPECT_EQ(100U, data_length);
  6487. body.append(data, data_length);
  6488. return true;
  6489. });
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6493. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6494. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6495. "7890123456789012345678901234567890",
  6496. body);
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. }
  6499. TEST_F(ServerTest, NoGzip) {
  6500. Headers headers;
  6501. headers.emplace("Accept-Encoding", "gzip, deflate");
  6502. auto res = cli_.Get("/nocompress", headers);
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6505. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6506. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6507. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6508. "7890123456789012345678901234567890",
  6509. res->body);
  6510. EXPECT_EQ(StatusCode::OK_200, res->status);
  6511. }
  6512. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6513. Headers headers;
  6514. headers.emplace("Accept-Encoding", "gzip, deflate");
  6515. std::string body;
  6516. auto res = cli_.Get("/nocompress", headers,
  6517. [&](const char *data, uint64_t data_length) {
  6518. EXPECT_EQ(100U, data_length);
  6519. body.append(data, data_length);
  6520. return true;
  6521. });
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6524. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6525. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6526. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6527. "7890123456789012345678901234567890",
  6528. body);
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. }
  6531. TEST_F(ServerTest, MultipartFormDataGzip) {
  6532. UploadFormDataItems items = {
  6533. {"key1", "test", "", ""},
  6534. {"key2", "--abcdefg123", "", ""},
  6535. };
  6536. cli_.set_compress(true);
  6537. auto res = cli_.Post("/compress-multipart", items);
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::OK_200, res->status);
  6540. }
  6541. #endif
  6542. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6543. TEST_F(ServerTest, Brotli) {
  6544. Headers headers;
  6545. headers.emplace("Accept-Encoding", "br");
  6546. auto res = cli_.Get("/compress", headers);
  6547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6548. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6550. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6551. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6552. "7890123456789012345678901234567890",
  6553. res->body);
  6554. EXPECT_EQ(StatusCode::OK_200, res->status);
  6555. }
  6556. #endif
  6557. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6558. TEST_F(ServerTest, Zstd) {
  6559. Headers headers;
  6560. headers.emplace("Accept-Encoding", "zstd");
  6561. auto res = cli_.Get("/compress", headers);
  6562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6563. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6564. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6565. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6566. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6567. "7890123456789012345678901234567890",
  6568. res->body);
  6569. EXPECT_EQ(StatusCode::OK_200, res->status);
  6570. }
  6571. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6572. Headers headers;
  6573. headers.emplace("Accept-Encoding", "");
  6574. auto res = cli_.Get("/compress", headers);
  6575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6576. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6577. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6578. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6579. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6580. "7890123456789012345678901234567890",
  6581. res->body);
  6582. EXPECT_EQ(StatusCode::OK_200, res->status);
  6583. }
  6584. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6585. Headers headers;
  6586. headers.emplace("Accept-Encoding", "zstd");
  6587. std::string body;
  6588. auto res = cli_.Get("/compress", headers,
  6589. [&](const char *data, uint64_t data_length) {
  6590. EXPECT_EQ(100U, data_length);
  6591. body.append(data, data_length);
  6592. return true;
  6593. });
  6594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6595. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6597. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6598. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6599. "7890123456789012345678901234567890",
  6600. body);
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. }
  6603. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6604. Headers headers;
  6605. headers.emplace("Accept-Encoding", "zstd");
  6606. cli_.set_decompress(false);
  6607. auto res = cli_.Get("/compress", headers);
  6608. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6609. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6610. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6611. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6615. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6616. EXPECT_EQ(StatusCode::OK_200, res->status);
  6617. ASSERT_EQ(26U, res->body.size());
  6618. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6619. 0);
  6620. }
  6621. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6622. Headers headers;
  6623. headers.emplace("Accept-Encoding", "");
  6624. std::string body;
  6625. auto res = cli_.Get("/compress", headers,
  6626. [&](const char *data, uint64_t data_length) {
  6627. EXPECT_EQ(100U, data_length);
  6628. body.append(data, data_length);
  6629. return true;
  6630. });
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6634. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6635. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6636. "7890123456789012345678901234567890",
  6637. body);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. }
  6640. TEST_F(ServerTest, NoZstd) {
  6641. Headers headers;
  6642. headers.emplace("Accept-Encoding", "zstd");
  6643. auto res = cli_.Get("/nocompress", headers);
  6644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6645. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6646. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6647. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6648. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6649. "7890123456789012345678901234567890",
  6650. res->body);
  6651. EXPECT_EQ(StatusCode::OK_200, res->status);
  6652. }
  6653. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6654. Headers headers;
  6655. headers.emplace("Accept-Encoding", "zstd");
  6656. std::string body;
  6657. auto res = cli_.Get("/nocompress", headers,
  6658. [&](const char *data, uint64_t data_length) {
  6659. EXPECT_EQ(100U, data_length);
  6660. body.append(data, data_length);
  6661. return true;
  6662. });
  6663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6664. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6665. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6666. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6667. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6668. "7890123456789012345678901234567890",
  6669. body);
  6670. EXPECT_EQ(StatusCode::OK_200, res->status);
  6671. }
  6672. // TODO: How to enable zstd ??
  6673. TEST_F(ServerTest, MultipartFormDataZstd) {
  6674. UploadFormDataItems items = {
  6675. {"key1", "test", "", ""},
  6676. {"key2", "--abcdefg123", "", ""},
  6677. };
  6678. Headers headers;
  6679. headers.emplace("Accept-Encoding", "zstd");
  6680. cli_.set_compress(true);
  6681. auto res = cli_.Post("/compress-multipart", headers, items);
  6682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. }
  6685. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6686. Headers headers;
  6687. headers.emplace("Accept-Encoding", "zstd");
  6688. cli_.set_compress(true);
  6689. auto res = cli_.Put(
  6690. "/put", headers, 3,
  6691. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6692. sink.os << "PUT";
  6693. return true;
  6694. },
  6695. "text/plain");
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::OK_200, res->status);
  6698. EXPECT_EQ("PUT", res->body);
  6699. }
  6700. // Pre-compression logging tests
  6701. TEST_F(ServerTest, PreCompressionLogging) {
  6702. // Test data for compression (matches the actual /compress endpoint content)
  6703. const std::string test_content =
  6704. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6705. "3456789012345678901234567890";
  6706. // Variables to capture logging data
  6707. std::string pre_compression_body;
  6708. std::string pre_compression_content_type;
  6709. std::string pre_compression_content_encoding;
  6710. std::string post_compression_body;
  6711. std::string post_compression_content_type;
  6712. std::string post_compression_content_encoding;
  6713. // Set up pre-compression logger
  6714. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6715. const Response &res) {
  6716. pre_compression_body = res.body;
  6717. pre_compression_content_type = res.get_header_value("Content-Type");
  6718. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6719. });
  6720. // Set up post-compression logger
  6721. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6722. post_compression_body = res.body;
  6723. post_compression_content_type = res.get_header_value("Content-Type");
  6724. post_compression_content_encoding =
  6725. res.get_header_value("Content-Encoding");
  6726. });
  6727. // Test with gzip compression
  6728. Headers headers;
  6729. headers.emplace("Accept-Encoding", "gzip");
  6730. auto res = cli_.Get("/compress", headers);
  6731. // Verify response was compressed
  6732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6733. EXPECT_EQ(StatusCode::OK_200, res->status);
  6734. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6735. // Verify pre-compression logger captured uncompressed content
  6736. EXPECT_EQ(test_content, pre_compression_body);
  6737. EXPECT_EQ("text/plain", pre_compression_content_type);
  6738. EXPECT_TRUE(pre_compression_content_encoding
  6739. .empty()); // No encoding header before compression
  6740. // Verify post-compression logger captured compressed content
  6741. EXPECT_NE(test_content,
  6742. post_compression_body); // Should be different after compression
  6743. EXPECT_EQ("text/plain", post_compression_content_type);
  6744. EXPECT_EQ("gzip", post_compression_content_encoding);
  6745. // Verify compressed content is smaller
  6746. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6747. }
  6748. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6749. const std::string test_content =
  6750. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6751. "3456789012345678901234567890";
  6752. std::string pre_compression_body;
  6753. std::string post_compression_body;
  6754. svr_.set_pre_compression_logger(
  6755. [&](const Request & /*req*/, const Response &res) {
  6756. pre_compression_body = res.body;
  6757. });
  6758. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6759. post_compression_body = res.body;
  6760. });
  6761. Headers headers;
  6762. headers.emplace("Accept-Encoding", "br");
  6763. auto res = cli_.Get("/compress", headers);
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6767. // Verify pre-compression content is uncompressed
  6768. EXPECT_EQ(test_content, pre_compression_body);
  6769. // Verify post-compression content is compressed
  6770. EXPECT_NE(test_content, post_compression_body);
  6771. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6772. }
  6773. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6774. const std::string test_content =
  6775. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6776. "3456789012345678901234567890";
  6777. std::string pre_compression_body;
  6778. std::string post_compression_body;
  6779. svr_.set_pre_compression_logger(
  6780. [&](const Request & /*req*/, const Response &res) {
  6781. pre_compression_body = res.body;
  6782. });
  6783. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6784. post_compression_body = res.body;
  6785. });
  6786. // Request without compression (use /nocompress endpoint)
  6787. Headers headers;
  6788. auto res = cli_.Get("/nocompress", headers);
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6792. // Pre-compression logger should not be called when no compression is applied
  6793. EXPECT_TRUE(
  6794. pre_compression_body.empty()); // Pre-compression logger not called
  6795. EXPECT_EQ(
  6796. test_content,
  6797. post_compression_body); // Post-compression logger captures final content
  6798. }
  6799. TEST_F(ServerTest, LoggerSeesContentLength) {
  6800. size_t logged_content_length = 0;
  6801. std::string logged_content_length_header;
  6802. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6803. logged_content_length = res.content_length_;
  6804. logged_content_length_header = res.get_header_value("Content-Length");
  6805. });
  6806. auto res = cli_.Get("/nocompress");
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::OK_200, res->status);
  6809. EXPECT_EQ(res->body.size(), logged_content_length);
  6810. EXPECT_EQ(std::to_string(logged_content_length),
  6811. logged_content_length_header);
  6812. }
  6813. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6814. const std::string test_content =
  6815. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6816. "3456789012345678901234567890";
  6817. std::string pre_compression_body;
  6818. bool pre_logger_called = false;
  6819. // Set only pre-compression logger
  6820. svr_.set_pre_compression_logger(
  6821. [&](const Request & /*req*/, const Response &res) {
  6822. pre_compression_body = res.body;
  6823. pre_logger_called = true;
  6824. });
  6825. Headers headers;
  6826. headers.emplace("Accept-Encoding", "gzip");
  6827. auto res = cli_.Get("/compress", headers);
  6828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6829. EXPECT_EQ(StatusCode::OK_200, res->status);
  6830. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6831. // Verify pre-compression logger was called
  6832. EXPECT_TRUE(pre_logger_called);
  6833. EXPECT_EQ(test_content, pre_compression_body);
  6834. }
  6835. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6836. {
  6837. // Test with Expect: 100-continue header - success case
  6838. // Server returns 100 Continue, client sends body, server returns 200 OK
  6839. Request req;
  6840. req.method = "POST";
  6841. req.path = "/post-large";
  6842. req.set_header("Expect", "100-continue");
  6843. req.body = LARGE_DATA;
  6844. Response res;
  6845. auto error = Error::Success;
  6846. cli_.set_keep_alive(true);
  6847. auto ret = cli_.send(req, res, error);
  6848. EXPECT_TRUE(ret);
  6849. EXPECT_EQ(StatusCode::OK_200, res.status);
  6850. EXPECT_EQ(LARGE_DATA, res.body);
  6851. }
  6852. {
  6853. // Test with Expect: 100-continue header - error case
  6854. // Client should not send the body when server returns an error
  6855. Request req;
  6856. req.method = "POST";
  6857. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6858. req.set_header("Expect", "100-continue");
  6859. req.body = LARGE_DATA;
  6860. Response res;
  6861. auto error = Error::Success;
  6862. auto start = std::chrono::high_resolution_clock::now();
  6863. cli_.set_keep_alive(true);
  6864. auto ret = cli_.send(req, res, error);
  6865. auto end = std::chrono::high_resolution_clock::now();
  6866. auto elapsed =
  6867. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6868. .count();
  6869. // With Expect: 100-continue, request completes successfully but with error
  6870. EXPECT_TRUE(ret);
  6871. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6872. EXPECT_EQ("close", res.get_header_value("Connection"));
  6873. EXPECT_FALSE(cli_.is_socket_open());
  6874. EXPECT_LE(elapsed, 2000);
  6875. }
  6876. {
  6877. // Send an extra GET request to ensure error recovery without hanging
  6878. Request req;
  6879. req.method = "GET";
  6880. req.path = "/hi";
  6881. auto start = std::chrono::high_resolution_clock::now();
  6882. auto res = cli_.send(req);
  6883. auto end = std::chrono::high_resolution_clock::now();
  6884. auto elapsed =
  6885. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6886. .count();
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. EXPECT_EQ("Hello World!", res->body);
  6890. EXPECT_LE(elapsed, 500);
  6891. }
  6892. }
  6893. TEST(ZstdDecompressor, ChunkedDecompression) {
  6894. std::string data;
  6895. for (size_t i = 0; i < 32 * 1024; ++i) {
  6896. data.push_back(static_cast<char>('a' + i % 26));
  6897. }
  6898. std::string compressed_data;
  6899. {
  6900. httplib::detail::zstd_compressor compressor;
  6901. bool result = compressor.compress(
  6902. data.data(), data.size(),
  6903. /*last=*/true,
  6904. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6905. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6906. compressed_data_size);
  6907. return true;
  6908. });
  6909. ASSERT_TRUE(result);
  6910. }
  6911. std::string decompressed_data;
  6912. {
  6913. httplib::detail::zstd_decompressor decompressor;
  6914. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6915. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6916. size_t chunk_size = 130;
  6917. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6918. chunk_begin += chunk_size) {
  6919. size_t current_chunk_size =
  6920. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6921. bool result = decompressor.decompress(
  6922. compressed_data.data() + chunk_begin, current_chunk_size,
  6923. [&](const char *decompressed_data_chunk,
  6924. size_t decompressed_data_chunk_size) {
  6925. decompressed_data.insert(decompressed_data.size(),
  6926. decompressed_data_chunk,
  6927. decompressed_data_chunk_size);
  6928. return true;
  6929. });
  6930. ASSERT_TRUE(result);
  6931. }
  6932. }
  6933. ASSERT_EQ(data, decompressed_data);
  6934. }
  6935. TEST(ZstdDecompressor, Decompress) {
  6936. std::string original_text = "Compressed with ZSTD";
  6937. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6938. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6939. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6940. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6941. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6942. std::string decompressed_data;
  6943. {
  6944. httplib::detail::zstd_decompressor decompressor;
  6945. bool result = decompressor.decompress(
  6946. compressed_data.data(), compressed_data.size(),
  6947. [&](const char *decompressed_data_chunk,
  6948. size_t decompressed_data_chunk_size) {
  6949. decompressed_data.insert(decompressed_data.size(),
  6950. decompressed_data_chunk,
  6951. decompressed_data_chunk_size);
  6952. return true;
  6953. });
  6954. ASSERT_TRUE(result);
  6955. }
  6956. ASSERT_EQ(original_text, decompressed_data);
  6957. }
  6958. #endif
  6959. // Sends a raw request to a server listening at HOST:PORT.
  6960. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6961. std::string *resp = nullptr) {
  6962. auto error = Error::Success;
  6963. auto client_sock = detail::create_client_socket(
  6964. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6965. /*connection_timeout_sec=*/5, 0,
  6966. /*read_timeout_sec=*/5, 0,
  6967. /*write_timeout_sec=*/5, 0, std::string(), error);
  6968. if (client_sock == INVALID_SOCKET) { return false; }
  6969. auto ret = detail::process_client_socket(
  6970. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6971. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6972. if (req.size() !=
  6973. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6974. return false;
  6975. }
  6976. char buf[512];
  6977. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6978. while (line_reader.getline()) {
  6979. if (resp) { *resp += line_reader.ptr(); }
  6980. }
  6981. return true;
  6982. });
  6983. detail::close_socket(client_sock);
  6984. return ret;
  6985. }
  6986. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6987. Server svr;
  6988. std::string header_value;
  6989. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6990. header_value = req.get_header_value("foo");
  6991. res.set_content("ok", "text/plain");
  6992. });
  6993. thread t = thread([&] { svr.listen(HOST, PORT); });
  6994. auto se = detail::scope_exit([&] {
  6995. svr.stop();
  6996. t.join();
  6997. ASSERT_FALSE(svr.is_running());
  6998. });
  6999. svr.wait_until_ready();
  7000. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  7001. // like characters are not treated the same - use vertical tab and escape.
  7002. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  7003. "foo: \t \v bar \x1B\t \r\n"
  7004. "Connection: close\r\n"
  7005. "\r\n";
  7006. std::string res;
  7007. ASSERT_TRUE(send_request(5, req, &res));
  7008. EXPECT_EQ(header_value, "");
  7009. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  7010. }
  7011. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  7012. Server svr;
  7013. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  7014. auto i = new int(0);
  7015. res.set_header("Trailer", "X-Safe, X-Reflected");
  7016. res.set_chunked_content_provider(
  7017. "text/plain",
  7018. [i](size_t /*offset*/, DataSink &sink) {
  7019. if (*i == 0) {
  7020. sink.os << "body";
  7021. } else {
  7022. Headers trailer;
  7023. // A valid trailer that must survive.
  7024. trailer.emplace("X-Safe", "safe");
  7025. // Attacker-controlled value carrying CR/LF (response splitting).
  7026. trailer.emplace("X-Reflected",
  7027. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7028. // Attacker-controlled name carrying CR/LF.
  7029. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7030. sink.done_with_trailer(trailer);
  7031. }
  7032. (*i)++;
  7033. return true;
  7034. },
  7035. [i](bool /*success*/) { delete i; });
  7036. });
  7037. thread t = thread([&] { svr.listen(HOST, PORT); });
  7038. auto se = detail::scope_exit([&] {
  7039. svr.stop();
  7040. t.join();
  7041. ASSERT_FALSE(svr.is_running());
  7042. });
  7043. svr.wait_until_ready();
  7044. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  7045. "Host: " + HOST +
  7046. "\r\n"
  7047. "Connection: close\r\n"
  7048. "\r\n";
  7049. std::string res;
  7050. ASSERT_TRUE(send_request(5, req, &res));
  7051. // The injected fields must not appear anywhere in the raw response.
  7052. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7053. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7054. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7055. // Invalid trailers are dropped entirely, matching set_header().
  7056. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7057. // The valid trailer still passes through.
  7058. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7059. }
  7060. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  7061. Server svr;
  7062. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  7063. // res.headers is a public field an application can populate directly,
  7064. // bypassing set_header()'s validation (e.g. reflecting a request value).
  7065. // A valid header that must survive.
  7066. res.headers.emplace("X-Safe", "safe");
  7067. // Attacker-controlled value carrying CR/LF (response splitting).
  7068. res.headers.emplace("X-Reflected",
  7069. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  7070. // Attacker-controlled name carrying CR/LF.
  7071. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7072. res.set_content("body", "text/plain");
  7073. });
  7074. thread t = thread([&] { svr.listen(HOST, PORT); });
  7075. auto se = detail::scope_exit([&] {
  7076. svr.stop();
  7077. t.join();
  7078. ASSERT_FALSE(svr.is_running());
  7079. });
  7080. svr.wait_until_ready();
  7081. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7082. "Host: " + HOST +
  7083. "\r\n"
  7084. "Connection: close\r\n"
  7085. "\r\n";
  7086. std::string res;
  7087. ASSERT_TRUE(send_request(5, req, &res));
  7088. // The injected fields must not appear anywhere in the raw response.
  7089. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7090. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7091. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7092. // Invalid headers are dropped entirely, matching set_header().
  7093. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7094. // The valid header still passes through.
  7095. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7096. }
  7097. // Forward declaration: in split builds split.py strips `inline` and moves the
  7098. // definition into httplib.cc, so detail::write_request_line is not visible from
  7099. // the public httplib.h. Re-declaring it here lets the tests link against the
  7100. // symbol in both header-only and split builds.
  7101. namespace httplib {
  7102. namespace detail {
  7103. ssize_t write_request_line(Stream &strm, const std::string &method,
  7104. const std::string &path);
  7105. } // namespace detail
  7106. } // namespace httplib
  7107. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7108. // A well-formed target is written verbatim.
  7109. {
  7110. detail::BufferStream strm;
  7111. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7112. EXPECT_GT(n, 0);
  7113. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7114. }
  7115. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7116. // otherwise it splits the request line and injects a header or a whole
  7117. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7118. // when path encoding is disabled.
  7119. const std::string evil_targets[] = {
  7120. "/a\r\nInjected: pwned",
  7121. "/a\rInjected",
  7122. "/a\nInjected",
  7123. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7124. };
  7125. for (const auto &evil : evil_targets) {
  7126. detail::BufferStream strm;
  7127. auto n = detail::write_request_line(strm, "GET", evil);
  7128. EXPECT_LT(n, 0);
  7129. EXPECT_TRUE(strm.get_buffer().empty());
  7130. }
  7131. }
  7132. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7133. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7134. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7135. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7136. // client must fail cleanly with Error::Write instead of putting a
  7137. // request-line-less, header-injecting request on the wire.
  7138. Server svr;
  7139. svr.Get("/a", [](const Request &, Response &res) {
  7140. res.set_content("ok", "text/plain");
  7141. });
  7142. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7143. auto se = detail::scope_exit([&] {
  7144. svr.stop();
  7145. thread.join();
  7146. ASSERT_FALSE(svr.is_running());
  7147. });
  7148. svr.wait_until_ready();
  7149. {
  7150. Client cli(HOST, PORT);
  7151. cli.set_path_encode(false);
  7152. // The request is rejected before anything is written, so the connection
  7153. // stays silent and the subsequent response read would otherwise block for
  7154. // the full default read timeout. Shorten it -- the assertion is on the
  7155. // error, not the timeout.
  7156. cli.set_read_timeout(1, 0);
  7157. auto res = cli.Get("/a\r\nInjected: pwned");
  7158. EXPECT_FALSE(res);
  7159. EXPECT_EQ(Error::Write, res.error());
  7160. }
  7161. }
  7162. // Sends a raw request and verifies that there isn't a crash or exception.
  7163. static void test_raw_request(const std::string &req,
  7164. std::string *out = nullptr) {
  7165. Server svr;
  7166. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7167. res.set_content("ok", "text/plain");
  7168. });
  7169. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7170. res.set_content("ok", "text/plain");
  7171. });
  7172. svr.Get("/header_field_value_check",
  7173. [&](const Request & /*req*/, Response &res) {
  7174. res.set_content("ok", "text/plain");
  7175. });
  7176. // Server read timeout must be longer than the client read timeout for the
  7177. // bug to reproduce, probably to force the server to process a request
  7178. // without a trailing blank line.
  7179. const time_t client_read_timeout_sec = 1;
  7180. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7181. bool listen_thread_ok = false;
  7182. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7183. auto se = detail::scope_exit([&] {
  7184. svr.stop();
  7185. t.join();
  7186. ASSERT_FALSE(svr.is_running());
  7187. EXPECT_TRUE(listen_thread_ok);
  7188. });
  7189. svr.wait_until_ready();
  7190. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7191. }
  7192. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7193. // A certain header line causes an exception if the header property is parsed
  7194. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7195. test_raw_request(
  7196. "GET /hi HTTP/1.1\r\n"
  7197. " : "
  7198. " "
  7199. " ");
  7200. }
  7201. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7202. // A certain header line causes an exception if the header property *name* is
  7203. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7204. // greedy matcher and requires backtracking when there are a lot of ":"
  7205. // characters.
  7206. // This occurs with libc++ but not libstdc++.
  7207. test_raw_request(
  7208. "GET /hi HTTP/1.1\r\n"
  7209. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7210. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7211. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7212. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7213. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7214. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7215. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7216. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7217. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7218. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7219. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7220. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7221. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7222. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7223. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7224. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7225. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7226. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7227. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7228. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7229. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7230. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7231. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7232. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7233. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7234. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7235. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7236. "&&&%%%");
  7237. }
  7238. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7239. // Make sure this doesn't crash the server.
  7240. // In a previous version of the header line regex, the "\r" rendered the line
  7241. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7242. // a new position where the leading white space ended and the field value
  7243. // began.
  7244. // The crash occurs with libc++ but not libstdc++.
  7245. test_raw_request("GET /hi HTTP/1.1\r\n"
  7246. "a:" +
  7247. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7248. "\r\n"
  7249. "\r\n");
  7250. }
  7251. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7252. std::string out;
  7253. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7254. "Content-Type: text/plain\r\n"
  7255. "Transfer-Encoding: chunked\r\n"
  7256. "\r\n"
  7257. "nothex\r\n",
  7258. &out);
  7259. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7260. }
  7261. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7262. std::string out;
  7263. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7264. "Content-Type: text/plain\r\n"
  7265. "Transfer-Encoding: chunked\r\n"
  7266. "\r\n"
  7267. "3\r\n"
  7268. "xyz\r\n"
  7269. "NaN\r\n",
  7270. &out);
  7271. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7272. }
  7273. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7274. std::string out;
  7275. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7276. "Content-Type: text/plain\r\n"
  7277. "Transfer-Encoding: chunked\r\n"
  7278. "\r\n"
  7279. // Length is too large for 64 bits.
  7280. "1ffffffffffffffff\r\n"
  7281. "xyz\r\n",
  7282. &out);
  7283. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7284. }
  7285. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7286. test_raw_request("GET /hi HTTP/1.1\r\n"
  7287. "Content-Type: text/plain\r\n\r");
  7288. }
  7289. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7290. std::string out;
  7291. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7293. }
  7294. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7295. Server svr;
  7296. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7297. EXPECT_TRUE(!req.remote_addr.empty());
  7298. });
  7299. thread t = thread([&] { svr.listen(HOST, PORT); });
  7300. auto se = detail::scope_exit([&] {
  7301. svr.stop();
  7302. t.join();
  7303. ASSERT_FALSE(svr.is_running());
  7304. });
  7305. svr.wait_until_ready();
  7306. // Send an invalid request line to trigger Bad Request
  7307. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7308. std::string out;
  7309. ASSERT_TRUE(send_request(5, bad_req, &out));
  7310. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7311. }
  7312. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7313. std::string out;
  7314. std::string request(
  7315. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7316. test_raw_request(request, &out);
  7317. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7318. }
  7319. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7320. std::string out;
  7321. std::string request(
  7322. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7323. test_raw_request(request, &out);
  7324. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7325. }
  7326. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7327. std::string out;
  7328. std::string request(
  7329. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7330. test_raw_request(request, &out);
  7331. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7332. }
  7333. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7334. std::string out;
  7335. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7336. "Test: \r\n\r\n",
  7337. &out);
  7338. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7339. }
  7340. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7341. Server svr;
  7342. std::string x_custom;
  7343. std::string cookie;
  7344. std::string xff;
  7345. std::string x_unicode;
  7346. std::string x_iis;
  7347. svr.Get("/check", [&](const Request &req, Response &res) {
  7348. x_custom = req.get_header_value("X-Custom");
  7349. cookie = req.get_header_value("Cookie");
  7350. xff = req.get_header_value("X-Forwarded-For");
  7351. x_unicode = req.get_header_value("X-Unicode");
  7352. x_iis = req.get_header_value("X-IIS");
  7353. res.set_content("ok", "text/plain");
  7354. });
  7355. thread t = thread([&] { svr.listen(HOST, PORT); });
  7356. auto se = detail::scope_exit([&] {
  7357. svr.stop();
  7358. t.join();
  7359. ASSERT_FALSE(svr.is_running());
  7360. });
  7361. svr.wait_until_ready();
  7362. const std::string req = "GET /check HTTP/1.1\r\n"
  7363. "Host: localhost\r\n"
  7364. "X-Custom: a%0D%0AInjected: b\r\n"
  7365. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7366. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7367. "X-Unicode: %E3%81%82\r\n"
  7368. "X-IIS: %u00E9\r\n"
  7369. "Connection: close\r\n"
  7370. "\r\n";
  7371. std::string res;
  7372. ASSERT_TRUE(send_request(5, req, &res));
  7373. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7374. // Every value must be returned verbatim (wire form), with no decoding.
  7375. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7376. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7377. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7378. EXPECT_EQ("%E3%81%82", x_unicode);
  7379. EXPECT_EQ("%u00E9", x_iis);
  7380. }
  7381. // Applications that previously relied on automatic percent-decoding can
  7382. // reproduce the old behavior by explicitly calling decode_path_component()
  7383. // or, for RFC 3986 conformance, decode_uri_component().
  7384. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7385. Server svr;
  7386. std::string decoded;
  7387. svr.Get("/check", [&](const Request &req, Response &res) {
  7388. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7389. res.set_content("ok", "text/plain");
  7390. });
  7391. thread t = thread([&] { svr.listen(HOST, PORT); });
  7392. auto se = detail::scope_exit([&] {
  7393. svr.stop();
  7394. t.join();
  7395. ASSERT_FALSE(svr.is_running());
  7396. });
  7397. svr.wait_until_ready();
  7398. const std::string req = "GET /check HTTP/1.1\r\n"
  7399. "Host: localhost\r\n"
  7400. "X-Custom: hello%20world\r\n"
  7401. "Connection: close\r\n"
  7402. "\r\n";
  7403. std::string res;
  7404. ASSERT_TRUE(send_request(5, req, &res));
  7405. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7406. EXPECT_EQ("hello world", decoded);
  7407. }
  7408. // Regression test for #2033. Browsers send Referer values that include
  7409. // percent-encoded characters such as %0A inside the URL. Decoding the
  7410. // header value would either trip the post-decode CR/LF/NUL guard (the
  7411. // original bug, returning 400) or, after that guard was relaxed, silently
  7412. // store a literal LF — both unacceptable. The wire form must round-trip.
  7413. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7414. Server svr;
  7415. std::string referer;
  7416. svr.Get("/check", [&](const Request &req, Response &res) {
  7417. referer = req.get_header_value("Referer");
  7418. res.set_content("ok", "text/plain");
  7419. });
  7420. thread t = thread([&] { svr.listen(HOST, PORT); });
  7421. auto se = detail::scope_exit([&] {
  7422. svr.stop();
  7423. t.join();
  7424. ASSERT_FALSE(svr.is_running());
  7425. });
  7426. svr.wait_until_ready();
  7427. const std::string req = "GET /check HTTP/1.1\r\n"
  7428. "Host: localhost\r\n"
  7429. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7430. "Connection: close\r\n"
  7431. "\r\n";
  7432. std::string res;
  7433. ASSERT_TRUE(send_request(5, req, &res));
  7434. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7435. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7436. }
  7437. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7438. Server svr;
  7439. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7440. res.set_header("Cache-Control", "no-cache");
  7441. res.set_chunked_content_provider(
  7442. "text/event-stream", [](size_t offset, DataSink &sink) {
  7443. std::string s = "data:";
  7444. s += std::to_string(offset);
  7445. s += "\n\n";
  7446. auto ret = sink.write(s.data(), s.size());
  7447. EXPECT_TRUE(ret);
  7448. std::this_thread::sleep_for(std::chrono::seconds(1));
  7449. return true;
  7450. });
  7451. });
  7452. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7453. svr.wait_until_ready();
  7454. Client client(HOST, PORT);
  7455. const Headers headers = {{"Accept", "text/event-stream"}};
  7456. auto get_thread = std::thread([&client, &headers]() {
  7457. auto res = client.Get(
  7458. "/events", headers,
  7459. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7460. });
  7461. auto se = detail::scope_exit([&] {
  7462. svr.stop();
  7463. get_thread.join();
  7464. listen_thread.join();
  7465. ASSERT_FALSE(svr.is_running());
  7466. });
  7467. // Give GET time to get a few messages.
  7468. std::this_thread::sleep_for(std::chrono::seconds(2));
  7469. }
  7470. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7471. httplib::Server svr;
  7472. svr.Post("/hi",
  7473. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7474. res.status = StatusCode::OK_200;
  7475. });
  7476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7477. svr.wait_until_ready();
  7478. Client cli(HOST, PORT);
  7479. auto res = cli.Post("/hi", "data", "text/plain");
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::OK_200, res->status);
  7482. svr.stop();
  7483. thread.join();
  7484. ASSERT_FALSE(svr.is_running());
  7485. res = cli.Post("/hi", "data", "text/plain");
  7486. ASSERT_FALSE(res);
  7487. }
  7488. TEST(ServerStopTest, ListenFailure) {
  7489. Server svr;
  7490. auto t = thread([&]() {
  7491. auto ret = svr.listen("????", PORT);
  7492. EXPECT_FALSE(ret);
  7493. });
  7494. svr.wait_until_ready();
  7495. svr.stop();
  7496. t.join();
  7497. }
  7498. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7499. TEST(ServerStopTest, Decommision) {
  7500. Server svr;
  7501. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7502. for (int i = 0; i < 4; i++) {
  7503. auto is_even = !(i % 2);
  7504. std::thread t{[&] {
  7505. try {
  7506. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7507. if (is_even) {
  7508. throw std::runtime_error("Some thing that happens to go wrong.");
  7509. }
  7510. svr.listen(HOST, PORT);
  7511. } catch (...) { svr.decommission(); }
  7512. }};
  7513. svr.wait_until_ready();
  7514. // Server is up
  7515. {
  7516. Client cli(HOST, PORT);
  7517. auto res = cli.Get("/hi");
  7518. if (is_even) {
  7519. EXPECT_FALSE(res);
  7520. } else {
  7521. EXPECT_TRUE(res);
  7522. EXPECT_EQ("hi...", res->body);
  7523. }
  7524. }
  7525. svr.stop();
  7526. t.join();
  7527. // Server is down...
  7528. {
  7529. Client cli(HOST, PORT);
  7530. auto res = cli.Get("/hi");
  7531. EXPECT_FALSE(res);
  7532. }
  7533. }
  7534. }
  7535. #endif
  7536. // Helper function for string body upload progress tests
  7537. template <typename SetupHandler, typename ClientCall>
  7538. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7539. ClientCall &&client_call,
  7540. const string &body) {
  7541. Server svr;
  7542. setup_handler(svr);
  7543. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7544. auto se = detail::scope_exit([&] {
  7545. svr.stop();
  7546. t.join();
  7547. });
  7548. svr.wait_until_ready();
  7549. Client cli(HOST, PORT);
  7550. vector<uint64_t> progress_values;
  7551. bool progress_called = false;
  7552. auto res =
  7553. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7554. progress_values.push_back(current);
  7555. progress_called = true;
  7556. return true;
  7557. });
  7558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7559. EXPECT_EQ(200, res->status);
  7560. EXPECT_TRUE(progress_called);
  7561. }
  7562. TEST(UploadProgressTest, PostStringBodyBasic) {
  7563. TestStringBodyUploadProgress(
  7564. [](Server &svr) {
  7565. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7566. res.set_content("received", "text/plain");
  7567. });
  7568. },
  7569. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7570. return cli.Post("/test", body, "text/plain", progress_callback);
  7571. },
  7572. "test data for upload progress");
  7573. }
  7574. TEST(UploadProgressTest, PutStringBodyBasic) {
  7575. TestStringBodyUploadProgress(
  7576. [](Server &svr) {
  7577. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7578. res.set_content("put received", "text/plain");
  7579. });
  7580. },
  7581. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7582. return cli.Put("/test", body, "text/plain", progress_callback);
  7583. },
  7584. "put test data for upload progress");
  7585. }
  7586. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7587. TestStringBodyUploadProgress(
  7588. [](Server &svr) {
  7589. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7590. res.set_content("patch received", "text/plain");
  7591. });
  7592. },
  7593. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7594. return cli.Patch("/test", body, "text/plain", progress_callback);
  7595. },
  7596. "patch test data for upload progress");
  7597. }
  7598. // Helper function for content provider upload progress tests
  7599. template <typename SetupHandler, typename ClientCall>
  7600. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7601. ClientCall &&client_call) {
  7602. Server svr;
  7603. setup_handler(svr);
  7604. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7605. auto se = detail::scope_exit([&] {
  7606. svr.stop();
  7607. t.join();
  7608. });
  7609. svr.wait_until_ready();
  7610. Client cli(HOST, PORT);
  7611. vector<uint64_t> progress_values;
  7612. auto res =
  7613. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7614. progress_values.push_back(current);
  7615. return true;
  7616. });
  7617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7618. EXPECT_EQ(200, res->status);
  7619. EXPECT_FALSE(progress_values.empty());
  7620. }
  7621. TEST(UploadProgressTest, PostContentProviderProgress) {
  7622. TestContentProviderUploadProgress(
  7623. [](Server &svr) {
  7624. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7625. res.set_content("provider received", "text/plain");
  7626. });
  7627. },
  7628. [](Client &cli, UploadProgress progress_callback) {
  7629. return cli.Post(
  7630. "/test", 10,
  7631. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7632. sink.os << "test data";
  7633. return true;
  7634. },
  7635. "text/plain", progress_callback);
  7636. });
  7637. }
  7638. // Helper function for multipart upload progress tests
  7639. template <typename SetupHandler, typename ClientCall>
  7640. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7641. ClientCall &&client_call,
  7642. const string &endpoint) {
  7643. Server svr;
  7644. setup_handler(svr);
  7645. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7646. auto se = detail::scope_exit([&] {
  7647. svr.stop();
  7648. t.join();
  7649. });
  7650. svr.wait_until_ready();
  7651. Client cli(HOST, PORT);
  7652. vector<uint64_t> progress_values;
  7653. UploadFormDataItems items = {
  7654. {"field1", "value1", "", ""},
  7655. {"field2", "longer value for progress tracking test", "", ""},
  7656. {"file1", "file content data for upload progress", "test.txt",
  7657. "text/plain"}};
  7658. auto res = client_call(cli, endpoint, items,
  7659. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7660. progress_values.push_back(current);
  7661. return true;
  7662. });
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ(200, res->status);
  7665. EXPECT_FALSE(progress_values.empty());
  7666. }
  7667. TEST(UploadProgressTest, PostMultipartProgress) {
  7668. TestMultipartUploadProgress(
  7669. [](Server &svr) {
  7670. svr.Post("/multipart", [](const Request &req, Response &res) {
  7671. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7672. res.set_content("multipart received", "text/plain");
  7673. });
  7674. },
  7675. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7676. UploadProgress progress_callback) {
  7677. return cli.Post(endpoint, items, progress_callback);
  7678. },
  7679. "/multipart");
  7680. }
  7681. // Helper function for basic download progress tests
  7682. template <typename SetupHandler, typename ClientCall>
  7683. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7684. ClientCall &&client_call, const string &endpoint,
  7685. size_t expected_content_size) {
  7686. Server svr;
  7687. setup_handler(svr);
  7688. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7689. auto se = detail::scope_exit([&] {
  7690. svr.stop();
  7691. t.join();
  7692. });
  7693. svr.wait_until_ready();
  7694. Client cli(HOST, PORT);
  7695. vector<uint64_t> progress_values;
  7696. auto res = client_call(cli, endpoint,
  7697. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7698. progress_values.push_back(current);
  7699. return true;
  7700. });
  7701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7702. EXPECT_EQ(200, res->status);
  7703. EXPECT_FALSE(progress_values.empty());
  7704. EXPECT_EQ(expected_content_size, res->body.size());
  7705. }
  7706. TEST(DownloadProgressTest, GetBasic) {
  7707. TestBasicDownloadProgress(
  7708. [](Server &svr) {
  7709. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7710. string content(1000, 'D');
  7711. res.set_content(content, "text/plain");
  7712. });
  7713. },
  7714. [](Client &cli, const string &endpoint,
  7715. DownloadProgress progress_callback) {
  7716. return cli.Get(endpoint, progress_callback);
  7717. },
  7718. "/download", 1000u);
  7719. }
  7720. // Helper function for content receiver download progress tests
  7721. template <typename SetupHandler, typename ClientCall>
  7722. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7723. ClientCall &&client_call,
  7724. const string &endpoint,
  7725. size_t expected_content_size) {
  7726. Server svr;
  7727. setup_handler(svr);
  7728. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7729. auto se = detail::scope_exit([&] {
  7730. svr.stop();
  7731. t.join();
  7732. });
  7733. svr.wait_until_ready();
  7734. Client cli(HOST, PORT);
  7735. vector<uint64_t> progress_values;
  7736. string received_body;
  7737. auto res = client_call(
  7738. cli, endpoint,
  7739. [&](const char *data, size_t data_length) -> bool {
  7740. received_body.append(data, data_length);
  7741. return true;
  7742. },
  7743. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7744. progress_values.push_back(current);
  7745. return true;
  7746. });
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(200, res->status);
  7749. EXPECT_FALSE(progress_values.empty());
  7750. EXPECT_EQ(expected_content_size, received_body.size());
  7751. EXPECT_TRUE(res->body.empty());
  7752. }
  7753. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7754. TestContentReceiverDownloadProgress(
  7755. [](Server &svr) {
  7756. svr.Get("/download-receiver",
  7757. [](const Request & /*req*/, Response &res) {
  7758. string content(2000, 'R');
  7759. res.set_content(content, "text/plain");
  7760. });
  7761. },
  7762. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7763. DownloadProgress progress_callback) {
  7764. return cli.Get(endpoint, content_receiver, progress_callback);
  7765. },
  7766. "/download-receiver", 2000u);
  7767. }
  7768. TEST(StreamingTest, NoContentLengthStreaming) {
  7769. Server svr;
  7770. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7771. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7772. if (offset < 6) {
  7773. sink.os << (offset < 3 ? "a" : "b");
  7774. } else {
  7775. sink.done();
  7776. }
  7777. return true;
  7778. });
  7779. });
  7780. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7781. auto listen_se = detail::scope_exit([&] {
  7782. svr.stop();
  7783. listen_thread.join();
  7784. ASSERT_FALSE(svr.is_running());
  7785. });
  7786. svr.wait_until_ready();
  7787. Client client(HOST, PORT);
  7788. auto get_thread = std::thread([&client]() {
  7789. std::string s;
  7790. auto res =
  7791. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7792. s += std::string(data, len);
  7793. return true;
  7794. });
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::OK_200, res->status);
  7797. EXPECT_EQ("aaabbb", s);
  7798. });
  7799. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7800. // Give GET time to get a few messages.
  7801. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7802. }
  7803. TEST(MountTest, Unmount) {
  7804. Server svr;
  7805. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7806. auto se = detail::scope_exit([&] {
  7807. svr.stop();
  7808. listen_thread.join();
  7809. ASSERT_FALSE(svr.is_running());
  7810. });
  7811. svr.wait_until_ready();
  7812. Client cli("localhost", PORT);
  7813. svr.set_mount_point("/mount2", "./www2");
  7814. auto res = cli.Get("/");
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7817. res = cli.Get("/mount2/dir/test.html");
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::OK_200, res->status);
  7820. svr.set_mount_point("/", "./www");
  7821. res = cli.Get("/dir/");
  7822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7823. EXPECT_EQ(StatusCode::OK_200, res->status);
  7824. svr.remove_mount_point("/");
  7825. res = cli.Get("/dir/");
  7826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7827. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7828. svr.remove_mount_point("/mount2");
  7829. res = cli.Get("/mount2/dir/test.html");
  7830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7831. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7832. }
  7833. TEST(MountTest, Redicect) {
  7834. Server svr;
  7835. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7836. auto se = detail::scope_exit([&] {
  7837. svr.stop();
  7838. listen_thread.join();
  7839. ASSERT_FALSE(svr.is_running());
  7840. });
  7841. svr.set_mount_point("/", "./www");
  7842. svr.wait_until_ready();
  7843. Client cli("localhost", PORT);
  7844. auto res = cli.Get("/dir/");
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::OK_200, res->status);
  7847. res = cli.Get("/dir");
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7850. res = cli.Get("/file");
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::OK_200, res->status);
  7853. res = cli.Get("/file/");
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7856. cli.set_follow_location(true);
  7857. res = cli.Get("/dir");
  7858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7859. EXPECT_EQ(StatusCode::OK_200, res->status);
  7860. }
  7861. TEST(MountTest, MultibytesPathName) {
  7862. Server svr;
  7863. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7864. auto se = detail::scope_exit([&] {
  7865. svr.stop();
  7866. listen_thread.join();
  7867. ASSERT_FALSE(svr.is_running());
  7868. });
  7869. svr.set_mount_point("/", "./www");
  7870. svr.wait_until_ready();
  7871. Client cli("localhost", PORT);
  7872. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7874. EXPECT_EQ(StatusCode::OK_200, res->status);
  7875. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7876. }
  7877. #ifdef _WIN32
  7878. // Issue #2435: mmap::open() must succeed even when another handle holds
  7879. // the file open for writing (e.g. an active log file).
  7880. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7881. const char *path = "mmap_concurrent_writer_test.txt";
  7882. const char *content = "hello";
  7883. {
  7884. std::ofstream f(path, std::ios::binary);
  7885. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7886. }
  7887. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7888. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7889. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7890. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7891. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7892. detail::mmap m(path);
  7893. ASSERT_TRUE(m.is_open());
  7894. EXPECT_EQ(strlen(content), m.size());
  7895. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7896. }
  7897. #endif
  7898. TEST(KeepAliveTest, ReadTimeout) {
  7899. Server svr;
  7900. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7901. std::this_thread::sleep_for(std::chrono::seconds(2));
  7902. res.set_content("a", "text/plain");
  7903. });
  7904. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7905. res.set_content("b", "text/plain");
  7906. });
  7907. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7908. auto se = detail::scope_exit([&] {
  7909. svr.stop();
  7910. listen_thread.join();
  7911. ASSERT_FALSE(svr.is_running());
  7912. });
  7913. svr.wait_until_ready();
  7914. Client cli("localhost", PORT);
  7915. cli.set_keep_alive(true);
  7916. cli.set_read_timeout(std::chrono::seconds(1));
  7917. auto resa = cli.Get("/a");
  7918. ASSERT_FALSE(resa);
  7919. EXPECT_EQ(Error::Read, resa.error());
  7920. auto resb = cli.Get("/b");
  7921. ASSERT_TRUE(resb);
  7922. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7923. EXPECT_EQ("b", resb->body);
  7924. }
  7925. TEST(KeepAliveTest, MaxCount) {
  7926. size_t keep_alive_max_count = 3;
  7927. Server svr;
  7928. svr.set_keep_alive_max_count(keep_alive_max_count);
  7929. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7930. res.set_content("Hello World!", "text/plain");
  7931. });
  7932. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7933. auto se = detail::scope_exit([&] {
  7934. svr.stop();
  7935. listen_thread.join();
  7936. ASSERT_FALSE(svr.is_running());
  7937. });
  7938. svr.wait_until_ready();
  7939. Client cli(HOST, PORT);
  7940. cli.set_keep_alive(true);
  7941. for (size_t i = 0; i < 5; i++) {
  7942. auto result = cli.Get("/hi");
  7943. ASSERT_TRUE(result);
  7944. EXPECT_EQ(StatusCode::OK_200, result->status);
  7945. if (i == keep_alive_max_count - 1) {
  7946. EXPECT_EQ("close", result->get_header_value("Connection"));
  7947. } else {
  7948. EXPECT_FALSE(result->has_header("Connection"));
  7949. }
  7950. }
  7951. }
  7952. TEST(KeepAliveTest, Issue1041) {
  7953. Server svr;
  7954. svr.set_keep_alive_timeout(3);
  7955. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7956. res.set_content("Hello World!", "text/plain");
  7957. });
  7958. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7959. auto se = detail::scope_exit([&] {
  7960. svr.stop();
  7961. listen_thread.join();
  7962. ASSERT_FALSE(svr.is_running());
  7963. });
  7964. svr.wait_until_ready();
  7965. Client cli(HOST, PORT);
  7966. cli.set_keep_alive(true);
  7967. auto result = cli.Get("/hi");
  7968. ASSERT_TRUE(result);
  7969. EXPECT_EQ(StatusCode::OK_200, result->status);
  7970. std::this_thread::sleep_for(std::chrono::seconds(5));
  7971. result = cli.Get("/hi");
  7972. ASSERT_TRUE(result);
  7973. EXPECT_EQ(StatusCode::OK_200, result->status);
  7974. }
  7975. TEST(KeepAliveTest, Issue1959) {
  7976. Server svr;
  7977. svr.set_keep_alive_timeout(5);
  7978. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7979. res.set_content("a", "text/plain");
  7980. });
  7981. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7982. auto se = detail::scope_exit([&] {
  7983. if (!svr.is_running()) return;
  7984. svr.stop();
  7985. listen_thread.join();
  7986. ASSERT_FALSE(svr.is_running());
  7987. });
  7988. svr.wait_until_ready();
  7989. Client cli("localhost", PORT);
  7990. cli.set_keep_alive(true);
  7991. using namespace std::chrono;
  7992. auto start = steady_clock::now();
  7993. cli.Get("/a");
  7994. svr.stop();
  7995. listen_thread.join();
  7996. auto end = steady_clock::now();
  7997. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7998. EXPECT_LT(elapsed, 5000);
  7999. }
  8000. #ifdef CPPHTTPLIB_SSL_ENABLED
  8001. TEST(KeepAliveTest, SSLClientReconnection) {
  8002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8003. ASSERT_TRUE(svr.is_valid());
  8004. svr.set_keep_alive_timeout(1);
  8005. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  8006. res.set_content("Hello World!", "text/plain");
  8007. });
  8008. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8009. auto se = detail::scope_exit([&] {
  8010. svr.stop();
  8011. listen_thread.join();
  8012. ASSERT_FALSE(svr.is_running());
  8013. });
  8014. svr.wait_until_ready();
  8015. SSLClient cli(HOST, PORT);
  8016. cli.enable_server_certificate_verification(false);
  8017. cli.set_keep_alive(true);
  8018. auto result = cli.Get("/hi");
  8019. ASSERT_TRUE(result);
  8020. EXPECT_EQ(StatusCode::OK_200, result->status);
  8021. result = cli.Get("/hi");
  8022. ASSERT_TRUE(result);
  8023. EXPECT_EQ(StatusCode::OK_200, result->status);
  8024. std::this_thread::sleep_for(std::chrono::seconds(2));
  8025. // Recoonect
  8026. result = cli.Get("/hi");
  8027. ASSERT_TRUE(result);
  8028. EXPECT_EQ(StatusCode::OK_200, result->status);
  8029. result = cli.Get("/hi");
  8030. ASSERT_TRUE(result);
  8031. EXPECT_EQ(StatusCode::OK_200, result->status);
  8032. }
  8033. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  8034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8035. ASSERT_TRUE(svr.is_valid());
  8036. svr.set_keep_alive_timeout(1);
  8037. std::string content = "reconnect";
  8038. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  8039. res.set_content("Hello World!", "text/plain");
  8040. });
  8041. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8042. auto se = detail::scope_exit([&] {
  8043. svr.stop();
  8044. listen_thread.join();
  8045. ASSERT_FALSE(svr.is_running());
  8046. });
  8047. svr.wait_until_ready();
  8048. SSLClient cli(HOST, PORT);
  8049. cli.enable_server_certificate_verification(false);
  8050. cli.set_keep_alive(true);
  8051. auto result = cli.Post(
  8052. "/hi", content.size(),
  8053. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8054. sink.write(content.c_str(), content.size());
  8055. return true;
  8056. },
  8057. "text/plain");
  8058. ASSERT_TRUE(result);
  8059. EXPECT_EQ(200, result->status);
  8060. std::this_thread::sleep_for(std::chrono::seconds(2));
  8061. // Recoonect
  8062. result = cli.Post(
  8063. "/hi", content.size(),
  8064. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8065. sink.write(content.c_str(), content.size());
  8066. return true;
  8067. },
  8068. "text/plain");
  8069. ASSERT_TRUE(result);
  8070. EXPECT_EQ(200, result->status);
  8071. result = cli.Post(
  8072. "/hi", content.size(),
  8073. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8074. sink.write(content.c_str(), content.size());
  8075. return true;
  8076. },
  8077. "text/plain");
  8078. ASSERT_TRUE(result);
  8079. EXPECT_EQ(200, result->status);
  8080. }
  8081. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8082. using namespace httplib::tls;
  8083. {
  8084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8085. ASSERT_TRUE(svr.is_valid());
  8086. svr.Get("/sni", [&](const Request &req, Response &res) {
  8087. std::string expected = req.sni();
  8088. EXPECT_EQ(expected, req.get_param_value("expected"));
  8089. res.set_content("ok", "text/plain");
  8090. });
  8091. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8092. auto se = detail::scope_exit([&] {
  8093. svr.stop();
  8094. listen_thread.join();
  8095. ASSERT_FALSE(svr.is_running());
  8096. });
  8097. svr.wait_until_ready();
  8098. {
  8099. SSLClient cli("localhost", PORT);
  8100. cli.enable_server_certificate_verification(false);
  8101. auto res = cli.Get("/sni?expected=localhost");
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. }
  8104. {
  8105. SSLClient cli("::1", PORT);
  8106. cli.enable_server_certificate_verification(false);
  8107. auto res = cli.Get("/sni?expected=");
  8108. // NOTE: This may fail if the server is listening on IPv4 only
  8109. // (e.g., when localhost resolves to 127.0.0.1 only)
  8110. if (res) {
  8111. EXPECT_EQ(StatusCode::OK_200, res->status);
  8112. } else {
  8113. EXPECT_EQ(Error::Connection, res.error());
  8114. }
  8115. }
  8116. }
  8117. }
  8118. #endif
  8119. TEST(ClientProblemDetectionTest, ContentProvider) {
  8120. Server svr;
  8121. size_t content_length = 1024 * 1024;
  8122. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8123. res.set_content_provider(
  8124. content_length, "text/plain",
  8125. [&](size_t offset, size_t length, DataSink &sink) {
  8126. auto out_len = std::min(length, static_cast<size_t>(1024));
  8127. std::string out(out_len, '@');
  8128. sink.write(out.data(), out_len);
  8129. return offset < 4096;
  8130. },
  8131. [](bool success) { ASSERT_FALSE(success); });
  8132. });
  8133. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8134. res.set_content_provider(
  8135. 0, "text/plain",
  8136. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8137. EXPECT_TRUE(false);
  8138. return true;
  8139. },
  8140. [](bool success) { ASSERT_FALSE(success); });
  8141. });
  8142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8143. auto se = detail::scope_exit([&] {
  8144. svr.stop();
  8145. listen_thread.join();
  8146. ASSERT_FALSE(svr.is_running());
  8147. });
  8148. svr.wait_until_ready();
  8149. Client cli("localhost", PORT);
  8150. {
  8151. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8152. size_t /*data_length*/) { return false; });
  8153. ASSERT_FALSE(res);
  8154. }
  8155. {
  8156. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8157. size_t /*data_length*/) { return false; });
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. }
  8160. }
  8161. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8162. Server svr;
  8163. svr.set_error_handler([](Request const &, Response &res) -> void {
  8164. res.set_chunked_content_provider(
  8165. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8166. sink.os << "hello";
  8167. sink.os << "world";
  8168. sink.done();
  8169. return true;
  8170. });
  8171. });
  8172. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8173. auto se = detail::scope_exit([&] {
  8174. svr.stop();
  8175. listen_thread.join();
  8176. ASSERT_FALSE(svr.is_running());
  8177. });
  8178. svr.wait_until_ready();
  8179. Client cli("localhost", PORT);
  8180. auto res = cli.Get("/");
  8181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8183. EXPECT_EQ("helloworld", res->body);
  8184. }
  8185. TEST(LongPollingTest, ClientCloseDetection) {
  8186. Server svr;
  8187. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8188. res.set_chunked_content_provider(
  8189. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8190. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8191. sink.os << "hello";
  8192. auto count = 10;
  8193. while (count > 0 && sink.is_writable()) {
  8194. this_thread::sleep_for(chrono::milliseconds(10));
  8195. count--;
  8196. }
  8197. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8198. return true;
  8199. });
  8200. });
  8201. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8202. auto se = detail::scope_exit([&] {
  8203. svr.stop();
  8204. listen_thread.join();
  8205. ASSERT_FALSE(svr.is_running());
  8206. });
  8207. svr.wait_until_ready();
  8208. Client cli("localhost", PORT);
  8209. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8210. EXPECT_EQ("hello", string(data, data_length));
  8211. return false; // close the socket immediately.
  8212. });
  8213. ASSERT_FALSE(res);
  8214. }
  8215. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8216. Server svr;
  8217. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8218. res.set_chunked_content_provider(
  8219. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8220. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8221. sink.os << "hello";
  8222. EXPECT_TRUE(sink.os.good());
  8223. // Wait for the client to close the connection
  8224. auto count = 10;
  8225. while (count > 0 && sink.is_writable()) {
  8226. this_thread::sleep_for(chrono::milliseconds(10));
  8227. count--;
  8228. }
  8229. // After client disconnect, write repeatedly until the socket
  8230. // write actually fails (small writes may be absorbed by the
  8231. // kernel buffer)
  8232. std::string chunk(1024, 'x');
  8233. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8234. sink.os << chunk;
  8235. }
  8236. EXPECT_TRUE(sink.os.fail());
  8237. return true;
  8238. });
  8239. });
  8240. auto port = svr.bind_to_any_port("localhost");
  8241. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8242. auto se = detail::scope_exit([&] {
  8243. svr.stop();
  8244. listen_thread.join();
  8245. ASSERT_FALSE(svr.is_running());
  8246. });
  8247. svr.wait_until_ready();
  8248. Client cli("localhost", port);
  8249. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8250. EXPECT_EQ("hello", string(data, data_length));
  8251. return false; // close the socket immediately.
  8252. });
  8253. ASSERT_FALSE(res);
  8254. }
  8255. TEST(GetWithParametersTest, GetWithParameters) {
  8256. Server svr;
  8257. svr.Get("/", [&](const Request &req, Response &) {
  8258. EXPECT_EQ("world", req.get_param_value("hello"));
  8259. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8260. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8261. });
  8262. svr.Get("/params", [&](const Request &req, Response &) {
  8263. EXPECT_EQ("world", req.get_param_value("hello"));
  8264. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8265. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8266. });
  8267. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8268. EXPECT_EQ("resource-id", req.matches[1]);
  8269. EXPECT_EQ("foo", req.get_param_value("param1"));
  8270. EXPECT_EQ("bar", req.get_param_value("param2"));
  8271. });
  8272. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8273. EXPECT_EQ("user-id", req.path_params.at("id"));
  8274. EXPECT_EQ("foo", req.get_param_value("param1"));
  8275. EXPECT_EQ("bar", req.get_param_value("param2"));
  8276. });
  8277. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8278. auto se = detail::scope_exit([&] {
  8279. svr.stop();
  8280. listen_thread.join();
  8281. ASSERT_FALSE(svr.is_running());
  8282. });
  8283. svr.wait_until_ready();
  8284. {
  8285. Client cli(HOST, PORT);
  8286. Params params;
  8287. params.emplace("hello", "world");
  8288. params.emplace("hello2", "world2");
  8289. params.emplace("hello3", "world3");
  8290. auto res = cli.Get("/", params, Headers{});
  8291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8292. EXPECT_EQ(StatusCode::OK_200, res->status);
  8293. }
  8294. {
  8295. Client cli(HOST, PORT);
  8296. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8298. EXPECT_EQ(StatusCode::OK_200, res->status);
  8299. }
  8300. {
  8301. Client cli(HOST, PORT);
  8302. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8304. EXPECT_EQ(StatusCode::OK_200, res->status);
  8305. }
  8306. {
  8307. Client cli(HOST, PORT);
  8308. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8310. EXPECT_EQ(StatusCode::OK_200, res->status);
  8311. }
  8312. }
  8313. TEST(GetWithParametersTest, GetWithParameters2) {
  8314. Server svr;
  8315. svr.Get("/", [&](const Request &req, Response &res) {
  8316. auto text = req.get_param_value("hello");
  8317. res.set_content(text, "text/plain");
  8318. });
  8319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8320. auto se = detail::scope_exit([&] {
  8321. svr.stop();
  8322. listen_thread.join();
  8323. ASSERT_FALSE(svr.is_running());
  8324. });
  8325. svr.wait_until_ready();
  8326. Client cli("localhost", PORT);
  8327. Params params;
  8328. params.emplace("hello", "world");
  8329. std::string body;
  8330. auto res = cli.Get("/", params, Headers{},
  8331. [&](const char *data, size_t data_length) {
  8332. body.append(data, data_length);
  8333. return true;
  8334. });
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. EXPECT_EQ("world", body);
  8338. }
  8339. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8340. Server svr;
  8341. svr.Get("/search", [&](const Request &req, Response &res) {
  8342. auto q = req.get_param_value("q");
  8343. res.set_content(q, "text/plain");
  8344. });
  8345. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8346. auto se = detail::scope_exit([&] {
  8347. svr.stop();
  8348. listen_thread.join();
  8349. ASSERT_FALSE(svr.is_running());
  8350. });
  8351. svr.wait_until_ready();
  8352. Client cli("localhost", PORT);
  8353. // Verify that Get(path, params) works without requiring Headers argument
  8354. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ("cpp-httplib", res->body);
  8358. }
  8359. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8360. auto host = "httpbingo.org";
  8361. auto path = std::string{"/range/32"};
  8362. #ifdef CPPHTTPLIB_SSL_ENABLED
  8363. SSLClient cli(host);
  8364. #else
  8365. Client cli(host);
  8366. #endif
  8367. cli.set_default_headers({make_range_header({{1, 10}})});
  8368. cli.set_connection_timeout(5);
  8369. {
  8370. auto res = cli.Get(path);
  8371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8372. EXPECT_EQ("bcdefghijk", res->body);
  8373. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8374. }
  8375. {
  8376. auto res = cli.Get(path);
  8377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8378. EXPECT_EQ("bcdefghijk", res->body);
  8379. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8380. }
  8381. }
  8382. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8383. Server svr;
  8384. svr.set_default_headers({{"Hello", "World"}});
  8385. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8386. res.set_content("ok", "text/plain");
  8387. });
  8388. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8389. auto se = detail::scope_exit([&] {
  8390. svr.stop();
  8391. listen_thread.join();
  8392. ASSERT_FALSE(svr.is_running());
  8393. });
  8394. svr.wait_until_ready();
  8395. Client cli("localhost", PORT);
  8396. auto res = cli.Get("/");
  8397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8398. EXPECT_EQ(StatusCode::OK_200, res->status);
  8399. EXPECT_EQ("ok", res->body);
  8400. EXPECT_EQ("World", res->get_header_value("Hello"));
  8401. }
  8402. #ifdef CPPHTTPLIB_SSL_ENABLED
  8403. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8404. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8405. ASSERT_TRUE(svr.is_valid());
  8406. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8407. std::this_thread::sleep_for(std::chrono::seconds(2));
  8408. res.set_content("a", "text/plain");
  8409. });
  8410. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8411. res.set_content("b", "text/plain");
  8412. });
  8413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8414. auto se = detail::scope_exit([&] {
  8415. svr.stop();
  8416. listen_thread.join();
  8417. ASSERT_FALSE(svr.is_running());
  8418. });
  8419. svr.wait_until_ready();
  8420. SSLClient cli("localhost", PORT);
  8421. cli.enable_server_certificate_verification(false);
  8422. cli.set_keep_alive(true);
  8423. cli.set_read_timeout(std::chrono::seconds(1));
  8424. auto resa = cli.Get("/a");
  8425. ASSERT_TRUE(!resa);
  8426. EXPECT_EQ(Error::Read, resa.error());
  8427. auto resb = cli.Get("/b");
  8428. ASSERT_TRUE(resb);
  8429. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8430. EXPECT_EQ("b", resb->body);
  8431. }
  8432. #endif
  8433. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8434. protected:
  8435. ServerTestWithAI_PASSIVE()
  8436. : cli_(HOST, PORT)
  8437. #ifdef CPPHTTPLIB_SSL_ENABLED
  8438. ,
  8439. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8440. #endif
  8441. {
  8442. #ifdef CPPHTTPLIB_SSL_ENABLED
  8443. cli_.enable_server_certificate_verification(false);
  8444. #endif
  8445. }
  8446. virtual void SetUp() {
  8447. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8448. res.set_content("Hello World!", "text/plain");
  8449. });
  8450. t_ = thread(
  8451. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8452. svr_.wait_until_ready();
  8453. }
  8454. virtual void TearDown() {
  8455. svr_.stop();
  8456. t_.join();
  8457. }
  8458. #ifdef CPPHTTPLIB_SSL_ENABLED
  8459. SSLClient cli_;
  8460. SSLServer svr_;
  8461. #else
  8462. Client cli_;
  8463. Server svr_;
  8464. #endif
  8465. thread t_;
  8466. };
  8467. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8468. auto res = cli_.Get("/hi");
  8469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8470. EXPECT_EQ(StatusCode::OK_200, res->status);
  8471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8472. EXPECT_EQ("Hello World!", res->body);
  8473. }
  8474. class ServerUpDownTest : public ::testing::Test {
  8475. protected:
  8476. ServerUpDownTest() : cli_(HOST, PORT) {}
  8477. virtual void SetUp() {
  8478. t_ = thread([&]() {
  8479. svr_.bind_to_any_port(HOST);
  8480. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8481. ASSERT_TRUE(svr_.listen_after_bind());
  8482. });
  8483. svr_.wait_until_ready();
  8484. }
  8485. virtual void TearDown() {
  8486. svr_.stop();
  8487. t_.join();
  8488. }
  8489. Client cli_;
  8490. Server svr_;
  8491. thread t_;
  8492. };
  8493. TEST_F(ServerUpDownTest, QuickStartStop) {
  8494. // Should not crash, especially when run with
  8495. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8496. }
  8497. class PayloadMaxLengthTest : public ::testing::Test {
  8498. protected:
  8499. PayloadMaxLengthTest()
  8500. : cli_(HOST, PORT)
  8501. #ifdef CPPHTTPLIB_SSL_ENABLED
  8502. ,
  8503. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8504. #endif
  8505. {
  8506. #ifdef CPPHTTPLIB_SSL_ENABLED
  8507. cli_.enable_server_certificate_verification(false);
  8508. #endif
  8509. }
  8510. virtual void SetUp() {
  8511. svr_.set_payload_max_length(8);
  8512. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8513. res.set_content("test", "text/plain");
  8514. });
  8515. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8516. svr_.wait_until_ready();
  8517. }
  8518. virtual void TearDown() {
  8519. svr_.stop();
  8520. t_.join();
  8521. }
  8522. #ifdef CPPHTTPLIB_SSL_ENABLED
  8523. SSLClient cli_;
  8524. SSLServer svr_;
  8525. #else
  8526. Client cli_;
  8527. Server svr_;
  8528. #endif
  8529. thread t_;
  8530. };
  8531. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8532. auto res = cli_.Post("/test", "123456789", "text/plain");
  8533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8534. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8535. res = cli_.Post("/test", "12345678", "text/plain");
  8536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8537. EXPECT_EQ(StatusCode::OK_200, res->status);
  8538. }
  8539. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8540. // Test chunked encoding with payload exceeding the 8-byte limit
  8541. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8542. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8544. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8545. }
  8546. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8547. // Test chunked encoding with payload within the 8-byte limit
  8548. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8549. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8551. EXPECT_EQ(StatusCode::OK_200, res->status);
  8552. }
  8553. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8554. // Test using send_request to send chunked data exceeding payload limit
  8555. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8556. "Host: " +
  8557. std::string(HOST) + ":" + std::to_string(PORT) +
  8558. "\r\n"
  8559. "Transfer-Encoding: chunked\r\n"
  8560. "Connection: close\r\n"
  8561. "\r\n"
  8562. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8563. "0123456789\r\n"
  8564. "0\r\n" // End chunk
  8565. "\r\n";
  8566. std::string response;
  8567. bool result = send_request(1, chunked_request, &response);
  8568. if (!result) {
  8569. // If send_request fails, it might be because the server closed the
  8570. // connection due to payload limit enforcement, which is acceptable
  8571. SUCCEED()
  8572. << "Server rejected oversized chunked request (connection closed)";
  8573. } else {
  8574. // If we got a response, check if it's an error response or connection was
  8575. // closed early Short response length indicates connection was closed due to
  8576. // payload limit
  8577. if (response.length() <= 10) {
  8578. SUCCEED() << "Server closed connection for oversized chunked request";
  8579. } else {
  8580. // Check for error status codes
  8581. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8582. response.find("Payload Too Large") != std::string::npos ||
  8583. response.find("400") != std::string::npos);
  8584. }
  8585. }
  8586. }
  8587. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8588. // Test request without Content-Length header exceeding payload limit
  8589. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8590. "Host: " +
  8591. std::string(HOST) + ":" +
  8592. std::to_string(PORT) +
  8593. "\r\n"
  8594. "Connection: close\r\n"
  8595. "\r\n";
  8596. // Add payload exceeding the 8-byte limit
  8597. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8598. request_without_content_length += large_payload;
  8599. std::string response;
  8600. bool result = send_request(1, request_without_content_length, &response);
  8601. if (!result) {
  8602. // If send_request fails, server likely closed connection due to payload
  8603. // limit
  8604. SUCCEED() << "Server rejected oversized request without Content-Length "
  8605. "(connection closed)";
  8606. } else {
  8607. // Check if server responded with error or closed connection early
  8608. if (response.length() <= 10) {
  8609. SUCCEED() << "Server closed connection for oversized request without "
  8610. "Content-Length";
  8611. } else {
  8612. // Check for error status codes
  8613. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8614. response.find("Payload Too Large") != std::string::npos ||
  8615. response.find("400") != std::string::npos);
  8616. }
  8617. }
  8618. }
  8619. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8620. // Test request without Content-Length header within payload limit
  8621. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8622. "Host: " +
  8623. std::string(HOST) + ":" +
  8624. std::to_string(PORT) +
  8625. "\r\n"
  8626. "Connection: close\r\n"
  8627. "\r\n";
  8628. // Add payload within the 8-byte limit
  8629. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8630. request_without_content_length += small_payload;
  8631. std::string response;
  8632. bool result = send_request(1, request_without_content_length, &response);
  8633. // For requests without Content-Length, the server may have different behavior
  8634. // The key is that it should not reject due to payload limit for small
  8635. // payloads
  8636. if (result) {
  8637. // Check for any HTTP response (success or error, but not connection closed)
  8638. if (response.length() > 10) {
  8639. SUCCEED()
  8640. << "Server processed request without Content-Length within limit";
  8641. } else {
  8642. // Short response might indicate connection closed, which is acceptable
  8643. SUCCEED() << "Server closed connection for request without "
  8644. "Content-Length (acceptable behavior)";
  8645. }
  8646. } else {
  8647. // Connection failure might be due to protocol requirements
  8648. SUCCEED() << "Connection issue with request without Content-Length "
  8649. "(environment-specific)";
  8650. }
  8651. }
  8652. class LargePayloadMaxLengthTest : public ::testing::Test {
  8653. protected:
  8654. LargePayloadMaxLengthTest()
  8655. : cli_(HOST, PORT)
  8656. #ifdef CPPHTTPLIB_SSL_ENABLED
  8657. ,
  8658. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8659. #endif
  8660. {
  8661. #ifdef CPPHTTPLIB_SSL_ENABLED
  8662. cli_.enable_server_certificate_verification(false);
  8663. #endif
  8664. }
  8665. virtual void SetUp() {
  8666. // Set 10MB payload limit
  8667. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8668. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8669. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8670. res.set_content("Large payload test", "text/plain");
  8671. });
  8672. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8673. svr_.wait_until_ready();
  8674. }
  8675. virtual void TearDown() {
  8676. svr_.stop();
  8677. t_.join();
  8678. }
  8679. #ifdef CPPHTTPLIB_SSL_ENABLED
  8680. SSLClient cli_;
  8681. SSLServer svr_;
  8682. #else
  8683. Client cli_;
  8684. Server svr_;
  8685. #endif
  8686. thread t_;
  8687. };
  8688. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8689. // Test chunked encoding with payload within 10MB limit
  8690. std::string medium_payload(5 * 1024 * 1024,
  8691. 'A'); // 5MB payload, within 10MB limit
  8692. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8694. EXPECT_EQ(StatusCode::OK_200, res->status);
  8695. }
  8696. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8697. // Test chunked encoding with payload exceeding 10MB limit
  8698. std::string large_payload(12 * 1024 * 1024,
  8699. 'B'); // 12MB payload, exceeds 10MB limit
  8700. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8701. // Server may either return 413 or close the connection
  8702. if (res) {
  8703. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8704. } else {
  8705. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8706. }
  8707. }
  8708. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8709. // Test request without Content-Length header within 10MB limit
  8710. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8711. "Host: " +
  8712. std::string(HOST) + ":" +
  8713. std::to_string(PORT) +
  8714. "\r\n"
  8715. "Connection: close\r\n"
  8716. "\r\n";
  8717. // Add 1MB payload (within 10MB limit)
  8718. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8719. request_without_content_length += medium_payload;
  8720. std::string response;
  8721. bool result = send_request(5, request_without_content_length, &response);
  8722. if (result) {
  8723. // Should get a proper HTTP response for payloads within limit
  8724. if (response.length() > 10) {
  8725. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8726. "10MB limit";
  8727. } else {
  8728. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8729. "Content-Length)";
  8730. }
  8731. } else {
  8732. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8733. }
  8734. }
  8735. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8736. // Test request without Content-Length header exceeding 10MB limit
  8737. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8738. "Host: " +
  8739. std::string(HOST) + ":" +
  8740. std::to_string(PORT) +
  8741. "\r\n"
  8742. "Connection: close\r\n"
  8743. "\r\n";
  8744. // Add 12MB payload (exceeds 10MB limit)
  8745. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8746. request_without_content_length += large_payload;
  8747. std::string response;
  8748. bool result = send_request(10, request_without_content_length, &response);
  8749. if (!result) {
  8750. // Server should close connection due to payload limit
  8751. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8752. "(connection closed)";
  8753. } else {
  8754. // Check for error response
  8755. if (response.length() <= 10) {
  8756. SUCCEED()
  8757. << "Server closed connection for 12MB request exceeding 10MB limit";
  8758. } else {
  8759. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8760. response.find("Payload Too Large") != std::string::npos ||
  8761. response.find("400") != std::string::npos);
  8762. }
  8763. }
  8764. }
  8765. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8766. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8767. // path.
  8768. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8769. Server svr;
  8770. const size_t LIMIT = 64 * 1024; // 64KB
  8771. svr.set_payload_max_length(LIMIT);
  8772. size_t total = 0;
  8773. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8774. const ContentReader &content_reader) {
  8775. content_reader([&](const char * /*data*/, size_t len) {
  8776. total += len;
  8777. return true;
  8778. });
  8779. res.status = 200;
  8780. res.set_content("stream_ok", "text/plain");
  8781. });
  8782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8783. auto se = detail::scope_exit([&] {
  8784. svr.stop();
  8785. thread.join();
  8786. ASSERT_FALSE(svr.is_running());
  8787. });
  8788. svr.wait_until_ready();
  8789. // Prepare 256KB raw data and gzip-compress it
  8790. std::string raw(256 * 1024, 'A');
  8791. std::string gz;
  8792. {
  8793. z_stream zs{};
  8794. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8795. Z_DEFAULT_STRATEGY);
  8796. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8797. zs.avail_in = static_cast<uInt>(raw.size());
  8798. char outbuf[4096];
  8799. int ret;
  8800. do {
  8801. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8802. zs.avail_out = sizeof(outbuf);
  8803. ret = deflate(&zs, Z_FINISH);
  8804. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8805. } while (ret != Z_STREAM_END);
  8806. deflateEnd(&zs);
  8807. }
  8808. Client cli(HOST, PORT);
  8809. cli.set_connection_timeout(std::chrono::seconds(5));
  8810. Headers headers = {{"Content-Encoding", "gzip"}};
  8811. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8812. "application/octet-stream");
  8813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8814. // Server must reject oversized decompressed payloads with 413.
  8815. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8816. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8817. EXPECT_LE(total, LIMIT);
  8818. }
  8819. #endif
  8820. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  8821. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  8822. // the payload must be passed through untouched instead of being rejected.
  8823. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  8824. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  8825. Server svr;
  8826. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  8827. res.set_content(body, "image/jpeg");
  8828. res.set_header("Content-Encoding", "UTF-8");
  8829. });
  8830. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  8831. res.set_content(body, "image/jpeg");
  8832. res.set_header("Content-Encoding", "identity");
  8833. });
  8834. svr.Post("/echo", [](const Request &req, Response &res) {
  8835. res.set_content(req.body, "image/jpeg");
  8836. });
  8837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8838. auto se = detail::scope_exit([&] {
  8839. svr.stop();
  8840. t.join();
  8841. ASSERT_FALSE(svr.is_running());
  8842. });
  8843. svr.wait_until_ready();
  8844. Client cli(HOST, PORT);
  8845. {
  8846. auto res = cli.Get("/image");
  8847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8848. EXPECT_EQ(StatusCode::OK_200, res->status);
  8849. EXPECT_EQ(body, res->body);
  8850. }
  8851. {
  8852. auto res = cli.Get("/identity");
  8853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8854. EXPECT_EQ(StatusCode::OK_200, res->status);
  8855. EXPECT_EQ(body, res->body);
  8856. }
  8857. {
  8858. // The same applies to a request body reaching the server.
  8859. Headers headers = {{"Content-Encoding", "UTF-8"}};
  8860. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  8861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8862. EXPECT_EQ(StatusCode::OK_200, res->status);
  8863. EXPECT_EQ(body, res->body);
  8864. }
  8865. }
  8866. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  8867. // gzip-encoded response even when the build has no zlib support.
  8868. static const char GZIPPED_HELLO_WORLD[] = {
  8869. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  8870. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  8871. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  8872. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  8873. // A content coding cpp-httplib recognizes but was not built with must be
  8874. // reported as such. Handing the still-compressed payload back to the caller
  8875. // would silently corrupt it.
  8876. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  8877. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  8878. Server svr;
  8879. // "image/jpeg" keeps the server from applying a content coding of its own,
  8880. // so the hand-crafted Content-Encoding below survives.
  8881. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  8882. res.set_content(gzipped, "image/jpeg");
  8883. res.set_header("Content-Encoding", "gzip");
  8884. });
  8885. // Content codings are case-insensitive (RFC 9110 8.4.1).
  8886. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  8887. res.set_content(gzipped, "image/jpeg");
  8888. res.set_header("Content-Encoding", "GZIP");
  8889. });
  8890. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8891. auto se = detail::scope_exit([&] {
  8892. svr.stop();
  8893. t.join();
  8894. ASSERT_FALSE(svr.is_running());
  8895. });
  8896. svr.wait_until_ready();
  8897. Client cli(HOST, PORT);
  8898. {
  8899. auto res = cli.Get("/gzipped");
  8900. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8902. EXPECT_EQ("Hello World!", res->body);
  8903. #else
  8904. ASSERT_FALSE(res);
  8905. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  8906. #endif
  8907. }
  8908. {
  8909. // open_stream() must behave the same way.
  8910. auto handle = cli.open_stream("GET", "/gzipped");
  8911. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8912. ASSERT_TRUE(handle.is_valid());
  8913. std::string received;
  8914. char buf[256];
  8915. ssize_t n;
  8916. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  8917. received.append(buf, static_cast<size_t>(n));
  8918. }
  8919. EXPECT_EQ("Hello World!", received);
  8920. #else
  8921. EXPECT_FALSE(handle.is_valid());
  8922. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  8923. #endif
  8924. }
  8925. {
  8926. // A differently-cased coding must not be mistaken for an unknown one, or
  8927. // the body would be handed back still compressed.
  8928. auto res = cli.Get("/gzipped-uppercase");
  8929. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8931. EXPECT_EQ("Hello World!", res->body);
  8932. #else
  8933. ASSERT_FALSE(res);
  8934. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  8935. #endif
  8936. }
  8937. }
  8938. // Regression test for DoS vulnerability: a malicious server sending a response
  8939. // without Content-Length header must not cause unbounded memory consumption on
  8940. // the client side. The client should stop reading after a reasonable limit,
  8941. // similar to the server-side set_payload_max_length protection.
  8942. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8943. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8944. #ifndef _WIN32
  8945. signal(SIGPIPE, SIG_IGN);
  8946. #endif
  8947. auto server_thread = std::thread([] {
  8948. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8949. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8950. default_socket_options(srv);
  8951. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8952. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8953. sockaddr_in addr{};
  8954. addr.sin_family = AF_INET;
  8955. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8956. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8957. int opt = 1;
  8958. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8959. #ifdef _WIN32
  8960. reinterpret_cast<const char *>(&opt),
  8961. #else
  8962. &opt,
  8963. #endif
  8964. sizeof(opt));
  8965. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8966. ::listen(srv, 1);
  8967. sockaddr_in cli_addr{};
  8968. socklen_t cli_len = sizeof(cli_addr);
  8969. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8970. if (cli != INVALID_SOCKET) {
  8971. char buf[4096];
  8972. ::recv(cli, buf, sizeof(buf), 0);
  8973. // Malicious response: no Content-Length, no chunked encoding
  8974. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8975. "Connection: close\r\n"
  8976. "\r\n";
  8977. ::send(cli,
  8978. #ifdef _WIN32
  8979. static_cast<const char *>(response_header.c_str()),
  8980. static_cast<int>(response_header.size()),
  8981. #else
  8982. response_header.c_str(), response_header.size(),
  8983. #endif
  8984. 0);
  8985. // Send 10MB of data
  8986. std::string chunk(64 * 1024, 'A');
  8987. size_t total_sent = 0;
  8988. while (total_sent < MALICIOUS_DATA_SIZE) {
  8989. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8990. auto sent = ::send(cli,
  8991. #ifdef _WIN32
  8992. static_cast<const char *>(chunk.c_str()),
  8993. static_cast<int>(to_send),
  8994. #else
  8995. chunk.c_str(), to_send,
  8996. #endif
  8997. 0);
  8998. if (sent <= 0) break;
  8999. total_sent += static_cast<size_t>(sent);
  9000. }
  9001. detail::close_socket(cli);
  9002. }
  9003. detail::close_socket(srv);
  9004. });
  9005. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9006. size_t total_read = 0;
  9007. {
  9008. Client cli("127.0.0.1", PORT + 2);
  9009. cli.set_read_timeout(5, 0);
  9010. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9011. auto stream = cli.open_stream("GET", "/malicious");
  9012. ASSERT_TRUE(stream.is_valid());
  9013. char buffer[64 * 1024];
  9014. ssize_t n;
  9015. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9016. total_read += static_cast<size_t>(n);
  9017. }
  9018. } // StreamHandle and Client destroyed here, closing the socket
  9019. server_thread.join();
  9020. // With set_payload_max_length, the client must stop reading before consuming
  9021. // all 10MB. The read loop should be cut off at or near the configured limit.
  9022. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  9023. << "Client read " << total_read << " bytes, exceeding the configured "
  9024. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  9025. }
  9026. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  9027. // the entire response body without truncation.
  9028. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  9029. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  9030. #ifndef _WIN32
  9031. signal(SIGPIPE, SIG_IGN);
  9032. #endif
  9033. auto server_thread = std::thread([] {
  9034. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9035. default_socket_options(srv);
  9036. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9037. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9038. sockaddr_in addr{};
  9039. addr.sin_family = AF_INET;
  9040. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9041. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9042. int opt = 1;
  9043. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9044. #ifdef _WIN32
  9045. reinterpret_cast<const char *>(&opt),
  9046. #else
  9047. &opt,
  9048. #endif
  9049. sizeof(opt));
  9050. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9051. ::listen(srv, 1);
  9052. sockaddr_in cli_addr{};
  9053. socklen_t cli_len = sizeof(cli_addr);
  9054. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9055. if (cli != INVALID_SOCKET) {
  9056. char buf[4096];
  9057. ::recv(cli, buf, sizeof(buf), 0);
  9058. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9059. "Connection: close\r\n"
  9060. "\r\n";
  9061. ::send(cli,
  9062. #ifdef _WIN32
  9063. static_cast<const char *>(response_header.c_str()),
  9064. static_cast<int>(response_header.size()),
  9065. #else
  9066. response_header.c_str(), response_header.size(),
  9067. #endif
  9068. 0);
  9069. std::string chunk(64 * 1024, 'A');
  9070. size_t total_sent = 0;
  9071. while (total_sent < DATA_SIZE) {
  9072. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9073. auto sent = ::send(cli,
  9074. #ifdef _WIN32
  9075. static_cast<const char *>(chunk.c_str()),
  9076. static_cast<int>(to_send),
  9077. #else
  9078. chunk.c_str(), to_send,
  9079. #endif
  9080. 0);
  9081. if (sent <= 0) break;
  9082. total_sent += static_cast<size_t>(sent);
  9083. }
  9084. #ifdef _WIN32
  9085. ::shutdown(cli, SD_SEND);
  9086. #else
  9087. ::shutdown(cli, SHUT_WR);
  9088. #endif
  9089. // Drain until the client closes its end, ensuring all data is delivered
  9090. char drain[1024];
  9091. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9092. detail::close_socket(cli);
  9093. }
  9094. detail::close_socket(srv);
  9095. });
  9096. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9097. size_t total_read = 0;
  9098. {
  9099. Client cli("127.0.0.1", PORT + 2);
  9100. cli.set_read_timeout(5, 0);
  9101. cli.set_payload_max_length(0); // 0 means no limit
  9102. auto stream = cli.open_stream("GET", "/data");
  9103. ASSERT_TRUE(stream.is_valid());
  9104. char buffer[64 * 1024];
  9105. ssize_t n;
  9106. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9107. total_read += static_cast<size_t>(n);
  9108. }
  9109. }
  9110. server_thread.join();
  9111. EXPECT_EQ(total_read, DATA_SIZE)
  9112. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  9113. << " bytes without truncation, but only read " << total_read << " bytes.";
  9114. }
  9115. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  9116. // enormous Content-Length must not cause the client to pre-allocate a huge
  9117. // response body buffer. The reservation is capped at payload_max_length_, and
  9118. // the read itself fails when the body exceeds the limit.
  9119. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  9120. #ifndef _WIN32
  9121. signal(SIGPIPE, SIG_IGN);
  9122. #endif
  9123. auto server_thread = std::thread([] {
  9124. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9125. default_socket_options(srv);
  9126. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9127. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9128. sockaddr_in addr{};
  9129. addr.sin_family = AF_INET;
  9130. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9131. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9132. int opt = 1;
  9133. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9134. #ifdef _WIN32
  9135. reinterpret_cast<const char *>(&opt),
  9136. #else
  9137. &opt,
  9138. #endif
  9139. sizeof(opt));
  9140. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9141. ::listen(srv, 1);
  9142. sockaddr_in cli_addr{};
  9143. socklen_t cli_len = sizeof(cli_addr);
  9144. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9145. if (cli != INVALID_SOCKET) {
  9146. char buf[4096];
  9147. ::recv(cli, buf, sizeof(buf), 0);
  9148. // Malicious response: claim a 20GB body but send only a tiny payload.
  9149. std::string response = "HTTP/1.1 200 OK\r\n"
  9150. "Content-Length: 20000000000\r\n"
  9151. "\r\n"
  9152. "abc";
  9153. ::send(cli,
  9154. #ifdef _WIN32
  9155. static_cast<const char *>(response.c_str()),
  9156. static_cast<int>(response.size()),
  9157. #else
  9158. response.c_str(), response.size(),
  9159. #endif
  9160. 0);
  9161. detail::close_socket(cli);
  9162. }
  9163. detail::close_socket(srv);
  9164. });
  9165. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9166. {
  9167. Client cli("127.0.0.1", PORT + 2);
  9168. cli.set_read_timeout(5, 0);
  9169. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  9170. // result in a 20GB pre-allocation. The Get() call is expected to fail
  9171. // (server claims more bytes than payload_max_length permits), but it must
  9172. // not exhaust memory before getting there.
  9173. auto res = cli.Get("/malicious");
  9174. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  9175. }
  9176. server_thread.join();
  9177. }
  9178. // Verify that content_receiver bypasses the default payload_max_length,
  9179. // allowing streaming downloads larger than 100MB without requiring an explicit
  9180. // set_payload_max_length call.
  9181. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  9182. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9183. #ifndef _WIN32
  9184. signal(SIGPIPE, SIG_IGN);
  9185. #endif
  9186. auto server_thread = std::thread([] {
  9187. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9188. default_socket_options(srv);
  9189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9190. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9191. sockaddr_in addr{};
  9192. addr.sin_family = AF_INET;
  9193. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9194. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9195. int opt = 1;
  9196. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9197. #ifdef _WIN32
  9198. reinterpret_cast<const char *>(&opt),
  9199. #else
  9200. &opt,
  9201. #endif
  9202. sizeof(opt));
  9203. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9204. ::listen(srv, 1);
  9205. sockaddr_in cli_addr{};
  9206. socklen_t cli_len = sizeof(cli_addr);
  9207. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9208. if (cli != INVALID_SOCKET) {
  9209. char buf[4096];
  9210. ::recv(cli, buf, sizeof(buf), 0);
  9211. // Response with Content-Length larger than default 100MB limit
  9212. auto content_length = std::to_string(DATA_SIZE);
  9213. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9214. "Content-Length: " +
  9215. content_length +
  9216. "\r\n"
  9217. "Connection: close\r\n"
  9218. "\r\n";
  9219. ::send(cli,
  9220. #ifdef _WIN32
  9221. static_cast<const char *>(response_header.c_str()),
  9222. static_cast<int>(response_header.size()),
  9223. #else
  9224. response_header.c_str(), response_header.size(),
  9225. #endif
  9226. 0);
  9227. std::string chunk(64 * 1024, 'A');
  9228. size_t total_sent = 0;
  9229. while (total_sent < DATA_SIZE) {
  9230. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9231. auto sent = ::send(cli,
  9232. #ifdef _WIN32
  9233. static_cast<const char *>(chunk.c_str()),
  9234. static_cast<int>(to_send),
  9235. #else
  9236. chunk.c_str(), to_send,
  9237. #endif
  9238. 0);
  9239. if (sent <= 0) break;
  9240. total_sent += static_cast<size_t>(sent);
  9241. }
  9242. detail::close_socket(cli);
  9243. }
  9244. detail::close_socket(srv);
  9245. });
  9246. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9247. size_t total_received = 0;
  9248. {
  9249. Client cli("127.0.0.1", PORT + 2);
  9250. cli.set_read_timeout(10, 0);
  9251. // Do NOT call set_payload_max_length — use the default 100MB limit
  9252. auto res =
  9253. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9254. total_received += data_length;
  9255. return true;
  9256. });
  9257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9258. EXPECT_EQ(StatusCode::OK_200, res->status);
  9259. }
  9260. server_thread.join();
  9261. EXPECT_EQ(total_received, DATA_SIZE)
  9262. << "With content_receiver, the client should read all " << DATA_SIZE
  9263. << " bytes despite the default 100MB payload_max_length, but only read "
  9264. << total_received << " bytes.";
  9265. }
  9266. // Verify that an explicit set_payload_max_length smaller than the response is
  9267. // enforced even when a content_receiver is used.
  9268. TEST(ClientVulnerabilityTest,
  9269. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9270. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9271. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9272. #ifndef _WIN32
  9273. signal(SIGPIPE, SIG_IGN);
  9274. #endif
  9275. auto server_thread = std::thread([] {
  9276. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9277. default_socket_options(srv);
  9278. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9279. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9280. sockaddr_in addr{};
  9281. addr.sin_family = AF_INET;
  9282. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9283. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9284. int opt = 1;
  9285. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9286. #ifdef _WIN32
  9287. reinterpret_cast<const char *>(&opt),
  9288. #else
  9289. &opt,
  9290. #endif
  9291. sizeof(opt));
  9292. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9293. ::listen(srv, 1);
  9294. sockaddr_in cli_addr{};
  9295. socklen_t cli_len = sizeof(cli_addr);
  9296. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9297. if (cli != INVALID_SOCKET) {
  9298. char buf[4096];
  9299. ::recv(cli, buf, sizeof(buf), 0);
  9300. auto content_length = std::to_string(DATA_SIZE);
  9301. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9302. "Content-Length: " +
  9303. content_length +
  9304. "\r\n"
  9305. "Connection: close\r\n"
  9306. "\r\n";
  9307. ::send(cli,
  9308. #ifdef _WIN32
  9309. static_cast<const char *>(response_header.c_str()),
  9310. static_cast<int>(response_header.size()),
  9311. #else
  9312. response_header.c_str(), response_header.size(),
  9313. #endif
  9314. 0);
  9315. std::string chunk(64 * 1024, 'A');
  9316. size_t total_sent = 0;
  9317. while (total_sent < DATA_SIZE) {
  9318. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9319. auto sent = ::send(cli,
  9320. #ifdef _WIN32
  9321. static_cast<const char *>(chunk.c_str()),
  9322. static_cast<int>(to_send),
  9323. #else
  9324. chunk.c_str(), to_send,
  9325. #endif
  9326. 0);
  9327. if (sent <= 0) break;
  9328. total_sent += static_cast<size_t>(sent);
  9329. }
  9330. detail::close_socket(cli);
  9331. }
  9332. detail::close_socket(srv);
  9333. });
  9334. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9335. size_t total_received = 0;
  9336. {
  9337. Client cli("127.0.0.1", PORT + 2);
  9338. cli.set_read_timeout(10, 0);
  9339. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9340. auto res =
  9341. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9342. total_received += data_length;
  9343. return true;
  9344. });
  9345. // Should fail because 200MB exceeds the explicit 150MB limit
  9346. EXPECT_FALSE(res);
  9347. }
  9348. server_thread.join();
  9349. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9350. << "Client with content_receiver should respect the explicit "
  9351. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9352. << total_received << " bytes.";
  9353. }
  9354. // Verify that an explicit set_payload_max_length larger than the response
  9355. // allows the content_receiver to read all data successfully.
  9356. TEST(ClientVulnerabilityTest,
  9357. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9358. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9359. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9360. #ifndef _WIN32
  9361. signal(SIGPIPE, SIG_IGN);
  9362. #endif
  9363. auto server_thread = std::thread([] {
  9364. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9365. default_socket_options(srv);
  9366. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9367. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9368. sockaddr_in addr{};
  9369. addr.sin_family = AF_INET;
  9370. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9371. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9372. int opt = 1;
  9373. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9374. #ifdef _WIN32
  9375. reinterpret_cast<const char *>(&opt),
  9376. #else
  9377. &opt,
  9378. #endif
  9379. sizeof(opt));
  9380. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9381. ::listen(srv, 1);
  9382. sockaddr_in cli_addr{};
  9383. socklen_t cli_len = sizeof(cli_addr);
  9384. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9385. if (cli != INVALID_SOCKET) {
  9386. char buf[4096];
  9387. ::recv(cli, buf, sizeof(buf), 0);
  9388. auto content_length = std::to_string(DATA_SIZE);
  9389. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9390. "Content-Length: " +
  9391. content_length +
  9392. "\r\n"
  9393. "Connection: close\r\n"
  9394. "\r\n";
  9395. ::send(cli,
  9396. #ifdef _WIN32
  9397. static_cast<const char *>(response_header.c_str()),
  9398. static_cast<int>(response_header.size()),
  9399. #else
  9400. response_header.c_str(), response_header.size(),
  9401. #endif
  9402. 0);
  9403. std::string chunk(64 * 1024, 'A');
  9404. size_t total_sent = 0;
  9405. while (total_sent < DATA_SIZE) {
  9406. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9407. auto sent = ::send(cli,
  9408. #ifdef _WIN32
  9409. static_cast<const char *>(chunk.c_str()),
  9410. static_cast<int>(to_send),
  9411. #else
  9412. chunk.c_str(), to_send,
  9413. #endif
  9414. 0);
  9415. if (sent <= 0) break;
  9416. total_sent += static_cast<size_t>(sent);
  9417. }
  9418. #ifdef _WIN32
  9419. ::shutdown(cli, SD_SEND);
  9420. #else
  9421. ::shutdown(cli, SHUT_WR);
  9422. #endif
  9423. char drain[1024];
  9424. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9425. detail::close_socket(cli);
  9426. }
  9427. detail::close_socket(srv);
  9428. });
  9429. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9430. size_t total_received = 0;
  9431. {
  9432. Client cli("127.0.0.1", PORT + 2);
  9433. cli.set_read_timeout(10, 0);
  9434. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9435. auto res =
  9436. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9437. total_received += data_length;
  9438. return true;
  9439. });
  9440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9441. EXPECT_EQ(StatusCode::OK_200, res->status);
  9442. }
  9443. server_thread.join();
  9444. EXPECT_EQ(total_received, DATA_SIZE)
  9445. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9446. << " bytes (larger than " << DATA_SIZE
  9447. << " bytes response), content_receiver should read all data, but only "
  9448. "read "
  9449. << total_received << " bytes.";
  9450. }
  9451. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9452. // Regression test for "zip bomb" attack on the client side: a malicious server
  9453. // sends a small gzip-compressed response that decompresses to a huge payload.
  9454. // The client must enforce payload_max_length on the decompressed size.
  9455. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9456. constexpr size_t DECOMPRESSED_SIZE =
  9457. 10 * 1024 * 1024; // 10MB after decompression
  9458. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9459. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9460. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9461. std::string compressed;
  9462. {
  9463. httplib::detail::gzip_compressor compressor;
  9464. bool ok =
  9465. compressor.compress(uncompressed.data(), uncompressed.size(),
  9466. /*last=*/true, [&](const char *buf, size_t len) {
  9467. compressed.append(buf, len);
  9468. return true;
  9469. });
  9470. ASSERT_TRUE(ok);
  9471. }
  9472. // Sanity: compressed data should be much smaller than the decompressed size
  9473. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9474. #ifndef _WIN32
  9475. signal(SIGPIPE, SIG_IGN);
  9476. #endif
  9477. // Set up the listening socket in the main thread so the server is guaranteed
  9478. // to be ready before the client connects (eliminates race condition).
  9479. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9480. default_socket_options(srv);
  9481. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9482. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9483. sockaddr_in addr{};
  9484. addr.sin_family = AF_INET;
  9485. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9487. int opt = 1;
  9488. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9489. #ifdef _WIN32
  9490. reinterpret_cast<const char *>(&opt),
  9491. #else
  9492. &opt,
  9493. #endif
  9494. sizeof(opt));
  9495. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9496. ASSERT_EQ(0, ::listen(srv, 1));
  9497. auto server_thread = std::thread([&compressed, srv] {
  9498. sockaddr_in cli_addr{};
  9499. socklen_t cli_len = sizeof(cli_addr);
  9500. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9501. if (cli != INVALID_SOCKET) {
  9502. // Read the full HTTP request (until \r\n\r\n)
  9503. char buf[4096];
  9504. size_t total = 0;
  9505. while (total < sizeof(buf)) {
  9506. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9507. if (n <= 0) break;
  9508. total += static_cast<size_t>(n);
  9509. // Check for end of headers
  9510. if (total >= 4) {
  9511. std::string req(buf, total);
  9512. if (req.find("\r\n\r\n") != std::string::npos) break;
  9513. }
  9514. }
  9515. // Malicious response: gzip-compressed body, no Content-Length
  9516. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9517. "Content-Encoding: gzip\r\n"
  9518. "Connection: close\r\n"
  9519. "\r\n";
  9520. ::send(cli,
  9521. #ifdef _WIN32
  9522. static_cast<const char *>(response_header.c_str()),
  9523. static_cast<int>(response_header.size()),
  9524. #else
  9525. response_header.c_str(), response_header.size(),
  9526. #endif
  9527. 0);
  9528. // Send the compressed payload (small on the wire, huge when decompressed)
  9529. size_t total_sent = 0;
  9530. while (total_sent < compressed.size()) {
  9531. auto to_send = std::min(compressed.size() - total_sent,
  9532. static_cast<size_t>(64 * 1024));
  9533. auto sent =
  9534. ::send(cli,
  9535. #ifdef _WIN32
  9536. static_cast<const char *>(compressed.c_str() + total_sent),
  9537. static_cast<int>(to_send),
  9538. #else
  9539. compressed.c_str() + total_sent, to_send,
  9540. #endif
  9541. 0);
  9542. if (sent <= 0) break;
  9543. total_sent += static_cast<size_t>(sent);
  9544. }
  9545. detail::close_socket(cli);
  9546. }
  9547. });
  9548. auto se = detail::scope_exit([&] {
  9549. detail::close_socket(srv);
  9550. server_thread.join();
  9551. });
  9552. size_t total_decompressed = 0;
  9553. {
  9554. Client cli("127.0.0.1", PORT + 3);
  9555. cli.set_read_timeout(5, 0);
  9556. cli.set_decompress(true);
  9557. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9558. auto stream = cli.open_stream("GET", "/zipbomb");
  9559. ASSERT_TRUE(stream.is_valid());
  9560. char buffer[64 * 1024];
  9561. ssize_t n;
  9562. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9563. total_decompressed += static_cast<size_t>(n);
  9564. }
  9565. }
  9566. // The decompressed size must be capped by payload_max_length. Without
  9567. // protection, the client would decompress the full 10MB from a tiny
  9568. // compressed payload, enabling a zip bomb DoS attack.
  9569. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9570. << "Client decompressed " << total_decompressed
  9571. << " bytes from a gzip response. The decompressed size should be "
  9572. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9573. }
  9574. #endif
  9575. TEST(HostAndPortPropertiesTest, NoSSL) {
  9576. httplib::Client cli("www.google.com", 1234);
  9577. ASSERT_EQ("www.google.com", cli.host());
  9578. ASSERT_EQ(1234, cli.port());
  9579. }
  9580. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9581. httplib::Client cli("www.google.com:1234");
  9582. ASSERT_EQ("www.google.com", cli.host());
  9583. ASSERT_EQ(1234, cli.port());
  9584. }
  9585. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9586. // Port number that overflows int — should not crash, client becomes invalid
  9587. httplib::Client cli("http://www.google.com:99999999999999999999");
  9588. ASSERT_FALSE(cli.is_valid());
  9589. }
  9590. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9591. // Port 99999 exceeds valid range (1-65535) — should not crash
  9592. httplib::Client cli("http://www.google.com:99999");
  9593. ASSERT_FALSE(cli.is_valid());
  9594. }
  9595. #ifdef CPPHTTPLIB_SSL_ENABLED
  9596. TEST(HostAndPortPropertiesTest, SSL) {
  9597. httplib::SSLClient cli("www.google.com");
  9598. ASSERT_EQ("www.google.com", cli.host());
  9599. ASSERT_EQ(443, cli.port());
  9600. }
  9601. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9602. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9603. std::string cert;
  9604. read_file(CA_CERT_FILE, cert);
  9605. httplib::SSLClient httplib_client("www.google.com");
  9606. // Load CA store first time
  9607. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9608. // Load CA store second time (update)
  9609. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9610. // Verify client is still valid and can make connections
  9611. httplib_client.enable_server_certificate_verification(true);
  9612. auto res = httplib_client.Get("/");
  9613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9614. // Google may return 200 or 301 depending on various factors
  9615. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9616. res->status == StatusCode::MovedPermanently_301);
  9617. }
  9618. TEST(SSLClientTest, ServerNameIndication_Online) {
  9619. auto host = "httpbingo.org";
  9620. auto path = std::string{"/get"};
  9621. SSLClient cli(host, 443);
  9622. auto res = cli.Get(path);
  9623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9624. ASSERT_EQ(StatusCode::OK_200, res->status);
  9625. }
  9626. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9627. // Use a site that will cause SSL verification failure due to self-signed cert
  9628. SSLClient cli("self-signed.badssl.com", 443);
  9629. cli.enable_server_certificate_verification(true);
  9630. auto res = cli.Get("/");
  9631. ASSERT_TRUE(!res);
  9632. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9633. // Verify backend error is captured for SSLServerVerification
  9634. // This occurs when certificate verification fails
  9635. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9636. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9637. EXPECT_NE(0UL, res.ssl_backend_error());
  9638. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9639. // For OpenSSL, ssl_error is 0 for verification errors
  9640. EXPECT_EQ(0, res.ssl_error());
  9641. #if !defined(_WIN32) || \
  9642. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9643. // On non-Windows or when Windows Schannel is disabled, the error comes
  9644. // from OpenSSL's verification
  9645. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9646. res.ssl_backend_error());
  9647. #endif
  9648. #endif
  9649. }
  9650. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9651. // Use a site where hostname doesn't match the certificate
  9652. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9653. SSLClient cli("wrong.host.badssl.com", 443);
  9654. cli.enable_server_certificate_verification(true);
  9655. cli.enable_server_hostname_verification(true);
  9656. auto res = cli.Get("/");
  9657. ASSERT_TRUE(!res);
  9658. // The error type depends on when hostname verification occurs:
  9659. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9660. // - Mbed TLS: SSLServerVerification (during handshake)
  9661. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9662. res.error() == Error::SSLServerVerification);
  9663. // Verify backend error is captured for hostname verification failure
  9664. EXPECT_NE(0UL, res.ssl_backend_error());
  9665. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9666. // For OpenSSL, ssl_error is 0 for verification errors
  9667. EXPECT_EQ(0, res.ssl_error());
  9668. #if !defined(_WIN32) || \
  9669. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9670. // On non-Windows or when Windows Schannel is disabled, the error comes
  9671. // from OpenSSL's hostname verification
  9672. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9673. res.ssl_backend_error());
  9674. #endif
  9675. #endif
  9676. }
  9677. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9678. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9679. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9680. SSLClient cli("www.google.com", 443);
  9681. cli.enable_server_certificate_verification(true);
  9682. auto res = cli.Get("/");
  9683. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9684. }
  9685. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9686. SSLClient cli("www.google.com", 443);
  9687. cli.enable_server_certificate_verification(true);
  9688. cli.enable_windows_certificate_verification(false);
  9689. auto res = cli.Get("/");
  9690. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9691. }
  9692. #endif
  9693. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9694. Client cli("https://google.com");
  9695. auto res = cli.Get("/");
  9696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9697. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9698. }
  9699. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9700. SSLClient cli("google.com");
  9701. cli.set_ca_cert_path(CA_CERT_FILE);
  9702. auto res = cli.Get("/");
  9703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9704. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9705. }
  9706. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9707. SSLClient cli("google.com");
  9708. cli.enable_server_certificate_verification(true);
  9709. cli.set_ca_cert_path("hello");
  9710. auto res = cli.Get("/");
  9711. ASSERT_TRUE(!res);
  9712. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9713. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9714. // should be set
  9715. EXPECT_EQ(0, res.ssl_error());
  9716. // Verify backend error is captured for SSLLoadingCerts
  9717. // This error occurs when loading CA certificates fails
  9718. EXPECT_NE(0UL, res.ssl_backend_error());
  9719. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9720. // OpenSSL specific error codes:
  9721. // > openssl errstr 0x80000002
  9722. // error:80000002:system library::No such file or directory
  9723. // > openssl errstr 0xA000126
  9724. // error:0A000126:SSL routines::unexpected eof while reading
  9725. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9726. res.ssl_backend_error() == 0xA000126);
  9727. #endif
  9728. }
  9729. TEST(SSLClientTest, ServerCertificateVerification4) {
  9730. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9731. ASSERT_TRUE(svr.is_valid());
  9732. svr.Get("/test", [&](const Request &, Response &res) {
  9733. res.set_content("test", "text/plain");
  9734. svr.stop();
  9735. ASSERT_TRUE(true);
  9736. });
  9737. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9738. auto se = detail::scope_exit([&] {
  9739. t.join();
  9740. ASSERT_FALSE(svr.is_running());
  9741. });
  9742. svr.wait_until_ready();
  9743. SSLClient cli("127.0.0.1", PORT);
  9744. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9745. cli.enable_server_certificate_verification(true);
  9746. cli.set_connection_timeout(30);
  9747. auto res = cli.Get("/test");
  9748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9749. ASSERT_EQ(StatusCode::OK_200, res->status);
  9750. }
  9751. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9752. std::string cert;
  9753. read_file(CA_CERT_FILE, cert);
  9754. SSLClient cli("google.com");
  9755. cli.load_ca_cert_store(cert.data(), cert.size());
  9756. const auto res = cli.Get("/");
  9757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9758. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9759. }
  9760. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9761. // clang-format off
  9762. static constexpr char cert[] =
  9763. "GlobalSign Root CA\n"
  9764. "==================\n"
  9765. "-----BEGIN CERTIFICATE-----\n"
  9766. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9767. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9768. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9769. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9770. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9771. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9772. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9773. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9774. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9775. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9776. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9777. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9778. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9779. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9780. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9781. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9782. "-----END CERTIFICATE-----\n";
  9783. // clang-format on
  9784. SSLClient cli("google.com");
  9785. cli.load_ca_cert_store(cert, sizeof(cert));
  9786. const auto res = cli.Get("/");
  9787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9788. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9789. }
  9790. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9791. SSLClient cli("www.youtube.com");
  9792. cli.set_ca_cert_path(CA_CERT_FILE);
  9793. cli.enable_server_certificate_verification(true);
  9794. cli.set_follow_location(true);
  9795. auto res = cli.Get("/");
  9796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9797. ASSERT_EQ(StatusCode::OK_200, res->status);
  9798. }
  9799. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9800. SSLClient cli("wWw.YouTube.Com");
  9801. cli.set_ca_cert_path(CA_CERT_FILE);
  9802. cli.enable_server_certificate_verification(true);
  9803. cli.enable_server_hostname_verification(true);
  9804. cli.set_follow_location(true);
  9805. auto res = cli.Get("/");
  9806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9807. ASSERT_EQ(StatusCode::OK_200, res->status);
  9808. }
  9809. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9810. SSLClient cli("gOoGlE.COm");
  9811. cli.enable_server_certificate_verification(true);
  9812. cli.enable_server_hostname_verification(true);
  9813. cli.set_follow_location(true);
  9814. auto res = cli.Get("/");
  9815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9816. ASSERT_EQ(StatusCode::OK_200, res->status);
  9817. }
  9818. TEST(SSLClientTest, Issue2004_Online) {
  9819. Client client("https://google.com");
  9820. client.set_follow_location(true);
  9821. auto res = client.Get("/");
  9822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9823. ASSERT_EQ(StatusCode::OK_200, res->status);
  9824. auto body = res->body;
  9825. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9826. }
  9827. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9828. // Create SSLClient with invalid cert/key to make is_valid() return false
  9829. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9830. "nonexistent_key.pem");
  9831. // is_valid() should be false due to cert loading failure
  9832. ASSERT_FALSE(cli.is_valid());
  9833. auto res = cli.Get("/");
  9834. ASSERT_FALSE(res);
  9835. EXPECT_EQ(Error::SSLConnection, res.error());
  9836. }
  9837. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9838. // Test for Issue #2251: SSL error not properly reported when client cert
  9839. // and key paths are swapped or mismatched
  9840. // This simulates the scenario where user accidentally swaps the cert and key
  9841. // files
  9842. // Using client cert file as private key and vice versa (completely wrong)
  9843. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9844. // Should fail validation due to cert/key mismatch
  9845. ASSERT_FALSE(cli.is_valid());
  9846. // Attempt to make a request should fail with proper error
  9847. auto res = cli.Get("/");
  9848. ASSERT_FALSE(res);
  9849. EXPECT_EQ(Error::SSLConnection, res.error());
  9850. // SSL error should be recorded in the Result object (this is the key fix for
  9851. // Issue #2251)
  9852. auto backend_error = res.ssl_backend_error();
  9853. EXPECT_NE(0u, backend_error);
  9854. }
  9855. // Tests cert/key mismatch detection at the TLS context level
  9856. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9857. // Test that using mismatched cert/key causes connection failure.
  9858. // We verify this at the SSLClient level rather than through internal
  9859. // TLS API functions.
  9860. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9861. cli.enable_server_certificate_verification(false);
  9862. cli.set_connection_timeout(2);
  9863. // The mismatch should cause a connection or handshake error
  9864. auto res = cli.Get("/test");
  9865. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9866. // Either way, the request should fail
  9867. EXPECT_FALSE(res);
  9868. }
  9869. #endif
  9870. #if 0
  9871. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9872. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9873. ASSERT_TRUE(cli != nullptr);
  9874. cli->set_address_family(AF_INET6);
  9875. cli->set_interface("en0");
  9876. auto res = cli->Get("/get");
  9877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9878. ASSERT_EQ(StatusCode::OK_200, res->status);
  9879. }
  9880. #endif
  9881. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9882. #ifdef CPPHTTPLIB_SSL_ENABLED
  9883. void ClientCertPresent(
  9884. const std::string &client_cert_file,
  9885. const std::string &client_private_key_file,
  9886. const std::string &client_encrypted_private_key_pass = std::string()) {
  9887. using namespace httplib::tls;
  9888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9889. CLIENT_CA_CERT_DIR);
  9890. ASSERT_TRUE(svr.is_valid());
  9891. svr.Get("/test", [&](const Request &req, Response &res) {
  9892. res.set_content("test", "text/plain");
  9893. auto cert = req.peer_cert();
  9894. ASSERT_TRUE(static_cast<bool>(cert));
  9895. std::string common_name = cert.subject_cn();
  9896. EXPECT_EQ("Common Name", common_name);
  9897. });
  9898. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. t.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. });
  9904. svr.wait_until_ready();
  9905. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9906. client_encrypted_private_key_pass);
  9907. cli.enable_server_certificate_verification(false);
  9908. cli.set_connection_timeout(30);
  9909. auto res = cli.Get("/test");
  9910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9911. ASSERT_EQ(StatusCode::OK_200, res->status);
  9912. }
  9913. TEST(SSLClientServerTest, ClientCertPresent) {
  9914. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9915. }
  9916. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9917. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9918. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9919. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9920. }
  9921. // PEM memory-based constructor tests (works with all TLS backends)
  9922. void PemMemoryClientCertPresent(
  9923. const std::string &client_cert_file,
  9924. const std::string &client_private_key_file,
  9925. const std::string &client_encrypted_private_key_pass = std::string()) {
  9926. // Read PEM files into memory
  9927. std::string server_cert_pem, server_key_pem;
  9928. std::string client_ca_pem;
  9929. std::string client_cert_pem, client_key_pem;
  9930. read_file(SERVER_CERT_FILE, server_cert_pem);
  9931. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9932. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9933. read_file(client_cert_file, client_cert_pem);
  9934. read_file(client_private_key_file, client_key_pem);
  9935. // Create server with PEM memory
  9936. SSLServer::PemMemory server_pem = {
  9937. server_cert_pem.c_str(),
  9938. server_cert_pem.size(),
  9939. server_key_pem.c_str(),
  9940. server_key_pem.size(),
  9941. client_ca_pem.c_str(),
  9942. client_ca_pem.size(),
  9943. nullptr // no password for server key
  9944. };
  9945. SSLServer svr(server_pem);
  9946. ASSERT_TRUE(svr.is_valid());
  9947. svr.Get("/test", [&](const Request &, Response &res) {
  9948. res.set_content("test", "text/plain");
  9949. });
  9950. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9951. auto se = detail::scope_exit([&] {
  9952. svr.stop();
  9953. t.join();
  9954. ASSERT_FALSE(svr.is_running());
  9955. });
  9956. svr.wait_until_ready();
  9957. // Create client with PEM memory
  9958. const char *password = client_encrypted_private_key_pass.empty()
  9959. ? nullptr
  9960. : client_encrypted_private_key_pass.c_str();
  9961. SSLClient::PemMemory client_pem = {
  9962. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9963. client_key_pem.size(), password};
  9964. SSLClient cli(HOST, PORT, client_pem);
  9965. cli.enable_server_certificate_verification(false);
  9966. cli.set_connection_timeout(30);
  9967. auto res = cli.Get("/test");
  9968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9969. ASSERT_EQ(StatusCode::OK_200, res->status);
  9970. }
  9971. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9972. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9973. }
  9974. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9975. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9976. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9977. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9978. }
  9979. TEST(SSLClientServerTest, ClientCertMissing) {
  9980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9981. CLIENT_CA_CERT_DIR);
  9982. ASSERT_TRUE(svr.is_valid());
  9983. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9985. auto se = detail::scope_exit([&] {
  9986. svr.stop();
  9987. t.join();
  9988. ASSERT_FALSE(svr.is_running());
  9989. });
  9990. svr.wait_until_ready();
  9991. SSLClient cli(HOST, PORT);
  9992. cli.set_connection_timeout(30);
  9993. auto res = cli.Get("/test");
  9994. ASSERT_TRUE(!res);
  9995. // When client cert is missing and server requires it, connection fails
  9996. // Error type depends on backend implementation
  9997. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9998. res.error() == Error::SSLConnection);
  9999. // Verify backend error is captured
  10000. // Note: This test may have different error codes depending on the exact
  10001. // verification failure
  10002. EXPECT_NE(0UL, res.ssl_backend_error());
  10003. }
  10004. TEST(SSLClientServerTest, TrustDirOptional) {
  10005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10006. ASSERT_TRUE(svr.is_valid());
  10007. svr.Get("/test", [&](const Request &, Response &res) {
  10008. res.set_content("test", "text/plain");
  10009. });
  10010. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. t.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10018. cli.enable_server_certificate_verification(false);
  10019. cli.set_connection_timeout(30);
  10020. auto res = cli.Get("/test");
  10021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10022. ASSERT_EQ(StatusCode::OK_200, res->status);
  10023. }
  10024. TEST(SSLClientServerTest, SSLConnectTimeout) {
  10025. class NoListenSSLServer : public SSLServer {
  10026. public:
  10027. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  10028. const char *client_ca_cert_file_path,
  10029. const char *client_ca_cert_dir_path = nullptr)
  10030. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  10031. client_ca_cert_dir_path),
  10032. stop_(false) {}
  10033. std::atomic_bool stop_;
  10034. private:
  10035. bool process_and_close_socket(socket_t /*sock*/) override {
  10036. // Don't create SSL context
  10037. while (!stop_.load()) {
  10038. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10039. }
  10040. return true;
  10041. }
  10042. };
  10043. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10044. CLIENT_CA_CERT_FILE);
  10045. ASSERT_TRUE(svr.is_valid());
  10046. svr.Get("/test", [&](const Request &, Response &res) {
  10047. res.set_content("test", "text/plain");
  10048. });
  10049. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10050. auto se = detail::scope_exit([&] {
  10051. svr.stop_ = true;
  10052. svr.stop();
  10053. t.join();
  10054. ASSERT_FALSE(svr.is_running());
  10055. });
  10056. svr.wait_until_ready();
  10057. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10058. cli.enable_server_certificate_verification(false);
  10059. cli.set_connection_timeout(1);
  10060. auto res = cli.Get("/test");
  10061. ASSERT_TRUE(!res);
  10062. EXPECT_EQ(Error::SSLConnection, res.error());
  10063. // Timeout results in WantRead error code (maps to backend-specific value)
  10064. EXPECT_NE(0, res.ssl_error());
  10065. }
  10066. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  10067. // Test SSLServer with client certificate verification using the standard
  10068. // constructor (ContextSetupCallback is tested by backend-specific tests)
  10069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  10070. CLIENT_CA_CERT_DIR);
  10071. ASSERT_TRUE(svr.is_valid());
  10072. svr.Get("/test", [&](const Request &req, Response &res) {
  10073. res.set_content("test", "text/plain");
  10074. auto cert = req.peer_cert();
  10075. ASSERT_TRUE(static_cast<bool>(cert));
  10076. auto common_name = cert.subject_cn();
  10077. EXPECT_EQ("Common Name", common_name);
  10078. });
  10079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10080. auto se = detail::scope_exit([&] {
  10081. svr.stop();
  10082. t.join();
  10083. ASSERT_FALSE(svr.is_running());
  10084. });
  10085. svr.wait_until_ready();
  10086. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10087. cli.enable_server_certificate_verification(false);
  10088. cli.set_connection_timeout(30);
  10089. auto res = cli.Get("/test");
  10090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10091. ASSERT_EQ(StatusCode::OK_200, res->status);
  10092. }
  10093. // Test verify_hostname for both OpenSSL and MbedTLS backends
  10094. // Verifies that wildcard matching and exact matching work consistently
  10095. TEST(SSLClientServerTest, TlsVerifyHostname) {
  10096. using namespace httplib::tls;
  10097. // We need a running server to test against
  10098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10099. ASSERT_TRUE(svr.is_valid());
  10100. svr.Get("/test", [](const Request &, Response &res) {
  10101. res.set_content("ok", "text/plain");
  10102. });
  10103. thread t([&]() { svr.listen(HOST, PORT); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. t.join();
  10107. });
  10108. svr.wait_until_ready();
  10109. bool verify_callback_called = false;
  10110. bool verify_result_wrong = false;
  10111. SSLClient cli(HOST, PORT);
  10112. cli.enable_server_certificate_verification(true);
  10113. cli.set_ca_cert_path(CA_CERT_FILE);
  10114. cli.set_connection_timeout(5);
  10115. // Note: Test certificate has CN="Common Name", not "localhost"
  10116. bool verify_result_cn = false;
  10117. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10118. verify_callback_called = true;
  10119. if (!ctx.cert) return false;
  10120. // Test 1: "Common Name" should match (our test server cert CN)
  10121. verify_result_cn = ctx.check_hostname("Common Name");
  10122. // Test 2: wrong hostname should not match
  10123. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  10124. return true; // Accept for the purpose of this test
  10125. });
  10126. auto res = cli.Get("/test");
  10127. // The request may succeed or fail depending on cert configuration
  10128. // but the callback should have been called
  10129. ASSERT_TRUE(verify_callback_called)
  10130. << "Verify callback should have been called";
  10131. // CN="Common Name" should match our test certificate
  10132. //
  10133. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  10134. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  10135. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  10136. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  10137. // <openssl/base.h>, which is included transitively when
  10138. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  10139. #if defined(OPENSSL_IS_BORINGSSL)
  10140. EXPECT_FALSE(verify_result_cn)
  10141. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  10142. #else
  10143. EXPECT_TRUE(verify_result_cn)
  10144. << "verify_hostname should match 'Common Name' (certificate CN)";
  10145. #endif
  10146. // Wrong hostname should not match
  10147. EXPECT_FALSE(verify_result_wrong)
  10148. << "verify_hostname should not match 'wronghost.example.com'";
  10149. }
  10150. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  10151. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  10152. // X509_check_ip behavior and must hold for every backend.
  10153. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  10154. using namespace httplib::tls;
  10155. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  10156. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  10157. ASSERT_TRUE(svr.is_valid());
  10158. svr.Get("/test", [](const Request &, Response &res) {
  10159. res.set_content("ok", "text/plain");
  10160. });
  10161. thread t([&]() { svr.listen(HOST, PORT); });
  10162. auto se = detail::scope_exit([&] {
  10163. svr.stop();
  10164. t.join();
  10165. });
  10166. svr.wait_until_ready();
  10167. bool verify_callback_called = false;
  10168. bool ip_matched_via_cn = true;
  10169. SSLClient cli(HOST, PORT);
  10170. cli.enable_server_certificate_verification(true);
  10171. cli.set_ca_cert_path(CA_CERT_FILE);
  10172. cli.set_connection_timeout(5);
  10173. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10174. verify_callback_called = true;
  10175. if (!ctx.cert) return false;
  10176. // The IP appears only in the CN, so it must NOT be accepted.
  10177. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  10178. return true; // Accept for the purpose of this test
  10179. });
  10180. cli.Get("/test");
  10181. ASSERT_TRUE(verify_callback_called)
  10182. << "Verify callback should have been called";
  10183. EXPECT_FALSE(ip_matched_via_cn)
  10184. << "An IP host must not be authenticated via the certificate CN";
  10185. }
  10186. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  10187. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  10188. using namespace httplib::tls;
  10189. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10190. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10191. ASSERT_TRUE(svr.is_valid());
  10192. svr.Get("/test", [](const Request &, Response &res) {
  10193. res.set_content("ok", "text/plain");
  10194. });
  10195. thread t([&]() { svr.listen(HOST, PORT); });
  10196. auto se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. t.join();
  10199. });
  10200. svr.wait_until_ready();
  10201. bool verify_callback_called = false;
  10202. bool san_matched = false;
  10203. bool wrong_ipv6_matched = true;
  10204. bool cn_ipv6_matched = true;
  10205. SSLClient cli(HOST, PORT);
  10206. cli.enable_server_certificate_verification(true);
  10207. cli.set_ca_cert_path(CA_CERT_FILE);
  10208. cli.set_connection_timeout(5);
  10209. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10210. verify_callback_called = true;
  10211. if (!ctx.cert) return false;
  10212. // Matches the IPv6 iPAddress SAN.
  10213. san_matched = ctx.check_hostname("2001:db8::1");
  10214. // A different IPv6 address must not match.
  10215. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10216. // "::1" lives only in the CN, so it must not be accepted.
  10217. cn_ipv6_matched = ctx.check_hostname("::1");
  10218. return true; // Accept for the purpose of this test
  10219. });
  10220. cli.Get("/test");
  10221. ASSERT_TRUE(verify_callback_called)
  10222. << "Verify callback should have been called";
  10223. EXPECT_TRUE(san_matched)
  10224. << "verify_hostname should match an IPv6 iPAddress SAN";
  10225. EXPECT_FALSE(wrong_ipv6_matched)
  10226. << "verify_hostname should not match a non-matching IPv6 address";
  10227. EXPECT_FALSE(cn_ipv6_matched)
  10228. << "An IPv6 host must not be authenticated via the certificate CN";
  10229. }
  10230. #endif
  10231. // mbedTLS-specific callback constructor test
  10232. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10233. #ifdef CPPHTTPLIB_SSL_ENABLED
  10234. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10236. ASSERT_TRUE(svr.is_valid());
  10237. // Set up a handler to verify client certificate is present
  10238. bool client_cert_verified = false;
  10239. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10240. // Verify that client certificate was provided
  10241. client_cert_verified = true;
  10242. res.set_content("success", "text/plain");
  10243. });
  10244. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10245. auto se = detail::scope_exit([&] {
  10246. svr.stop();
  10247. t.join();
  10248. ASSERT_FALSE(svr.is_running());
  10249. });
  10250. svr.wait_until_ready();
  10251. // Client with certificate
  10252. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10253. cli.enable_server_certificate_verification(false);
  10254. cli.set_connection_timeout(30);
  10255. auto res = cli.Get("/test");
  10256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10257. ASSERT_EQ(StatusCode::OK_200, res->status);
  10258. ASSERT_TRUE(client_cert_verified);
  10259. EXPECT_EQ("success", res->body);
  10260. }
  10261. #endif
  10262. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10263. // backends
  10264. #ifdef CPPHTTPLIB_SSL_ENABLED
  10265. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10266. using namespace httplib::tls;
  10267. // Test that when client CA cert file is provided,
  10268. // the server properly requests and validates client certificates
  10269. // Create a server with client authentication
  10270. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10271. ASSERT_TRUE(svr.is_valid());
  10272. bool handler_called = false;
  10273. svr.Get("/test", [&](const Request &req, Response &res) {
  10274. handler_called = true;
  10275. // Verify that a client certificate was provided
  10276. auto cert = req.peer_cert();
  10277. ASSERT_TRUE(static_cast<bool>(cert));
  10278. // Get the issuer name
  10279. std::string issuer_str = cert.issuer_name();
  10280. ASSERT_FALSE(issuer_str.empty());
  10281. // The client certificate should be issued by our test CA
  10282. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10283. res.set_content("authenticated", "text/plain");
  10284. });
  10285. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10286. auto se = detail::scope_exit([&] {
  10287. svr.stop();
  10288. t.join();
  10289. ASSERT_FALSE(svr.is_running());
  10290. });
  10291. svr.wait_until_ready();
  10292. // Connect with a client certificate issued by the CA
  10293. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10294. cli.enable_server_certificate_verification(false);
  10295. cli.set_connection_timeout(30);
  10296. auto res = cli.Get("/test");
  10297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10298. ASSERT_EQ(StatusCode::OK_200, res->status);
  10299. ASSERT_TRUE(handler_called);
  10300. EXPECT_EQ("authenticated", res->body);
  10301. }
  10302. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10303. using namespace httplib::tls;
  10304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10305. ASSERT_TRUE(svr.is_valid());
  10306. svr.Get("/test", [](const Request &, Response &res) {
  10307. res.set_content("ok", "text/plain");
  10308. });
  10309. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10310. auto se = detail::scope_exit([&] {
  10311. svr.stop();
  10312. t.join();
  10313. });
  10314. svr.wait_until_ready();
  10315. SSLClient cli(HOST, PORT);
  10316. cli.enable_server_certificate_verification(false);
  10317. cli.set_connection_timeout(30);
  10318. bool cert_checked = false;
  10319. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10320. if (ctx.cert) {
  10321. auto sans = ctx.sans();
  10322. // Test certificate may or may not have SANs - just verify the API
  10323. // works If SANs exist, verify the types are valid
  10324. for (const auto &san : sans) {
  10325. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10326. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10327. san.type == SanType::OTHER);
  10328. EXPECT_FALSE(san.value.empty());
  10329. }
  10330. cert_checked = true;
  10331. }
  10332. return true;
  10333. });
  10334. auto res = cli.Get("/test");
  10335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10336. EXPECT_TRUE(cert_checked);
  10337. }
  10338. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10339. using namespace httplib::tls;
  10340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10341. ASSERT_TRUE(svr.is_valid());
  10342. svr.Get("/test", [](const Request &, Response &res) {
  10343. res.set_content("ok", "text/plain");
  10344. });
  10345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10346. auto se = detail::scope_exit([&] {
  10347. svr.stop();
  10348. t.join();
  10349. });
  10350. svr.wait_until_ready();
  10351. SSLClient cli(HOST, PORT);
  10352. cli.enable_server_certificate_verification(false);
  10353. cli.set_connection_timeout(30);
  10354. bool validity_checked = false;
  10355. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10356. if (ctx.cert) {
  10357. time_t not_before = 0, not_after = 0;
  10358. bool result = ctx.validity(not_before, not_after);
  10359. EXPECT_TRUE(result);
  10360. // Verify that not_before < now < not_after for a valid cert
  10361. time_t now = time(nullptr);
  10362. EXPECT_LT(not_before, now);
  10363. EXPECT_GT(not_after, now);
  10364. validity_checked = true;
  10365. }
  10366. return true;
  10367. });
  10368. auto res = cli.Get("/test");
  10369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10370. EXPECT_TRUE(validity_checked);
  10371. }
  10372. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10373. using namespace httplib::tls;
  10374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10375. ASSERT_TRUE(svr.is_valid());
  10376. svr.Get("/test", [](const Request &, Response &res) {
  10377. res.set_content("ok", "text/plain");
  10378. });
  10379. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10380. auto se = detail::scope_exit([&] {
  10381. svr.stop();
  10382. t.join();
  10383. });
  10384. svr.wait_until_ready();
  10385. SSLClient cli(HOST, PORT);
  10386. cli.enable_server_certificate_verification(false);
  10387. cli.set_connection_timeout(30);
  10388. bool serial_checked = false;
  10389. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10390. if (ctx.cert) {
  10391. std::string serial = ctx.serial();
  10392. EXPECT_FALSE(serial.empty());
  10393. // Serial should be a hex string
  10394. for (char c : serial) {
  10395. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10396. (c >= 'a' && c <= 'f'));
  10397. }
  10398. serial_checked = true;
  10399. }
  10400. return true;
  10401. });
  10402. auto res = cli.Get("/test");
  10403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10404. EXPECT_TRUE(serial_checked);
  10405. }
  10406. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10407. // Test 1: Valid CA file - no error should be recorded
  10408. {
  10409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10410. CLIENT_CA_CERT_FILE);
  10411. ASSERT_TRUE(svr.is_valid());
  10412. // With valid setup, last_ssl_error should be 0
  10413. EXPECT_EQ(0, svr.ssl_last_error());
  10414. }
  10415. // Test 2: Invalid CA file content
  10416. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10417. {
  10418. // Create a temporary file with completely invalid content
  10419. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10420. {
  10421. std::ofstream ofs(temp_invalid_ca);
  10422. ofs << "This is not a certificate file at all\n";
  10423. ofs << "Just plain text content\n";
  10424. }
  10425. // Create server with invalid CA file
  10426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10427. // Clean up temporary file
  10428. std::remove(temp_invalid_ca);
  10429. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10430. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10431. // Note: SSL_CTX_load_verify_locations typically fails first,
  10432. // but our error handling code path is still exercised
  10433. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10434. }
  10435. }
  10436. TEST(VerifyCallbackTest, VerifyContextFields) {
  10437. using namespace httplib::tls;
  10438. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10439. ASSERT_TRUE(svr.is_valid());
  10440. svr.Get("/test", [](const Request &, Response &res) {
  10441. res.set_content("ok", "text/plain");
  10442. });
  10443. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10444. auto se = detail::scope_exit([&] {
  10445. svr.stop();
  10446. t.join();
  10447. });
  10448. svr.wait_until_ready();
  10449. SSLClient cli(HOST, PORT);
  10450. cli.enable_server_certificate_verification(false);
  10451. cli.set_connection_timeout(30);
  10452. int callback_count = 0;
  10453. bool saw_leaf_cert = false;
  10454. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10455. if (ctx.cert) {
  10456. callback_count++;
  10457. // We should see at least one certificate (the leaf)
  10458. std::string cn = ctx.subject_cn();
  10459. if (!cn.empty()) { saw_leaf_cert = true; }
  10460. // Verify context fields are populated
  10461. EXPECT_NE(ctx.session, nullptr);
  10462. EXPECT_GE(ctx.depth, 0);
  10463. }
  10464. return true;
  10465. });
  10466. auto res = cli.Get("/test");
  10467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10468. EXPECT_GT(callback_count, 0);
  10469. EXPECT_TRUE(saw_leaf_cert);
  10470. }
  10471. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10472. using httplib::tls::TlsError;
  10473. // Test that verify_error_to_string returns empty for success
  10474. std::string success_str = TlsError::verify_error_to_string(0);
  10475. EXPECT_TRUE(success_str.empty());
  10476. // Test that verify_error_to_string returns non-empty for error codes
  10477. // Using a common error code (certificate expired)
  10478. std::string error_str =
  10479. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10480. EXPECT_FALSE(error_str.empty());
  10481. }
  10482. TEST(SessionVerifierTest, CertificateAccepted) {
  10483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10484. ASSERT_TRUE(svr.is_valid());
  10485. svr.Get("/test", [](const Request &, Response &res) {
  10486. res.set_content("ok", "text/plain");
  10487. });
  10488. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10489. auto se = detail::scope_exit([&] {
  10490. svr.stop();
  10491. t.join();
  10492. });
  10493. svr.wait_until_ready();
  10494. SSLClient cli(HOST, PORT);
  10495. cli.enable_server_certificate_verification(false);
  10496. cli.set_connection_timeout(30);
  10497. bool callback_called = false;
  10498. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10499. EXPECT_NE(session, nullptr);
  10500. callback_called = true;
  10501. return SSLVerifierResponse::CertificateAccepted;
  10502. });
  10503. auto res = cli.Get("/test");
  10504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10505. EXPECT_EQ(200, res->status);
  10506. EXPECT_TRUE(callback_called);
  10507. }
  10508. TEST(SessionVerifierTest, CertificateRejected) {
  10509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10510. ASSERT_TRUE(svr.is_valid());
  10511. svr.Get("/test", [](const Request &, Response &res) {
  10512. res.set_content("ok", "text/plain");
  10513. });
  10514. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10515. auto se = detail::scope_exit([&] {
  10516. svr.stop();
  10517. t.join();
  10518. });
  10519. svr.wait_until_ready();
  10520. SSLClient cli(HOST, PORT);
  10521. cli.enable_server_certificate_verification(false);
  10522. cli.set_connection_timeout(30);
  10523. bool callback_called = false;
  10524. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10525. EXPECT_NE(session, nullptr);
  10526. callback_called = true;
  10527. return SSLVerifierResponse::CertificateRejected;
  10528. });
  10529. auto res = cli.Get("/test");
  10530. EXPECT_FALSE(res);
  10531. EXPECT_TRUE(callback_called);
  10532. }
  10533. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10534. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10535. ASSERT_TRUE(svr.is_valid());
  10536. svr.Get("/test", [](const Request &, Response &res) {
  10537. res.set_content("ok", "text/plain");
  10538. });
  10539. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10540. auto se = detail::scope_exit([&] {
  10541. svr.stop();
  10542. t.join();
  10543. });
  10544. svr.wait_until_ready();
  10545. // NoDecisionMade with verification disabled should succeed (no default check)
  10546. SSLClient cli(HOST, PORT);
  10547. cli.enable_server_certificate_verification(false);
  10548. cli.set_connection_timeout(30);
  10549. bool callback_called = false;
  10550. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10551. EXPECT_NE(session, nullptr);
  10552. callback_called = true;
  10553. return SSLVerifierResponse::NoDecisionMade;
  10554. });
  10555. auto res = cli.Get("/test");
  10556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10557. EXPECT_EQ(200, res->status);
  10558. EXPECT_TRUE(callback_called);
  10559. }
  10560. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10562. ASSERT_TRUE(svr.is_valid());
  10563. svr.Get("/test", [](const Request &, Response &res) {
  10564. res.set_content("ok", "text/plain");
  10565. });
  10566. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10567. auto se = detail::scope_exit([&] {
  10568. svr.stop();
  10569. t.join();
  10570. });
  10571. svr.wait_until_ready();
  10572. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10573. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10574. // so we only check that the request fails, not whether the callback was
  10575. // called.
  10576. SSLClient cli(HOST, PORT);
  10577. cli.enable_server_certificate_verification(true);
  10578. cli.set_connection_timeout(30);
  10579. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10580. EXPECT_NE(session, nullptr);
  10581. return SSLVerifierResponse::NoDecisionMade;
  10582. });
  10583. auto res = cli.Get("/test");
  10584. EXPECT_FALSE(res);
  10585. }
  10586. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10587. // Test SSL server using PemMemory constructor with client CA certificates
  10588. // Read PEM files
  10589. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10590. read_file(SERVER_CERT_FILE, server_cert_pem);
  10591. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10592. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10593. // Create SSLServer with PemMemory constructor including client CA
  10594. SSLServer::PemMemory server_pem = {
  10595. server_cert_pem.c_str(),
  10596. server_cert_pem.size(),
  10597. server_key_pem.c_str(),
  10598. server_key_pem.size(),
  10599. client_ca_pem.c_str(),
  10600. client_ca_pem.size(),
  10601. nullptr // no password for server key
  10602. };
  10603. SSLServer svr(server_pem);
  10604. ASSERT_TRUE(svr.is_valid());
  10605. // No SSL error should be recorded for valid setup
  10606. EXPECT_EQ(0, svr.ssl_last_error());
  10607. // Set up server endpoints
  10608. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10609. res.set_content("ok", "text/plain");
  10610. });
  10611. // Start server in a thread
  10612. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10613. svr.wait_until_ready();
  10614. // Connect with client certificate (using constructor with paths)
  10615. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10616. cli.enable_server_certificate_verification(false);
  10617. auto res = cli.Get("/test-pem-ca");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. EXPECT_EQ(200, res->status);
  10620. EXPECT_EQ("ok", res->body);
  10621. svr.stop();
  10622. server_thread.join();
  10623. }
  10624. #endif
  10625. #ifdef _WIN32
  10626. TEST(CleanupTest, WSACleanup) {
  10627. int ret = WSACleanup();
  10628. ASSERT_EQ(0, ret);
  10629. }
  10630. #endif
  10631. #ifndef CPPHTTPLIB_SSL_ENABLED
  10632. TEST(NoSSLSupport, SimpleInterface) {
  10633. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10634. }
  10635. #endif
  10636. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10637. TEST(InvalidScheme, SimpleInterface) {
  10638. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10639. }
  10640. #endif
  10641. TEST(NoScheme, SimpleInterface) {
  10642. Client cli("yahoo.com:80");
  10643. ASSERT_TRUE(cli.is_valid());
  10644. }
  10645. TEST(SendAPI, SimpleInterface_Online) {
  10646. Client cli("http://yahoo.com");
  10647. Request req;
  10648. req.method = "GET";
  10649. req.path = "/";
  10650. auto res = cli.send(req);
  10651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10652. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10653. }
  10654. TEST(SendAPI, WithParamsInRequest) {
  10655. Server svr;
  10656. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10657. EXPECT_TRUE(req.has_param("test"));
  10658. EXPECT_EQ("test_value", req.get_param_value("test"));
  10659. });
  10660. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10661. auto se = detail::scope_exit([&] {
  10662. svr.stop();
  10663. t.join();
  10664. ASSERT_FALSE(svr.is_running());
  10665. });
  10666. svr.wait_until_ready();
  10667. Client cli(HOST, PORT);
  10668. {
  10669. Request req;
  10670. req.method = "GET";
  10671. req.path = "/";
  10672. req.params.emplace("test", "test_value");
  10673. auto res = cli.send(req);
  10674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10675. }
  10676. {
  10677. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10679. }
  10680. }
  10681. TEST(ClientImplMethods, GetSocketTest) {
  10682. httplib::Server svr;
  10683. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10684. res.status = StatusCode::OK_200;
  10685. });
  10686. auto port = svr.bind_to_any_port("127.0.0.1");
  10687. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10688. auto se = detail::scope_exit([&] {
  10689. svr.stop();
  10690. thread.join();
  10691. ASSERT_FALSE(svr.is_running());
  10692. });
  10693. svr.wait_until_ready();
  10694. {
  10695. httplib::Client cli("127.0.0.1", port);
  10696. cli.set_keep_alive(true);
  10697. // Use the behavior of cpp-httplib of opening the connection
  10698. // only when the first request happens. If that changes,
  10699. // this test would be obsolete.
  10700. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10701. // This also implicitly tests the server. But other tests would fail much
  10702. // earlier than this one to be considered.
  10703. auto res = cli.Get("/");
  10704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10705. EXPECT_EQ(StatusCode::OK_200, res->status);
  10706. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10707. }
  10708. }
  10709. #ifdef CPPHTTPLIB_SSL_ENABLED
  10710. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10711. Client cli("http://yahoo.com");
  10712. auto res = cli.Get("/");
  10713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10714. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10715. cli.set_follow_location(true);
  10716. res = cli.Get("/");
  10717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10718. EXPECT_EQ(StatusCode::OK_200, res->status);
  10719. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10720. }
  10721. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10722. Client cli("https://yahoo.com");
  10723. auto res = cli.Get("/");
  10724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10725. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10726. cli.set_follow_location(true);
  10727. res = cli.Get("/");
  10728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10729. EXPECT_EQ(StatusCode::OK_200, res->status);
  10730. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10731. }
  10732. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10733. Client cli("https://yahoo.com");
  10734. auto res = cli.Get("/");
  10735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10736. ASSERT_FALSE(!res);
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. ASSERT_FALSE(res == nullptr);
  10739. ASSERT_TRUE(res != nullptr);
  10740. EXPECT_EQ(Error::Success, res.error());
  10741. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10742. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10743. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10744. cli.set_follow_location(true);
  10745. res = cli.Get("/");
  10746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10747. EXPECT_EQ(Error::Success, res.error());
  10748. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10749. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10750. EXPECT_EQ(StatusCode::OK_200, res->status);
  10751. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10752. }
  10753. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10754. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10755. Client cli("https://cdnjs.cloudflare.com");
  10756. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10757. Headers{{"Accept-Encoding", "br"}});
  10758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10759. EXPECT_EQ(StatusCode::OK_200, res->status);
  10760. EXPECT_EQ(287630U, res->body.size());
  10761. EXPECT_EQ("application/javascript; charset=utf-8",
  10762. res->get_header_value("Content-Type"));
  10763. }
  10764. #endif
  10765. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10766. #undef REDIR_HOST // Silence compiler warning
  10767. #define REDIR_HOST "https://httpbingo.org"
  10768. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10769. Client cli(REDIR_HOST);
  10770. cli.set_follow_location(true);
  10771. auto res =
  10772. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10774. EXPECT_EQ(StatusCode::OK_200, res->status);
  10775. }
  10776. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10777. Client cli(REDIR_HOST);
  10778. cli.set_follow_location(true);
  10779. Params params;
  10780. params.emplace("url", "http://example.com");
  10781. params.emplace("status_code", "302");
  10782. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10784. EXPECT_EQ(StatusCode::OK_200, res->status);
  10785. }
  10786. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10787. Client cli(REDIR_HOST);
  10788. cli.set_follow_location(true);
  10789. Params params;
  10790. params.emplace("url", "http://example.com");
  10791. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10793. EXPECT_EQ(StatusCode::OK_200, res->status);
  10794. }
  10795. TEST(HttpToHttpsRedirectTest, CertFile) {
  10796. auto ssl_port = PORT + 1;
  10797. Server svr;
  10798. ASSERT_TRUE(svr.is_valid());
  10799. svr.Get("/index", [&](const Request &, Response &res) {
  10800. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10801. "/index");
  10802. svr.stop();
  10803. });
  10804. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10805. ASSERT_TRUE(ssl_svr.is_valid());
  10806. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10807. res.set_content("test", "text/plain");
  10808. ssl_svr.stop();
  10809. });
  10810. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10811. thread t2 =
  10812. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10813. auto se = detail::scope_exit([&] {
  10814. t2.join();
  10815. t.join();
  10816. ASSERT_FALSE(svr.is_running());
  10817. });
  10818. svr.wait_until_ready();
  10819. ssl_svr.wait_until_ready();
  10820. Client cli("127.0.0.1", PORT);
  10821. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10822. cli.enable_server_certificate_verification(true);
  10823. cli.set_follow_location(true);
  10824. cli.set_connection_timeout(30);
  10825. auto res = cli.Get("/index");
  10826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10827. ASSERT_EQ(StatusCode::OK_200, res->status);
  10828. }
  10829. TEST(SSLClientRedirectTest, CertFile) {
  10830. auto ssl_port = PORT + 1;
  10831. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10832. ASSERT_TRUE(ssl_svr1.is_valid());
  10833. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10834. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10835. "/index");
  10836. ssl_svr1.stop();
  10837. });
  10838. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10839. ASSERT_TRUE(ssl_svr2.is_valid());
  10840. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10841. res.set_content("test", "text/plain");
  10842. ssl_svr2.stop();
  10843. });
  10844. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10845. thread t2 =
  10846. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10847. auto se = detail::scope_exit([&] {
  10848. t2.join();
  10849. t.join();
  10850. ASSERT_FALSE(ssl_svr1.is_running());
  10851. });
  10852. ssl_svr1.wait_until_ready();
  10853. ssl_svr2.wait_until_ready();
  10854. SSLClient cli("127.0.0.1", PORT);
  10855. std::string cert;
  10856. read_file(SERVER_CERT2_FILE, cert);
  10857. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10858. cli.enable_server_certificate_verification(true);
  10859. cli.set_follow_location(true);
  10860. cli.set_connection_timeout(30);
  10861. auto res = cli.Get("/index");
  10862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10863. ASSERT_EQ(StatusCode::OK_200, res->status);
  10864. }
  10865. #endif
  10866. #ifdef CPPHTTPLIB_SSL_ENABLED
  10867. // Test that set_ca_cert_store() skips system certs (consistent with
  10868. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10869. // should be trusted - system certs should NOT be loaded.
  10870. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10871. // Load a specific cert that is NOT a system CA cert
  10872. std::string cert;
  10873. read_file(SERVER_CERT2_FILE, cert);
  10874. SSLClient cli("google.com");
  10875. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10876. cli.enable_server_certificate_verification(true);
  10877. // This should FAIL because:
  10878. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10879. // 2. System certs should NOT be loaded when custom store is set
  10880. // If system certs WERE loaded, this would succeed
  10881. auto res = cli.Get("/");
  10882. ASSERT_FALSE(res);
  10883. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10884. }
  10885. // Same as above, but through the native store handle path. Regression test:
  10886. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10887. // merged system certs into the user-provided store.
  10888. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10889. std::string cert;
  10890. read_file(SERVER_CERT2_FILE, cert);
  10891. SSLClient cli("google.com");
  10892. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10893. cli.enable_server_certificate_verification(true);
  10894. auto res = cli.Get("/");
  10895. ASSERT_FALSE(res);
  10896. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10897. }
  10898. // A custom store set via the native handle must still verify a server whose
  10899. // cert it does contain.
  10900. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10901. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10902. ASSERT_TRUE(svr.is_valid());
  10903. svr.Get("/test", [&](const Request &, Response &res) {
  10904. res.set_content("test", "text/plain");
  10905. });
  10906. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10907. auto se = detail::scope_exit([&] {
  10908. svr.stop();
  10909. t.join();
  10910. ASSERT_FALSE(svr.is_running());
  10911. });
  10912. svr.wait_until_ready();
  10913. SSLClient cli("127.0.0.1", PORT);
  10914. std::string cert;
  10915. read_file(SERVER_CERT2_FILE, cert);
  10916. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10917. cli.enable_server_certificate_verification(true);
  10918. cli.set_connection_timeout(30);
  10919. auto res = cli.Get("/test");
  10920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10921. ASSERT_EQ(StatusCode::OK_200, res->status);
  10922. }
  10923. // CA certs loaded through the universal Client must be transferred to the
  10924. // client created internally for following an HTTPS redirect. Regression test:
  10925. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10926. // the CA data for redirect transfer.
  10927. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10928. auto ssl_port = PORT + 1;
  10929. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10930. ASSERT_TRUE(ssl_svr1.is_valid());
  10931. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10932. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10933. "/index");
  10934. });
  10935. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10936. ASSERT_TRUE(ssl_svr2.is_valid());
  10937. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10938. res.set_content("test", "text/plain");
  10939. });
  10940. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10941. thread t2 =
  10942. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10943. auto se = detail::scope_exit([&] {
  10944. ssl_svr2.stop();
  10945. ssl_svr1.stop();
  10946. t2.join();
  10947. t.join();
  10948. ASSERT_FALSE(ssl_svr1.is_running());
  10949. });
  10950. ssl_svr1.wait_until_ready();
  10951. ssl_svr2.wait_until_ready();
  10952. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10953. std::string cert;
  10954. read_file(SERVER_CERT2_FILE, cert);
  10955. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10956. cli.enable_server_certificate_verification(true);
  10957. cli.set_follow_location(true);
  10958. cli.set_connection_timeout(30);
  10959. auto res = cli.Get("/index");
  10960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10961. ASSERT_EQ(StatusCode::OK_200, res->status);
  10962. }
  10963. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10964. // so a host signed by a system CA verifies even though a custom CA is set
  10965. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10966. std::string cert;
  10967. read_file(SERVER_CERT2_FILE, cert);
  10968. SSLClient cli("google.com");
  10969. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10970. cli.enable_system_ca(true);
  10971. cli.enable_server_certificate_verification(true);
  10972. auto res = cli.Get("/");
  10973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10974. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10975. }
  10976. // The custom CA remains effective when combined with the system CA
  10977. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10978. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10979. ASSERT_TRUE(svr.is_valid());
  10980. svr.Get("/test", [&](const Request &, Response &res) {
  10981. res.set_content("test", "text/plain");
  10982. });
  10983. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10984. auto se = detail::scope_exit([&] {
  10985. svr.stop();
  10986. t.join();
  10987. ASSERT_FALSE(svr.is_running());
  10988. });
  10989. svr.wait_until_ready();
  10990. SSLClient cli("127.0.0.1", PORT);
  10991. std::string cert;
  10992. read_file(SERVER_CERT2_FILE, cert);
  10993. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10994. cli.enable_system_ca(true);
  10995. cli.enable_server_certificate_verification(true);
  10996. cli.set_connection_timeout(30);
  10997. auto res = cli.Get("/test");
  10998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10999. ASSERT_EQ(StatusCode::OK_200, res->status);
  11000. }
  11001. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  11002. // skip chain verification entirely (only the certificate identity was
  11003. // checked), so a server presenting an untrusted certificate with a matching
  11004. // IP SAN was accepted. The chain must be validated for IP hosts too.
  11005. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  11006. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11007. ASSERT_TRUE(svr.is_valid());
  11008. svr.Get("/test", [&](const Request &, Response &res) {
  11009. res.set_content("test", "text/plain");
  11010. });
  11011. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11012. auto se = detail::scope_exit([&] {
  11013. svr.stop();
  11014. t.join();
  11015. ASSERT_FALSE(svr.is_running());
  11016. });
  11017. svr.wait_until_ready();
  11018. SSLClient cli("127.0.0.1", PORT);
  11019. std::string cert;
  11020. // A trusted CA that did not sign the server certificate. The server cert
  11021. // (cert2) carries the matching IP SAN, so only chain validation can reject
  11022. // this connection.
  11023. read_file(CLIENT_CA_CERT_FILE, cert);
  11024. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11025. cli.enable_server_certificate_verification(true);
  11026. cli.set_connection_timeout(30);
  11027. auto res = cli.Get("/test");
  11028. ASSERT_FALSE(res);
  11029. }
  11030. // enable_system_ca(false) prevents system CA loading entirely
  11031. TEST(SSLClientTest, DisableSystemCa_Online) {
  11032. SSLClient cli("google.com");
  11033. cli.enable_system_ca(false);
  11034. cli.enable_server_certificate_verification(true);
  11035. auto res = cli.Get("/");
  11036. ASSERT_FALSE(res);
  11037. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  11038. // itself when the CA chain is empty
  11039. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  11040. res.error() == Error::SSLConnection);
  11041. }
  11042. // The universal Client forwards enable_system_ca()
  11043. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  11044. std::string cert;
  11045. read_file(SERVER_CERT2_FILE, cert);
  11046. Client cli("https://google.com");
  11047. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11048. cli.enable_system_ca(true);
  11049. cli.enable_server_certificate_verification(true);
  11050. auto res = cli.Get("/");
  11051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11052. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11053. }
  11054. // The system CA policy must carry over to the client created internally for
  11055. // following a cross-host HTTPS redirect
  11056. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  11057. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11058. ASSERT_TRUE(svr.is_valid());
  11059. svr.Get("/index", [&](const Request &, Response &res) {
  11060. res.set_redirect("https://www.google.com/");
  11061. });
  11062. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11063. auto se = detail::scope_exit([&] {
  11064. svr.stop();
  11065. t.join();
  11066. ASSERT_FALSE(svr.is_running());
  11067. });
  11068. svr.wait_until_ready();
  11069. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  11070. std::string cert;
  11071. read_file(SERVER_CERT2_FILE, cert);
  11072. cli.load_ca_cert_store(cert.c_str(), cert.size());
  11073. cli.enable_system_ca(true);
  11074. cli.enable_server_certificate_verification(true);
  11075. cli.set_follow_location(true);
  11076. cli.set_connection_timeout(30);
  11077. // Receiving any response proves the redirect client completed the TLS
  11078. // handshake with a system-CA-signed host
  11079. auto res = cli.Get("/index");
  11080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11081. }
  11082. TEST(MultipartFormDataTest, LargeData) {
  11083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11084. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  11085. const ContentReader &content_reader) {
  11086. if (req.is_multipart_form_data()) {
  11087. std::vector<FormData> items;
  11088. content_reader(
  11089. [&](const FormData &file) {
  11090. items.push_back(file);
  11091. return true;
  11092. },
  11093. [&](const char *data, size_t data_length) {
  11094. items.back().content.append(data, data_length);
  11095. return true;
  11096. });
  11097. EXPECT_TRUE(std::string(items[0].name) == "document");
  11098. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11099. EXPECT_TRUE(items[0].filename == "2MB_data");
  11100. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11101. EXPECT_TRUE(items[1].name == "hello");
  11102. EXPECT_TRUE(items[1].content == "world");
  11103. EXPECT_TRUE(items[1].filename == "");
  11104. EXPECT_TRUE(items[1].content_type == "");
  11105. } else {
  11106. std::string body;
  11107. content_reader([&](const char *data, size_t data_length) {
  11108. body.append(data, data_length);
  11109. return true;
  11110. });
  11111. }
  11112. });
  11113. auto port = svr.bind_to_any_port(HOST);
  11114. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11115. auto se = detail::scope_exit([&] {
  11116. svr.stop();
  11117. t.join();
  11118. ASSERT_FALSE(svr.is_running());
  11119. });
  11120. svr.wait_until_ready();
  11121. {
  11122. std::string data(1024 * 1024 * 2, '.');
  11123. std::stringstream buffer;
  11124. buffer << data;
  11125. SSLClient cli(HOST, port);
  11126. cli.enable_server_certificate_verification(false);
  11127. UploadFormDataItems items{
  11128. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11129. {"hello", "world", "", ""},
  11130. };
  11131. auto res = cli.Post("/post", items);
  11132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11133. ASSERT_EQ(StatusCode::OK_200, res->status);
  11134. }
  11135. }
  11136. TEST(MultipartFormDataTest, DataProviderItems) {
  11137. std::random_device seed_gen;
  11138. std::mt19937 random(seed_gen());
  11139. std::string rand1;
  11140. rand1.resize(1000);
  11141. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  11142. std::string rand2;
  11143. rand2.resize(3000);
  11144. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  11145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11146. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  11147. const ContentReader &content_reader) {
  11148. ASSERT_FALSE(req.is_multipart_form_data());
  11149. std::string body;
  11150. content_reader([&](const char *data, size_t data_length) {
  11151. body.append(data, data_length);
  11152. return true;
  11153. });
  11154. EXPECT_EQ(body, "");
  11155. });
  11156. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  11157. const ContentReader &content_reader) {
  11158. ASSERT_TRUE(req.is_multipart_form_data());
  11159. std::vector<FormData> items;
  11160. content_reader(
  11161. [&](const FormData &file) {
  11162. items.push_back(file);
  11163. return true;
  11164. },
  11165. [&](const char *data, size_t data_length) {
  11166. items.back().content.append(data, data_length);
  11167. return true;
  11168. });
  11169. ASSERT_TRUE(items.size() == 2);
  11170. EXPECT_EQ(std::string(items[0].name), "name1");
  11171. EXPECT_EQ(items[0].content, "Testing123");
  11172. EXPECT_EQ(items[0].filename, "filename1");
  11173. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11174. EXPECT_EQ(items[1].name, "name2");
  11175. EXPECT_EQ(items[1].content, "Testing456");
  11176. EXPECT_EQ(items[1].filename, "");
  11177. EXPECT_EQ(items[1].content_type, "");
  11178. });
  11179. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  11180. const ContentReader &content_reader) {
  11181. ASSERT_TRUE(req.is_multipart_form_data());
  11182. std::vector<FormData> items;
  11183. content_reader(
  11184. [&](const FormData &file) {
  11185. items.push_back(file);
  11186. return true;
  11187. },
  11188. [&](const char *data, size_t data_length) {
  11189. items.back().content.append(data, data_length);
  11190. return true;
  11191. });
  11192. ASSERT_TRUE(items.size() == 2);
  11193. EXPECT_EQ(items[0].name, "name3");
  11194. EXPECT_EQ(items[0].content, rand1);
  11195. EXPECT_EQ(items[0].filename, "filename3");
  11196. EXPECT_EQ(items[0].content_type, "");
  11197. EXPECT_EQ(items[1].name, "name4");
  11198. EXPECT_EQ(items[1].content, rand2);
  11199. EXPECT_EQ(items[1].filename, "filename4");
  11200. EXPECT_EQ(items[1].content_type, "");
  11201. });
  11202. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11203. const ContentReader &content_reader) {
  11204. ASSERT_TRUE(req.is_multipart_form_data());
  11205. std::vector<FormData> items;
  11206. content_reader(
  11207. [&](const FormData &file) {
  11208. items.push_back(file);
  11209. return true;
  11210. },
  11211. [&](const char *data, size_t data_length) {
  11212. items.back().content.append(data, data_length);
  11213. return true;
  11214. });
  11215. ASSERT_TRUE(items.size() == 4);
  11216. EXPECT_EQ(std::string(items[0].name), "name1");
  11217. EXPECT_EQ(items[0].content, "Testing123");
  11218. EXPECT_EQ(items[0].filename, "filename1");
  11219. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11220. EXPECT_EQ(items[1].name, "name2");
  11221. EXPECT_EQ(items[1].content, "Testing456");
  11222. EXPECT_EQ(items[1].filename, "");
  11223. EXPECT_EQ(items[1].content_type, "");
  11224. EXPECT_EQ(items[2].name, "name3");
  11225. EXPECT_EQ(items[2].content, rand1);
  11226. EXPECT_EQ(items[2].filename, "filename3");
  11227. EXPECT_EQ(items[2].content_type, "");
  11228. EXPECT_EQ(items[3].name, "name4");
  11229. EXPECT_EQ(items[3].content, rand2);
  11230. EXPECT_EQ(items[3].filename, "filename4");
  11231. EXPECT_EQ(items[3].content_type, "");
  11232. });
  11233. auto port = svr.bind_to_any_port("localhost");
  11234. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11235. auto se = detail::scope_exit([&] {
  11236. svr.stop();
  11237. t.join();
  11238. ASSERT_FALSE(svr.is_running());
  11239. });
  11240. svr.wait_until_ready();
  11241. {
  11242. SSLClient cli("localhost", port);
  11243. cli.enable_server_certificate_verification(false);
  11244. UploadFormDataItems items{
  11245. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11246. {"name2", "Testing456", "", ""}, // not a file
  11247. };
  11248. {
  11249. auto res = cli.Post("/post-none", {}, {}, {});
  11250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11251. ASSERT_EQ(StatusCode::OK_200, res->status);
  11252. }
  11253. FormDataProviderItems providers;
  11254. {
  11255. auto res =
  11256. cli.Post("/post-items", {}, items, providers); // empty providers
  11257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11258. ASSERT_EQ(StatusCode::OK_200, res->status);
  11259. }
  11260. providers.push_back({"name3",
  11261. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11262. // test the offset is given correctly at each step
  11263. if (!offset)
  11264. sink.os.write(rand1.data(), 30);
  11265. else if (offset == 30)
  11266. sink.os.write(rand1.data() + 30, 300);
  11267. else if (offset == 330)
  11268. sink.os.write(rand1.data() + 330, 670);
  11269. else if (offset == rand1.size())
  11270. sink.done();
  11271. return true;
  11272. },
  11273. "filename3",
  11274. {}});
  11275. providers.push_back({"name4",
  11276. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11277. // test the offset is given correctly at each step
  11278. if (!offset)
  11279. sink.os.write(rand2.data(), 2000);
  11280. else if (offset == 2000)
  11281. sink.os.write(rand2.data() + 2000, 1);
  11282. else if (offset == 2001)
  11283. sink.os.write(rand2.data() + 2001, 999);
  11284. else if (offset == rand2.size())
  11285. sink.done();
  11286. return true;
  11287. },
  11288. "filename4",
  11289. {}});
  11290. {
  11291. auto res = cli.Post("/post-providers", {}, {}, providers);
  11292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11293. ASSERT_EQ(StatusCode::OK_200, res->status);
  11294. }
  11295. {
  11296. auto res = cli.Post("/post-both", {}, items, providers);
  11297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11298. ASSERT_EQ(StatusCode::OK_200, res->status);
  11299. }
  11300. }
  11301. }
  11302. TEST(MultipartFormDataTest, BadHeader) {
  11303. Server svr;
  11304. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11305. res.set_content("ok", "text/plain");
  11306. });
  11307. thread t = thread([&] { svr.listen(HOST, PORT); });
  11308. auto se = detail::scope_exit([&] {
  11309. svr.stop();
  11310. t.join();
  11311. ASSERT_FALSE(svr.is_running());
  11312. });
  11313. svr.wait_until_ready();
  11314. const std::string body =
  11315. "This is the preamble. It is to be ignored, though it\r\n"
  11316. "is a handy place for composition agents to include an\r\n"
  11317. "explanatory note to non-MIME conformant readers.\r\n"
  11318. "\r\n"
  11319. "\r\n"
  11320. "--simple boundary\r\n"
  11321. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11322. ": BAD...\r\n"
  11323. "\r\n"
  11324. "value1\r\n"
  11325. "--simple boundary\r\n"
  11326. "Content-Disposition: form-data; name=\"field2\"; "
  11327. "filename=\"example.txt\"\r\n"
  11328. "\r\n"
  11329. "value2\r\n"
  11330. "--simple boundary--\r\n"
  11331. "This is the epilogue. It is also to be ignored.\r\n";
  11332. std::string content_type =
  11333. R"(multipart/form-data; boundary="simple boundary")";
  11334. Client cli(HOST, PORT);
  11335. auto res = cli.Post("/post", body, content_type.c_str());
  11336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11337. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11338. }
  11339. TEST(MultipartFormDataTest, WithPreamble) {
  11340. Server svr;
  11341. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11342. res.set_content("ok", "text/plain");
  11343. });
  11344. thread t = thread([&] { svr.listen(HOST, PORT); });
  11345. auto se = detail::scope_exit([&] {
  11346. svr.stop();
  11347. t.join();
  11348. ASSERT_FALSE(svr.is_running());
  11349. });
  11350. svr.wait_until_ready();
  11351. const std::string body =
  11352. "This is the preamble. It is to be ignored, though it\r\n"
  11353. "is a handy place for composition agents to include an\r\n"
  11354. "explanatory note to non-MIME conformant readers.\r\n"
  11355. "\r\n"
  11356. "\r\n"
  11357. "--simple boundary\r\n"
  11358. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11359. "\r\n"
  11360. "value1\r\n"
  11361. "--simple boundary\r\n"
  11362. "Content-Disposition: form-data; name=\"field2\"; "
  11363. "filename=\"example.txt\"\r\n"
  11364. "\r\n"
  11365. "value2\r\n"
  11366. "--simple boundary--\r\n"
  11367. "This is the epilogue. It is also to be ignored.\r\n";
  11368. std::string content_type =
  11369. R"(multipart/form-data; boundary="simple boundary")";
  11370. Client cli(HOST, PORT);
  11371. auto res = cli.Post("/post", body, content_type.c_str());
  11372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11373. EXPECT_EQ(StatusCode::OK_200, res->status);
  11374. }
  11375. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11377. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11378. const ContentReader &content_reader) {
  11379. if (req.is_multipart_form_data()) {
  11380. std::vector<FormData> items;
  11381. content_reader(
  11382. [&](const FormData &file) {
  11383. items.push_back(file);
  11384. return true;
  11385. },
  11386. [&](const char *data, size_t data_length) {
  11387. items.back().content.append(data, data_length);
  11388. return true;
  11389. });
  11390. EXPECT_TRUE(std::string(items[0].name) == "document");
  11391. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11392. EXPECT_TRUE(items[0].filename == "2MB_data");
  11393. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11394. EXPECT_TRUE(items[1].name == "hello");
  11395. EXPECT_TRUE(items[1].content == "world");
  11396. EXPECT_TRUE(items[1].filename == "");
  11397. EXPECT_TRUE(items[1].content_type == "");
  11398. } else {
  11399. std::string body;
  11400. content_reader([&](const char *data, size_t data_length) {
  11401. body.append(data, data_length);
  11402. return true;
  11403. });
  11404. }
  11405. });
  11406. auto port = svr.bind_to_any_port("localhost");
  11407. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11408. auto se = detail::scope_exit([&] {
  11409. svr.stop();
  11410. t.join();
  11411. ASSERT_FALSE(svr.is_running());
  11412. });
  11413. svr.wait_until_ready();
  11414. {
  11415. std::string data(1024 * 1024 * 2, '.');
  11416. std::stringstream buffer;
  11417. buffer << data;
  11418. SSLClient cli("localhost", port);
  11419. cli.enable_server_certificate_verification(false);
  11420. UploadFormDataItems items{
  11421. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11422. {"hello", "world", "", ""},
  11423. };
  11424. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11426. ASSERT_EQ(StatusCode::OK_200, res->status);
  11427. }
  11428. }
  11429. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11430. std::string data(1024 * 1024 * 2, '&');
  11431. std::stringstream buffer;
  11432. buffer << data;
  11433. Client cli("https://localhost:8080");
  11434. UploadFormDataItems items{
  11435. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11436. {"hello", "world", "", ""},
  11437. };
  11438. for (const char &c : " \t\r\n") {
  11439. auto res =
  11440. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11441. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11442. ASSERT_FALSE(res);
  11443. }
  11444. }
  11445. TEST(MultipartFormDataTest, PutFormData) {
  11446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11447. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11448. const ContentReader &content_reader) {
  11449. if (req.is_multipart_form_data()) {
  11450. std::vector<FormData> items;
  11451. content_reader(
  11452. [&](const FormData &file) {
  11453. items.push_back(file);
  11454. return true;
  11455. },
  11456. [&](const char *data, size_t data_length) {
  11457. items.back().content.append(data, data_length);
  11458. return true;
  11459. });
  11460. EXPECT_TRUE(std::string(items[0].name) == "document");
  11461. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11462. EXPECT_TRUE(items[0].filename == "2MB_data");
  11463. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11464. EXPECT_TRUE(items[1].name == "hello");
  11465. EXPECT_TRUE(items[1].content == "world");
  11466. EXPECT_TRUE(items[1].filename == "");
  11467. EXPECT_TRUE(items[1].content_type == "");
  11468. } else {
  11469. std::string body;
  11470. content_reader([&](const char *data, size_t data_length) {
  11471. body.append(data, data_length);
  11472. return true;
  11473. });
  11474. }
  11475. });
  11476. auto port = svr.bind_to_any_port("localhost");
  11477. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11478. auto se = detail::scope_exit([&] {
  11479. svr.stop();
  11480. t.join();
  11481. ASSERT_FALSE(svr.is_running());
  11482. });
  11483. svr.wait_until_ready();
  11484. {
  11485. std::string data(1024 * 1024 * 2, '&');
  11486. std::stringstream buffer;
  11487. buffer << data;
  11488. SSLClient cli("localhost", port);
  11489. cli.enable_server_certificate_verification(false);
  11490. UploadFormDataItems items{
  11491. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11492. {"hello", "world", "", ""},
  11493. };
  11494. auto res = cli.Put("/put", items);
  11495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11496. ASSERT_EQ(StatusCode::OK_200, res->status);
  11497. }
  11498. }
  11499. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11501. svr.Put("/put_customboundary",
  11502. [&](const Request &req, const Response & /*res*/,
  11503. const ContentReader &content_reader) {
  11504. if (req.is_multipart_form_data()) {
  11505. std::vector<FormData> items;
  11506. content_reader(
  11507. [&](const FormData &file) {
  11508. items.push_back(file);
  11509. return true;
  11510. },
  11511. [&](const char *data, size_t data_length) {
  11512. items.back().content.append(data, data_length);
  11513. return true;
  11514. });
  11515. EXPECT_TRUE(std::string(items[0].name) == "document");
  11516. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11517. EXPECT_TRUE(items[0].filename == "2MB_data");
  11518. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11519. EXPECT_TRUE(items[1].name == "hello");
  11520. EXPECT_TRUE(items[1].content == "world");
  11521. EXPECT_TRUE(items[1].filename == "");
  11522. EXPECT_TRUE(items[1].content_type == "");
  11523. } else {
  11524. std::string body;
  11525. content_reader([&](const char *data, size_t data_length) {
  11526. body.append(data, data_length);
  11527. return true;
  11528. });
  11529. }
  11530. });
  11531. auto port = svr.bind_to_any_port("localhost");
  11532. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11533. auto se = detail::scope_exit([&] {
  11534. svr.stop();
  11535. t.join();
  11536. ASSERT_FALSE(svr.is_running());
  11537. });
  11538. svr.wait_until_ready();
  11539. {
  11540. std::string data(1024 * 1024 * 2, '&');
  11541. std::stringstream buffer;
  11542. buffer << data;
  11543. SSLClient cli("localhost", port);
  11544. cli.enable_server_certificate_verification(false);
  11545. UploadFormDataItems items{
  11546. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11547. {"hello", "world", "", ""},
  11548. };
  11549. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11551. ASSERT_EQ(StatusCode::OK_200, res->status);
  11552. }
  11553. }
  11554. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11555. std::string data(1024 * 1024 * 2, '&');
  11556. std::stringstream buffer;
  11557. buffer << data;
  11558. Client cli("https://localhost:8080");
  11559. cli.enable_server_certificate_verification(false);
  11560. UploadFormDataItems items{
  11561. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11562. {"hello", "world", "", ""},
  11563. };
  11564. for (const char &c : " \t\r\n") {
  11565. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11566. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11567. ASSERT_FALSE(res);
  11568. }
  11569. }
  11570. TEST(MultipartFormDataTest, AlternateFilename) {
  11571. auto handled = false;
  11572. Server svr;
  11573. svr.Post("/test", [&](const Request &req, Response &res) {
  11574. ASSERT_EQ(2u, req.form.files.size());
  11575. ASSERT_EQ(1u, req.form.fields.size());
  11576. // Test files
  11577. const auto &file1 = req.form.get_file("file1");
  11578. ASSERT_EQ("file1", file1.name);
  11579. ASSERT_EQ("A.txt", file1.filename);
  11580. ASSERT_EQ("text/plain", file1.content_type);
  11581. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11582. const auto &file2 = req.form.get_file("file2");
  11583. ASSERT_EQ("file2", file2.name);
  11584. ASSERT_EQ("a.html", file2.filename);
  11585. ASSERT_EQ("text/html", file2.content_type);
  11586. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11587. file2.content);
  11588. // Test text field
  11589. const auto &text = req.form.get_field("text");
  11590. ASSERT_EQ("text default", text);
  11591. res.set_content("ok", "text/plain");
  11592. handled = true;
  11593. });
  11594. thread t = thread([&] { svr.listen(HOST, PORT); });
  11595. auto se = detail::scope_exit([&] {
  11596. svr.stop();
  11597. t.join();
  11598. ASSERT_FALSE(svr.is_running());
  11599. ASSERT_TRUE(handled);
  11600. });
  11601. svr.wait_until_ready();
  11602. auto req = "POST /test HTTP/1.1\r\n"
  11603. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11604. "Content-Length: 399\r\n"
  11605. "\r\n"
  11606. "----------\r\n"
  11607. "Content-Disposition: form-data; name=\"text\"\r\n"
  11608. "\r\n"
  11609. "text default\r\n"
  11610. "----------\r\n"
  11611. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11612. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11613. "Content-Type: text/plain\r\n"
  11614. "\r\n"
  11615. "Content of a.txt.\r\n"
  11616. "\r\n"
  11617. "----------\r\n"
  11618. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11619. "\"a.html\"\r\n"
  11620. "Content-Type: text/html\r\n"
  11621. "\r\n"
  11622. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11623. "\r\n"
  11624. "------------\r\n";
  11625. ASSERT_TRUE(send_request(1, req));
  11626. }
  11627. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11628. auto handled = false;
  11629. Server svr;
  11630. svr.Post("/test", [&](const Request &req, Response &res) {
  11631. // Case-insensitive "utf-8''" prefix with a long value
  11632. const auto &file = req.form.get_file("file1");
  11633. ASSERT_EQ("file1", file.name);
  11634. // 8000 chars exercises both the Content-Disposition parser and the
  11635. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11636. // Prior to the fix, std::regex_match on this header would cause O(N)
  11637. // stack recursion in libstdc++, leading to SIGSEGV.
  11638. std::string expected_filename(8000, 'A');
  11639. ASSERT_EQ(expected_filename, file.filename);
  11640. res.set_content("ok", "text/plain");
  11641. handled = true;
  11642. });
  11643. thread t = thread([&] { svr.listen(HOST, PORT); });
  11644. auto se = detail::scope_exit([&] {
  11645. svr.stop();
  11646. t.join();
  11647. ASSERT_FALSE(svr.is_running());
  11648. ASSERT_TRUE(handled);
  11649. });
  11650. svr.wait_until_ready();
  11651. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11652. // Regression test for GHSA-qq6v-r583-3h69
  11653. std::string long_filename(8000, 'A');
  11654. std::string body = "----------\r\n"
  11655. "Content-Disposition: form-data; name=\"file1\"; "
  11656. "filename*=\"Utf-8''" +
  11657. long_filename +
  11658. "\"\r\n"
  11659. "\r\n"
  11660. "hello\r\n"
  11661. "------------\r\n";
  11662. auto req = "POST /test HTTP/1.1\r\n"
  11663. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11664. "Content-Length: " +
  11665. std::to_string(body.size()) + "\r\n\r\n" + body;
  11666. ASSERT_TRUE(send_request(1, req));
  11667. }
  11668. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11669. auto handled = false;
  11670. Server svr;
  11671. svr.Post("/test", [&](const Request &req, Response &) {
  11672. ASSERT_EQ(2u, req.form.fields.size());
  11673. const auto &text1 = req.form.get_field("text1");
  11674. ASSERT_EQ("text1", text1);
  11675. const auto &text2 = req.form.get_field("text2");
  11676. ASSERT_EQ("text2", text2);
  11677. handled = true;
  11678. });
  11679. thread t = thread([&] { svr.listen(HOST, PORT); });
  11680. auto se = detail::scope_exit([&] {
  11681. svr.stop();
  11682. t.join();
  11683. ASSERT_FALSE(svr.is_running());
  11684. ASSERT_TRUE(handled);
  11685. });
  11686. svr.wait_until_ready();
  11687. auto req = "POST /test HTTP/1.1\r\n"
  11688. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11689. "Content-Length: 146\r\n"
  11690. "\r\n----------\r\n"
  11691. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11692. "\r\n"
  11693. "text1"
  11694. "\r\n----------\r\n"
  11695. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11696. "\r\n"
  11697. "text2"
  11698. "\r\n------------";
  11699. std::string response;
  11700. ASSERT_TRUE(send_request(1, req, &response));
  11701. ASSERT_EQ("200", response.substr(9, 3));
  11702. }
  11703. TEST(MultipartFormDataTest, ContentLength) {
  11704. auto handled = false;
  11705. Server svr;
  11706. svr.Post("/test", [&](const Request &req, Response &) {
  11707. ASSERT_EQ(2u, req.form.fields.size());
  11708. const auto &text1 = req.form.get_field("text1");
  11709. ASSERT_EQ("text1", text1);
  11710. const auto &text2 = req.form.get_field("text2");
  11711. ASSERT_EQ("text2", text2);
  11712. handled = true;
  11713. });
  11714. thread t = thread([&] { svr.listen(HOST, PORT); });
  11715. auto se = detail::scope_exit([&] {
  11716. svr.stop();
  11717. t.join();
  11718. ASSERT_FALSE(svr.is_running());
  11719. ASSERT_TRUE(handled);
  11720. });
  11721. svr.wait_until_ready();
  11722. auto req = "POST /test HTTP/1.1\r\n"
  11723. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11724. "Content-Length: 167\r\n"
  11725. "\r\n----------\r\n"
  11726. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11727. "Content-Length: 5\r\n"
  11728. "\r\n"
  11729. "text1"
  11730. "\r\n----------\r\n"
  11731. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11732. "\r\n"
  11733. "text2"
  11734. "\r\n------------\r\n";
  11735. std::string response;
  11736. ASSERT_TRUE(send_request(1, req, &response));
  11737. ASSERT_EQ("200", response.substr(9, 3));
  11738. }
  11739. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11740. auto handled = false;
  11741. Server svr;
  11742. svr.Post("/test", [&](const Request &req, Response &) {
  11743. ASSERT_EQ(2u, req.form.fields.size());
  11744. const auto &text1 = req.form.get_field("text1");
  11745. ASSERT_EQ("text1", text1);
  11746. // TODO: Add header access for text fields if needed
  11747. const auto &text2 = req.form.get_field("text2");
  11748. ASSERT_EQ("text2", text2);
  11749. // TODO: Header access for text fields needs to be implemented
  11750. // auto &headers = it->second.headers;
  11751. // ASSERT_EQ(3U, headers.size());
  11752. // auto custom_header = headers.find("x-whatever");
  11753. // ASSERT_TRUE(custom_header != headers.end());
  11754. // ASSERT_NE("customvalue", custom_header->second);
  11755. // ASSERT_EQ("CustomValue", custom_header->second);
  11756. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11757. handled = true;
  11758. });
  11759. thread t = thread([&] { svr.listen(HOST, PORT); });
  11760. auto se = detail::scope_exit([&] {
  11761. svr.stop();
  11762. t.join();
  11763. ASSERT_FALSE(svr.is_running());
  11764. ASSERT_TRUE(handled);
  11765. });
  11766. svr.wait_until_ready();
  11767. auto req = "POST /test HTTP/1.1\r\n"
  11768. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11769. "Content-Length: 232\r\n"
  11770. "\r\n----------\r\n"
  11771. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11772. "Content-Length: 5\r\n"
  11773. "X-Test: 1\r\n"
  11774. "\r\n"
  11775. "text1"
  11776. "\r\n----------\r\n"
  11777. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11778. "Content-Type: text/plain\r\n"
  11779. "X-Whatever: CustomValue\r\n"
  11780. "\r\n"
  11781. "text2"
  11782. "\r\n------------\r\n"
  11783. "That should be disregarded. Not even read";
  11784. std::string response;
  11785. ASSERT_TRUE(send_request(1, req, &response));
  11786. ASSERT_EQ("200", response.substr(9, 3));
  11787. }
  11788. TEST(MultipartFormDataTest, LargeHeader) {
  11789. auto handled = false;
  11790. Server svr;
  11791. svr.Post("/test", [&](const Request &req, Response &) {
  11792. ASSERT_EQ(1u, req.form.fields.size());
  11793. const auto &text = req.form.get_field("name1");
  11794. ASSERT_EQ("text1", text);
  11795. handled = true;
  11796. });
  11797. thread t = thread([&] { svr.listen(HOST, PORT); });
  11798. auto se = detail::scope_exit([&] {
  11799. svr.stop();
  11800. t.join();
  11801. ASSERT_FALSE(svr.is_running());
  11802. ASSERT_TRUE(handled);
  11803. });
  11804. svr.wait_until_ready();
  11805. auto boundary = std::string("cpp-httplib-multipart-data");
  11806. std::string content = "--" + boundary +
  11807. "\r\n"
  11808. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11809. "\r\n"
  11810. "text1\r\n"
  11811. "--" +
  11812. boundary + "--\r\n";
  11813. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11814. "Content-Type: multipart/form-data;boundary=" +
  11815. boundary +
  11816. "\r\n"
  11817. "Content-Length: " +
  11818. std::to_string(content.size()) +
  11819. "\r\n"
  11820. "Dummy-Header: ";
  11821. std::string header_suffix = "\r\n"
  11822. "\r\n";
  11823. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11824. size_t header_dummy_size =
  11825. read_buff_size -
  11826. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11827. auto header_dummy = std::string(header_dummy_size, '@');
  11828. auto req = header_prefix + header_dummy + header_suffix + content;
  11829. std::string response;
  11830. ASSERT_TRUE(send_request(1, req, &response));
  11831. ASSERT_EQ("200", response.substr(9, 3));
  11832. }
  11833. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11834. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11835. // (not chunked Transfer-Encoding) after the streaming refactor.
  11836. auto handled = false;
  11837. Server svr;
  11838. svr.Post("/upload", [&](const Request &req, Response &res) {
  11839. auto cl_it = req.headers.find("Content-Length");
  11840. EXPECT_TRUE(cl_it != req.headers.end());
  11841. auto te_it = req.headers.find("Transfer-Encoding");
  11842. EXPECT_TRUE(te_it == req.headers.end());
  11843. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11844. res.set_content("ok", "text/plain");
  11845. handled = true;
  11846. });
  11847. auto port = svr.bind_to_any_port(HOST);
  11848. auto t = thread([&] { svr.listen_after_bind(); });
  11849. auto se = detail::scope_exit([&] {
  11850. svr.stop();
  11851. t.join();
  11852. ASSERT_FALSE(svr.is_running());
  11853. ASSERT_TRUE(handled);
  11854. });
  11855. svr.wait_until_ready();
  11856. UploadFormDataItems items = {
  11857. {"field1", "hello", "", "text/plain"},
  11858. {"file1", "world", "test.txt", "application/octet-stream"},
  11859. };
  11860. Client cli(HOST, port);
  11861. auto res = cli.Post("/upload", {}, items);
  11862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11863. EXPECT_EQ(StatusCode::OK_200, res->status);
  11864. }
  11865. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11866. // Verify that make_multipart_content_provider coalesces many small segments
  11867. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11868. constexpr size_t kItemCount = 1000;
  11869. UploadFormDataItems items;
  11870. items.reserve(kItemCount);
  11871. for (size_t i = 0; i < kItemCount; i++) {
  11872. items.push_back(
  11873. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11874. }
  11875. const std::string boundary = "----test-boundary";
  11876. auto content_length = detail::get_multipart_content_length(items, boundary);
  11877. auto provider = detail::make_multipart_content_provider(items, boundary);
  11878. // Drive the provider the same way write_content_with_progress does
  11879. size_t write_count = 0;
  11880. size_t total_bytes = 0;
  11881. DataSink sink;
  11882. size_t offset = 0;
  11883. sink.write = [&](const char *d, size_t l) -> bool {
  11884. (void)d;
  11885. write_count++;
  11886. total_bytes += l;
  11887. offset += l;
  11888. return true;
  11889. };
  11890. sink.is_writable = []() -> bool { return true; };
  11891. while (offset < content_length) {
  11892. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11893. }
  11894. EXPECT_EQ(content_length, total_bytes);
  11895. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11896. // With buffering into 64KB blocks, write_count should be much smaller.
  11897. auto segment_count = 3 * kItemCount + 1;
  11898. EXPECT_LT(write_count, segment_count / 10);
  11899. }
  11900. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11901. // Integration test: send many UploadFormDataItems and verify the server
  11902. // receives all of them correctly (#2410).
  11903. constexpr size_t kItemCount = 500;
  11904. auto handled = false;
  11905. Server svr;
  11906. svr.Post("/upload", [&](const Request &req, Response &res) {
  11907. EXPECT_EQ(kItemCount, req.form.fields.size());
  11908. for (size_t i = 0; i < kItemCount; i++) {
  11909. auto key = "field" + std::to_string(i);
  11910. auto val = "value" + std::to_string(i);
  11911. auto it = req.form.fields.find(key);
  11912. if (it != req.form.fields.end()) {
  11913. EXPECT_EQ(val, it->second.content);
  11914. } else {
  11915. ADD_FAILURE() << "Missing field: " << key;
  11916. }
  11917. }
  11918. res.set_content("ok", "text/plain");
  11919. handled = true;
  11920. });
  11921. auto port = svr.bind_to_any_port(HOST);
  11922. auto t = thread([&] { svr.listen_after_bind(); });
  11923. auto se = detail::scope_exit([&] {
  11924. svr.stop();
  11925. t.join();
  11926. ASSERT_FALSE(svr.is_running());
  11927. ASSERT_TRUE(handled);
  11928. });
  11929. svr.wait_until_ready();
  11930. UploadFormDataItems items;
  11931. items.reserve(kItemCount);
  11932. for (size_t i = 0; i < kItemCount; i++) {
  11933. items.push_back(
  11934. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11935. }
  11936. Client cli(HOST, port);
  11937. auto res = cli.Post("/upload", items);
  11938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11939. EXPECT_EQ(StatusCode::OK_200, res->status);
  11940. }
  11941. TEST(MultipartFormDataTest, MakeFileProvider) {
  11942. // Verify make_file_provider sends a file's contents correctly.
  11943. const std::string file_content(4096, 'Z');
  11944. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11945. {
  11946. std::ofstream ofs(tmp_path, std::ios::binary);
  11947. ofs.write(file_content.data(),
  11948. static_cast<std::streamsize>(file_content.size()));
  11949. }
  11950. auto handled = false;
  11951. Server svr;
  11952. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11953. const ContentReader &content_reader) {
  11954. ASSERT_TRUE(req.is_multipart_form_data());
  11955. std::vector<FormData> items;
  11956. content_reader(
  11957. [&](const FormData &file) {
  11958. items.push_back(file);
  11959. return true;
  11960. },
  11961. [&](const char *data, size_t data_length) {
  11962. items.back().content.append(data, data_length);
  11963. return true;
  11964. });
  11965. ASSERT_EQ(1u, items.size());
  11966. EXPECT_EQ("myfile", items[0].name);
  11967. EXPECT_EQ("data.bin", items[0].filename);
  11968. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11969. EXPECT_EQ(file_content, items[0].content);
  11970. handled = true;
  11971. });
  11972. auto port = svr.bind_to_any_port(HOST);
  11973. auto t = thread([&] { svr.listen_after_bind(); });
  11974. auto se = detail::scope_exit([&] {
  11975. svr.stop();
  11976. t.join();
  11977. ASSERT_FALSE(svr.is_running());
  11978. ASSERT_TRUE(handled);
  11979. std::remove(tmp_path.c_str());
  11980. });
  11981. svr.wait_until_ready();
  11982. FormDataProviderItems providers;
  11983. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11984. "application/octet-stream"));
  11985. Client cli(HOST, port);
  11986. auto res = cli.Post("/upload", {}, {}, providers);
  11987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11988. EXPECT_EQ(StatusCode::OK_200, res->status);
  11989. }
  11990. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11991. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11992. // (100) headers is rejected with a 400 Bad Request response.
  11993. Server svr;
  11994. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11995. res.set_content("ok", "text/plain");
  11996. });
  11997. thread t = thread([&] { svr.listen(HOST, PORT); });
  11998. auto se = detail::scope_exit([&] {
  11999. svr.stop();
  12000. t.join();
  12001. ASSERT_FALSE(svr.is_running());
  12002. });
  12003. svr.wait_until_ready();
  12004. // Build a multipart part with 101 custom headers (exceeding
  12005. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  12006. std::stringstream body;
  12007. body << "--simpleboundary\r\n"
  12008. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  12009. for (int i = 0; i < 101; i++) {
  12010. body << "X-Custom-Header-" << i << ": value\r\n";
  12011. }
  12012. body << "\r\n"
  12013. << "value1\r\n"
  12014. << "--simpleboundary--\r\n";
  12015. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  12016. Client cli(HOST, PORT);
  12017. auto res = cli.Post("/post", body.str(), content_type.c_str());
  12018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12019. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12020. }
  12021. TEST(MakeFileBodyTest, Basic) {
  12022. const std::string file_content(4096, 'Z');
  12023. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  12024. {
  12025. std::ofstream ofs(tmp_path, std::ios::binary);
  12026. ofs.write(file_content.data(),
  12027. static_cast<std::streamsize>(file_content.size()));
  12028. }
  12029. auto handled = false;
  12030. Server svr;
  12031. svr.Post("/upload", [&](const Request &req, Response &res) {
  12032. EXPECT_EQ(file_content, req.body);
  12033. handled = true;
  12034. res.status = StatusCode::OK_200;
  12035. });
  12036. auto port = svr.bind_to_any_port(HOST);
  12037. auto t = thread([&] { svr.listen_after_bind(); });
  12038. auto se = detail::scope_exit([&] {
  12039. svr.stop();
  12040. t.join();
  12041. ASSERT_FALSE(svr.is_running());
  12042. ASSERT_TRUE(handled);
  12043. std::remove(tmp_path.c_str());
  12044. });
  12045. svr.wait_until_ready();
  12046. auto fb = make_file_body(tmp_path);
  12047. ASSERT_GT(fb.first, 0u);
  12048. Client cli(HOST, port);
  12049. auto res =
  12050. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  12051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12052. EXPECT_EQ(StatusCode::OK_200, res->status);
  12053. }
  12054. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  12055. static constexpr unsigned int number_of_tasks{1000000};
  12056. std::atomic_uint count{0};
  12057. std::unique_ptr<TaskQueue> task_queue{
  12058. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  12059. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12060. auto queued = task_queue->enqueue(
  12061. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  12062. EXPECT_TRUE(queued);
  12063. }
  12064. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12065. task_queue->shutdown();
  12066. #else
  12067. EXPECT_NO_THROW(task_queue->shutdown());
  12068. #endif
  12069. EXPECT_EQ(number_of_tasks, count.load());
  12070. }
  12071. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  12072. static constexpr unsigned int number_of_tasks{1000000};
  12073. static constexpr unsigned int qlimit{2};
  12074. unsigned int queued_count{0};
  12075. std::atomic_uint count{0};
  12076. std::unique_ptr<TaskQueue> task_queue{
  12077. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  12078. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  12079. if (task_queue->enqueue(
  12080. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  12081. queued_count++;
  12082. }
  12083. }
  12084. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12085. task_queue->shutdown();
  12086. #else
  12087. EXPECT_NO_THROW(task_queue->shutdown());
  12088. #endif
  12089. EXPECT_EQ(queued_count, count.load());
  12090. EXPECT_TRUE(queued_count <= number_of_tasks);
  12091. EXPECT_TRUE(queued_count >= qlimit);
  12092. }
  12093. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  12094. // Use a short idle timeout so a dynamic thread spawns, times out and
  12095. // exits during the test, and the pool keeps working afterwards.
  12096. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  12097. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  12098. /*idle_timeout_sec=*/1}};
  12099. std::atomic_uint count{0};
  12100. std::condition_variable cv;
  12101. std::mutex mtx;
  12102. bool release = false;
  12103. // Block the base thread so the second task spawns a dynamic thread.
  12104. EXPECT_TRUE(task_queue->enqueue([&] {
  12105. std::unique_lock<std::mutex> lock(mtx);
  12106. while (!release) {
  12107. cv.wait(lock);
  12108. }
  12109. count++;
  12110. }));
  12111. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12112. // Let the dynamic thread finish its task and exceed the idle timeout.
  12113. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12114. {
  12115. std::unique_lock<std::mutex> lock(mtx);
  12116. release = true;
  12117. }
  12118. cv.notify_all();
  12119. // The pool must still accept and run tasks after the dynamic thread exited.
  12120. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  12121. task_queue->shutdown();
  12122. EXPECT_EQ(3u, count.load());
  12123. }
  12124. TEST(TaskQueueTest, MaxQueuedRequests) {
  12125. static constexpr unsigned int qlimit{3};
  12126. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  12127. std::condition_variable sem_cv;
  12128. std::mutex sem_mtx;
  12129. int credits = 0;
  12130. bool queued;
  12131. /* Fill up the queue with tasks that will block until we give them credits to
  12132. * complete. */
  12133. for (unsigned int n = 0; n <= qlimit;) {
  12134. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  12135. std::unique_lock<std::mutex> lock(sem_mtx);
  12136. while (credits <= 0) {
  12137. sem_cv.wait(lock);
  12138. }
  12139. /* Consume the credit and signal the test code if they are all gone. */
  12140. if (--credits == 0) { sem_cv.notify_one(); }
  12141. });
  12142. if (n < qlimit) {
  12143. /* The first qlimit enqueues must succeed. */
  12144. EXPECT_TRUE(queued);
  12145. } else {
  12146. /* The last one will succeed only when the worker thread
  12147. * starts and dequeues the first blocking task. Although
  12148. * not necessary for the correctness of this test, we sleep for
  12149. * a short while to avoid busy waiting. */
  12150. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12151. }
  12152. if (queued) { n++; }
  12153. }
  12154. /* Further enqueues must fail since the queue is full. */
  12155. for (auto i = 0; i < 4; i++) {
  12156. queued = task_queue->enqueue([] {});
  12157. EXPECT_FALSE(queued);
  12158. }
  12159. /* Give the credits to allow the previous tasks to complete. */
  12160. {
  12161. std::unique_lock<std::mutex> lock(sem_mtx);
  12162. credits += qlimit + 1;
  12163. }
  12164. sem_cv.notify_all();
  12165. /* Wait for all the credits to be consumed. */
  12166. {
  12167. std::unique_lock<std::mutex> lock(sem_mtx);
  12168. while (credits > 0) {
  12169. sem_cv.wait(lock);
  12170. }
  12171. }
  12172. /* Check that we are able again to enqueue at least qlimit tasks. */
  12173. for (unsigned int i = 0; i < qlimit; i++) {
  12174. queued = task_queue->enqueue([] {});
  12175. EXPECT_TRUE(queued);
  12176. }
  12177. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  12178. task_queue->shutdown();
  12179. #else
  12180. EXPECT_NO_THROW(task_queue->shutdown());
  12181. #endif
  12182. }
  12183. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  12184. Server svr;
  12185. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12186. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  12187. });
  12188. svr.Get("/hello", [](const Request &req, Response &res) {
  12189. res.set_content(req.get_param_value("key"), "text/plain");
  12190. });
  12191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12192. auto se = detail::scope_exit([&] {
  12193. svr.stop();
  12194. thread.join();
  12195. ASSERT_FALSE(svr.is_running());
  12196. });
  12197. svr.wait_until_ready();
  12198. {
  12199. Client cli(HOST, PORT);
  12200. cli.set_follow_location(true);
  12201. auto res = cli.Get("/");
  12202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12203. EXPECT_EQ(StatusCode::OK_200, res->status);
  12204. EXPECT_EQ("val&key2=val2", res->body);
  12205. }
  12206. }
  12207. #endif
  12208. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12209. Server svr;
  12210. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12211. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12212. });
  12213. svr.Get("/hello", [](const Request &req, Response &res) {
  12214. res.set_content(req.get_param_value("key"), "text/plain");
  12215. });
  12216. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12217. auto se = detail::scope_exit([&] {
  12218. svr.stop();
  12219. thread.join();
  12220. ASSERT_FALSE(svr.is_running());
  12221. });
  12222. svr.wait_until_ready();
  12223. {
  12224. Client cli(HOST, PORT);
  12225. cli.set_follow_location(true);
  12226. auto res = cli.Get("/");
  12227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12228. EXPECT_EQ(StatusCode::OK_200, res->status);
  12229. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12230. }
  12231. }
  12232. TEST(RedirectTest, RedirectWithPlusInPath) {
  12233. Server svr;
  12234. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12235. res.set_redirect("/a+b");
  12236. });
  12237. // Route pattern uses regex; escape + as \\+
  12238. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12239. res.set_content(req.path, "text/plain");
  12240. });
  12241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12242. auto se = detail::scope_exit([&] {
  12243. svr.stop();
  12244. thread.join();
  12245. ASSERT_FALSE(svr.is_running());
  12246. });
  12247. svr.wait_until_ready();
  12248. {
  12249. Client cli(HOST, PORT);
  12250. cli.set_follow_location(true);
  12251. auto res = cli.Get("/");
  12252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12253. EXPECT_EQ(StatusCode::OK_200, res->status);
  12254. EXPECT_EQ("/a+b", res->body);
  12255. }
  12256. }
  12257. #ifdef CPPHTTPLIB_SSL_ENABLED
  12258. TEST(RedirectTest, Issue2185_Online) {
  12259. SSLClient client("github.com");
  12260. client.set_follow_location(true);
  12261. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12262. "Coollab-Windows.zip");
  12263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12264. EXPECT_EQ(StatusCode::OK_200, res->status);
  12265. EXPECT_EQ(9920427U, res->body.size());
  12266. }
  12267. #endif
  12268. TEST(VulnerabilityTest, CRLFInjection) {
  12269. Server svr;
  12270. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12271. res.set_content("Hello 1", "text/plain");
  12272. });
  12273. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12274. res.set_content("Hello 2", "text/plain");
  12275. });
  12276. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12277. res.set_content("Hello 3", "text/plain");
  12278. });
  12279. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12280. res.set_content("Hello 4", "text/plain");
  12281. });
  12282. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12283. for (const auto &x : req.headers) {
  12284. auto key = x.first;
  12285. EXPECT_STRNE("evil", key.c_str());
  12286. }
  12287. });
  12288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12289. auto se = detail::scope_exit([&] {
  12290. svr.stop();
  12291. thread.join();
  12292. ASSERT_FALSE(svr.is_running());
  12293. });
  12294. svr.wait_until_ready();
  12295. {
  12296. Client cli(HOST, PORT);
  12297. cli.Post("/test1", "A=B",
  12298. "application/x-www-form-urlencoded\r\nevil: hello1");
  12299. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12300. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12301. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12302. }
  12303. }
  12304. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12305. auto server_thread = std::thread([] {
  12306. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12307. default_socket_options(srv);
  12308. sockaddr_in addr{};
  12309. addr.sin_family = AF_INET;
  12310. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12311. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12312. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12313. ::listen(srv, 1);
  12314. sockaddr_in cli_addr{};
  12315. socklen_t cli_len = sizeof(cli_addr);
  12316. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12317. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12318. std::string buf_all;
  12319. char buf[2048];
  12320. ssize_t n;
  12321. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12322. buf_all.append(buf, static_cast<size_t>(n));
  12323. size_t pos;
  12324. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12325. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12326. auto e = request_block.find("\r\n");
  12327. if (e != std::string::npos) {
  12328. auto request_line = request_block.substr(0, e);
  12329. std::string msg =
  12330. "CRLF injection detected in request line: '" + request_line + "'";
  12331. EXPECT_FALSE(true) << msg;
  12332. }
  12333. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12334. ::send(cli,
  12335. #ifdef _WIN32
  12336. static_cast<const char *>(resp.c_str()),
  12337. static_cast<int>(resp.size()),
  12338. #else
  12339. resp.c_str(), resp.size(),
  12340. #endif
  12341. 0);
  12342. buf_all.erase(0, pos + 4);
  12343. }
  12344. }
  12345. detail::close_socket(cli);
  12346. detail::close_socket(srv);
  12347. });
  12348. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12349. auto cli = Client("127.0.0.1", PORT + 1);
  12350. auto headers = Headers{
  12351. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12352. {"Connection", "keep-alive"}};
  12353. auto res = cli.Get("/hi", headers);
  12354. EXPECT_FALSE(res);
  12355. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12356. server_thread.join();
  12357. }
  12358. TEST(PathParamsTest, StaticMatch) {
  12359. const auto pattern = "/users/all";
  12360. detail::PathParamsMatcher matcher(pattern);
  12361. Request request;
  12362. request.path = "/users/all";
  12363. ASSERT_TRUE(matcher.match(request));
  12364. std::unordered_map<std::string, std::string> expected_params = {};
  12365. EXPECT_EQ(request.path_params, expected_params);
  12366. }
  12367. TEST(PathParamsTest, StaticMismatch) {
  12368. const auto pattern = "/users/all";
  12369. detail::PathParamsMatcher matcher(pattern);
  12370. Request request;
  12371. request.path = "/users/1";
  12372. ASSERT_FALSE(matcher.match(request));
  12373. }
  12374. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12375. const auto pattern = "/users/:id/subscriptions";
  12376. detail::PathParamsMatcher matcher(pattern);
  12377. Request request;
  12378. request.path = "/users/42/subscriptions";
  12379. ASSERT_TRUE(matcher.match(request));
  12380. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12381. EXPECT_EQ(request.path_params, expected_params);
  12382. }
  12383. TEST(PathParamsTest, SingleParamInTheEnd) {
  12384. const auto pattern = "/users/:id";
  12385. detail::PathParamsMatcher matcher(pattern);
  12386. Request request;
  12387. request.path = "/users/24";
  12388. ASSERT_TRUE(matcher.match(request));
  12389. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12390. EXPECT_EQ(request.path_params, expected_params);
  12391. }
  12392. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12393. const auto pattern = "/users/:id/";
  12394. detail::PathParamsMatcher matcher(pattern);
  12395. Request request;
  12396. request.path = "/users/42/";
  12397. ASSERT_TRUE(matcher.match(request));
  12398. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12399. EXPECT_EQ(request.path_params, expected_params);
  12400. }
  12401. TEST(PathParamsTest, EmptyParam) {
  12402. const auto pattern = "/users/:id/";
  12403. detail::PathParamsMatcher matcher(pattern);
  12404. Request request;
  12405. request.path = "/users//";
  12406. ASSERT_TRUE(matcher.match(request));
  12407. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12408. EXPECT_EQ(request.path_params, expected_params);
  12409. }
  12410. TEST(PathParamsTest, FragmentMismatch) {
  12411. const auto pattern = "/users/:id/";
  12412. detail::PathParamsMatcher matcher(pattern);
  12413. Request request;
  12414. request.path = "/admins/24/";
  12415. ASSERT_FALSE(matcher.match(request));
  12416. }
  12417. TEST(PathParamsTest, ExtraFragments) {
  12418. const auto pattern = "/users/:id";
  12419. detail::PathParamsMatcher matcher(pattern);
  12420. Request request;
  12421. request.path = "/users/42/subscriptions";
  12422. ASSERT_FALSE(matcher.match(request));
  12423. }
  12424. TEST(PathParamsTest, MissingTrailingParam) {
  12425. const auto pattern = "/users/:id";
  12426. detail::PathParamsMatcher matcher(pattern);
  12427. Request request;
  12428. request.path = "/users";
  12429. ASSERT_FALSE(matcher.match(request));
  12430. }
  12431. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12432. const auto pattern = "/users/:id/subscriptions";
  12433. detail::PathParamsMatcher matcher(pattern);
  12434. Request request;
  12435. request.path = "/users/subscriptions";
  12436. ASSERT_FALSE(matcher.match(request));
  12437. }
  12438. TEST(PathParamsTest, MultipleParams) {
  12439. const auto pattern = "/users/:userid/subscriptions/:subid";
  12440. detail::PathParamsMatcher matcher(pattern);
  12441. Request request;
  12442. request.path = "/users/42/subscriptions/2";
  12443. ASSERT_TRUE(matcher.match(request));
  12444. std::unordered_map<std::string, std::string> expected_params = {
  12445. {"userid", "42"}, {"subid", "2"}};
  12446. EXPECT_EQ(request.path_params, expected_params);
  12447. }
  12448. TEST(PathParamsTest, SequenceOfParams) {
  12449. const auto pattern = "/values/:x/:y/:z";
  12450. detail::PathParamsMatcher matcher(pattern);
  12451. Request request;
  12452. request.path = "/values/1/2/3";
  12453. ASSERT_TRUE(matcher.match(request));
  12454. std::unordered_map<std::string, std::string> expected_params = {
  12455. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12456. EXPECT_EQ(request.path_params, expected_params);
  12457. }
  12458. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12459. const auto pattern = "/prefix:suffix";
  12460. detail::PathParamsMatcher matcher(pattern);
  12461. Request request;
  12462. request.path = "/prefix:suffix";
  12463. ASSERT_TRUE(matcher.match(request));
  12464. const std::unordered_map<std::string, std::string> expected_params = {};
  12465. EXPECT_EQ(request.path_params, expected_params);
  12466. }
  12467. TEST(ParseUrlTest, VariousPatterns) {
  12468. {
  12469. detail::UrlComponents uc;
  12470. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12471. EXPECT_EQ("http", uc.scheme);
  12472. EXPECT_EQ("example.com", uc.host);
  12473. EXPECT_EQ("8080", uc.port);
  12474. EXPECT_EQ("/path", uc.path);
  12475. EXPECT_EQ("?q=1", uc.query);
  12476. }
  12477. {
  12478. detail::UrlComponents uc;
  12479. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12480. EXPECT_EQ("https", uc.scheme);
  12481. EXPECT_EQ("example.com", uc.host);
  12482. EXPECT_TRUE(uc.port.empty());
  12483. EXPECT_EQ("/path", uc.path);
  12484. }
  12485. {
  12486. detail::UrlComponents uc;
  12487. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12488. EXPECT_EQ("::1", uc.host);
  12489. EXPECT_EQ("8080", uc.port);
  12490. EXPECT_EQ("/path", uc.path);
  12491. }
  12492. {
  12493. detail::UrlComponents uc;
  12494. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12495. }
  12496. {
  12497. detail::UrlComponents uc;
  12498. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12499. EXPECT_TRUE(uc.scheme.empty());
  12500. EXPECT_EQ("example.com", uc.host);
  12501. EXPECT_EQ("/path", uc.path);
  12502. EXPECT_EQ("?q=1", uc.query);
  12503. }
  12504. {
  12505. detail::UrlComponents uc;
  12506. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12507. EXPECT_TRUE(uc.host.empty());
  12508. EXPECT_EQ("/path", uc.path);
  12509. EXPECT_EQ("?q=1", uc.query);
  12510. }
  12511. {
  12512. detail::UrlComponents uc;
  12513. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12514. EXPECT_EQ("example.com", uc.host);
  12515. EXPECT_EQ("8080", uc.port);
  12516. }
  12517. {
  12518. // Unix socket path — must not be parsed as host
  12519. detail::UrlComponents uc;
  12520. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12521. EXPECT_TRUE(uc.host.empty());
  12522. }
  12523. {
  12524. detail::UrlComponents uc;
  12525. ASSERT_TRUE(detail::parse_url("", uc));
  12526. EXPECT_TRUE(uc.host.empty());
  12527. EXPECT_TRUE(uc.path.empty());
  12528. }
  12529. {
  12530. detail::UrlComponents uc;
  12531. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12532. }
  12533. {
  12534. detail::UrlComponents uc;
  12535. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12536. }
  12537. {
  12538. // Accepted by parse_url; callers restrict to http/https
  12539. detail::UrlComponents uc;
  12540. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12541. EXPECT_EQ("ftp", uc.scheme);
  12542. }
  12543. {
  12544. detail::UrlComponents uc;
  12545. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12546. }
  12547. {
  12548. detail::UrlComponents uc;
  12549. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12550. }
  12551. }
  12552. TEST(ParseUrlTest, FragmentHandling) {
  12553. {
  12554. detail::UrlComponents uc;
  12555. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12556. EXPECT_EQ("/path", uc.path);
  12557. EXPECT_TRUE(uc.query.empty());
  12558. }
  12559. {
  12560. detail::UrlComponents uc;
  12561. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12562. EXPECT_TRUE(uc.path.empty());
  12563. EXPECT_TRUE(uc.query.empty());
  12564. }
  12565. }
  12566. TEST(ParseUrlTest, UserinfoHandling) {
  12567. // Userinfo with @ but no colon — host includes @
  12568. detail::UrlComponents uc;
  12569. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12570. EXPECT_EQ("user@host.com", uc.host);
  12571. EXPECT_EQ("/path", uc.path);
  12572. }
  12573. TEST(ParseUrlTest, IPv6EdgeCases) {
  12574. {
  12575. detail::UrlComponents uc;
  12576. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12577. EXPECT_TRUE(uc.scheme.empty());
  12578. EXPECT_EQ("::1", uc.host);
  12579. EXPECT_EQ("8080", uc.port);
  12580. }
  12581. {
  12582. // Zone ID '%25' is not in [a-fA-F0-9:]
  12583. detail::UrlComponents uc;
  12584. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12585. }
  12586. }
  12587. TEST(ParseUrlTest, SchemeEdgeCases) {
  12588. {
  12589. detail::UrlComponents uc;
  12590. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12591. }
  12592. {
  12593. detail::UrlComponents uc;
  12594. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12595. }
  12596. {
  12597. detail::UrlComponents uc;
  12598. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12599. }
  12600. }
  12601. TEST(ParseUrlTest, PortEdgeCases) {
  12602. {
  12603. detail::UrlComponents uc;
  12604. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12605. EXPECT_TRUE(uc.port.empty());
  12606. EXPECT_EQ("/path", uc.path);
  12607. }
  12608. {
  12609. // parse_url accepts any port string; validation is done by parse_port
  12610. detail::UrlComponents uc;
  12611. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12612. EXPECT_EQ("abc", uc.port);
  12613. }
  12614. }
  12615. TEST(ParseUrlTest, WebSocketPatterns) {
  12616. {
  12617. detail::UrlComponents uc;
  12618. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12619. EXPECT_EQ("ws", uc.scheme);
  12620. EXPECT_EQ("echo.example.com", uc.host);
  12621. EXPECT_EQ("8080", uc.port);
  12622. EXPECT_EQ("/ws", uc.path);
  12623. }
  12624. {
  12625. detail::UrlComponents uc;
  12626. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12627. EXPECT_EQ("wss", uc.scheme);
  12628. EXPECT_EQ("echo.example.com", uc.host);
  12629. EXPECT_TRUE(uc.port.empty());
  12630. EXPECT_EQ("/ws", uc.path);
  12631. }
  12632. }
  12633. TEST(ParseUrlTest, QueryOnly) {
  12634. detail::UrlComponents uc;
  12635. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12636. EXPECT_TRUE(uc.host.empty());
  12637. EXPECT_TRUE(uc.path.empty());
  12638. EXPECT_EQ("?q=1&r=2", uc.query);
  12639. }
  12640. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12641. detail::UrlComponents uc;
  12642. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12643. EXPECT_TRUE(uc.scheme.empty());
  12644. EXPECT_EQ("example.com", uc.host);
  12645. EXPECT_EQ("443", uc.port);
  12646. EXPECT_EQ("/path", uc.path);
  12647. }
  12648. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12649. // If ipv6 regex working, regex match codepath is taken.
  12650. // else port will default to 80 in Client impl
  12651. int clientImplMagicPort = 80;
  12652. int port = 4321;
  12653. // above ports must be different to avoid false negative
  12654. EXPECT_NE(clientImplMagicPort, port);
  12655. std::string ipV6TestURL = "http://[ff06::c3]";
  12656. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12657. CLIENT_PRIVATE_KEY_FILE);
  12658. EXPECT_EQ(cli.port(), port);
  12659. }
  12660. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12661. auto file_path = "./www/dir/index.html";
  12662. auto dir_path = "./www/dir";
  12663. detail::FileStat stat_file(file_path);
  12664. EXPECT_TRUE(stat_file.is_file());
  12665. EXPECT_FALSE(stat_file.is_dir());
  12666. detail::FileStat stat_dir(dir_path);
  12667. EXPECT_FALSE(stat_dir.is_file());
  12668. EXPECT_TRUE(stat_dir.is_dir());
  12669. }
  12670. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12671. // IPv4 with default HTTP port (80)
  12672. EXPECT_EQ("example.com",
  12673. detail::make_host_and_port_string("example.com", 80, false));
  12674. // IPv4 with default HTTPS port (443)
  12675. EXPECT_EQ("example.com",
  12676. detail::make_host_and_port_string("example.com", 443, true));
  12677. // IPv4 with non-default HTTP port
  12678. EXPECT_EQ("example.com:8080",
  12679. detail::make_host_and_port_string("example.com", 8080, false));
  12680. // IPv4 with non-default HTTPS port
  12681. EXPECT_EQ("example.com:8443",
  12682. detail::make_host_and_port_string("example.com", 8443, true));
  12683. // IPv6 with default HTTP port (80)
  12684. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12685. // IPv6 with default HTTPS port (443)
  12686. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12687. // IPv6 with non-default HTTP port
  12688. EXPECT_EQ("[::1]:8080",
  12689. detail::make_host_and_port_string("::1", 8080, false));
  12690. // IPv6 with non-default HTTPS port
  12691. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12692. // IPv6 full address with default port
  12693. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12694. detail::make_host_and_port_string(
  12695. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12696. // IPv6 full address with non-default port
  12697. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12698. detail::make_host_and_port_string(
  12699. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12700. // IPv6 localhost with non-default port
  12701. EXPECT_EQ("[::1]:3000",
  12702. detail::make_host_and_port_string("::1", 3000, false));
  12703. // IPv6 with zone ID (link-local address) with default port
  12704. EXPECT_EQ("[fe80::1%eth0]",
  12705. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12706. // IPv6 with zone ID (link-local address) with non-default port
  12707. EXPECT_EQ("[fe80::1%eth0]:8080",
  12708. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12709. // Edge case: Port 443 with is_ssl=false (should add port)
  12710. EXPECT_EQ("example.com:443",
  12711. detail::make_host_and_port_string("example.com", 443, false));
  12712. // Edge case: Port 80 with is_ssl=true (should add port)
  12713. EXPECT_EQ("example.com:80",
  12714. detail::make_host_and_port_string("example.com", 80, true));
  12715. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12716. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12717. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12718. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12719. // Security fix: Already bracketed IPv6 should not get double brackets
  12720. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12721. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12722. EXPECT_EQ("[::1]:8080",
  12723. detail::make_host_and_port_string("[::1]", 8080, false));
  12724. EXPECT_EQ("[2001:db8::1]:8080",
  12725. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12726. EXPECT_EQ("[fe80::1%eth0]",
  12727. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12728. EXPECT_EQ("[fe80::1%eth0]:8080",
  12729. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12730. // Edge case: Empty host (should return as-is)
  12731. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12732. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12733. // This is a known limitation but shouldn't crash
  12734. EXPECT_EQ("[host:name]",
  12735. detail::make_host_and_port_string("host:name", 80, false));
  12736. // Port number edge cases (no validation, but should not crash)
  12737. EXPECT_EQ("example.com:0",
  12738. detail::make_host_and_port_string("example.com", 0, false));
  12739. EXPECT_EQ("example.com:-1",
  12740. detail::make_host_and_port_string("example.com", -1, false));
  12741. EXPECT_EQ("example.com:65535",
  12742. detail::make_host_and_port_string("example.com", 65535, false));
  12743. EXPECT_EQ("example.com:65536",
  12744. detail::make_host_and_port_string("example.com", 65536, false));
  12745. }
  12746. #ifdef CPPHTTPLIB_SSL_ENABLED
  12747. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12748. httplib::SSLClient cli("roblox.com", 443);
  12749. cli.set_follow_location(true);
  12750. auto res = cli.Get("/");
  12751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12752. EXPECT_EQ(StatusCode::OK_200, res->status);
  12753. }
  12754. #endif
  12755. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12756. Server svr;
  12757. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12758. EXPECT_EQ(res.status, 400);
  12759. });
  12760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12761. auto se = detail::scope_exit([&] {
  12762. svr.stop();
  12763. thread.join();
  12764. ASSERT_FALSE(svr.is_running());
  12765. });
  12766. svr.wait_until_ready();
  12767. Client cli(HOST, PORT);
  12768. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12769. }
  12770. TEST(InvalidHeaderCharsTest, is_field_name) {
  12771. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12772. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12773. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12774. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12775. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12776. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12777. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12778. EXPECT_FALSE(detail::fields::is_field_name(""));
  12779. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12780. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12781. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12782. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12783. }
  12784. TEST(InvalidHeaderCharsTest, is_field_value) {
  12785. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12786. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12787. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12788. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12789. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12790. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12791. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12792. EXPECT_TRUE(detail::fields::is_field_value(""));
  12793. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12794. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12795. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12796. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12797. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12798. }
  12799. TEST(InvalidHeaderCharsTest, OnServer) {
  12800. Server svr;
  12801. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12802. std::string header = "Not Set";
  12803. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12804. res.set_header(header, "value");
  12805. res.set_content("Page Content Page Content", "text/plain");
  12806. });
  12807. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12808. std::string header = "Not Set";
  12809. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12810. res.set_header("X-Test", header);
  12811. res.set_content("Page Content Page Content", "text/plain");
  12812. });
  12813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop();
  12816. thread.join();
  12817. ASSERT_FALSE(svr.is_running());
  12818. });
  12819. svr.wait_until_ready();
  12820. Client cli(HOST, PORT);
  12821. {
  12822. auto res = cli.Get(
  12823. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12825. EXPECT_EQ("Page Content Page Content", res->body);
  12826. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12827. }
  12828. {
  12829. auto res = cli.Get(
  12830. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12832. EXPECT_EQ("Page Content Page Content", res->body);
  12833. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12834. }
  12835. }
  12836. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12837. auto handled = false;
  12838. Server svr;
  12839. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12840. thread t = thread([&] { svr.listen(HOST, PORT); });
  12841. auto se = detail::scope_exit([&] {
  12842. svr.stop();
  12843. t.join();
  12844. ASSERT_FALSE(svr.is_running());
  12845. ASSERT_FALSE(handled);
  12846. });
  12847. svr.wait_until_ready();
  12848. auto req = "POST /test HTTP/1.1\r\n"
  12849. "Content-Length: x\r\n"
  12850. "\r\n";
  12851. std::string response;
  12852. ASSERT_TRUE(send_request(1, req, &response));
  12853. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12854. response.substr(0, response.find("\r\n")));
  12855. }
  12856. #ifndef _WIN32
  12857. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12858. static constexpr char reject[] = "Unauthorized";
  12859. static constexpr char accept[] = "Upload accepted";
  12860. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12861. Server svr;
  12862. svr.set_expect_100_continue_handler(
  12863. [](const Request & /*req*/, Response &res) {
  12864. res.status = StatusCode::Unauthorized_401;
  12865. res.set_content(reject, "text/plain");
  12866. return res.status;
  12867. });
  12868. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12869. res.set_content(accept, "text/plain");
  12870. });
  12871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12872. auto se = detail::scope_exit([&] {
  12873. svr.stop();
  12874. thread.join();
  12875. ASSERT_FALSE(svr.is_running());
  12876. });
  12877. svr.wait_until_ready();
  12878. {
  12879. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12880. curl_easy_init(), &curl_easy_cleanup};
  12881. ASSERT_NE(curl, nullptr);
  12882. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12883. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12884. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12885. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12886. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12887. &curl_slist_free_all};
  12888. ASSERT_NE(list, nullptr);
  12889. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12890. struct read_data {
  12891. size_t read_size;
  12892. size_t total_size;
  12893. } data = {0, total_size};
  12894. using read_callback_t =
  12895. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12896. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12897. void *userdata) -> size_t {
  12898. read_data *d = (read_data *)userdata;
  12899. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12900. std::fill_n(ptr, size * nmemb, 'A');
  12901. d->read_size += size * nmemb;
  12902. return size * nmemb;
  12903. };
  12904. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12905. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12906. std::vector<char> buffer;
  12907. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12908. using write_callback_t =
  12909. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12910. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12911. void *userdata) -> size_t {
  12912. std::vector<char> *buf = (std::vector<char> *)userdata;
  12913. buf->reserve(buf->size() + size * nmemb + 1);
  12914. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12915. return size * nmemb;
  12916. };
  12917. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12918. {
  12919. const auto res = curl_easy_perform(curl.get());
  12920. ASSERT_EQ(res, CURLE_OK);
  12921. }
  12922. {
  12923. auto response_code = long{};
  12924. const auto res =
  12925. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12926. ASSERT_EQ(res, CURLE_OK);
  12927. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12928. }
  12929. {
  12930. auto dl = curl_off_t{};
  12931. const auto res =
  12932. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12933. ASSERT_EQ(res, CURLE_OK);
  12934. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12935. }
  12936. {
  12937. buffer.push_back('\0');
  12938. ASSERT_STRCASEEQ(buffer.data(), reject);
  12939. }
  12940. }
  12941. }
  12942. #endif
  12943. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12944. // Regression test for #2458.
  12945. //
  12946. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12947. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12948. // ticket can make the client socket spuriously readable during the
  12949. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12950. // the client withholds the body and then blocks reading a response that never
  12951. // comes, failing with `Failed to read connection`.
  12952. //
  12953. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12954. // within the timeout. This raw OpenSSL server deliberately never sends
  12955. // `100 Continue`; the client must still deliver the body and receive 200.
  12956. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12957. signal(SIGPIPE, SIG_IGN);
  12958. const auto port = PORT + 4;
  12959. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12960. ASSERT_NE(srv, INVALID_SOCKET);
  12961. int opt = 1;
  12962. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12963. sockaddr_in addr{};
  12964. addr.sin_family = AF_INET;
  12965. addr.sin_port = htons(static_cast<uint16_t>(port));
  12966. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12967. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12968. ASSERT_EQ(0, ::listen(srv, 1));
  12969. std::atomic<size_t> server_body_bytes{0};
  12970. auto server_thread = std::thread([&] {
  12971. sockaddr_in cli_addr{};
  12972. socklen_t cli_len = sizeof(cli_addr);
  12973. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12974. if (cli == INVALID_SOCKET) { return; }
  12975. // Bound the lifetime of the server side so a buggy client (which never
  12976. // sends the body) cannot make this thread block forever on join.
  12977. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12978. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12979. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12980. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12981. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12982. SSL *ssl = SSL_new(ctx);
  12983. SSL_set_fd(ssl, static_cast<int>(cli));
  12984. if (SSL_accept(ssl) > 0) {
  12985. // Read the request headers. Reading here also flushes the TLS 1.3
  12986. // session tickets to the client. Deliberately do NOT send
  12987. // `100 Continue`.
  12988. std::string buf;
  12989. char tmp[1024];
  12990. while (buf.find("\r\n\r\n") == std::string::npos) {
  12991. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12992. if (n <= 0) { break; }
  12993. buf.append(tmp, static_cast<size_t>(n));
  12994. }
  12995. // A correct client sends the body now; count what arrives.
  12996. auto pos = buf.find("\r\n\r\n");
  12997. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12998. while (body < 4096) {
  12999. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  13000. if (n <= 0) { break; }
  13001. body += static_cast<size_t>(n);
  13002. }
  13003. server_body_bytes = body;
  13004. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  13005. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  13006. SSL_shutdown(ssl);
  13007. }
  13008. SSL_free(ssl);
  13009. detail::close_socket(cli);
  13010. SSL_CTX_free(ctx);
  13011. });
  13012. auto se = detail::scope_exit([&] {
  13013. server_thread.join();
  13014. detail::close_socket(srv);
  13015. });
  13016. SSLClient cli("127.0.0.1", port);
  13017. cli.enable_server_certificate_verification(false);
  13018. cli.set_connection_timeout(5, 0);
  13019. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  13020. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  13021. std::string body(4096, 'A');
  13022. auto res = cli.Put("/api/test", body, "application/json");
  13023. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  13024. EXPECT_EQ(StatusCode::OK_200, res->status);
  13025. EXPECT_EQ(body.size(), server_body_bytes.load());
  13026. }
  13027. #endif
  13028. template <typename S, typename C>
  13029. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  13030. svr.Get("/stream", [&](const Request &, Response &res) {
  13031. auto data = new std::string("01234567890123456789");
  13032. res.set_content_provider(
  13033. data->size(), "text/plain",
  13034. [&, data](size_t offset, size_t length, DataSink &sink) {
  13035. const size_t DATA_CHUNK_SIZE = 4;
  13036. const auto &d = *data;
  13037. std::this_thread::sleep_for(std::chrono::seconds(1));
  13038. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  13039. return true;
  13040. },
  13041. [data](bool success) {
  13042. EXPECT_FALSE(success);
  13043. delete data;
  13044. });
  13045. });
  13046. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  13047. auto i = new size_t(0);
  13048. res.set_content_provider(
  13049. "text/plain",
  13050. [i](size_t, DataSink &sink) {
  13051. if (*i < 5) {
  13052. std::this_thread::sleep_for(std::chrono::seconds(1));
  13053. sink.write("abcd", 4);
  13054. (*i)++;
  13055. } else {
  13056. sink.done();
  13057. }
  13058. return true;
  13059. },
  13060. [i](bool success) {
  13061. EXPECT_FALSE(success);
  13062. delete i;
  13063. });
  13064. });
  13065. svr.Get("/chunked", [&](const Request &, Response &res) {
  13066. auto i = new size_t(0);
  13067. res.set_chunked_content_provider(
  13068. "text/plain",
  13069. [i](size_t, DataSink &sink) {
  13070. if (*i < 5) {
  13071. std::this_thread::sleep_for(std::chrono::seconds(1));
  13072. sink.os << "abcd";
  13073. (*i)++;
  13074. } else {
  13075. sink.done();
  13076. }
  13077. return true;
  13078. },
  13079. [i](bool success) {
  13080. EXPECT_FALSE(success);
  13081. delete i;
  13082. });
  13083. });
  13084. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13085. auto se = detail::scope_exit([&] {
  13086. svr.stop();
  13087. listen_thread.join();
  13088. ASSERT_FALSE(svr.is_running());
  13089. });
  13090. svr.wait_until_ready();
  13091. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  13092. {
  13093. auto start = std::chrono::steady_clock::now();
  13094. auto res = cli.Get("/stream");
  13095. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13096. std::chrono::steady_clock::now() - start)
  13097. .count();
  13098. ASSERT_FALSE(res);
  13099. EXPECT_EQ(Error::Read, res.error());
  13100. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13101. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13102. }
  13103. {
  13104. auto start = std::chrono::steady_clock::now();
  13105. auto res = cli.Get("/stream_without_length");
  13106. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13107. std::chrono::steady_clock::now() - start)
  13108. .count();
  13109. ASSERT_FALSE(res);
  13110. EXPECT_EQ(Error::Read, res.error());
  13111. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13112. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13113. }
  13114. {
  13115. auto start = std::chrono::steady_clock::now();
  13116. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  13117. EXPECT_EQ("abcd", string(data, data_length));
  13118. return true;
  13119. });
  13120. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13121. std::chrono::steady_clock::now() - start)
  13122. .count();
  13123. ASSERT_FALSE(res);
  13124. EXPECT_EQ(Error::Read, res.error());
  13125. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  13126. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  13127. }
  13128. }
  13129. TEST(MaxTimeoutTest, ContentStream) {
  13130. time_t timeout = 2000;
  13131. time_t threshold = 200;
  13132. Server svr;
  13133. Client cli("localhost", PORT);
  13134. max_timeout_test(svr, cli, timeout, threshold);
  13135. }
  13136. #ifdef CPPHTTPLIB_SSL_ENABLED
  13137. TEST(MaxTimeoutTest, ContentStreamSSL) {
  13138. time_t timeout = 2000;
  13139. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  13140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13141. SSLClient cli("localhost", PORT);
  13142. cli.enable_server_certificate_verification(false);
  13143. max_timeout_test(svr, cli, timeout, threshold);
  13144. }
  13145. #endif
  13146. class EventDispatcher {
  13147. public:
  13148. EventDispatcher() {}
  13149. bool wait_event(DataSink *sink) {
  13150. unique_lock<mutex> lk(m_);
  13151. int id = id_;
  13152. // Wait with timeout to prevent hanging if client disconnects
  13153. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  13154. [&] { return cid_ == id; })) {
  13155. return false; // Timeout occurred
  13156. }
  13157. sink->write(message_.data(), message_.size());
  13158. return true;
  13159. }
  13160. void send_event(const string &message) {
  13161. lock_guard<mutex> lk(m_);
  13162. cid_ = id_++;
  13163. message_ = message;
  13164. cv_.notify_all();
  13165. }
  13166. private:
  13167. mutex m_;
  13168. condition_variable cv_;
  13169. atomic_int id_{0};
  13170. atomic_int cid_{-1};
  13171. string message_;
  13172. };
  13173. TEST(ClientInThreadTest, Issue2068) {
  13174. EventDispatcher ed;
  13175. Server svr;
  13176. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  13177. res.set_chunked_content_provider("text/event-stream",
  13178. [&](size_t /*offset*/, DataSink &sink) {
  13179. return ed.wait_event(&sink);
  13180. });
  13181. });
  13182. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  13183. svr.wait_until_ready();
  13184. thread event_thread([&] {
  13185. int id = 0;
  13186. while (svr.is_running()) {
  13187. this_thread::sleep_for(chrono::milliseconds(500));
  13188. std::stringstream ss;
  13189. ss << "data: " << id << "\n\n";
  13190. ed.send_event(ss.str());
  13191. id++;
  13192. }
  13193. });
  13194. auto se = detail::scope_exit([&] {
  13195. svr.stop();
  13196. listen_thread.join();
  13197. event_thread.join();
  13198. ASSERT_FALSE(svr.is_running());
  13199. });
  13200. {
  13201. auto client = detail::make_unique<Client>(HOST, PORT);
  13202. client->set_read_timeout(std::chrono::minutes(10));
  13203. std::atomic<bool> stop{false};
  13204. std::thread t([&] {
  13205. client->Get("/event1",
  13206. [&](const char *, size_t) -> bool { return !stop; });
  13207. });
  13208. std::this_thread::sleep_for(std::chrono::seconds(2));
  13209. stop = true;
  13210. client->stop();
  13211. t.join();
  13212. // Reset client after thread has finished
  13213. client.reset();
  13214. }
  13215. }
  13216. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13217. auto handled = false;
  13218. Server svr;
  13219. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13221. auto se = detail::scope_exit([&] {
  13222. svr.stop();
  13223. t.join();
  13224. ASSERT_FALSE(svr.is_running());
  13225. ASSERT_FALSE(handled);
  13226. });
  13227. svr.wait_until_ready();
  13228. // Two Content-Length headers with different values — must be rejected
  13229. auto req = "POST /test HTTP/1.1\r\n"
  13230. "Content-Length: 5\r\n"
  13231. "Content-Length: 10\r\n"
  13232. "\r\n"
  13233. "hello";
  13234. std::string response;
  13235. ASSERT_TRUE(send_request(1, req, &response));
  13236. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13237. response.substr(0, response.find("\r\n")));
  13238. }
  13239. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13240. auto handled = false;
  13241. Server svr;
  13242. svr.Post("/test", [&](const Request &, Response &res) {
  13243. handled = true;
  13244. res.set_content("ok", "text/plain");
  13245. });
  13246. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13247. auto se = detail::scope_exit([&] {
  13248. svr.stop();
  13249. t.join();
  13250. ASSERT_FALSE(svr.is_running());
  13251. ASSERT_TRUE(handled);
  13252. });
  13253. svr.wait_until_ready();
  13254. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13255. auto req = "POST /test HTTP/1.1\r\n"
  13256. "Content-Length: 5\r\n"
  13257. "Content-Length: 5\r\n"
  13258. "\r\n"
  13259. "hello";
  13260. std::string response;
  13261. ASSERT_TRUE(send_request(1, req, &response));
  13262. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13263. }
  13264. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13265. Server svr;
  13266. svr.Get("/", [](const Request &req, Response &res) {
  13267. EXPECT_EQ(2U, req.trailers.size());
  13268. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13269. // Denied
  13270. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13271. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13272. // Accepted
  13273. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13274. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13275. EXPECT_TRUE(req.has_trailer("X-World"));
  13276. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13277. res.set_content("ok", "text/plain");
  13278. });
  13279. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13280. auto se = detail::scope_exit([&] {
  13281. svr.stop();
  13282. t.join();
  13283. ASSERT_FALSE(svr.is_running());
  13284. });
  13285. svr.wait_until_ready();
  13286. const std::string req = "GET / HTTP/1.1\r\n"
  13287. "Transfer-Encoding: chunked\r\n"
  13288. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13289. "\r\n"
  13290. "0\r\n"
  13291. "Content-Length: 10\r\n"
  13292. "Host: internal.local\r\n"
  13293. "Content-Type: malicious/content\r\n"
  13294. "Cookie: any\r\n"
  13295. "Set-Cookie: any\r\n"
  13296. "X-Forwarded-For: attacker.com\r\n"
  13297. "X-Real-Ip: 1.1.1.1\r\n"
  13298. "X-Hello: hello\r\n"
  13299. "X-World: world\r\n"
  13300. "\r\n";
  13301. std::string res;
  13302. ASSERT_TRUE(send_request(1, req, &res));
  13303. }
  13304. // A direct client that is not listed in trusted_proxies must not be able to
  13305. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13306. // the peer address on the actual TCP connection determines whether the
  13307. // header is honored.
  13308. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13309. Server svr;
  13310. // Deliberately does NOT include the loopback address the test client
  13311. // actually connects from, so the direct connection is not a trusted proxy.
  13312. svr.set_trusted_proxies({"203.0.113.66"});
  13313. std::string observed_remote_addr;
  13314. svr.Get("/ip", [&](const Request &req, Response &res) {
  13315. observed_remote_addr = req.remote_addr;
  13316. res.set_content("ok", "text/plain");
  13317. });
  13318. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13319. auto se = detail::scope_exit([&] {
  13320. svr.stop();
  13321. t.join();
  13322. ASSERT_FALSE(svr.is_running());
  13323. });
  13324. svr.wait_until_ready();
  13325. Client cli(HOST, PORT);
  13326. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13328. EXPECT_EQ(StatusCode::OK_200, res->status);
  13329. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13330. // ignored entirely and the real connection-level address retained.
  13331. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13332. observed_remote_addr == "127.0.0.1");
  13333. }
  13334. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13335. Server svr;
  13336. std::string observed_remote_addr;
  13337. std::string observed_xff;
  13338. svr.Get("/ip", [&](const Request &req, Response &res) {
  13339. observed_remote_addr = req.remote_addr;
  13340. observed_xff = req.get_header_value("X-Forwarded-For");
  13341. res.set_content("ok", "text/plain");
  13342. });
  13343. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13344. auto se = detail::scope_exit([&] {
  13345. svr.stop();
  13346. t.join();
  13347. ASSERT_FALSE(svr.is_running());
  13348. });
  13349. svr.wait_until_ready();
  13350. Client cli(HOST, PORT);
  13351. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13353. EXPECT_EQ(StatusCode::OK_200, res->status);
  13354. EXPECT_EQ(observed_xff, "203.0.113.66");
  13355. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13356. observed_remote_addr == "127.0.0.1");
  13357. }
  13358. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13359. Server svr;
  13360. svr.set_trusted_proxies({"203.0.113.66"});
  13361. std::string observed_remote_addr;
  13362. std::string observed_xff;
  13363. svr.Get("/ip", [&](const Request &req, Response &res) {
  13364. observed_remote_addr = req.remote_addr;
  13365. observed_xff = req.get_header_value("X-Forwarded-For");
  13366. res.set_content("ok", "text/plain");
  13367. });
  13368. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13369. auto se = detail::scope_exit([&] {
  13370. svr.stop();
  13371. t.join();
  13372. ASSERT_FALSE(svr.is_running());
  13373. });
  13374. svr.wait_until_ready();
  13375. Client cli(HOST, PORT);
  13376. auto res = cli.Get("/ip");
  13377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13378. EXPECT_EQ(StatusCode::OK_200, res->status);
  13379. EXPECT_EQ(observed_xff, "");
  13380. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13381. observed_remote_addr == "127.0.0.1");
  13382. }
  13383. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13384. Server svr;
  13385. // Include the loopback address the test client actually connects from, so
  13386. // the direct connection itself is recognized as the trusted proxy hop.
  13387. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13388. std::string observed_remote_addr;
  13389. std::string observed_xff;
  13390. svr.Get("/ip", [&](const Request &req, Response &res) {
  13391. observed_remote_addr = req.remote_addr;
  13392. observed_xff = req.get_header_value("X-Forwarded-For");
  13393. res.set_content("ok", "text/plain");
  13394. });
  13395. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13396. auto se = detail::scope_exit([&] {
  13397. svr.stop();
  13398. t.join();
  13399. ASSERT_FALSE(svr.is_running());
  13400. });
  13401. svr.wait_until_ready();
  13402. Client cli(HOST, PORT);
  13403. auto res = cli.Get(
  13404. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13406. EXPECT_EQ(StatusCode::OK_200, res->status);
  13407. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13408. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13409. }
  13410. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13411. Server svr;
  13412. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13413. std::string observed_remote_addr;
  13414. std::string observed_xff;
  13415. svr.Get("/ip", [&](const Request &req, Response &res) {
  13416. observed_remote_addr = req.remote_addr;
  13417. observed_xff = req.get_header_value("X-Forwarded-For");
  13418. res.set_content("ok", "text/plain");
  13419. });
  13420. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13421. auto se = detail::scope_exit([&] {
  13422. svr.stop();
  13423. t.join();
  13424. ASSERT_FALSE(svr.is_running());
  13425. });
  13426. svr.wait_until_ready();
  13427. Client cli(HOST, PORT);
  13428. auto res = cli.Get(
  13429. "/ip",
  13430. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13432. EXPECT_EQ(StatusCode::OK_200, res->status);
  13433. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13434. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13435. }
  13436. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13437. Server svr;
  13438. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13439. std::string observed_remote_addr;
  13440. std::string observed_xff;
  13441. svr.Get("/ip", [&](const Request &req, Response &res) {
  13442. observed_remote_addr = req.remote_addr;
  13443. observed_xff = req.get_header_value("X-Forwarded-For");
  13444. res.set_content("ok", "text/plain");
  13445. });
  13446. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13447. auto se = detail::scope_exit([&] {
  13448. svr.stop();
  13449. t.join();
  13450. ASSERT_FALSE(svr.is_running());
  13451. });
  13452. svr.wait_until_ready();
  13453. Client cli(HOST, PORT);
  13454. auto res = cli.Get(
  13455. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13457. EXPECT_EQ(StatusCode::OK_200, res->status);
  13458. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13459. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13460. // and must not be selected.
  13461. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13462. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13463. }
  13464. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13465. Server svr;
  13466. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13467. std::string observed_remote_addr;
  13468. svr.Get("/ip", [&](const Request &req, Response &res) {
  13469. observed_remote_addr = req.remote_addr;
  13470. res.set_content("ok", "text/plain");
  13471. });
  13472. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13473. auto se = detail::scope_exit([&] {
  13474. svr.stop();
  13475. t.join();
  13476. ASSERT_FALSE(svr.is_running());
  13477. });
  13478. svr.wait_until_ready();
  13479. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13480. // a forged address and the trusted proxy's own address; the forged value must
  13481. // not win over the address the trusted proxy actually recorded.
  13482. Client cli(HOST, PORT);
  13483. auto res = cli.Get(
  13484. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13486. EXPECT_EQ(StatusCode::OK_200, res->status);
  13487. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13488. }
  13489. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13490. Server svr;
  13491. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13492. std::string observed_remote_addr;
  13493. std::string observed_xff;
  13494. svr.Get("/ip", [&](const Request &req, Response &res) {
  13495. observed_remote_addr = req.remote_addr;
  13496. observed_xff = req.get_header_value("X-Forwarded-For");
  13497. res.set_content("ok", "text/plain");
  13498. });
  13499. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13500. auto se = detail::scope_exit([&] {
  13501. svr.stop();
  13502. t.join();
  13503. ASSERT_FALSE(svr.is_running());
  13504. });
  13505. svr.wait_until_ready();
  13506. Client cli(HOST, PORT);
  13507. auto res = cli.Get(
  13508. "/ip",
  13509. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13511. EXPECT_EQ(StatusCode::OK_200, res->status);
  13512. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13513. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13514. }
  13515. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13516. Server svr;
  13517. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13518. std::string observed_remote_addr;
  13519. std::string observed_xff;
  13520. svr.Get("/ip", [&](const Request &req, Response &res) {
  13521. observed_remote_addr = req.remote_addr;
  13522. observed_xff = req.get_header_value("X-Forwarded-For");
  13523. res.set_content("ok", "text/plain");
  13524. });
  13525. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13526. auto se = detail::scope_exit([&] {
  13527. svr.stop();
  13528. t.join();
  13529. ASSERT_FALSE(svr.is_running());
  13530. });
  13531. svr.wait_until_ready();
  13532. std::string raw_req =
  13533. "GET /ip HTTP/1.1\r\n"
  13534. "Host: localhost\r\n"
  13535. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13536. "Connection: close\r\n"
  13537. "\r\n";
  13538. std::string out;
  13539. ASSERT_TRUE(send_request(5, raw_req, &out));
  13540. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13541. // Header parser trims surrounding whitespace of the header value
  13542. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13543. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13544. }
  13545. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13546. // crash the server (it used to call front() on an empty vector inside
  13547. // get_client_ip). The connection-level remote address must be retained instead.
  13548. static void run_malformed_xff_test(const std::string &xff_value) {
  13549. Server svr;
  13550. svr.set_trusted_proxies({"192.0.2.45"});
  13551. std::string observed_remote_addr;
  13552. svr.Get("/ip", [&](const Request &req, Response &res) {
  13553. observed_remote_addr = req.remote_addr;
  13554. res.set_content("ok", "text/plain");
  13555. });
  13556. int port = 0;
  13557. thread t = thread([&]() {
  13558. port = svr.bind_to_any_port(HOST);
  13559. svr.listen_after_bind();
  13560. });
  13561. auto se = detail::scope_exit([&] {
  13562. svr.stop();
  13563. t.join();
  13564. ASSERT_FALSE(svr.is_running());
  13565. });
  13566. svr.wait_until_ready();
  13567. Client cli(HOST, port);
  13568. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13570. EXPECT_EQ(StatusCode::OK_200, res->status);
  13571. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13572. observed_remote_addr == "127.0.0.1");
  13573. }
  13574. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13575. run_malformed_xff_test("");
  13576. }
  13577. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13578. run_malformed_xff_test(",");
  13579. }
  13580. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13581. run_malformed_xff_test(", , ,");
  13582. }
  13583. #ifndef _WIN32
  13584. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13585. Server svr;
  13586. svr.Post("/post", [&](const Request &req, Response &res) {
  13587. res.set_content(req.body, "text/plain");
  13588. });
  13589. svr.Put("/put", [&](const Request &req, Response &res) {
  13590. res.set_content(req.body, "text/plain");
  13591. });
  13592. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13593. res.set_content(req.body, "text/plain");
  13594. });
  13595. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13596. res.set_content(req.body, "text/plain");
  13597. });
  13598. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13599. auto se = detail::scope_exit([&] {
  13600. svr.stop();
  13601. t.join();
  13602. ASSERT_FALSE(svr.is_running());
  13603. });
  13604. svr.wait_until_ready();
  13605. std::string resp;
  13606. // POST without Content-Length
  13607. ASSERT_TRUE(send_request(5,
  13608. "POST /post HTTP/1.1\r\n"
  13609. "Host: localhost\r\n"
  13610. "Connection: close\r\n"
  13611. "\r\n",
  13612. &resp));
  13613. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13614. // PUT without Content-Length
  13615. resp.clear();
  13616. ASSERT_TRUE(send_request(5,
  13617. "PUT /put HTTP/1.1\r\n"
  13618. "Host: localhost\r\n"
  13619. "Connection: close\r\n"
  13620. "\r\n",
  13621. &resp));
  13622. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13623. // PATCH without Content-Length
  13624. resp.clear();
  13625. ASSERT_TRUE(send_request(5,
  13626. "PATCH /patch HTTP/1.1\r\n"
  13627. "Host: localhost\r\n"
  13628. "Connection: close\r\n"
  13629. "\r\n",
  13630. &resp));
  13631. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13632. // DELETE without Content-Length
  13633. resp.clear();
  13634. ASSERT_TRUE(send_request(5,
  13635. "DELETE /delete HTTP/1.1\r\n"
  13636. "Host: localhost\r\n"
  13637. "Connection: close\r\n"
  13638. "\r\n",
  13639. &resp));
  13640. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13641. }
  13642. #endif
  13643. //==============================================================================
  13644. // open_stream() Tests
  13645. //==============================================================================
  13646. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13647. std::string result;
  13648. char buf[8192];
  13649. ssize_t n;
  13650. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13651. result.append(buf, static_cast<size_t>(n));
  13652. }
  13653. return result;
  13654. }
  13655. // Mock stream for unit tests
  13656. class MockStream : public Stream {
  13657. public:
  13658. std::string data;
  13659. size_t pos = 0;
  13660. ssize_t error_after = -1; // -1 = no error
  13661. explicit MockStream(const std::string &d, ssize_t err = -1)
  13662. : data(d), error_after(err) {}
  13663. bool is_readable() const override { return true; }
  13664. bool wait_readable() const override { return true; }
  13665. bool wait_writable() const override { return true; }
  13666. ssize_t read(char *ptr, size_t size) override {
  13667. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13668. if (pos >= data.size()) return 0;
  13669. size_t limit =
  13670. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13671. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13672. std::memcpy(ptr, data.data() + pos, to_read);
  13673. pos += to_read;
  13674. return static_cast<ssize_t>(to_read);
  13675. }
  13676. ssize_t write(const char *, size_t) override { return -1; }
  13677. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13678. ip = "127.0.0.1";
  13679. port = 0;
  13680. }
  13681. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13682. ip = "127.0.0.1";
  13683. port = 0;
  13684. }
  13685. socket_t socket() const override { return INVALID_SOCKET; }
  13686. time_t duration() const override { return 0; }
  13687. };
  13688. TEST(StreamHandleTest, Basic) {
  13689. ClientImpl::StreamHandle handle;
  13690. EXPECT_FALSE(handle.is_valid());
  13691. handle.response = detail::make_unique<Response>();
  13692. handle.error = Error::Connection;
  13693. EXPECT_FALSE(handle.is_valid());
  13694. handle.error = Error::Success;
  13695. EXPECT_TRUE(handle.is_valid());
  13696. }
  13697. TEST(BodyReaderTest, Basic) {
  13698. MockStream stream("Hello, World!");
  13699. detail::BodyReader reader;
  13700. reader.stream = &stream;
  13701. reader.content_length = 13;
  13702. char buf[32];
  13703. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13704. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13705. EXPECT_TRUE(reader.eof);
  13706. }
  13707. TEST(BodyReaderTest, NoStream) {
  13708. detail::BodyReader reader;
  13709. char buf[32];
  13710. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13711. EXPECT_EQ(Error::Connection, reader.last_error);
  13712. }
  13713. TEST(BodyReaderTest, Error) {
  13714. MockStream stream("Hello, World!", 5);
  13715. detail::BodyReader reader;
  13716. reader.stream = &stream;
  13717. reader.content_length = 13;
  13718. char buf[32];
  13719. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13720. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13721. EXPECT_EQ(Error::Read, reader.last_error);
  13722. }
  13723. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13724. // Mock-based StreamHandle tests relying on private internals are removed.
  13725. class OpenStreamTest : public ::testing::Test {
  13726. protected:
  13727. void SetUp() override {
  13728. svr_.Get("/hello", [](const Request &, Response &res) {
  13729. res.set_content("Hello World!", "text/plain");
  13730. });
  13731. svr_.Get("/large", [](const Request &, Response &res) {
  13732. res.set_content(std::string(10000, 'X'), "text/plain");
  13733. });
  13734. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  13735. res.set_content("Hello World!", "image/jpeg");
  13736. res.set_header("Content-Encoding", "UTF-8");
  13737. });
  13738. svr_.Get("/chunked", [](const Request &, Response &res) {
  13739. res.set_chunked_content_provider("text/plain",
  13740. [](size_t offset, DataSink &sink) {
  13741. if (offset < 15) {
  13742. sink.write("chunk", 5);
  13743. return true;
  13744. }
  13745. sink.done();
  13746. return true;
  13747. });
  13748. });
  13749. svr_.Get("/compressible", [](const Request &, Response &res) {
  13750. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13751. DataSink &sink) {
  13752. if (offset < 100 * 1024) {
  13753. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13754. sink.write(chunk.data(), chunk.size());
  13755. return true;
  13756. }
  13757. sink.done();
  13758. return true;
  13759. });
  13760. });
  13761. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13762. [](const Request & /*req*/, Response &res) {
  13763. auto i = new int(0);
  13764. res.set_header("Trailer", "Content-Length, X-Allowed");
  13765. res.set_chunked_content_provider(
  13766. "text/plain",
  13767. [i](size_t /*offset*/, DataSink &sink) {
  13768. switch (*i) {
  13769. case 0: sink.os << "123"; break;
  13770. case 1: sink.os << "456"; break;
  13771. case 2: sink.os << "789"; break;
  13772. case 3: {
  13773. sink.done_with_trailer(
  13774. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13775. } break;
  13776. }
  13777. (*i)++;
  13778. return true;
  13779. },
  13780. [i](bool success) {
  13781. EXPECT_TRUE(success);
  13782. delete i;
  13783. });
  13784. });
  13785. // Echo headers endpoint for header-related tests
  13786. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13787. std::string body;
  13788. for (const auto &h : req.headers) {
  13789. body.append(h.first);
  13790. body.push_back(':');
  13791. body.append(h.second);
  13792. body.push_back('\n');
  13793. }
  13794. res.set_content(body, "text/plain");
  13795. });
  13796. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13797. std::string body;
  13798. for (const auto &h : req.headers) {
  13799. body.append(h.first);
  13800. body.push_back(':');
  13801. body.append(h.second);
  13802. body.push_back('\n');
  13803. }
  13804. res.set_content(body, "text/plain");
  13805. });
  13806. port_ = svr_.bind_to_any_port("127.0.0.1");
  13807. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13808. svr_.wait_until_ready();
  13809. }
  13810. void TearDown() override {
  13811. svr_.stop();
  13812. if (thread_.joinable()) thread_.join();
  13813. }
  13814. Server svr_;
  13815. std::thread thread_;
  13816. int port_ = 0;
  13817. };
  13818. TEST_F(OpenStreamTest, Basic) {
  13819. Client cli("127.0.0.1", port_);
  13820. auto handle = cli.open_stream("GET", "/hello");
  13821. EXPECT_TRUE(handle.is_valid());
  13822. EXPECT_EQ("Hello World!", read_all(handle));
  13823. }
  13824. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  13825. Client cli("127.0.0.1", port_);
  13826. auto handle = cli.open_stream("GET", "/unknown-encoding");
  13827. ASSERT_TRUE(handle.is_valid());
  13828. EXPECT_EQ("Hello World!", read_all(handle));
  13829. }
  13830. TEST_F(OpenStreamTest, SmallBuffer) {
  13831. Client cli("127.0.0.1", port_);
  13832. auto handle = cli.open_stream("GET", "/hello");
  13833. std::string result;
  13834. char buf[4];
  13835. ssize_t n;
  13836. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13837. result.append(buf, static_cast<size_t>(n));
  13838. EXPECT_EQ("Hello World!", result);
  13839. }
  13840. TEST_F(OpenStreamTest, DefaultHeaders) {
  13841. Client cli("127.0.0.1", port_);
  13842. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13843. {
  13844. auto handle = cli.open_stream("GET", "/echo-headers");
  13845. ASSERT_TRUE(handle.is_valid());
  13846. auto body = read_all(handle);
  13847. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13848. std::string::npos);
  13849. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13850. std::string::npos);
  13851. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13852. }
  13853. // open_stream POST with body and no explicit content_type should NOT add
  13854. // text/plain Content-Type (behavior differs from non-streaming path), but
  13855. // should include Content-Length
  13856. {
  13857. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13858. ASSERT_TRUE(handle.is_valid());
  13859. auto body = read_all(handle);
  13860. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13861. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13862. }
  13863. // open_stream POST with explicit Content-Type should preserve it
  13864. {
  13865. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13866. {{"Content-Type", "application/custom"}},
  13867. "{}", "application/custom");
  13868. ASSERT_TRUE(handle.is_valid());
  13869. auto body = read_all(handle);
  13870. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13871. }
  13872. // User-specified User-Agent must not be overwritten for stream API
  13873. {
  13874. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13875. {{"User-Agent", "MyAgent/1.2"}});
  13876. ASSERT_TRUE(handle.is_valid());
  13877. auto body = read_all(handle);
  13878. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13879. }
  13880. }
  13881. TEST_F(OpenStreamTest, Large) {
  13882. Client cli("127.0.0.1", port_);
  13883. auto handle = cli.open_stream("GET", "/large");
  13884. EXPECT_EQ(10000u, read_all(handle).size());
  13885. }
  13886. TEST_F(OpenStreamTest, ConnectionError) {
  13887. Client cli("127.0.0.1", 9999);
  13888. auto handle = cli.open_stream("GET", "/hello");
  13889. EXPECT_FALSE(handle.is_valid());
  13890. }
  13891. TEST_F(OpenStreamTest, Chunked) {
  13892. Client cli("127.0.0.1", port_);
  13893. auto handle = cli.open_stream("GET", "/chunked");
  13894. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13895. "Transfer-Encoding") == "chunked");
  13896. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13897. }
  13898. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13899. Client cli("127.0.0.1", port_);
  13900. auto handle =
  13901. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13902. ASSERT_TRUE(handle.is_valid());
  13903. // Consume body to allow trailers to be received/parsed
  13904. auto body = read_all(handle);
  13905. // Explicitly parse trailers (ensure trailers are available for assertion)
  13906. handle.parse_trailers_if_needed();
  13907. EXPECT_EQ(std::string("123456789"), body);
  13908. // The response should include a Trailer header declaring both names
  13909. ASSERT_TRUE(handle.response);
  13910. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13911. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13912. handle.response->get_header_value("Trailer"));
  13913. // Prohibited trailer must not be present
  13914. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13915. // Allowed trailer should be present
  13916. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13917. EXPECT_EQ(std::string("yes"),
  13918. handle.response->get_trailer_value("X-Allowed"));
  13919. // Verify trailers are NOT present as regular headers
  13920. EXPECT_EQ(std::string(""),
  13921. handle.response->get_header_value("Content-Length"));
  13922. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13923. }
  13924. static std::thread serve_single_response(std::promise<int> &port_promise,
  13925. const std::string &response) {
  13926. return std::thread([&port_promise, response] {
  13927. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13928. default_socket_options(srv);
  13929. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13930. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13931. sockaddr_in addr{};
  13932. addr.sin_family = AF_INET;
  13933. addr.sin_port = htons(0); // Let OS assign a free port
  13934. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13935. int opt = 1;
  13936. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13937. #ifdef _WIN32
  13938. reinterpret_cast<const char *>(&opt),
  13939. #else
  13940. &opt,
  13941. #endif
  13942. sizeof(opt));
  13943. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13944. ::listen(srv, 1) != 0) {
  13945. port_promise.set_value(-1);
  13946. detail::close_socket(srv);
  13947. return;
  13948. }
  13949. socklen_t addr_len = sizeof(addr);
  13950. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13951. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13952. sockaddr_in cli_addr{};
  13953. socklen_t cli_len = sizeof(cli_addr);
  13954. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13955. if (cli != INVALID_SOCKET) {
  13956. // Read the complete HTTP request (until the blank line that terminates
  13957. // headers) before sending the response. If the server closes the socket
  13958. // while the client's request data is still unread in the kernel receive
  13959. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13960. // connection on both sides: it discards the client's receive buffer
  13961. // (which already holds our response) and causes any in-progress write on
  13962. // the client to fail with ECONNRESET. Reading all request data first
  13963. // ensures close() emits a graceful FIN.
  13964. {
  13965. char rbuf[256];
  13966. std::string req;
  13967. while (req.find("\r\n\r\n") == std::string::npos) {
  13968. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13969. if (n <= 0) { break; }
  13970. req.append(rbuf, static_cast<size_t>(n));
  13971. }
  13972. }
  13973. ::send(cli,
  13974. #ifdef _WIN32
  13975. static_cast<const char *>(response.c_str()),
  13976. static_cast<int>(response.size()),
  13977. #else
  13978. response.c_str(), response.size(),
  13979. #endif
  13980. 0);
  13981. detail::close_socket(cli);
  13982. }
  13983. detail::close_socket(srv);
  13984. });
  13985. }
  13986. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13987. #ifndef _WIN32
  13988. signal(SIGPIPE, SIG_IGN);
  13989. #endif
  13990. std::promise<int> port_promise;
  13991. auto port_future = port_promise.get_future();
  13992. auto server_thread =
  13993. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13994. "Content-Type: text/plain\r\n"
  13995. "Content-Length: not-a-number\r\n"
  13996. "Connection: close\r\n"
  13997. "\r\n"
  13998. "hello");
  13999. auto port = port_future.get();
  14000. ASSERT_GT(port, 0);
  14001. Client cli("127.0.0.1", port);
  14002. auto handle = cli.open_stream("GET", "/");
  14003. EXPECT_FALSE(handle.is_valid());
  14004. server_thread.join();
  14005. }
  14006. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  14007. #ifndef _WIN32
  14008. signal(SIGPIPE, SIG_IGN);
  14009. #endif
  14010. std::promise<int> port_promise;
  14011. auto port_future = port_promise.get_future();
  14012. auto server_thread = serve_single_response(
  14013. port_promise, "HTTP/1.1 200 OK\r\n"
  14014. "Content-Type: text/plain\r\n"
  14015. "Content-Length: 99999999999999999999999999\r\n"
  14016. "Connection: close\r\n"
  14017. "\r\n"
  14018. "hello");
  14019. auto port = port_future.get();
  14020. ASSERT_GT(port, 0);
  14021. // Historically std::stoull would throw std::out_of_range here and crash
  14022. // the process, then parsing silently clamped to a bogus framing length and
  14023. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  14024. // so the stream fails to open, matching the not-a-number case above. The
  14025. // process still must NOT terminate.
  14026. Client cli("127.0.0.1", port);
  14027. auto handle = cli.open_stream("GET", "/");
  14028. EXPECT_FALSE(handle.is_valid());
  14029. server_thread.join();
  14030. }
  14031. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14032. TEST_F(OpenStreamTest, Gzip) {
  14033. Client cli("127.0.0.1", port_);
  14034. auto handle = cli.open_stream("GET", "/compressible", {},
  14035. {{"Accept-Encoding", "gzip"}});
  14036. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  14037. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14038. }
  14039. #endif
  14040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14041. TEST_F(OpenStreamTest, Brotli) {
  14042. Client cli("127.0.0.1", port_);
  14043. auto handle =
  14044. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  14045. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  14046. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14047. }
  14048. #endif
  14049. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14050. TEST_F(OpenStreamTest, Zstd) {
  14051. Client cli("127.0.0.1", port_);
  14052. auto handle = cli.open_stream("GET", "/compressible", {},
  14053. {{"Accept-Encoding", "zstd"}});
  14054. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  14055. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  14056. }
  14057. #endif
  14058. #ifdef CPPHTTPLIB_SSL_ENABLED
  14059. class SSLOpenStreamTest : public ::testing::Test {
  14060. protected:
  14061. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  14062. void SetUp() override {
  14063. svr_.Get("/hello", [](const Request &, Response &res) {
  14064. res.set_content("Hello SSL World!", "text/plain");
  14065. });
  14066. svr_.Get("/chunked", [](const Request &, Response &res) {
  14067. res.set_chunked_content_provider("text/plain",
  14068. [](size_t offset, DataSink &sink) {
  14069. if (offset < 15) {
  14070. sink.write("chunk", 5);
  14071. return true;
  14072. }
  14073. sink.done();
  14074. return true;
  14075. });
  14076. });
  14077. svr_.Post("/echo", [](const Request &req, Response &res) {
  14078. res.set_content(req.body, req.get_header_value("Content-Type"));
  14079. });
  14080. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  14081. std::string body = req.body;
  14082. res.set_chunked_content_provider(
  14083. "text/plain", [body](size_t offset, DataSink &sink) {
  14084. if (offset < body.size()) {
  14085. sink.write(body.data() + offset, body.size() - offset);
  14086. }
  14087. sink.done();
  14088. return true;
  14089. });
  14090. });
  14091. port_ = svr_.bind_to_any_port("127.0.0.1");
  14092. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14093. svr_.wait_until_ready();
  14094. }
  14095. void TearDown() override {
  14096. svr_.stop();
  14097. if (thread_.joinable()) thread_.join();
  14098. }
  14099. SSLServer svr_;
  14100. std::thread thread_;
  14101. int port_ = 0;
  14102. };
  14103. TEST_F(SSLOpenStreamTest, Basic) {
  14104. SSLClient cli("127.0.0.1", port_);
  14105. cli.enable_server_certificate_verification(false);
  14106. auto handle = cli.open_stream("GET", "/hello");
  14107. ASSERT_TRUE(handle.is_valid());
  14108. EXPECT_EQ("Hello SSL World!", read_all(handle));
  14109. }
  14110. TEST_F(SSLOpenStreamTest, Chunked) {
  14111. SSLClient cli("127.0.0.1", port_);
  14112. cli.enable_server_certificate_verification(false);
  14113. auto handle = cli.open_stream("GET", "/chunked");
  14114. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14115. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  14116. "Transfer-Encoding") == "chunked");
  14117. auto body = read_all(handle);
  14118. EXPECT_EQ("chunkchunkchunk", body);
  14119. }
  14120. TEST_F(SSLOpenStreamTest, Post) {
  14121. SSLClient cli("127.0.0.1", port_);
  14122. cli.enable_server_certificate_verification(false);
  14123. auto handle =
  14124. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  14125. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  14126. EXPECT_EQ(200, handle.response->status);
  14127. auto body = read_all(handle);
  14128. EXPECT_EQ("Hello SSL POST", body);
  14129. }
  14130. TEST_F(SSLOpenStreamTest, PostChunked) {
  14131. SSLClient cli("127.0.0.1", port_);
  14132. cli.enable_server_certificate_verification(false);
  14133. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  14134. "Chunked SSL Data", "text/plain");
  14135. ASSERT_TRUE(handle.is_valid());
  14136. EXPECT_EQ(200, handle.response->status);
  14137. auto body = read_all(handle);
  14138. EXPECT_EQ("Chunked SSL Data", body);
  14139. }
  14140. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  14141. // Content-Length is terminated by the server closing the connection. When the
  14142. // SSL peer sends a close_notify after the body, the client must treat it as a
  14143. // clean EOF and return a successful response rather than an error.
  14144. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  14145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14146. ASSERT_TRUE(svr.is_valid());
  14147. svr.set_keep_alive_max_count(1);
  14148. const std::string expected_body = "Hello from connection-close response!";
  14149. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  14150. res.set_content_provider("text/plain",
  14151. [&](size_t offset, DataSink &sink) -> bool {
  14152. if (offset < expected_body.size()) {
  14153. sink.write(expected_body.data() + offset,
  14154. expected_body.size() - offset);
  14155. }
  14156. sink.done();
  14157. return true;
  14158. });
  14159. });
  14160. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  14161. auto se = detail::scope_exit([&] {
  14162. svr.stop();
  14163. listen_thread.join();
  14164. ASSERT_FALSE(svr.is_running());
  14165. });
  14166. svr.wait_until_ready();
  14167. SSLClient cli(HOST, PORT);
  14168. cli.enable_server_certificate_verification(false);
  14169. auto res = cli.Get("/no-content-length");
  14170. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  14171. EXPECT_EQ(StatusCode::OK_200, res->status);
  14172. EXPECT_EQ(expected_body, res->body);
  14173. }
  14174. #endif // CPPHTTPLIB_SSL_ENABLED
  14175. //==============================================================================
  14176. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  14177. // results for various scenarios.
  14178. //==============================================================================
  14179. TEST(ParityTest, GetVsOpenStream) {
  14180. Server svr;
  14181. const std::string path = "/parity";
  14182. const std::string content = "Parity test content: hello world";
  14183. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14184. res.set_content(content, "text/plain");
  14185. });
  14186. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14187. auto se = detail::scope_exit([&] {
  14188. svr.stop();
  14189. t.join();
  14190. ASSERT_FALSE(svr.is_running());
  14191. });
  14192. svr.wait_until_ready();
  14193. Client cli(HOST, PORT);
  14194. // Non-stream path
  14195. auto r1 = cli.Get(path);
  14196. ASSERT_TRUE(r1);
  14197. EXPECT_EQ(StatusCode::OK_200, r1->status);
  14198. // Stream path
  14199. auto h = cli.open_stream("GET", path);
  14200. ASSERT_TRUE(h.is_valid());
  14201. EXPECT_EQ(r1->body, read_all(h));
  14202. }
  14203. // Helper to compress data with provided compressor type T
  14204. template <typename Compressor>
  14205. static std::string compress_payload_for_parity(const std::string &in) {
  14206. std::string out;
  14207. Compressor compressor;
  14208. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14209. [&](const char *data, size_t n) {
  14210. out.append(data, n);
  14211. return true;
  14212. });
  14213. EXPECT_TRUE(ok);
  14214. return out;
  14215. }
  14216. // Helper function for compression parity tests
  14217. template <typename Compressor>
  14218. static void test_compression_parity(const std::string &original,
  14219. const std::string &path,
  14220. const std::string &encoding) {
  14221. const std::string compressed =
  14222. compress_payload_for_parity<Compressor>(original);
  14223. Server svr;
  14224. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14225. res.set_content(compressed, "application/octet-stream");
  14226. res.set_header("Content-Encoding", encoding);
  14227. });
  14228. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14229. auto se = detail::scope_exit([&] {
  14230. svr.stop();
  14231. t.join();
  14232. ASSERT_FALSE(svr.is_running());
  14233. });
  14234. svr.wait_until_ready();
  14235. Client cli(HOST, PORT);
  14236. // Non-streaming
  14237. {
  14238. auto res = cli.Get(path);
  14239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14240. EXPECT_EQ(StatusCode::OK_200, res->status);
  14241. EXPECT_EQ(original, res->body);
  14242. }
  14243. // Streaming
  14244. {
  14245. auto h = cli.open_stream("GET", path);
  14246. ASSERT_TRUE(h.is_valid());
  14247. EXPECT_EQ(original, read_all(h));
  14248. }
  14249. }
  14250. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14251. TEST(ParityTest, Gzip) {
  14252. test_compression_parity<detail::gzip_compressor>(
  14253. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14254. }
  14255. #endif
  14256. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14257. TEST(ParityTest, Brotli) {
  14258. test_compression_parity<detail::brotli_compressor>(
  14259. "Hello, brotli parity test payload", "/parity-br", "br");
  14260. }
  14261. #endif
  14262. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14263. TEST(ParityTest, Zstd) {
  14264. test_compression_parity<detail::zstd_compressor>(
  14265. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14266. }
  14267. #endif
  14268. //==============================================================================
  14269. // New Stream API Tests
  14270. //==============================================================================
  14271. inline std::string read_body(httplib::stream::Result &result) {
  14272. std::string body;
  14273. while (result.next()) {
  14274. body.append(result.data(), result.size());
  14275. }
  14276. return body;
  14277. }
  14278. TEST(ClientConnectionTest, Basic) {
  14279. httplib::ClientConnection conn;
  14280. EXPECT_FALSE(conn.is_open());
  14281. conn.sock = 1;
  14282. EXPECT_TRUE(conn.is_open());
  14283. httplib::ClientConnection conn2(std::move(conn));
  14284. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14285. conn2.sock = INVALID_SOCKET;
  14286. }
  14287. // Unified test server for all stream::* tests
  14288. class StreamApiTest : public ::testing::Test {
  14289. protected:
  14290. void SetUp() override {
  14291. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14292. res.set_content("Hello World!", "text/plain");
  14293. });
  14294. svr_.Get("/echo-params",
  14295. [](const httplib::Request &req, httplib::Response &res) {
  14296. std::string r;
  14297. for (const auto &p : req.params) {
  14298. if (!r.empty()) r += "&";
  14299. r += p.first + "=" + p.second;
  14300. }
  14301. res.set_content(r, "text/plain");
  14302. });
  14303. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14304. res.set_content(req.body, req.get_header_value("Content-Type"));
  14305. });
  14306. svr_.Post("/echo-headers",
  14307. [](const httplib::Request &req, httplib::Response &res) {
  14308. std::string r;
  14309. for (const auto &h : req.headers)
  14310. r += h.first + ": " + h.second + "\n";
  14311. res.set_content(r, "text/plain");
  14312. });
  14313. svr_.Post("/echo-params",
  14314. [](const httplib::Request &req, httplib::Response &res) {
  14315. std::string r = "params:";
  14316. for (const auto &p : req.params)
  14317. r += p.first + "=" + p.second + ";";
  14318. res.set_content(r + " body:" + req.body, "text/plain");
  14319. });
  14320. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14321. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14322. });
  14323. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14324. res.set_content("PUT:" + req.body, "text/plain");
  14325. });
  14326. svr_.Patch("/echo",
  14327. [](const httplib::Request &req, httplib::Response &res) {
  14328. res.set_content("PATCH:" + req.body, "text/plain");
  14329. });
  14330. svr_.Delete(
  14331. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14332. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14333. "text/plain");
  14334. });
  14335. svr_.Get("/head-test",
  14336. [](const httplib::Request &, httplib::Response &res) {
  14337. res.set_content("body for HEAD", "text/plain");
  14338. });
  14339. svr_.Options("/options",
  14340. [](const httplib::Request &, httplib::Response &res) {
  14341. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14342. });
  14343. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14344. svr_.wait_until_ready();
  14345. }
  14346. void TearDown() override {
  14347. svr_.stop();
  14348. if (thread_.joinable()) thread_.join();
  14349. }
  14350. httplib::Server svr_;
  14351. std::thread thread_;
  14352. };
  14353. // stream::Get tests
  14354. TEST_F(StreamApiTest, GetBasic) {
  14355. httplib::Client cli(HOST, PORT);
  14356. auto result = httplib::stream::Get(cli, "/hello");
  14357. ASSERT_TRUE(result.is_valid());
  14358. EXPECT_EQ(200, result.status());
  14359. EXPECT_EQ("Hello World!", read_body(result));
  14360. }
  14361. TEST_F(StreamApiTest, GetWithParams) {
  14362. httplib::Client cli(HOST, PORT);
  14363. httplib::Params params{{"foo", "bar"}};
  14364. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14365. ASSERT_TRUE(result.is_valid());
  14366. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14367. }
  14368. TEST_F(StreamApiTest, GetConnectionError) {
  14369. httplib::Client cli(HOST, 9999);
  14370. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14371. }
  14372. TEST_F(StreamApiTest, Get404) {
  14373. httplib::Client cli(HOST, PORT);
  14374. auto result = httplib::stream::Get(cli, "/nonexistent");
  14375. EXPECT_TRUE(result.is_valid());
  14376. EXPECT_EQ(404, result.status());
  14377. }
  14378. // stream::Post tests
  14379. TEST_F(StreamApiTest, PostBasic) {
  14380. httplib::Client cli(HOST, PORT);
  14381. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14382. "application/json");
  14383. ASSERT_TRUE(result.is_valid());
  14384. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14385. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14386. }
  14387. TEST_F(StreamApiTest, PostWithHeaders) {
  14388. httplib::Client cli(HOST, PORT);
  14389. httplib::Headers headers{{"X-Custom", "value"}};
  14390. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14391. "text/plain");
  14392. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14393. }
  14394. TEST_F(StreamApiTest, PostWithParams) {
  14395. httplib::Client cli(HOST, PORT);
  14396. httplib::Params params{{"k", "v"}};
  14397. auto result =
  14398. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14399. auto body = read_body(result);
  14400. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14401. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14402. }
  14403. TEST_F(StreamApiTest, PostLarge) {
  14404. httplib::Client cli(HOST, PORT);
  14405. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14406. size_t total = 0;
  14407. while (result.next()) {
  14408. total += result.size();
  14409. }
  14410. EXPECT_EQ(100u * 1024u, total);
  14411. }
  14412. // stream::Put/Patch tests
  14413. TEST_F(StreamApiTest, PutAndPatch) {
  14414. httplib::Client cli(HOST, PORT);
  14415. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14416. EXPECT_EQ("PUT:test", read_body(put));
  14417. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14418. EXPECT_EQ("PATCH:test", read_body(patch));
  14419. }
  14420. // stream::Delete tests
  14421. TEST_F(StreamApiTest, Delete) {
  14422. httplib::Client cli(HOST, PORT);
  14423. auto del1 = httplib::stream::Delete(cli, "/resource");
  14424. EXPECT_EQ("Deleted", read_body(del1));
  14425. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14426. EXPECT_EQ("Deleted:data", read_body(del2));
  14427. }
  14428. // stream::Head/Options tests
  14429. TEST_F(StreamApiTest, HeadAndOptions) {
  14430. httplib::Client cli(HOST, PORT);
  14431. auto head = httplib::stream::Head(cli, "/head-test");
  14432. EXPECT_TRUE(head.is_valid());
  14433. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14434. auto opts = httplib::stream::Options(cli, "/options");
  14435. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14436. }
  14437. // SSL stream::* tests
  14438. #ifdef CPPHTTPLIB_SSL_ENABLED
  14439. class SSLStreamApiTest : public ::testing::Test {
  14440. protected:
  14441. void SetUp() override {
  14442. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14443. res.set_content("Hello SSL!", "text/plain");
  14444. });
  14445. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14446. res.set_content(req.body, "text/plain");
  14447. });
  14448. port_ = svr_.bind_to_any_port("127.0.0.1");
  14449. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14450. svr_.wait_until_ready();
  14451. }
  14452. void TearDown() override {
  14453. svr_.stop();
  14454. if (thread_.joinable()) thread_.join();
  14455. }
  14456. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14457. std::thread thread_;
  14458. int port_ = 0;
  14459. };
  14460. TEST_F(SSLStreamApiTest, GetAndPost) {
  14461. httplib::SSLClient cli("127.0.0.1", port_);
  14462. cli.enable_server_certificate_verification(false);
  14463. auto get = httplib::stream::Get(cli, "/hello");
  14464. EXPECT_EQ("Hello SSL!", read_body(get));
  14465. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14466. EXPECT_EQ("test", read_body(post));
  14467. }
  14468. #endif
  14469. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14470. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14471. // BodyReader
  14472. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14473. // Test that read timeout during streaming is detected
  14474. // Use a large content-length response where server delays mid-stream
  14475. Server svr;
  14476. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14477. // Send a large response with delay in the middle
  14478. res.set_content_provider(
  14479. 1000, // content_length
  14480. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14481. if (offset < 100) {
  14482. // Send first 100 bytes immediately
  14483. std::string data(100, 'A');
  14484. sink.write(data.c_str(), data.size());
  14485. return true;
  14486. }
  14487. // Then delay longer than client timeout
  14488. std::this_thread::sleep_for(std::chrono::seconds(3));
  14489. std::string data(900, 'B');
  14490. sink.write(data.c_str(), data.size());
  14491. return true;
  14492. });
  14493. });
  14494. auto port = 8091;
  14495. std::thread t([&]() { svr.listen("localhost", port); });
  14496. svr.wait_until_ready();
  14497. Client cli("localhost", port);
  14498. cli.set_read_timeout(1, 0); // 1 second timeout
  14499. auto handle = cli.open_stream("GET", "/slow-stream");
  14500. ASSERT_TRUE(handle.is_valid());
  14501. char buf[256];
  14502. ssize_t total = 0;
  14503. ssize_t n;
  14504. bool got_error = false;
  14505. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14506. total += n;
  14507. }
  14508. if (n < 0) {
  14509. got_error = true;
  14510. // Should be timeout or read error
  14511. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14512. handle.get_read_error() == Error::Read)
  14513. << "Actual error: " << to_string(handle.get_read_error());
  14514. }
  14515. // Either we got an error, or we got less data than expected
  14516. EXPECT_TRUE(got_error || total < 1000)
  14517. << "Expected timeout but got all " << total << " bytes";
  14518. svr.stop();
  14519. t.join();
  14520. }
  14521. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14522. // Test connection closed detection via BodyReader
  14523. Server svr;
  14524. std::atomic<bool> close_now{false};
  14525. svr.Get("/will-close", [&](const Request &, Response &res) {
  14526. res.set_content_provider(
  14527. 10000, // Large content_length that we won't fully send
  14528. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14529. if (offset < 100) {
  14530. std::string data(100, 'X');
  14531. sink.write(data.c_str(), data.size());
  14532. return true;
  14533. }
  14534. // Wait for signal then abort
  14535. while (!close_now) {
  14536. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14537. }
  14538. return false; // Abort - server will close connection
  14539. });
  14540. });
  14541. auto port = 8092;
  14542. std::thread t([&]() { svr.listen("localhost", port); });
  14543. svr.wait_until_ready();
  14544. Client cli("localhost", port);
  14545. auto handle = cli.open_stream("GET", "/will-close");
  14546. ASSERT_TRUE(handle.is_valid());
  14547. char buf[256];
  14548. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14549. EXPECT_GT(n, 0) << "First read should succeed";
  14550. // Signal server to close
  14551. close_now = true;
  14552. // Keep reading until error or EOF
  14553. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14554. // Keep reading
  14555. }
  14556. // Should get an error since content_length wasn't satisfied
  14557. if (n < 0) {
  14558. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14559. handle.get_read_error() == Error::Read)
  14560. << "Actual error: " << to_string(handle.get_read_error());
  14561. }
  14562. svr.stop();
  14563. t.join();
  14564. }
  14565. #ifdef CPPHTTPLIB_SSL_ENABLED
  14566. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14567. // Test that read timeout during SSL streaming is detected
  14568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14569. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14570. res.set_content_provider(
  14571. 1000, "text/plain",
  14572. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14573. if (offset < 100) {
  14574. std::string data(100, 'A');
  14575. sink.write(data.c_str(), data.size());
  14576. return true;
  14577. }
  14578. std::this_thread::sleep_for(std::chrono::seconds(3));
  14579. std::string data(900, 'B');
  14580. sink.write(data.c_str(), data.size());
  14581. return true;
  14582. });
  14583. });
  14584. auto port = 8093;
  14585. std::thread t([&]() { svr.listen("localhost", port); });
  14586. svr.wait_until_ready();
  14587. SSLClient cli("localhost", port);
  14588. cli.enable_server_certificate_verification(false);
  14589. cli.set_read_timeout(1, 0); // 1 second timeout
  14590. auto handle = cli.open_stream("GET", "/slow-stream");
  14591. ASSERT_TRUE(handle.is_valid());
  14592. char buf[256];
  14593. ssize_t total = 0;
  14594. ssize_t n;
  14595. bool got_error = false;
  14596. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14597. total += n;
  14598. }
  14599. if (n < 0) {
  14600. got_error = true;
  14601. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14602. handle.get_read_error() == Error::Read)
  14603. << "Actual error: " << to_string(handle.get_read_error());
  14604. }
  14605. EXPECT_TRUE(got_error || total < 1000)
  14606. << "Expected timeout but got all " << total << " bytes";
  14607. svr.stop();
  14608. t.join();
  14609. }
  14610. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14611. // Test SSL connection closed detection
  14612. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14613. std::atomic<bool> close_now{false};
  14614. svr.Get("/will-close", [&](const Request &, Response &res) {
  14615. res.set_content_provider(
  14616. 10000, "text/plain",
  14617. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14618. if (offset < 100) {
  14619. std::string data(100, 'X');
  14620. sink.write(data.c_str(), data.size());
  14621. return true;
  14622. }
  14623. while (!close_now) {
  14624. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14625. }
  14626. return false;
  14627. });
  14628. });
  14629. auto port = 8094;
  14630. std::thread t([&]() { svr.listen("localhost", port); });
  14631. svr.wait_until_ready();
  14632. SSLClient cli("localhost", port);
  14633. cli.enable_server_certificate_verification(false);
  14634. auto handle = cli.open_stream("GET", "/will-close");
  14635. ASSERT_TRUE(handle.is_valid());
  14636. char buf[256];
  14637. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14638. EXPECT_GT(n, 0);
  14639. // Signal server to close
  14640. close_now = true;
  14641. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14642. // Keep reading
  14643. }
  14644. if (n < 0) {
  14645. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14646. handle.get_read_error() == Error::Read)
  14647. << "Actual error: " << to_string(handle.get_read_error());
  14648. }
  14649. svr.stop();
  14650. t.join();
  14651. }
  14652. #endif
  14653. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14654. using namespace httplib;
  14655. // Create a test file
  14656. const char *fname = "etag_testfile.txt";
  14657. const char *content = "etag-content";
  14658. {
  14659. std::ofstream ofs(fname);
  14660. ofs << content;
  14661. ASSERT_TRUE(ofs.good());
  14662. }
  14663. Server svr;
  14664. svr.set_mount_point("/static", ".");
  14665. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14666. svr.wait_until_ready();
  14667. Client cli(HOST, PORT);
  14668. // First request: should get 200 with ETag header
  14669. auto res1 = cli.Get("/static/etag_testfile.txt");
  14670. ASSERT_TRUE(res1);
  14671. ASSERT_EQ(200, res1->status);
  14672. ASSERT_TRUE(res1->has_header("ETag"));
  14673. std::string etag = res1->get_header_value("ETag");
  14674. EXPECT_FALSE(etag.empty());
  14675. // Verify ETag format: W/"hex-hex"
  14676. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14677. EXPECT_EQ('W', etag[0]);
  14678. EXPECT_EQ('/', etag[1]);
  14679. EXPECT_EQ('"', etag[2]);
  14680. EXPECT_EQ('"', etag.back());
  14681. // Exact match: expect 304 Not Modified
  14682. Headers h2 = {{"If-None-Match", etag}};
  14683. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14684. ASSERT_TRUE(res2);
  14685. EXPECT_EQ(304, res2->status);
  14686. // Wildcard match: expect 304 Not Modified
  14687. Headers h3 = {{"If-None-Match", "*"}};
  14688. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14689. ASSERT_TRUE(res3);
  14690. EXPECT_EQ(304, res3->status);
  14691. // Non-matching ETag: expect 200
  14692. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14693. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14694. ASSERT_TRUE(res4);
  14695. EXPECT_EQ(200, res4->status);
  14696. // Multiple ETags with one matching: expect 304
  14697. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14698. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14699. ASSERT_TRUE(res5);
  14700. EXPECT_EQ(304, res5->status);
  14701. svr.stop();
  14702. t.join();
  14703. std::remove(fname);
  14704. }
  14705. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14706. using namespace httplib;
  14707. Server svr;
  14708. svr.set_mount_point("/static", ".");
  14709. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14710. svr.wait_until_ready();
  14711. Client cli(HOST, PORT);
  14712. // Send If-None-Match: * to a non-existent file
  14713. Headers h = {{"If-None-Match", "*"}};
  14714. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14716. EXPECT_EQ(404, res->status);
  14717. svr.stop();
  14718. t.join();
  14719. }
  14720. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14721. using namespace httplib;
  14722. // Create a test file
  14723. const char *fname = "etag_boundary_testfile.txt";
  14724. const char *content = "boundary-test";
  14725. {
  14726. std::ofstream ofs(fname);
  14727. ofs << content;
  14728. ASSERT_TRUE(ofs.good());
  14729. }
  14730. Server svr;
  14731. svr.set_mount_point("/static", ".");
  14732. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14733. svr.wait_until_ready();
  14734. Client cli(HOST, PORT);
  14735. // Get the actual ETag
  14736. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14737. ASSERT_TRUE(res1);
  14738. ASSERT_EQ(200, res1->status);
  14739. ASSERT_TRUE(res1->has_header("ETag"));
  14740. std::string etag = res1->get_header_value("ETag");
  14741. // Test 1: Very long ETag value (longer than actual ETag)
  14742. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14743. Headers h1 = {{"If-None-Match", "W/"
  14744. "\"very-long-etag-value-that-is-much-longer-"
  14745. "than-the-actual-etag-value\""}};
  14746. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14747. ASSERT_TRUE(res2);
  14748. EXPECT_EQ(200, res2->status); // Should not match
  14749. // Test 2: Long string followed by wildcard
  14750. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14751. // string)
  14752. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14753. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14754. ASSERT_TRUE(res3);
  14755. EXPECT_EQ(304, res3->status); // Should match on "*"
  14756. // Test 3: Wildcard followed by long string
  14757. // Should match on "*" immediately and return 304
  14758. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14759. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14760. ASSERT_TRUE(res4);
  14761. EXPECT_EQ(304, res4->status); // Should match on "*"
  14762. // Test 4: Multiple long non-matching values
  14763. // Should NOT match and return 200 (test that all comparisons are safe)
  14764. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14765. "W/\"second-long-non-matching-value\", "
  14766. "W/\"third-long-non-matching-value\""}};
  14767. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14768. ASSERT_TRUE(res5);
  14769. EXPECT_EQ(200, res5->status); // Should not match
  14770. // Test 5: Single character that is not "*" (edge case)
  14771. Headers h5 = {{"If-None-Match", "X"}};
  14772. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14773. ASSERT_TRUE(res6);
  14774. EXPECT_EQ(200, res6->status); // Should not match
  14775. svr.stop();
  14776. t.join();
  14777. std::remove(fname);
  14778. }
  14779. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14780. using namespace httplib;
  14781. // Create a test file
  14782. const char *fname = "ims_testfile.txt";
  14783. const char *content = "if-modified-since-test";
  14784. {
  14785. std::ofstream ofs(fname);
  14786. ofs << content;
  14787. ASSERT_TRUE(ofs.good());
  14788. }
  14789. Server svr;
  14790. svr.set_mount_point("/static", ".");
  14791. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14792. svr.wait_until_ready();
  14793. Client cli(HOST, PORT);
  14794. // First request: should get 200 with Last-Modified header
  14795. auto res1 = cli.Get("/static/ims_testfile.txt");
  14796. ASSERT_TRUE(res1);
  14797. ASSERT_EQ(200, res1->status);
  14798. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14799. std::string last_modified = res1->get_header_value("Last-Modified");
  14800. EXPECT_FALSE(last_modified.empty());
  14801. // If-Modified-Since with same time: expect 304
  14802. Headers h2 = {{"If-Modified-Since", last_modified}};
  14803. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14804. ASSERT_TRUE(res2);
  14805. EXPECT_EQ(304, res2->status);
  14806. // If-Modified-Since with future time: expect 304
  14807. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14808. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14809. ASSERT_TRUE(res3);
  14810. EXPECT_EQ(304, res3->status);
  14811. // If-Modified-Since with past time: expect 200
  14812. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14813. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14814. ASSERT_TRUE(res4);
  14815. EXPECT_EQ(200, res4->status);
  14816. // If-None-Match takes precedence over If-Modified-Since
  14817. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14818. ASSERT_TRUE(res1->has_header("ETag"));
  14819. std::string etag = res1->get_header_value("ETag");
  14820. Headers h5 = {{"If-None-Match", etag},
  14821. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14822. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14823. ASSERT_TRUE(res5);
  14824. EXPECT_EQ(304, res5->status);
  14825. svr.stop();
  14826. t.join();
  14827. std::remove(fname);
  14828. }
  14829. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14830. using namespace httplib;
  14831. Server svr;
  14832. // Endpoint that returns compressible content
  14833. svr.Get("/compressible", [](const Request &, Response &res) {
  14834. // Return a large enough body to trigger compression
  14835. std::string body(1000, 'a');
  14836. res.set_content(body, "text/plain");
  14837. });
  14838. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14839. svr.wait_until_ready();
  14840. Client cli(HOST, PORT);
  14841. // Request with gzip support: should get Vary header when compressed
  14842. cli.set_compress(true);
  14843. auto res1 = cli.Get("/compressible");
  14844. ASSERT_TRUE(res1);
  14845. EXPECT_EQ(200, res1->status);
  14846. // If Content-Encoding is set, Vary should also be set
  14847. if (res1->has_header("Content-Encoding")) {
  14848. EXPECT_TRUE(res1->has_header("Vary"));
  14849. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14850. }
  14851. // Request without Accept-Encoding header: should not have compression
  14852. Headers h_no_compress;
  14853. auto res2 = cli.Get("/compressible", h_no_compress);
  14854. ASSERT_TRUE(res2);
  14855. EXPECT_EQ(200, res2->status);
  14856. // Verify Vary header is present when compression is applied
  14857. // (the exact behavior depends on server configuration)
  14858. svr.stop();
  14859. t.join();
  14860. }
  14861. TEST(ETagTest, IfRangeWithETag) {
  14862. using namespace httplib;
  14863. // Create a test file with known content
  14864. const char *fname = "if_range_testfile.txt";
  14865. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14866. {
  14867. std::ofstream ofs(fname);
  14868. ofs << content;
  14869. ASSERT_TRUE(ofs.good());
  14870. }
  14871. Server svr;
  14872. svr.set_mount_point("/static", ".");
  14873. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14874. svr.wait_until_ready();
  14875. Client cli(HOST, PORT);
  14876. // First request: get ETag
  14877. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14878. ASSERT_TRUE(res1);
  14879. ASSERT_EQ(200, res1->status);
  14880. ASSERT_TRUE(res1->has_header("ETag"));
  14881. std::string etag = res1->get_header_value("ETag");
  14882. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14883. // Since our server generates weak ETags (W/"..."), If-Range with our
  14884. // ETag should NOT result in partial content - it should return full content.
  14885. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14886. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14887. ASSERT_TRUE(res2);
  14888. // Weak ETag in If-Range -> full content (200), not partial (206)
  14889. EXPECT_EQ(200, res2->status);
  14890. EXPECT_EQ(content, res2->body);
  14891. EXPECT_FALSE(res2->has_header("Content-Range"));
  14892. // Range request with non-matching If-Range (ETag): should get 200 (full
  14893. // content)
  14894. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14895. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14896. ASSERT_TRUE(res3);
  14897. EXPECT_EQ(200, res3->status);
  14898. EXPECT_EQ(content, res3->body);
  14899. EXPECT_FALSE(res3->has_header("Content-Range"));
  14900. // Range request with strong ETag (hypothetical - our server doesn't generate
  14901. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14902. // should return full content)
  14903. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14904. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14905. ASSERT_TRUE(res4);
  14906. EXPECT_EQ(200, res4->status);
  14907. EXPECT_EQ(content, res4->body);
  14908. EXPECT_FALSE(res4->has_header("Content-Range"));
  14909. svr.stop();
  14910. t.join();
  14911. std::remove(fname);
  14912. }
  14913. TEST(ETagTest, IfRangeWithDate) {
  14914. using namespace httplib;
  14915. // Create a test file
  14916. const char *fname = "if_range_date_testfile.txt";
  14917. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14918. {
  14919. std::ofstream ofs(fname);
  14920. ofs << content;
  14921. ASSERT_TRUE(ofs.good());
  14922. }
  14923. Server svr;
  14924. svr.set_mount_point("/static", ".");
  14925. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14926. svr.wait_until_ready();
  14927. Client cli(HOST, PORT);
  14928. // First request: get Last-Modified
  14929. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14930. ASSERT_TRUE(res1);
  14931. ASSERT_EQ(200, res1->status);
  14932. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14933. std::string last_modified = res1->get_header_value("Last-Modified");
  14934. // Range request with matching If-Range (date): should get 206
  14935. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14936. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14937. ASSERT_TRUE(res2);
  14938. EXPECT_EQ(206, res2->status);
  14939. EXPECT_EQ("FGHIJ", res2->body);
  14940. // Range request with old If-Range date: should get 200 (full content)
  14941. Headers h3 = {{"Range", "bytes=5-9"},
  14942. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14943. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14944. ASSERT_TRUE(res3);
  14945. EXPECT_EQ(200, res3->status);
  14946. EXPECT_EQ(content, res3->body);
  14947. // Range request with future If-Range date: should get 206
  14948. Headers h4 = {{"Range", "bytes=0-4"},
  14949. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14950. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14951. ASSERT_TRUE(res4);
  14952. EXPECT_EQ(206, res4->status);
  14953. EXPECT_EQ("ABCDE", res4->body);
  14954. svr.stop();
  14955. t.join();
  14956. std::remove(fname);
  14957. }
  14958. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14959. using namespace httplib;
  14960. const char *fname = "etag_malformed.txt";
  14961. const char *content = "malformed-etag";
  14962. {
  14963. std::ofstream ofs(fname);
  14964. ofs << content;
  14965. ASSERT_TRUE(ofs.good());
  14966. }
  14967. Server svr;
  14968. svr.set_mount_point("/static", ".");
  14969. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14970. svr.wait_until_ready();
  14971. Client cli(HOST, PORT);
  14972. // baseline: should get 200 and an ETag
  14973. auto res1 = cli.Get("/static/etag_malformed.txt");
  14974. ASSERT_TRUE(res1);
  14975. ASSERT_EQ(200, res1->status);
  14976. ASSERT_TRUE(res1->has_header("ETag"));
  14977. // Malformed ETag value (missing quotes) should be treated as non-matching
  14978. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14979. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14980. ASSERT_TRUE(res_bad);
  14981. EXPECT_EQ(200, res_bad->status);
  14982. // Whitespace-only header value should be considered invalid / non-matching
  14983. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14984. "Host: localhost\r\n"
  14985. "If-None-Match: \r\n"
  14986. "Connection: close\r\n"
  14987. "\r\n";
  14988. std::string out;
  14989. ASSERT_TRUE(send_request(5, raw_req, &out));
  14990. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14991. svr.stop();
  14992. t.join();
  14993. std::remove(fname);
  14994. }
  14995. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14996. using namespace httplib;
  14997. const char *fname = "ims_invalid_format.txt";
  14998. const char *content = "ims-bad-format";
  14999. {
  15000. std::ofstream ofs(fname);
  15001. ofs << content;
  15002. ASSERT_TRUE(ofs.good());
  15003. }
  15004. Server svr;
  15005. svr.set_mount_point("/static", ".");
  15006. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15007. svr.wait_until_ready();
  15008. Client cli(HOST, PORT);
  15009. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  15010. ASSERT_TRUE(res1);
  15011. ASSERT_EQ(200, res1->status);
  15012. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15013. // If-Modified-Since with invalid format should not result in 304
  15014. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  15015. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  15016. ASSERT_TRUE(res_bad);
  15017. EXPECT_EQ(200, res_bad->status);
  15018. // If-Range with invalid date format should be treated as mismatch -> full
  15019. // content (200)
  15020. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  15021. {"If-Range", "invalid-date"}};
  15022. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  15023. ASSERT_TRUE(res_ifrange);
  15024. EXPECT_EQ(200, res_ifrange->status);
  15025. svr.stop();
  15026. t.join();
  15027. std::remove(fname);
  15028. }
  15029. TEST(ETagTest, IfRangeWithMalformedETag) {
  15030. using namespace httplib;
  15031. const char *fname = "ifrange_malformed.txt";
  15032. const std::string content = "0123456789";
  15033. {
  15034. std::ofstream ofs(fname);
  15035. ofs << content;
  15036. ASSERT_TRUE(ofs.good());
  15037. }
  15038. Server svr;
  15039. svr.set_mount_point("/static", ".");
  15040. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15041. svr.wait_until_ready();
  15042. Client cli(HOST, PORT);
  15043. // First request: get ETag
  15044. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  15045. ASSERT_TRUE(res1);
  15046. ASSERT_EQ(200, res1->status);
  15047. ASSERT_TRUE(res1->has_header("ETag"));
  15048. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  15049. // full content (200)
  15050. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  15051. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  15052. ASSERT_TRUE(res2);
  15053. EXPECT_EQ(200, res2->status);
  15054. EXPECT_EQ(content, res2->body);
  15055. svr.stop();
  15056. t.join();
  15057. std::remove(fname);
  15058. }
  15059. TEST(ETagTest, ExtremeLargeDateValues) {
  15060. using namespace httplib;
  15061. const char *fname = "ims_extreme_date.txt";
  15062. const char *content = "ims-extreme-date";
  15063. {
  15064. std::ofstream ofs(fname);
  15065. ofs << content;
  15066. ASSERT_TRUE(ofs.good());
  15067. }
  15068. Server svr;
  15069. svr.set_mount_point("/static", ".");
  15070. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15071. svr.wait_until_ready();
  15072. Client cli(HOST, PORT);
  15073. auto res1 = cli.Get(std::string("/static/") + fname);
  15074. ASSERT_TRUE(res1);
  15075. ASSERT_EQ(200, res1->status);
  15076. ASSERT_TRUE(res1->has_header("Last-Modified"));
  15077. // Extremely large year that may overflow date parsing routines.
  15078. Headers h_large_date = {
  15079. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15080. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  15081. ASSERT_TRUE(res_bad);
  15082. // Expect server to treat this as invalid/mismatch and return full content
  15083. EXPECT_EQ(200, res_bad->status);
  15084. // If-Range with extremely large date should be treated as mismatch -> full
  15085. // content (200)
  15086. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  15087. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15088. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  15089. ASSERT_TRUE(res_ifrange);
  15090. EXPECT_EQ(200, res_ifrange->status);
  15091. svr.stop();
  15092. t.join();
  15093. std::remove(fname);
  15094. }
  15095. TEST(ETagTest, NegativeFileModificationTime) {
  15096. using namespace httplib;
  15097. const char *fname = "ims_negative_mtime.txt";
  15098. const std::string content = "negative-mtime";
  15099. {
  15100. std::ofstream ofs(fname);
  15101. ofs << content;
  15102. ASSERT_TRUE(ofs.good());
  15103. }
  15104. // Try to set file mtime to a negative value. This may fail on some
  15105. // platforms/filesystems; if it fails, the test will still verify server
  15106. // behaves safely by performing a regular conditional request.
  15107. #if defined(__APPLE__) || defined(__linux__)
  15108. bool set_negative = false;
  15109. do {
  15110. struct timeval times[2];
  15111. // access time: now
  15112. times[0].tv_sec = time(nullptr);
  15113. times[0].tv_usec = 0;
  15114. // modification time: negative (e.g., -1)
  15115. times[1].tv_sec = -1;
  15116. times[1].tv_usec = 0;
  15117. if (utimes(fname, times) == 0) { set_negative = true; }
  15118. } while (0);
  15119. #else
  15120. bool set_negative = false;
  15121. #endif
  15122. Server svr;
  15123. svr.set_mount_point("/static", ".");
  15124. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15125. svr.wait_until_ready();
  15126. Client cli(HOST, PORT);
  15127. auto res1 = cli.Get(std::string("/static/") + fname);
  15128. ASSERT_TRUE(res1);
  15129. ASSERT_EQ(200, res1->status);
  15130. bool has_last_modified = res1->has_header("Last-Modified");
  15131. std::string last_modified;
  15132. if (has_last_modified) {
  15133. last_modified = res1->get_header_value("Last-Modified");
  15134. }
  15135. if (set_negative) {
  15136. // If we successfully set a negative mtime, ensure server returns a
  15137. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  15138. // with an old date and ensure server handles it without crash.
  15139. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  15140. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  15141. ASSERT_TRUE(res2);
  15142. // Behavior may vary; at minimum ensure server responds (200 or 304).
  15143. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  15144. } else {
  15145. // Could not set negative mtime on this platform; fall back to verifying
  15146. // that normal invalid/malformed dates are treated safely (non-304).
  15147. Headers h_bad_date = {
  15148. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  15149. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  15150. ASSERT_TRUE(res_bad);
  15151. EXPECT_EQ(200, res_bad->status);
  15152. }
  15153. svr.stop();
  15154. t.join();
  15155. std::remove(fname);
  15156. }
  15157. //==============================================================================
  15158. // SSE Parsing Tests
  15159. //==============================================================================
  15160. class SSEParsingTest : public ::testing::Test {
  15161. protected:
  15162. // Test helper that mimics SSE parsing behavior
  15163. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  15164. int &retry_ms) {
  15165. // Blank line signals end of event
  15166. if (line.empty() || line == "\r") { return true; }
  15167. // Lines starting with ':' are comments (ignored)
  15168. if (!line.empty() && line[0] == ':') { return false; }
  15169. // Find the colon separator
  15170. auto colon_pos = line.find(':');
  15171. if (colon_pos == std::string::npos) {
  15172. // Line with no colon is treated as field name with empty value
  15173. return false;
  15174. }
  15175. std::string field = line.substr(0, colon_pos);
  15176. std::string value;
  15177. // Value starts after colon, skip optional single space
  15178. if (colon_pos + 1 < line.size()) {
  15179. size_t value_start = colon_pos + 1;
  15180. if (line[value_start] == ' ') { value_start++; }
  15181. value = line.substr(value_start);
  15182. // Remove trailing \r if present
  15183. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  15184. }
  15185. // Handle known fields
  15186. if (field == "event") {
  15187. msg.event = value;
  15188. } else if (field == "data") {
  15189. // Multiple data lines are concatenated with newlines
  15190. if (!msg.data.empty()) { msg.data += "\n"; }
  15191. msg.data += value;
  15192. } else if (field == "id") {
  15193. // Empty id is valid (clears the last event ID)
  15194. msg.id = value;
  15195. } else if (field == "retry") {
  15196. // Parse retry interval in milliseconds
  15197. {
  15198. int v = 0;
  15199. auto res =
  15200. detail::from_chars(value.data(), value.data() + value.size(), v);
  15201. if (res.ec == std::errc{}) { retry_ms = v; }
  15202. }
  15203. }
  15204. // Unknown fields are ignored per SSE spec
  15205. return false;
  15206. }
  15207. };
  15208. // Test: Single-line data
  15209. TEST_F(SSEParsingTest, SingleLineData) {
  15210. sse::SSEMessage msg;
  15211. int retry_ms = 3000;
  15212. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15213. EXPECT_EQ(msg.data, "hello");
  15214. EXPECT_EQ(msg.event, "message");
  15215. // Blank line ends event
  15216. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15217. }
  15218. // Test: Multi-line data
  15219. TEST_F(SSEParsingTest, MultiLineData) {
  15220. sse::SSEMessage msg;
  15221. int retry_ms = 3000;
  15222. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15223. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15224. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15225. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15226. }
  15227. // Test: Custom event types
  15228. TEST_F(SSEParsingTest, CustomEventType) {
  15229. sse::SSEMessage msg;
  15230. int retry_ms = 3000;
  15231. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15232. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15233. EXPECT_EQ(msg.event, "update");
  15234. EXPECT_EQ(msg.data, "payload");
  15235. }
  15236. // Test: Event ID handling
  15237. TEST_F(SSEParsingTest, EventIdHandling) {
  15238. sse::SSEMessage msg;
  15239. int retry_ms = 3000;
  15240. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15241. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15242. EXPECT_EQ(msg.id, "12345");
  15243. }
  15244. // Test: Empty event ID (clears last event ID)
  15245. TEST_F(SSEParsingTest, EmptyEventId) {
  15246. sse::SSEMessage msg;
  15247. msg.id = "previous";
  15248. int retry_ms = 3000;
  15249. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15250. EXPECT_EQ(msg.id, "");
  15251. }
  15252. // Test: Retry field parsing
  15253. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15254. sse::SSEMessage msg;
  15255. int retry_ms = 3000;
  15256. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15257. EXPECT_EQ(retry_ms, 5000);
  15258. }
  15259. // Test: Invalid retry value
  15260. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15261. sse::SSEMessage msg;
  15262. int retry_ms = 3000;
  15263. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15264. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15265. }
  15266. // Test: Comments (lines starting with :)
  15267. TEST_F(SSEParsingTest, CommentsIgnored) {
  15268. sse::SSEMessage msg;
  15269. int retry_ms = 3000;
  15270. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15271. EXPECT_EQ(msg.data, "");
  15272. EXPECT_EQ(msg.event, "message");
  15273. }
  15274. // Test: Colon in value
  15275. TEST_F(SSEParsingTest, ColonInValue) {
  15276. sse::SSEMessage msg;
  15277. int retry_ms = 3000;
  15278. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15279. EXPECT_EQ(msg.data, "hello:world:test");
  15280. }
  15281. // Test: Line with no colon (field name only)
  15282. TEST_F(SSEParsingTest, FieldNameOnly) {
  15283. sse::SSEMessage msg;
  15284. int retry_ms = 3000;
  15285. // According to SSE spec, this is treated as field name with empty value
  15286. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15287. // Since we don't recognize "data" without colon, data should be empty
  15288. EXPECT_EQ(msg.data, "");
  15289. }
  15290. // Test: Trailing \r handling
  15291. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15292. sse::SSEMessage msg;
  15293. int retry_ms = 3000;
  15294. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15295. EXPECT_EQ(msg.data, "hello");
  15296. }
  15297. // Test: Unknown fields ignored
  15298. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15299. sse::SSEMessage msg;
  15300. int retry_ms = 3000;
  15301. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15302. EXPECT_EQ(msg.data, "");
  15303. EXPECT_EQ(msg.event, "message");
  15304. }
  15305. // Test: Space after colon is optional
  15306. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15307. sse::SSEMessage msg1, msg2;
  15308. int retry_ms = 3000;
  15309. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15310. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15311. EXPECT_EQ(msg1.data, "hello");
  15312. EXPECT_EQ(msg2.data, "hello");
  15313. }
  15314. // Test: SSEMessage clear
  15315. TEST_F(SSEParsingTest, MessageClear) {
  15316. sse::SSEMessage msg;
  15317. msg.event = "custom";
  15318. msg.data = "some data";
  15319. msg.id = "123";
  15320. msg.clear();
  15321. EXPECT_EQ(msg.event, "message");
  15322. EXPECT_EQ(msg.data, "");
  15323. EXPECT_EQ(msg.id, "");
  15324. }
  15325. // Test: Complete event parsing
  15326. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15327. sse::SSEMessage msg;
  15328. int retry_ms = 3000;
  15329. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15330. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15331. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15332. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15333. // Blank line ends event
  15334. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15335. EXPECT_EQ(msg.event, "notification");
  15336. EXPECT_EQ(msg.id, "evt-42");
  15337. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15338. EXPECT_EQ(retry_ms, 1000);
  15339. }
  15340. //==============================================================================
  15341. // Integration Tests with Server
  15342. //==============================================================================
  15343. class SSEIntegrationTest : public ::testing::Test {
  15344. protected:
  15345. void SetUp() override {
  15346. stop_server_.store(false);
  15347. events_.clear();
  15348. server_ = httplib::detail::make_unique<Server>();
  15349. setup_server();
  15350. start_server();
  15351. }
  15352. void TearDown() override {
  15353. stop_server_.store(true);
  15354. event_cv_.notify_all();
  15355. server_->stop();
  15356. if (server_thread_.joinable()) { server_thread_.join(); }
  15357. }
  15358. void setup_server() {
  15359. // Simple SSE endpoint
  15360. server_->Get("/events", [this](const Request &req, Response &res) {
  15361. auto last_id = req.get_header_value("Last-Event-ID");
  15362. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15363. res.set_chunked_content_provider(
  15364. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15365. std::unique_lock<std::mutex> lock(event_mutex_);
  15366. if (event_cv_.wait_for(
  15367. lock, std::chrono::milliseconds(200), [this] {
  15368. return !events_.empty() || stop_server_.load();
  15369. })) {
  15370. if (stop_server_.load()) { return false; }
  15371. if (!events_.empty()) {
  15372. std::string event = events_.front();
  15373. events_.erase(events_.begin());
  15374. sink.write(event.data(), event.size());
  15375. return true;
  15376. }
  15377. }
  15378. return !stop_server_.load();
  15379. });
  15380. });
  15381. // Endpoint that returns error
  15382. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15383. res.status = 500;
  15384. res.set_content("Internal Server Error", "text/plain");
  15385. });
  15386. // Endpoint for custom event types
  15387. server_->Get("/custom-events", [](const Request &, Response &res) {
  15388. res.set_chunked_content_provider(
  15389. "text/event-stream", [](size_t offset, DataSink &sink) {
  15390. if (offset == 0) {
  15391. std::string event = "event: update\ndata: updated\n\n"
  15392. "event: delete\ndata: deleted\n\n";
  15393. sink.write(event.data(), event.size());
  15394. }
  15395. return false; // End stream after sending
  15396. });
  15397. });
  15398. }
  15399. void start_server() {
  15400. port_ = server_->bind_to_any_port(HOST);
  15401. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15402. // Wait for server to start
  15403. while (!server_->is_running()) {
  15404. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15405. }
  15406. }
  15407. int get_port() const { return port_; }
  15408. void send_event(const std::string &event) {
  15409. std::lock_guard<std::mutex> lock(event_mutex_);
  15410. events_.push_back(event);
  15411. event_cv_.notify_all();
  15412. }
  15413. std::unique_ptr<Server> server_;
  15414. std::thread server_thread_;
  15415. std::mutex event_mutex_;
  15416. std::condition_variable event_cv_;
  15417. std::vector<std::string> events_;
  15418. std::atomic<bool> stop_server_{false};
  15419. std::string last_received_event_id_;
  15420. int port_ = 0;
  15421. };
  15422. // Test: Successful connection and on_open callback
  15423. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15424. // Add a simple endpoint that sends one event and closes
  15425. server_->Get("/simple-event", [](const Request &, Response &res) {
  15426. res.set_chunked_content_provider(
  15427. "text/event-stream", [](size_t offset, DataSink &sink) {
  15428. if (offset == 0) {
  15429. std::string event = "data: hello\n\n";
  15430. sink.write(event.data(), event.size());
  15431. }
  15432. return false; // Close stream after sending
  15433. });
  15434. });
  15435. Client client("localhost", get_port());
  15436. sse::SSEClient sse(client, "/simple-event");
  15437. std::atomic<bool> open_called{false};
  15438. std::atomic<bool> message_received{false};
  15439. sse.on_open([&open_called]() { open_called.store(true); });
  15440. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15441. if (msg.data == "hello") { message_received.store(true); }
  15442. });
  15443. sse.set_reconnect_interval(100);
  15444. sse.set_max_reconnect_attempts(1);
  15445. // Start async
  15446. sse.start_async();
  15447. // Wait for message to be processed
  15448. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15449. sse.stop();
  15450. EXPECT_TRUE(open_called.load());
  15451. EXPECT_TRUE(message_received.load());
  15452. }
  15453. // Test: on_message callback
  15454. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15455. // Endpoint that sends multiple events then closes
  15456. server_->Get("/multi-event", [](const Request &, Response &res) {
  15457. res.set_chunked_content_provider(
  15458. "text/event-stream", [](size_t offset, DataSink &sink) {
  15459. if (offset == 0) {
  15460. std::string events = "data: message1\n\ndata: message2\n\n";
  15461. sink.write(events.data(), events.size());
  15462. }
  15463. return false;
  15464. });
  15465. });
  15466. Client client("localhost", get_port());
  15467. sse::SSEClient sse(client, "/multi-event");
  15468. std::vector<std::string> received_messages;
  15469. std::mutex messages_mutex;
  15470. sse.on_message([&](const sse::SSEMessage &msg) {
  15471. std::lock_guard<std::mutex> lock(messages_mutex);
  15472. received_messages.push_back(msg.data);
  15473. });
  15474. sse.set_reconnect_interval(100);
  15475. sse.set_max_reconnect_attempts(1);
  15476. sse.start_async();
  15477. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15478. sse.stop();
  15479. std::lock_guard<std::mutex> lock(messages_mutex);
  15480. EXPECT_GE(received_messages.size(), 2u);
  15481. if (received_messages.size() >= 2) {
  15482. EXPECT_EQ(received_messages[0], "message1");
  15483. EXPECT_EQ(received_messages[1], "message2");
  15484. }
  15485. }
  15486. // Test: on_event for specific types
  15487. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15488. Client client("localhost", get_port());
  15489. sse::SSEClient sse(client, "/custom-events");
  15490. std::atomic<bool> update_received{false};
  15491. std::atomic<bool> delete_received{false};
  15492. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15493. if (msg.data == "updated") { update_received.store(true); }
  15494. });
  15495. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15496. if (msg.data == "deleted") { delete_received.store(true); }
  15497. });
  15498. sse.set_max_reconnect_attempts(1);
  15499. sse.start_async();
  15500. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15501. sse.stop();
  15502. EXPECT_TRUE(update_received.load());
  15503. EXPECT_TRUE(delete_received.load());
  15504. }
  15505. // Test: on_error callback on connection failure
  15506. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15507. // Connect to a non-existent port
  15508. Client client("localhost", 59999);
  15509. sse::SSEClient sse(client, "/events");
  15510. std::atomic<bool> error_called{false};
  15511. Error received_error = Error::Success;
  15512. sse.on_error([&](Error err) {
  15513. error_called.store(true);
  15514. received_error = err;
  15515. });
  15516. sse.set_reconnect_interval(50);
  15517. sse.set_max_reconnect_attempts(1);
  15518. sse.start_async();
  15519. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15520. sse.stop();
  15521. EXPECT_TRUE(error_called.load());
  15522. EXPECT_NE(received_error, Error::Success);
  15523. }
  15524. // Test: Last-Event-ID header sent on reconnect
  15525. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15526. // Endpoint that sends event with ID
  15527. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15528. res.set_chunked_content_provider(
  15529. "text/event-stream", [](size_t offset, DataSink &sink) {
  15530. if (offset == 0) {
  15531. std::string event = "id: evt-123\ndata: test\n\n";
  15532. sink.write(event.data(), event.size());
  15533. }
  15534. return false;
  15535. });
  15536. });
  15537. Client client("localhost", get_port());
  15538. sse::SSEClient sse(client, "/event-with-id");
  15539. std::atomic<bool> id_received{false};
  15540. sse.on_message([&](const sse::SSEMessage &msg) {
  15541. if (!msg.id.empty()) { id_received.store(true); }
  15542. });
  15543. sse.set_reconnect_interval(100);
  15544. sse.set_max_reconnect_attempts(1);
  15545. sse.start_async();
  15546. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15547. sse.stop();
  15548. EXPECT_TRUE(id_received.load());
  15549. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15550. }
  15551. // Test: Manual stop
  15552. TEST_F(SSEIntegrationTest, ManualStop) {
  15553. // Endpoint that sends one event and stays open briefly
  15554. std::atomic<bool> handler_running{true};
  15555. server_->Get("/stay-open", [&handler_running](const Request &,
  15556. Response &res) {
  15557. res.set_chunked_content_provider(
  15558. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15559. if (offset == 0) {
  15560. std::string event = "data: connected\n\n";
  15561. sink.write(event.data(), event.size());
  15562. }
  15563. // Keep connection open while handler_running is true
  15564. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15565. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15566. }
  15567. return false;
  15568. });
  15569. });
  15570. Client client("localhost", get_port());
  15571. sse::SSEClient sse(client, "/stay-open");
  15572. std::atomic<bool> connected{false};
  15573. sse.on_open([&connected]() { connected.store(true); });
  15574. sse.set_reconnect_interval(100);
  15575. sse.set_max_reconnect_attempts(1);
  15576. sse.start_async();
  15577. // Wait for connection to establish
  15578. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15579. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15580. }
  15581. EXPECT_TRUE(connected.load());
  15582. EXPECT_TRUE(sse.is_connected());
  15583. // Signal handler to stop
  15584. handler_running.store(false);
  15585. // Stop SSE client
  15586. sse.stop();
  15587. EXPECT_FALSE(sse.is_connected());
  15588. }
  15589. // Test: SSEClient with custom headers
  15590. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15591. // Setup a server endpoint that checks for custom header
  15592. std::atomic<bool> header_received{false};
  15593. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15594. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15595. header_received.store(true);
  15596. }
  15597. res.set_chunked_content_provider("text/event-stream",
  15598. [](size_t, DataSink &) { return false; });
  15599. });
  15600. Client client("localhost", get_port());
  15601. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15602. sse::SSEClient sse(client, "/header-check", headers);
  15603. sse.set_max_reconnect_attempts(1);
  15604. sse.start_async();
  15605. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15606. sse.stop();
  15607. EXPECT_TRUE(header_received.load());
  15608. }
  15609. // Test: Reconnect interval configuration
  15610. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15611. Client client("localhost", get_port());
  15612. sse::SSEClient sse(client, "/events");
  15613. auto &result = sse.set_reconnect_interval(500);
  15614. // Builder pattern should return reference to self
  15615. EXPECT_EQ(&result, &sse);
  15616. }
  15617. // Test: Max reconnect attempts
  15618. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15619. // Connect to non-existent port to force reconnects
  15620. Client client("localhost", 59998);
  15621. sse::SSEClient sse(client, "/events");
  15622. std::atomic<int> error_count{0};
  15623. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15624. sse.set_reconnect_interval(50);
  15625. sse.set_max_reconnect_attempts(2);
  15626. auto start = std::chrono::steady_clock::now();
  15627. sse.start(); // Blocking call
  15628. auto end = std::chrono::steady_clock::now();
  15629. // Should have stopped after 2 failed attempts
  15630. EXPECT_GE(error_count.load(), 2);
  15631. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15632. auto duration =
  15633. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15634. #ifdef _WIN32
  15635. // Windows is much slower for socket connection failures
  15636. EXPECT_LT(duration.count(), 7000);
  15637. #else
  15638. EXPECT_LT(duration.count(), 1000);
  15639. #endif
  15640. }
  15641. // Test: Multi-line data in integration
  15642. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15643. // Endpoint with multi-line data
  15644. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15645. res.set_chunked_content_provider(
  15646. "text/event-stream", [](size_t offset, DataSink &sink) {
  15647. if (offset == 0) {
  15648. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15649. sink.write(event.data(), event.size());
  15650. }
  15651. return false;
  15652. });
  15653. });
  15654. Client client("localhost", get_port());
  15655. sse::SSEClient sse(client, "/multiline-data");
  15656. std::string received_data;
  15657. std::mutex data_mutex;
  15658. sse.on_message([&](const sse::SSEMessage &msg) {
  15659. std::lock_guard<std::mutex> lock(data_mutex);
  15660. received_data = msg.data;
  15661. });
  15662. sse.set_reconnect_interval(100);
  15663. sse.set_max_reconnect_attempts(1);
  15664. sse.start_async();
  15665. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15666. sse.stop();
  15667. std::lock_guard<std::mutex> lock(data_mutex);
  15668. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15669. }
  15670. // Test: Auto-reconnect after server disconnection
  15671. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15672. std::atomic<int> connection_count{0};
  15673. std::atomic<int> message_count{0};
  15674. // Endpoint that sends one event and closes, forcing reconnect
  15675. server_->Get("/reconnect-test",
  15676. [&connection_count](const Request &, Response &res) {
  15677. connection_count.fetch_add(1);
  15678. res.set_chunked_content_provider(
  15679. "text/event-stream", [](size_t offset, DataSink &sink) {
  15680. if (offset == 0) {
  15681. std::string event = "data: hello\n\n";
  15682. sink.write(event.data(), event.size());
  15683. }
  15684. return false; // Close connection after sending
  15685. });
  15686. });
  15687. Client client("localhost", get_port());
  15688. sse::SSEClient sse(client, "/reconnect-test");
  15689. sse.on_message([&message_count](const sse::SSEMessage &) {
  15690. message_count.fetch_add(1);
  15691. });
  15692. sse.set_reconnect_interval(100);
  15693. sse.set_max_reconnect_attempts(3);
  15694. sse.start_async();
  15695. // Wait long enough for multiple reconnects
  15696. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15697. sse.stop();
  15698. // Should have connected multiple times (initial + reconnects)
  15699. EXPECT_GE(connection_count.load(), 2);
  15700. // Should have received messages from multiple connections
  15701. EXPECT_GE(message_count.load(), 2);
  15702. }
  15703. // Test: Last-Event-ID sent on reconnect
  15704. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15705. std::atomic<int> connection_count{0};
  15706. std::vector<std::string> received_last_event_ids;
  15707. std::mutex id_mutex;
  15708. // Endpoint that checks Last-Event-ID header and sends event with ID
  15709. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15710. int conn = connection_count.fetch_add(1);
  15711. // Capture the Last-Event-ID header from each connection
  15712. {
  15713. std::lock_guard<std::mutex> lock(id_mutex);
  15714. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15715. }
  15716. res.set_chunked_content_provider(
  15717. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15718. if (offset == 0) {
  15719. std::string event =
  15720. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15721. sink.write(event.data(), event.size());
  15722. }
  15723. return false;
  15724. });
  15725. });
  15726. Client client("localhost", get_port());
  15727. sse::SSEClient sse(client, "/reconnect-with-id");
  15728. sse.set_reconnect_interval(100);
  15729. sse.set_max_reconnect_attempts(3);
  15730. sse.start_async();
  15731. // Wait for at least 2 connections
  15732. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15733. sse.stop();
  15734. // Verify behavior
  15735. std::lock_guard<std::mutex> lock(id_mutex);
  15736. EXPECT_GE(received_last_event_ids.size(), 2u);
  15737. // First connection should have no Last-Event-ID
  15738. if (!received_last_event_ids.empty()) {
  15739. EXPECT_EQ(received_last_event_ids[0], "");
  15740. }
  15741. // Second connection should have Last-Event-ID from first connection
  15742. if (received_last_event_ids.size() >= 2) {
  15743. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15744. }
  15745. }
  15746. // Test: set_headers updates headers used on reconnect
  15747. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15748. std::vector<std::string> received_tokens;
  15749. std::mutex token_mutex;
  15750. // Endpoint that captures Authorization header
  15751. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15752. {
  15753. std::lock_guard<std::mutex> lock(token_mutex);
  15754. received_tokens.push_back(req.get_header_value("Authorization"));
  15755. }
  15756. res.set_chunked_content_provider(
  15757. "text/event-stream", [](size_t offset, DataSink &sink) {
  15758. if (offset == 0) {
  15759. std::string event = "data: hello\n\n";
  15760. sink.write(event.data(), event.size());
  15761. }
  15762. return false; // Close connection to trigger reconnect
  15763. });
  15764. });
  15765. Client client("localhost", get_port());
  15766. Headers headers = {{"Authorization", "Bearer old-token"}};
  15767. sse::SSEClient sse(client, "/auth-check", headers);
  15768. // Update headers on each successful connection
  15769. sse.on_open(
  15770. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15771. sse.set_reconnect_interval(100);
  15772. sse.set_max_reconnect_attempts(3);
  15773. sse.start_async();
  15774. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15775. sse.stop();
  15776. std::lock_guard<std::mutex> lock(token_mutex);
  15777. ASSERT_GE(received_tokens.size(), 2u);
  15778. // First connection uses original header
  15779. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15780. // Second connection uses updated header from set_headers
  15781. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15782. }
  15783. // Test: 401 allows reconnection (so on_error can refresh headers)
  15784. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15785. std::atomic<int> connection_count{0};
  15786. // Endpoint: returns 401 on first attempt, 200 on second
  15787. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15788. int conn = connection_count.fetch_add(1);
  15789. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15790. res.status = StatusCode::Unauthorized_401;
  15791. res.set_content("Unauthorized", "text/plain");
  15792. return;
  15793. }
  15794. res.set_chunked_content_provider(
  15795. "text/event-stream", [](size_t offset, DataSink &sink) {
  15796. if (offset == 0) {
  15797. std::string event = "data: authenticated\n\n";
  15798. sink.write(event.data(), event.size());
  15799. }
  15800. return false;
  15801. });
  15802. });
  15803. Client client("localhost", get_port());
  15804. Headers headers = {{"Authorization", "Bearer expired"}};
  15805. sse::SSEClient sse(client, "/auth-retry", headers);
  15806. std::atomic<bool> message_received{false};
  15807. // Refresh token on error
  15808. sse.on_error(
  15809. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15810. sse.on_message([&](const sse::SSEMessage &msg) {
  15811. if (msg.data == "authenticated") { message_received.store(true); }
  15812. });
  15813. sse.set_reconnect_interval(100);
  15814. sse.set_max_reconnect_attempts(3);
  15815. sse.start_async();
  15816. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15817. sse.stop();
  15818. // Should have reconnected after 401 and succeeded with new token
  15819. EXPECT_GE(connection_count.load(), 2);
  15820. EXPECT_TRUE(message_received.load());
  15821. }
  15822. TEST(Issue2318Test, EmptyHostString) {
  15823. {
  15824. httplib::Client cli_empty("", PORT);
  15825. auto res = cli_empty.Get("/");
  15826. ASSERT_FALSE(res);
  15827. EXPECT_EQ(httplib::Error::Connection, res.error());
  15828. }
  15829. {
  15830. httplib::Client cli(" ", PORT);
  15831. auto res = cli.Get("/");
  15832. ASSERT_FALSE(res);
  15833. EXPECT_EQ(httplib::Error::Connection, res.error());
  15834. }
  15835. }
  15836. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15837. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15838. Server svr;
  15839. // Set a small payload limit (1KB)
  15840. svr.set_payload_max_length(1024);
  15841. svr.Post("/test", [&](const Request &req, Response &res) {
  15842. res.set_content("Body size: " + std::to_string(req.body.size()),
  15843. "text/plain");
  15844. });
  15845. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15846. auto se = detail::scope_exit([&] {
  15847. svr.stop();
  15848. listen_thread.join();
  15849. });
  15850. svr.wait_until_ready();
  15851. // Create data that compresses well but exceeds limit when decompressed
  15852. // 8KB of repeated null bytes compresses to a very small size
  15853. std::string original_data(8 * 1024, '\0');
  15854. // Compress the data using gzip
  15855. std::string compressed_data;
  15856. detail::gzip_compressor compressor;
  15857. compressor.compress(original_data.data(), original_data.size(), true,
  15858. [&](const char *data, size_t size) {
  15859. compressed_data.append(data, size);
  15860. return true;
  15861. });
  15862. // Verify compression worked (compressed should be much smaller)
  15863. ASSERT_LT(compressed_data.size(), original_data.size());
  15864. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15865. // Send compressed data with Content-Encoding: gzip
  15866. Client cli(HOST, PORT);
  15867. Headers headers = {{"Content-Encoding", "gzip"}};
  15868. auto res =
  15869. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15870. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15872. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15873. }
  15874. #endif
  15875. // ============================================================================
  15876. // OpenSSL-Specific Tests
  15877. // ============================================================================
  15878. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15879. X509 *readCertificate(const std::string &strFileName) {
  15880. std::ifstream inStream(strFileName);
  15881. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15882. std::istreambuf_iterator<char>());
  15883. if (strCertPEM.empty()) return (nullptr);
  15884. BIO *pbCert = BIO_new(BIO_s_mem());
  15885. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15886. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15887. BIO_free(pbCert);
  15888. return (pCert);
  15889. }
  15890. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15891. std::ifstream inStream(strFileName);
  15892. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15893. std::istreambuf_iterator<char>());
  15894. if (strPrivateKeyPEM.empty()) return (nullptr);
  15895. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15896. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15897. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15898. BIO_free(pbPrivKey);
  15899. return (pPrivateKey);
  15900. }
  15901. TEST(BindServerTest, UpdateCerts) {
  15902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15903. int port = svr.bind_to_any_port("0.0.0.0");
  15904. ASSERT_TRUE(svr.is_valid());
  15905. ASSERT_TRUE(port > 0);
  15906. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15907. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15908. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15909. ASSERT_TRUE(cert != nullptr);
  15910. ASSERT_TRUE(ca_cert != nullptr);
  15911. ASSERT_TRUE(key != nullptr);
  15912. X509_STORE *cert_store = X509_STORE_new();
  15913. X509_STORE_add_cert(cert_store, ca_cert);
  15914. // svr.update_certs(cert, key, cert_store); // deprecated
  15915. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15916. CLIENT_CA_CERT_FILE);
  15917. ASSERT_TRUE(svr.is_valid());
  15918. svr.stop();
  15919. X509_STORE_free(cert_store);
  15920. X509_free(cert);
  15921. X509_free(ca_cert);
  15922. EVP_PKEY_free(key);
  15923. }
  15924. // Test that update_certs() updates client CA list correctly
  15925. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15926. // Start with file-based constructor
  15927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15928. ASSERT_TRUE(svr.is_valid());
  15929. // Initially no client CA list should be set
  15930. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15931. ASSERT_TRUE(ssl_ctx != nullptr);
  15932. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15933. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15934. EXPECT_EQ(0, count_before);
  15935. // Now update with client CA (PEM string)
  15936. std::string cert_pem, key_pem, ca_pem;
  15937. read_file(SERVER_CERT_FILE, cert_pem);
  15938. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15939. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15940. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15941. ASSERT_TRUE(svr.is_valid());
  15942. // Now client CA list should be set
  15943. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15944. ASSERT_TRUE(ca_list_after != nullptr);
  15945. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15946. }
  15947. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15948. // Test that the file-path SSLServer constructor properly sets the client CA
  15949. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15951. ASSERT_TRUE(svr.is_valid());
  15952. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15953. ASSERT_TRUE(ssl_ctx != nullptr);
  15954. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15955. ASSERT_TRUE(ca_list != nullptr);
  15956. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15957. }
  15958. #endif
  15959. // ============================================================================
  15960. // MbedTLS-Specific Tests
  15961. // ============================================================================
  15962. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15963. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15964. using namespace httplib::tls;
  15965. // Track if callback was invoked
  15966. bool callback_invoked = false;
  15967. // The callback receives void* ctx which is actually MbedTlsContext*
  15968. // We can access the mbedtls_ssl_config via the context
  15969. auto setup_callback = [&callback_invoked](void *ctx) {
  15970. callback_invoked = true;
  15971. // Cast to MbedTlsContext* to access the ssl config
  15972. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15973. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15974. // Use static variables to hold certificate data (simplified for test)
  15975. static mbedtls_x509_crt own_cert;
  15976. static mbedtls_pk_context own_key;
  15977. static mbedtls_x509_crt ca_chain;
  15978. static bool initialized = false;
  15979. if (!initialized) {
  15980. mbedtls_x509_crt_init(&own_cert);
  15981. mbedtls_pk_init(&own_key);
  15982. mbedtls_x509_crt_init(&ca_chain);
  15983. // Load server certificate
  15984. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15985. return false;
  15986. }
  15987. // Load server private key.
  15988. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15989. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15990. #if MBEDTLS_VERSION_MAJOR == 3
  15991. ,
  15992. mbedtls_ctr_drbg_random, nullptr
  15993. #endif
  15994. ) != 0) {
  15995. return false;
  15996. }
  15997. // Load CA chain for client verification
  15998. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15999. return false;
  16000. }
  16001. initialized = true;
  16002. }
  16003. // Configure the SSL config
  16004. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  16005. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  16006. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  16007. // Set minimum TLS version using mbedTLS native API
  16008. #if MBEDTLS_VERSION_MAJOR >= 3
  16009. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  16010. #else
  16011. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  16012. MBEDTLS_SSL_MINOR_VERSION_3);
  16013. #endif
  16014. return true;
  16015. };
  16016. SSLServer svr(setup_callback);
  16017. ASSERT_TRUE(svr.is_valid());
  16018. ASSERT_TRUE(callback_invoked);
  16019. svr.Get("/test", [&](const Request &req, Response &res) {
  16020. res.set_content("test", "text/plain");
  16021. auto cert = req.peer_cert();
  16022. ASSERT_TRUE(static_cast<bool>(cert));
  16023. auto common_name = cert.subject_cn();
  16024. EXPECT_EQ("Common Name", common_name);
  16025. });
  16026. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16027. auto se = detail::scope_exit([&] {
  16028. svr.stop();
  16029. t.join();
  16030. ASSERT_FALSE(svr.is_running());
  16031. });
  16032. svr.wait_until_ready();
  16033. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16034. cli.enable_server_certificate_verification(false);
  16035. cli.set_connection_timeout(30);
  16036. auto res = cli.Get("/test");
  16037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16038. ASSERT_EQ(StatusCode::OK_200, res->status);
  16039. }
  16040. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  16041. // context (owning mbedtls_ssl_config) before shutting down a still-open
  16042. // keep-alive SSL session, which reads through that config in
  16043. // mbedtls_ssl_close_notify.
  16044. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  16045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16046. ASSERT_TRUE(svr.is_valid());
  16047. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16048. res.set_content("test", "text/plain");
  16049. });
  16050. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  16051. auto se = detail::scope_exit([&] {
  16052. svr.stop();
  16053. t.join();
  16054. ASSERT_FALSE(svr.is_running());
  16055. });
  16056. svr.wait_until_ready();
  16057. {
  16058. SSLClient cli(HOST, PORT);
  16059. cli.enable_server_certificate_verification(false);
  16060. cli.set_keep_alive(true);
  16061. auto res = cli.Get("/test");
  16062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16063. ASSERT_EQ(StatusCode::OK_200, res->status);
  16064. // cli is destructed here with the keep-alive SSL session still open.
  16065. }
  16066. }
  16067. #endif
  16068. // WebSocket Tests
  16069. TEST(WebSocketTest, RSVBitsMustBeZero) {
  16070. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  16071. // defining the meaning of these bits has been negotiated.
  16072. auto make_frame = [](uint8_t first_byte) {
  16073. std::string frame;
  16074. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  16075. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  16076. frame += "Hello";
  16077. return frame;
  16078. };
  16079. // RSV1 set (0x40)
  16080. {
  16081. detail::BufferStream strm;
  16082. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  16083. ws::Opcode opcode;
  16084. std::string payload;
  16085. bool fin;
  16086. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16087. false, 1024));
  16088. }
  16089. // RSV2 set (0x20)
  16090. {
  16091. detail::BufferStream strm;
  16092. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  16093. ws::Opcode opcode;
  16094. std::string payload;
  16095. bool fin;
  16096. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16097. false, 1024));
  16098. }
  16099. // RSV3 set (0x10)
  16100. {
  16101. detail::BufferStream strm;
  16102. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  16103. ws::Opcode opcode;
  16104. std::string payload;
  16105. bool fin;
  16106. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16107. false, 1024));
  16108. }
  16109. // No RSV bits set - should succeed
  16110. {
  16111. detail::BufferStream strm;
  16112. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  16113. ws::Opcode opcode;
  16114. std::string payload;
  16115. bool fin;
  16116. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16117. false, 1024));
  16118. EXPECT_EQ(ws::Opcode::Text, opcode);
  16119. EXPECT_EQ("Hello", payload);
  16120. EXPECT_TRUE(fin);
  16121. }
  16122. }
  16123. TEST(WebSocketTest, ControlFrameValidation) {
  16124. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  16125. // payload length <= 125.
  16126. // Ping with FIN=0 - must be rejected
  16127. {
  16128. detail::BufferStream strm;
  16129. std::string frame;
  16130. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  16131. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16132. strm.write(frame.data(), frame.size());
  16133. ws::Opcode opcode;
  16134. std::string payload;
  16135. bool fin;
  16136. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16137. false, 1024));
  16138. }
  16139. // Close with FIN=0 - must be rejected
  16140. {
  16141. detail::BufferStream strm;
  16142. std::string frame;
  16143. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  16144. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  16145. strm.write(frame.data(), frame.size());
  16146. ws::Opcode opcode;
  16147. std::string payload;
  16148. bool fin;
  16149. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16150. false, 1024));
  16151. }
  16152. // Ping with payload_len=126 (extended length) - must be rejected
  16153. {
  16154. detail::BufferStream strm;
  16155. std::string frame;
  16156. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16157. frame += static_cast<char>(126); // payload_len=126 (>125)
  16158. frame += static_cast<char>(0x00); // extended length high byte
  16159. frame += static_cast<char>(126); // extended length low byte
  16160. frame += std::string(126, 'x');
  16161. strm.write(frame.data(), frame.size());
  16162. ws::Opcode opcode;
  16163. std::string payload;
  16164. bool fin;
  16165. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16166. false, 1024));
  16167. }
  16168. // Ping with FIN=1 and payload_len=125 - should succeed
  16169. {
  16170. detail::BufferStream strm;
  16171. std::string frame;
  16172. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  16173. frame += static_cast<char>(125); // payload_len=125
  16174. frame += std::string(125, 'x');
  16175. strm.write(frame.data(), frame.size());
  16176. ws::Opcode opcode;
  16177. std::string payload;
  16178. bool fin;
  16179. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16180. false, 1024));
  16181. EXPECT_EQ(ws::Opcode::Ping, opcode);
  16182. EXPECT_EQ(125u, payload.size());
  16183. EXPECT_TRUE(fin);
  16184. }
  16185. }
  16186. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  16187. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  16188. // length MUST be 0.
  16189. // MSB set - must be rejected
  16190. {
  16191. detail::BufferStream strm;
  16192. std::string frame;
  16193. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16194. frame += static_cast<char>(127); // 64-bit extended length
  16195. frame += static_cast<char>(0x80); // MSB set (invalid)
  16196. frame += std::string(7, '\0'); // remaining 7 bytes of length
  16197. strm.write(frame.data(), frame.size());
  16198. ws::Opcode opcode;
  16199. std::string payload;
  16200. bool fin;
  16201. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16202. false, 1024));
  16203. }
  16204. // MSB clear - should pass length parsing (will be rejected by max_len,
  16205. // but that's a different check; use a small length to verify)
  16206. {
  16207. detail::BufferStream strm;
  16208. std::string frame;
  16209. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16210. frame += static_cast<char>(127); // 64-bit extended length
  16211. frame += std::string(7, '\0'); // high bytes = 0
  16212. frame += static_cast<char>(0x03); // length = 3
  16213. frame += "abc";
  16214. strm.write(frame.data(), frame.size());
  16215. ws::Opcode opcode;
  16216. std::string payload;
  16217. bool fin;
  16218. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16219. false, 1024));
  16220. EXPECT_EQ(ws::Opcode::Text, opcode);
  16221. EXPECT_EQ("abc", payload);
  16222. }
  16223. }
  16224. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16225. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16226. // Valid UTF-8
  16227. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16228. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16229. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16230. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16231. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16232. // Invalid UTF-8
  16233. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16234. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16235. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16236. EXPECT_FALSE(
  16237. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16238. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16239. }
  16240. TEST(WebSocketTest, ConnectAndDisconnect) {
  16241. Server svr;
  16242. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16243. std::string msg;
  16244. while (ws.read(msg)) {}
  16245. });
  16246. auto port = svr.bind_to_any_port(HOST);
  16247. std::thread t([&]() { svr.listen_after_bind(); });
  16248. svr.wait_until_ready();
  16249. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16250. ASSERT_TRUE(client.connect());
  16251. EXPECT_TRUE(client.is_open());
  16252. client.close();
  16253. EXPECT_FALSE(client.is_open());
  16254. svr.stop();
  16255. t.join();
  16256. }
  16257. TEST(WebSocketTest, ValidURL) {
  16258. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16259. EXPECT_TRUE(ws1.is_valid());
  16260. ws::WebSocketClient ws2("ws://example.com/path");
  16261. EXPECT_TRUE(ws2.is_valid());
  16262. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16263. EXPECT_TRUE(ws3.is_valid());
  16264. #ifdef CPPHTTPLIB_SSL_ENABLED
  16265. ws::WebSocketClient wss1("wss://example.com/path");
  16266. EXPECT_TRUE(wss1.is_valid());
  16267. ws::WebSocketClient wss2("wss://example.com:443/path");
  16268. EXPECT_TRUE(wss2.is_valid());
  16269. #endif
  16270. }
  16271. TEST(WebSocketTest, InvalidURL) {
  16272. // No scheme
  16273. ws::WebSocketClient ws1("localhost:8080/path");
  16274. EXPECT_FALSE(ws1.is_valid());
  16275. // No path
  16276. ws::WebSocketClient ws2("ws://localhost:8080");
  16277. EXPECT_FALSE(ws2.is_valid());
  16278. // Empty string
  16279. ws::WebSocketClient ws3("");
  16280. EXPECT_FALSE(ws3.is_valid());
  16281. // Missing host
  16282. ws::WebSocketClient ws4("ws://:8080/path");
  16283. EXPECT_FALSE(ws4.is_valid());
  16284. // Port number overflow — should not crash
  16285. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16286. EXPECT_FALSE(ws5.is_valid());
  16287. // Port out of range
  16288. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16289. EXPECT_FALSE(ws6.is_valid());
  16290. }
  16291. TEST(WebSocketTest, UnsupportedScheme) {
  16292. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16293. ws::WebSocketClient ws1("http://localhost:8080/path");
  16294. EXPECT_FALSE(ws1.is_valid());
  16295. ws::WebSocketClient ws2("https://localhost:8080/path");
  16296. EXPECT_FALSE(ws2.is_valid());
  16297. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16298. EXPECT_FALSE(ws3.is_valid());
  16299. #else
  16300. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16301. std::invalid_argument);
  16302. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16303. std::invalid_argument);
  16304. #endif
  16305. }
  16306. TEST(WebSocketTest, ConnectWhenInvalid) {
  16307. ws::WebSocketClient ws("not a valid url");
  16308. EXPECT_FALSE(ws.is_valid());
  16309. EXPECT_FALSE(ws.connect());
  16310. }
  16311. TEST(WebSocketTest, DefaultPort) {
  16312. ws::WebSocketClient ws1("ws://example.com/path");
  16313. EXPECT_TRUE(ws1.is_valid());
  16314. // ws:// defaults to port 80 (verified by successful parse)
  16315. #ifdef CPPHTTPLIB_SSL_ENABLED
  16316. ws::WebSocketClient ws2("wss://example.com/path");
  16317. EXPECT_TRUE(ws2.is_valid());
  16318. // wss:// defaults to port 443 (verified by successful parse)
  16319. #endif
  16320. }
  16321. TEST(WebSocketTest, IPv6LiteralAddress) {
  16322. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16323. EXPECT_TRUE(ws1.is_valid());
  16324. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16325. EXPECT_TRUE(ws2.is_valid());
  16326. }
  16327. TEST(WebSocketTest, ComplexPath) {
  16328. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16329. EXPECT_TRUE(ws1.is_valid());
  16330. ws::WebSocketClient ws2("ws://localhost:8080/");
  16331. EXPECT_TRUE(ws2.is_valid());
  16332. }
  16333. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16334. Server svr;
  16335. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16336. std::string msg;
  16337. while (ws.read(msg)) {}
  16338. });
  16339. auto port = svr.bind_to_any_port(HOST);
  16340. std::thread t([&]() { svr.listen_after_bind(); });
  16341. svr.wait_until_ready();
  16342. auto another_host = "example.com";
  16343. auto wrong_ip = "192.0.2.1";
  16344. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16345. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16346. ASSERT_TRUE(client.connect());
  16347. EXPECT_TRUE(client.is_open());
  16348. client.close();
  16349. svr.stop();
  16350. t.join();
  16351. }
  16352. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16353. Server svr;
  16354. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16355. std::string msg;
  16356. while (ws.read(msg)) {}
  16357. });
  16358. auto port = svr.bind_to_any_port(HOST);
  16359. std::thread t([&]() { svr.listen_after_bind(); });
  16360. svr.wait_until_ready();
  16361. auto wrong_ip = "192.0.2.1";
  16362. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16363. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16364. client.set_connection_timeout(1);
  16365. client.set_read_timeout(1);
  16366. client.set_write_timeout(1);
  16367. EXPECT_FALSE(client.connect());
  16368. EXPECT_FALSE(client.is_open());
  16369. svr.stop();
  16370. t.join();
  16371. }
  16372. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16373. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16374. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16375. // (RFC 6761) is only a map key and the Host header value.
  16376. auto host = "target.invalid";
  16377. Server svr;
  16378. std::string received_host;
  16379. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16380. received_host = req.get_header_value("Host");
  16381. std::string msg;
  16382. while (ws.read(msg)) {}
  16383. });
  16384. auto port = svr.bind_to_any_port(HOST);
  16385. std::thread t([&]() { svr.listen_after_bind(); });
  16386. // ASSERT_* below returns from the test body, which would leave t joinable
  16387. // and make ~thread call std::terminate.
  16388. auto se = detail::scope_exit([&] {
  16389. svr.stop();
  16390. if (t.joinable()) { t.join(); }
  16391. });
  16392. svr.wait_until_ready();
  16393. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16394. std::to_string(port) + "/ws");
  16395. client.set_hostname_addr_map({{host, HOST}});
  16396. ASSERT_TRUE(client.connect());
  16397. EXPECT_TRUE(client.is_open());
  16398. client.close();
  16399. svr.stop();
  16400. t.join();
  16401. // The mapping only redirects the connection; the identity stays host_.
  16402. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16403. }
  16404. class WebSocketIntegrationTest : public ::testing::Test {
  16405. protected:
  16406. void SetUp() override {
  16407. server_ = httplib::detail::make_unique<Server>();
  16408. setup_server();
  16409. start_server();
  16410. }
  16411. void TearDown() override {
  16412. server_->stop();
  16413. if (server_thread_.joinable()) { server_thread_.join(); }
  16414. }
  16415. void setup_server() {
  16416. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16417. std::string msg;
  16418. ws::ReadResult ret;
  16419. while ((ret = ws.read(msg))) {
  16420. if (ret == ws::Binary) {
  16421. ws.send(msg.data(), msg.size());
  16422. } else {
  16423. ws.send(msg);
  16424. }
  16425. }
  16426. });
  16427. server_->WebSocket("/ws-echo-string",
  16428. [](const Request &, ws::WebSocket &ws) {
  16429. std::string msg;
  16430. while (ws.read(msg)) {
  16431. ws.send("echo: " + msg);
  16432. }
  16433. });
  16434. server_->WebSocket(
  16435. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16436. // Echo back request metadata
  16437. ws.send("path:" + req.path);
  16438. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16439. std::string msg;
  16440. while (ws.read(msg)) {}
  16441. });
  16442. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16443. std::string msg;
  16444. ws.read(msg); // wait for a message
  16445. ws.close();
  16446. });
  16447. server_->WebSocket("/ws-close-status",
  16448. [](const Request &, ws::WebSocket &ws) {
  16449. std::string msg;
  16450. ws.read(msg); // wait for a message
  16451. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16452. });
  16453. server_->WebSocket(
  16454. "/ws-subprotocol",
  16455. [](const Request &, ws::WebSocket &ws) {
  16456. std::string msg;
  16457. while (ws.read(msg)) {
  16458. ws.send(msg);
  16459. }
  16460. },
  16461. [](const std::vector<std::string> &protocols) -> std::string {
  16462. for (const auto &p : protocols) {
  16463. if (p == "graphql-ws") { return p; }
  16464. }
  16465. return "";
  16466. });
  16467. }
  16468. void start_server() {
  16469. port_ = server_->bind_to_any_port(HOST);
  16470. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16471. server_->wait_until_ready();
  16472. }
  16473. std::unique_ptr<Server> server_;
  16474. std::thread server_thread_;
  16475. int port_ = 0;
  16476. };
  16477. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16478. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16479. "/ws-echo");
  16480. ASSERT_TRUE(client.connect());
  16481. ASSERT_TRUE(client.is_open());
  16482. ASSERT_TRUE(client.send("Hello WebSocket"));
  16483. std::string msg;
  16484. EXPECT_EQ(ws::Text, client.read(msg));
  16485. EXPECT_EQ("Hello WebSocket", msg);
  16486. client.close();
  16487. }
  16488. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16489. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16490. "/ws-echo");
  16491. ASSERT_TRUE(client.connect());
  16492. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16493. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16494. std::string msg;
  16495. EXPECT_EQ(ws::Binary, client.read(msg));
  16496. EXPECT_EQ(binary_data, msg);
  16497. client.close();
  16498. }
  16499. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16500. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16501. "/ws-echo");
  16502. ASSERT_TRUE(client.connect());
  16503. for (int i = 0; i < 10; i++) {
  16504. auto text = "message " + std::to_string(i);
  16505. ASSERT_TRUE(client.send(text));
  16506. std::string msg;
  16507. ASSERT_TRUE(client.read(msg));
  16508. EXPECT_EQ(text, msg);
  16509. }
  16510. client.close();
  16511. }
  16512. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16513. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16514. "/ws-close");
  16515. ASSERT_TRUE(client.connect());
  16516. // Send a message to trigger the server to close
  16517. ASSERT_TRUE(client.send("trigger close"));
  16518. // The server will close, so read should return false
  16519. std::string msg;
  16520. EXPECT_FALSE(client.read(msg));
  16521. EXPECT_FALSE(client.is_open());
  16522. }
  16523. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16524. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16525. "/ws-echo");
  16526. ASSERT_TRUE(client.connect());
  16527. // 128KB message
  16528. std::string large_data(128 * 1024, 'X');
  16529. ASSERT_TRUE(client.send(large_data));
  16530. std::string msg;
  16531. ASSERT_TRUE(client.read(msg));
  16532. EXPECT_EQ(large_data, msg);
  16533. client.close();
  16534. }
  16535. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16536. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16537. "/ws-echo");
  16538. ASSERT_TRUE(client.connect());
  16539. const int num_threads = 4;
  16540. std::vector<std::thread> threads;
  16541. std::atomic<int> send_count{0};
  16542. for (int t = 0; t < num_threads; t++) {
  16543. threads.emplace_back([&client, &send_count, t]() {
  16544. for (int i = 0; i < 5; i++) {
  16545. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16546. if (client.send(text)) { send_count++; }
  16547. }
  16548. });
  16549. }
  16550. for (auto &th : threads) {
  16551. th.join();
  16552. }
  16553. int received = 0;
  16554. std::string msg;
  16555. while (received < send_count.load()) {
  16556. if (!client.read(msg)) { break; }
  16557. received++;
  16558. }
  16559. EXPECT_EQ(send_count.load(), received);
  16560. client.close();
  16561. }
  16562. TEST_F(WebSocketIntegrationTest, ReadString) {
  16563. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16564. "/ws-echo-string");
  16565. ASSERT_TRUE(client.connect());
  16566. ASSERT_TRUE(client.send("hello"));
  16567. std::string msg;
  16568. ASSERT_TRUE(client.read(msg));
  16569. EXPECT_EQ("echo: hello", msg);
  16570. ASSERT_TRUE(client.send("world"));
  16571. ASSERT_TRUE(client.read(msg));
  16572. EXPECT_EQ("echo: world", msg);
  16573. client.close();
  16574. }
  16575. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16576. Headers headers = {{"X-Test-Header", "test-value"}};
  16577. ws::WebSocketClient client(
  16578. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16579. ASSERT_TRUE(client.connect());
  16580. std::string msg;
  16581. ASSERT_TRUE(client.read(msg));
  16582. EXPECT_EQ("path:/ws-request-info", msg);
  16583. ASSERT_TRUE(client.read(msg));
  16584. EXPECT_EQ("header:test-value", msg);
  16585. client.close();
  16586. }
  16587. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16588. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16589. "/ws-echo");
  16590. client.set_read_timeout(1, 0); // 1 second
  16591. ASSERT_TRUE(client.connect());
  16592. // Don't send anything — server echo handler waits for a message,
  16593. // so read() should time out and return false.
  16594. std::string msg;
  16595. EXPECT_FALSE(client.read(msg));
  16596. }
  16597. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16598. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16599. "/ws-echo");
  16600. client.set_read_timeout(5, 0);
  16601. ASSERT_TRUE(client.connect());
  16602. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16603. // The server should reject it and close the connection.
  16604. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16605. client.send(oversized);
  16606. // The server's read() should have failed due to payload limit,
  16607. // so our read() should return false (connection closed).
  16608. std::string msg;
  16609. EXPECT_FALSE(client.read(msg));
  16610. }
  16611. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16612. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16613. "/ws-echo");
  16614. client.set_read_timeout(10, 0);
  16615. ASSERT_TRUE(client.connect());
  16616. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16617. // This should succeed.
  16618. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16619. ASSERT_TRUE(client.send(at_limit));
  16620. std::string msg;
  16621. ASSERT_TRUE(client.read(msg));
  16622. EXPECT_EQ(at_limit.size(), msg.size());
  16623. client.close();
  16624. }
  16625. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16626. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16627. "/nonexistent");
  16628. EXPECT_FALSE(client.connect());
  16629. EXPECT_FALSE(client.is_open());
  16630. }
  16631. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16632. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16633. "/ws-echo");
  16634. ASSERT_TRUE(client.connect());
  16635. ASSERT_TRUE(client.send(""));
  16636. std::string msg;
  16637. EXPECT_EQ(ws::Text, client.read(msg));
  16638. EXPECT_EQ("", msg);
  16639. client.close();
  16640. }
  16641. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16642. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16643. "/ws-echo");
  16644. // First connection
  16645. ASSERT_TRUE(client.connect());
  16646. ASSERT_TRUE(client.send("first"));
  16647. std::string msg;
  16648. ASSERT_TRUE(client.read(msg));
  16649. EXPECT_EQ("first", msg);
  16650. client.close();
  16651. EXPECT_FALSE(client.is_open());
  16652. // Reconnect using the same client object
  16653. ASSERT_TRUE(client.connect());
  16654. ASSERT_TRUE(client.is_open());
  16655. ASSERT_TRUE(client.send("second"));
  16656. ASSERT_TRUE(client.read(msg));
  16657. EXPECT_EQ("second", msg);
  16658. client.close();
  16659. }
  16660. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16661. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16662. "/ws-close-status");
  16663. ASSERT_TRUE(client.connect());
  16664. // Trigger the server to close with GoingAway status
  16665. ASSERT_TRUE(client.send("trigger"));
  16666. // read() should return false after receiving the close frame
  16667. std::string msg;
  16668. EXPECT_FALSE(client.read(msg));
  16669. EXPECT_FALSE(client.is_open());
  16670. }
  16671. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16672. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16673. "/ws-echo");
  16674. ASSERT_TRUE(client.connect());
  16675. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16676. EXPECT_FALSE(client.is_open());
  16677. }
  16678. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16679. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16680. ws::WebSocketClient client(
  16681. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16682. ASSERT_TRUE(client.connect());
  16683. // Server should have selected graphql-ws
  16684. EXPECT_EQ("graphql-ws", client.subprotocol());
  16685. client.close();
  16686. }
  16687. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16688. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16689. ws::WebSocketClient client(
  16690. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16691. ASSERT_TRUE(client.connect());
  16692. // Server should not have selected any subprotocol
  16693. EXPECT_TRUE(client.subprotocol().empty());
  16694. client.close();
  16695. }
  16696. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16697. // Connect without requesting any subprotocol
  16698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16699. "/ws-subprotocol");
  16700. ASSERT_TRUE(client.connect());
  16701. EXPECT_TRUE(client.subprotocol().empty());
  16702. client.close();
  16703. }
  16704. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16705. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16706. "/ws-echo");
  16707. client.set_tcp_nodelay(true);
  16708. client.set_connection_timeout(3, 0);
  16709. bool socket_options_called = false;
  16710. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16711. ASSERT_TRUE(client.connect());
  16712. ASSERT_TRUE(client.is_open());
  16713. EXPECT_TRUE(socket_options_called);
  16714. ASSERT_TRUE(client.send("hello"));
  16715. std::string msg;
  16716. auto result = client.read(msg);
  16717. EXPECT_EQ(result, ws::ReadResult::Text);
  16718. EXPECT_EQ(msg, "hello");
  16719. client.close();
  16720. }
  16721. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16722. Server svr;
  16723. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16724. if (!req.has_header("Authorization")) {
  16725. res.status = StatusCode::Unauthorized_401;
  16726. res.set_content("Unauthorized", "text/plain");
  16727. return Server::HandlerResponse::Handled;
  16728. }
  16729. return Server::HandlerResponse::Unhandled;
  16730. });
  16731. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16732. std::string msg;
  16733. while (ws.read(msg)) {
  16734. ws.send(msg);
  16735. }
  16736. });
  16737. auto port = svr.bind_to_any_port("localhost");
  16738. std::thread t([&]() { svr.listen_after_bind(); });
  16739. svr.wait_until_ready();
  16740. // Without Authorization header - should be rejected before upgrade
  16741. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16742. EXPECT_FALSE(client1.connect());
  16743. // With Authorization header - should succeed
  16744. Headers headers = {{"Authorization", "Bearer token123"}};
  16745. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16746. headers);
  16747. ASSERT_TRUE(client2.connect());
  16748. ASSERT_TRUE(client2.send("hello"));
  16749. std::string msg;
  16750. ASSERT_TRUE(client2.read(msg));
  16751. EXPECT_EQ("hello", msg);
  16752. client2.close();
  16753. svr.stop();
  16754. t.join();
  16755. }
  16756. TEST(WebSocketTest, QueryStringInHandshake) {
  16757. Server svr;
  16758. std::mutex mtx;
  16759. std::string received_target;
  16760. std::string received_token;
  16761. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16762. {
  16763. std::lock_guard<std::mutex> lock(mtx);
  16764. received_target = req.target;
  16765. if (req.has_param("token")) {
  16766. received_token = req.get_param_value("token");
  16767. }
  16768. }
  16769. std::string msg;
  16770. while (ws.read(msg)) {
  16771. ws.send(msg);
  16772. }
  16773. });
  16774. auto port = svr.bind_to_any_port("localhost");
  16775. std::thread t([&]() { svr.listen_after_bind(); });
  16776. svr.wait_until_ready();
  16777. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16778. "/ws?token=ABC&session=123");
  16779. ASSERT_TRUE(client.connect());
  16780. // Round-trip ensures the handler has run and captured the request.
  16781. ASSERT_TRUE(client.send("hello"));
  16782. std::string msg;
  16783. ASSERT_TRUE(client.read(msg));
  16784. EXPECT_EQ("hello", msg);
  16785. client.close();
  16786. {
  16787. std::lock_guard<std::mutex> lock(mtx);
  16788. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16789. EXPECT_EQ("ABC", received_token);
  16790. }
  16791. svr.stop();
  16792. t.join();
  16793. }
  16794. // Run a handshake against a throwaway server and hand the request the server
  16795. // received back to the caller, so tests can assert on the headers the client
  16796. // actually put on the wire.
  16797. static void capture_websocket_handshake_request(
  16798. const Headers &client_headers,
  16799. std::function<void(const Request &, int port)> verify) {
  16800. Server svr;
  16801. std::mutex mtx;
  16802. Request received;
  16803. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16804. {
  16805. std::lock_guard<std::mutex> lock(mtx);
  16806. received = req;
  16807. }
  16808. std::string msg;
  16809. while (ws.read(msg)) {
  16810. ws.send(msg);
  16811. }
  16812. });
  16813. auto port = svr.bind_to_any_port("localhost");
  16814. std::thread t([&]() { svr.listen_after_bind(); });
  16815. auto se = detail::scope_exit([&] {
  16816. svr.stop();
  16817. t.join();
  16818. });
  16819. svr.wait_until_ready();
  16820. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  16821. client_headers);
  16822. ASSERT_TRUE(client.connect());
  16823. ASSERT_TRUE(client.send("hello"));
  16824. std::string msg;
  16825. ASSERT_TRUE(client.read(msg));
  16826. client.close();
  16827. {
  16828. std::lock_guard<std::mutex> lock(mtx);
  16829. verify(received, port);
  16830. }
  16831. }
  16832. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  16833. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  16834. // Non-default port must be present in the Host header. Default ports
  16835. // (80/443) are omitted; that logic is covered by
  16836. // MakeHostAndPortStringTest.
  16837. EXPECT_EQ("localhost:" + std::to_string(port),
  16838. req.get_header_value("Host"));
  16839. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  16840. req.get_header_value("User-Agent"));
  16841. EXPECT_FALSE(req.has_header("Accept"));
  16842. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  16843. EXPECT_FALSE(req.has_header("Content-Length"));
  16844. });
  16845. }
  16846. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  16847. capture_websocket_handshake_request(
  16848. {{"Host", "example.com"},
  16849. {"User-Agent", "custom-agent"},
  16850. {"X-Custom", "value"}},
  16851. [](const Request &req, int) {
  16852. EXPECT_EQ("example.com", req.get_header_value("Host"));
  16853. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  16854. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  16855. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  16856. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  16857. });
  16858. }
  16859. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  16860. capture_websocket_handshake_request(
  16861. {{"Upgrade", "bogus"},
  16862. {"Connection", "close"},
  16863. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  16864. {"Sec-WebSocket-Version", "8"}},
  16865. [](const Request &req, int) {
  16866. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  16867. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  16868. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  16869. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  16870. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  16871. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  16872. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  16873. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  16874. req.get_header_value("Sec-WebSocket-Key"));
  16875. });
  16876. }
  16877. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  16878. // A header the client refuses to send must abort the handshake before any
  16879. // part of it reaches the wire; a lone request line would otherwise sit in
  16880. // the peer's buffer as a truncated request.
  16881. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16882. ASSERT_NE(INVALID_SOCKET, srv);
  16883. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  16884. sockaddr_in addr{};
  16885. addr.sin_family = AF_INET;
  16886. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  16887. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16888. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16889. ASSERT_EQ(0, ::listen(srv, 1));
  16890. sockaddr_in bound{};
  16891. socklen_t bound_len = sizeof(bound);
  16892. ASSERT_EQ(
  16893. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  16894. auto port = ntohs(bound.sin_port);
  16895. ssize_t received = -1;
  16896. std::thread t([&] {
  16897. // Bound every blocking call so a regression fails the test with a bad
  16898. // value instead of hanging the suite.
  16899. fd_set rfds;
  16900. FD_ZERO(&rfds);
  16901. FD_SET(srv, &rfds);
  16902. timeval tv{5, 0};
  16903. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  16904. 0) {
  16905. return;
  16906. }
  16907. sockaddr_in cli_addr{};
  16908. socklen_t cli_len = sizeof(cli_addr);
  16909. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16910. if (cli == INVALID_SOCKET) { return; }
  16911. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  16912. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16913. char buf[4096];
  16914. received = ::recv(cli, buf, sizeof(buf), 0);
  16915. });
  16916. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  16917. // connect() has already shut the socket down by the time it returns false,
  16918. // so the peer sees EOF without waiting for the client to be destroyed.
  16919. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  16920. {{"X-Bad", "a\r\nInjected: 1"}});
  16921. EXPECT_FALSE(client.connect());
  16922. t.join();
  16923. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  16924. EXPECT_EQ(0, received);
  16925. }
  16926. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  16927. // The socket path doubles as the URL host, so it must not contain '/'.
  16928. const char *shard = getenv("GTEST_SHARD_INDEX");
  16929. const std::string sock_path =
  16930. shard ? std::string("httplib-ws-") + shard + ".sock"
  16931. : std::string("httplib-ws.sock");
  16932. std::remove(sock_path.c_str());
  16933. Server svr;
  16934. std::mutex mtx;
  16935. std::string received_host;
  16936. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16937. {
  16938. std::lock_guard<std::mutex> lock(mtx);
  16939. received_host = req.get_header_value("Host");
  16940. }
  16941. std::string msg;
  16942. while (ws.read(msg)) {
  16943. ws.send(msg);
  16944. }
  16945. });
  16946. svr.set_address_family(AF_UNIX);
  16947. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  16948. auto se = detail::scope_exit([&] {
  16949. svr.stop();
  16950. t.join();
  16951. std::remove(sock_path.c_str());
  16952. });
  16953. svr.wait_until_ready();
  16954. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  16955. client.set_address_family(AF_UNIX);
  16956. ASSERT_TRUE(client.connect());
  16957. ASSERT_TRUE(client.send("hello"));
  16958. std::string msg;
  16959. ASSERT_TRUE(client.read(msg));
  16960. client.close();
  16961. {
  16962. std::lock_guard<std::mutex> lock(mtx);
  16963. // There is no host:port for a Unix socket, so the same "localhost"
  16964. // placeholder the HTTP client uses is expected.
  16965. EXPECT_EQ("localhost", received_host);
  16966. }
  16967. }
  16968. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16969. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16970. protected:
  16971. void SetUp() override {
  16972. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16973. SERVER_PRIVATE_KEY_FILE);
  16974. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16975. std::string msg;
  16976. ws::ReadResult ret;
  16977. while ((ret = ws.read(msg))) {
  16978. if (ret == ws::Binary) {
  16979. ws.send(msg.data(), msg.size());
  16980. } else {
  16981. ws.send(msg);
  16982. }
  16983. }
  16984. });
  16985. port_ = server_->bind_to_any_port(HOST);
  16986. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16987. server_->wait_until_ready();
  16988. }
  16989. void TearDown() override {
  16990. server_->stop();
  16991. if (server_thread_.joinable()) { server_thread_.join(); }
  16992. }
  16993. std::unique_ptr<SSLServer> server_;
  16994. std::thread server_thread_;
  16995. int port_ = 0;
  16996. };
  16997. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16998. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16999. "/ws-echo");
  17000. client.enable_server_certificate_verification(false);
  17001. ASSERT_TRUE(client.connect());
  17002. ASSERT_TRUE(client.is_open());
  17003. ASSERT_TRUE(client.send("Hello WSS"));
  17004. std::string msg;
  17005. EXPECT_EQ(ws::Text, client.read(msg));
  17006. EXPECT_EQ("Hello WSS", msg);
  17007. client.close();
  17008. }
  17009. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  17010. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  17011. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  17012. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  17013. // client (without calling close() first) is the only path that runs
  17014. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  17015. // bug exactly.
  17016. //
  17017. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  17018. // when linked against an instrumented libssl; run under Valgrind to catch it
  17019. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  17020. // suite (the freed session otherwise stalls on the close handshake) — this test
  17021. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  17022. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  17023. {
  17024. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17025. "/ws-echo");
  17026. client.enable_server_certificate_verification(false);
  17027. client.set_read_timeout(2, 0);
  17028. client.set_write_timeout(2, 0);
  17029. ASSERT_TRUE(client.connect());
  17030. ASSERT_TRUE(client.is_open());
  17031. ASSERT_TRUE(client.send("still open"));
  17032. // Intentionally do NOT call client.close(): leaving scope runs
  17033. // shutdown_and_close() with the WebSocket still open, which must send the
  17034. // close frame while the TLS session is still alive.
  17035. }
  17036. }
  17037. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  17038. // shutdown_and_close() at the start of connect(), reproducing the same
  17039. // use-after-free within the test body rather than at scope exit. The second
  17040. // connect must succeed and echo, proving the close handshake ran over a live
  17041. // session. See the note above about memory-tool requirements.
  17042. TEST_F(WebSocketSSLIntegrationTest,
  17043. ReconnectWhileOpenSendsCloseOverLiveSession) {
  17044. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  17045. "/ws-echo");
  17046. client.enable_server_certificate_verification(false);
  17047. client.set_read_timeout(2, 0);
  17048. client.set_write_timeout(2, 0);
  17049. ASSERT_TRUE(client.connect());
  17050. ASSERT_TRUE(client.is_open());
  17051. ASSERT_TRUE(client.send("still open"));
  17052. // Reconnect without closing first: connect() calls shutdown_and_close() on
  17053. // the still-open connection, which must not touch a freed TLS session.
  17054. ASSERT_TRUE(client.connect());
  17055. ASSERT_TRUE(client.is_open());
  17056. ASSERT_TRUE(client.send("after reconnect"));
  17057. std::string msg;
  17058. EXPECT_EQ(ws::Text, client.read(msg));
  17059. EXPECT_EQ("after reconnect", msg);
  17060. client.close();
  17061. }
  17062. #endif
  17063. #ifdef CPPHTTPLIB_SSL_ENABLED
  17064. class WebSocketSSLCATest : public ::testing::Test {
  17065. protected:
  17066. void SetUp() override {
  17067. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  17068. SERVER_PRIVATE_KEY_FILE);
  17069. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17070. std::string msg;
  17071. while (ws.read(msg)) {
  17072. ws.send(msg);
  17073. }
  17074. });
  17075. port_ = server_->bind_to_any_port("127.0.0.1");
  17076. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  17077. server_->wait_until_ready();
  17078. }
  17079. void TearDown() override {
  17080. server_->stop();
  17081. if (server_thread_.joinable()) { server_thread_.join(); }
  17082. }
  17083. std::string url() const {
  17084. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  17085. }
  17086. std::unique_ptr<SSLServer> server_;
  17087. std::thread server_thread_;
  17088. int port_ = 0;
  17089. };
  17090. // A custom CA loaded as PEM verifies the server with full certificate
  17091. // verification enabled
  17092. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  17093. ws::WebSocketClient client(url());
  17094. std::string cert;
  17095. read_file(SERVER_CERT2_FILE, cert);
  17096. client.load_ca_cert_store(cert.c_str(), cert.size());
  17097. ASSERT_TRUE(client.connect());
  17098. ASSERT_TRUE(client.send("hello"));
  17099. std::string msg;
  17100. EXPECT_EQ(ws::Text, client.read(msg));
  17101. EXPECT_EQ("hello", msg);
  17102. client.close();
  17103. }
  17104. // A custom CA that does not cover the server must fail verification (the
  17105. // custom CA is exclusive; system certs are not loaded alongside it)
  17106. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  17107. ws::WebSocketClient client(url());
  17108. std::string cert;
  17109. read_file(CLIENT_CA_CERT_FILE, cert);
  17110. client.load_ca_cert_store(cert.c_str(), cert.size());
  17111. ASSERT_FALSE(client.connect());
  17112. }
  17113. // Regression test: reconnecting with a native custom CA store used to reuse
  17114. // a store handle the previous TLS context had already freed (use-after-free
  17115. // under the OpenSSL backend). The context now lives as long as the client.
  17116. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  17117. ws::WebSocketClient client(url());
  17118. std::string cert;
  17119. read_file(SERVER_CERT2_FILE, cert);
  17120. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  17121. ASSERT_TRUE(client.connect());
  17122. client.close();
  17123. ASSERT_TRUE(client.connect());
  17124. ASSERT_TRUE(client.send("again"));
  17125. std::string msg;
  17126. EXPECT_EQ(ws::Text, client.read(msg));
  17127. EXPECT_EQ("again", msg);
  17128. client.close();
  17129. }
  17130. // Regression test: a certificate with a trusted chain but no identity match
  17131. // for the server IP must be rejected. The Mbed TLS backend used to skip
  17132. // verification entirely for IP hosts, so this connection succeeded there.
  17133. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  17134. // chain verification while the identity check must still fail.
  17135. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  17136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17137. ASSERT_TRUE(svr.is_valid());
  17138. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  17139. std::string msg;
  17140. while (ws.read(msg)) {
  17141. ws.send(msg);
  17142. }
  17143. });
  17144. auto port = svr.bind_to_any_port("127.0.0.1");
  17145. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17146. auto se = detail::scope_exit([&] {
  17147. svr.stop();
  17148. t.join();
  17149. });
  17150. svr.wait_until_ready();
  17151. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  17152. "/echo");
  17153. std::string cert;
  17154. read_file(SERVER_CERT_FILE, cert);
  17155. client.load_ca_cert_store(cert.c_str(), cert.size());
  17156. ASSERT_FALSE(client.connect());
  17157. }
  17158. #endif
  17159. #if !defined(_WIN32)
  17160. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  17161. auto secret_dir = std::string("./symlink_test_secret");
  17162. auto served_dir = std::string("./symlink_test_served");
  17163. auto secret_file = secret_dir + "/secret.txt";
  17164. auto symlink_path = served_dir + "/escape";
  17165. // Setup: create directories and files
  17166. mkdir(secret_dir.c_str(), 0755);
  17167. mkdir(served_dir.c_str(), 0755);
  17168. {
  17169. std::ofstream ofs(secret_file);
  17170. ofs << "SECRET_DATA";
  17171. }
  17172. // Create symlink using absolute path so it resolves correctly
  17173. #ifdef PATH_MAX
  17174. char abs_secret[PATH_MAX];
  17175. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  17176. #else
  17177. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  17178. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  17179. ASSERT_NE(nullptr, abs_secret);
  17180. #endif
  17181. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  17182. auto se = detail::scope_exit([&] {
  17183. unlink(symlink_path.c_str());
  17184. unlink(secret_file.c_str());
  17185. rmdir(served_dir.c_str());
  17186. rmdir(secret_dir.c_str());
  17187. });
  17188. Server svr;
  17189. svr.set_mount_point("/", served_dir);
  17190. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17191. auto se2 = detail::scope_exit([&] {
  17192. svr.stop();
  17193. listen_thread.join();
  17194. });
  17195. svr.wait_until_ready();
  17196. Client cli("localhost", PORT);
  17197. // Symlink pointing outside base dir should be blocked
  17198. auto res = cli.Get("/escape/secret.txt");
  17199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17200. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17201. }
  17202. #endif
  17203. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17204. // A GET request with Content-Length to a static file handler must have its
  17205. // body drained before the keep-alive connection is reused. Otherwise the
  17206. // unread body bytes are interpreted as the next HTTP request.
  17207. //
  17208. // The body is sent AFTER receiving the first response (as in the original
  17209. // PoC) so that the stream_line_reader cannot buffer it together with the
  17210. // headers of the first request.
  17211. Server svr;
  17212. svr.set_mount_point("/", "./www");
  17213. std::atomic<int> smuggled_count(0);
  17214. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17215. smuggled_count++;
  17216. res.set_content("oops", "text/plain");
  17217. });
  17218. auto port = svr.bind_to_any_port("localhost");
  17219. thread t = thread([&] { svr.listen_after_bind(); });
  17220. auto se = detail::scope_exit([&] {
  17221. svr.stop();
  17222. t.join();
  17223. });
  17224. svr.wait_until_ready();
  17225. auto error = Error::Success;
  17226. auto sock = detail::create_client_socket(
  17227. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17228. /*connection_timeout_sec=*/2, 0,
  17229. /*read_timeout_sec=*/2, 0,
  17230. /*write_timeout_sec=*/2, 0, std::string(), error);
  17231. ASSERT_NE(INVALID_SOCKET, sock);
  17232. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17233. // The "smuggled" request will be sent as the body of the outer GET
  17234. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17235. "Host: localhost\r\n"
  17236. "Connection: close\r\n"
  17237. "\r\n";
  17238. // Step 1: Send only the outer request headers (no body yet)
  17239. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17240. "Host: localhost\r\n"
  17241. "Content-Length: " +
  17242. std::to_string(smuggled.size()) +
  17243. "\r\n"
  17244. "\r\n";
  17245. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17246. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17247. // Step 2: Read the first response (server serves file without reading body)
  17248. std::string first_response;
  17249. char buf[4096];
  17250. for (;;) {
  17251. auto n = recv(sock, buf, sizeof(buf), 0);
  17252. if (n <= 0) break;
  17253. first_response.append(buf, static_cast<size_t>(n));
  17254. // Stop once we have a complete response (headers + body)
  17255. auto hdr_end = first_response.find("\r\n\r\n");
  17256. if (hdr_end != std::string::npos) {
  17257. // Check for Content-Length to know when the body is complete
  17258. auto cl_pos = first_response.find("Content-Length:");
  17259. if (cl_pos != std::string::npos) {
  17260. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17261. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17262. auto cl = std::stoul(
  17263. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17264. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17265. } else {
  17266. break; // No Content-Length, assume headers-only response
  17267. }
  17268. }
  17269. }
  17270. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17271. // Step 3: Now send the body, which looks like a new HTTP request.
  17272. // On a vulnerable server the keep-alive loop reads this as a second request.
  17273. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17274. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17275. // Step 4: Try to read a second response (should NOT exist after fix)
  17276. std::string second_response;
  17277. for (;;) {
  17278. auto n = recv(sock, buf, sizeof(buf), 0);
  17279. if (n <= 0) break;
  17280. second_response.append(buf, static_cast<size_t>(n));
  17281. }
  17282. // The smuggled request must NOT have been processed
  17283. EXPECT_EQ(0, smuggled_count.load());
  17284. }
  17285. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17286. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17287. // must be rejected with 400 Bad Request.
  17288. Server svr;
  17289. svr.Post("/test", [&](const Request &, Response &res) {
  17290. res.set_content("ok", "text/plain");
  17291. });
  17292. thread t = thread([&] { svr.listen(HOST, PORT); });
  17293. auto se = detail::scope_exit([&] {
  17294. svr.stop();
  17295. t.join();
  17296. ASSERT_FALSE(svr.is_running());
  17297. });
  17298. svr.wait_until_ready();
  17299. // Exact "chunked"
  17300. {
  17301. auto req = "POST /test HTTP/1.1\r\n"
  17302. "Host: localhost\r\n"
  17303. "Content-Length: 5\r\n"
  17304. "Transfer-Encoding: chunked\r\n"
  17305. "Connection: close\r\n"
  17306. "\r\n"
  17307. "hello";
  17308. std::string response;
  17309. ASSERT_TRUE(send_request(1, req, &response));
  17310. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17311. response.substr(0, response.find("\r\n")));
  17312. }
  17313. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17314. {
  17315. auto req = "POST /test HTTP/1.1\r\n"
  17316. "Host: localhost\r\n"
  17317. "Content-Length: 5\r\n"
  17318. "Transfer-Encoding: gzip, chunked\r\n"
  17319. "Connection: close\r\n"
  17320. "\r\n"
  17321. "hello";
  17322. std::string response;
  17323. ASSERT_TRUE(send_request(1, req, &response));
  17324. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17325. response.substr(0, response.find("\r\n")));
  17326. }
  17327. }
  17328. // Regression for issue #2450: a DELETE without Content-Length on a
  17329. // keep-alive connection must not let the post-response drain consume the
  17330. // next request's bytes.
  17331. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17332. Server svr;
  17333. std::atomic<int> delete_count(0);
  17334. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17335. delete_count++;
  17336. res.status = StatusCode::NoContent_204;
  17337. });
  17338. auto port = svr.bind_to_any_port(HOST);
  17339. thread t = thread([&] { svr.listen_after_bind(); });
  17340. auto se = detail::scope_exit([&] {
  17341. svr.stop();
  17342. t.join();
  17343. });
  17344. svr.wait_until_ready();
  17345. auto error = Error::Success;
  17346. auto sock = detail::create_client_socket(
  17347. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17348. /*connection_timeout_sec=*/2, 0,
  17349. /*read_timeout_sec=*/2, 0,
  17350. /*write_timeout_sec=*/2, 0, std::string(), error);
  17351. ASSERT_NE(INVALID_SOCKET, sock);
  17352. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17353. auto send_request_and_read_response = [&](const std::string &req,
  17354. std::string &out) -> bool {
  17355. auto sent = send(sock, req.data(), req.size(), 0);
  17356. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17357. char buf[4096];
  17358. for (;;) {
  17359. auto n = recv(sock, buf, sizeof(buf), 0);
  17360. if (n <= 0) { return !out.empty(); }
  17361. out.append(buf, static_cast<size_t>(n));
  17362. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17363. }
  17364. };
  17365. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17366. "Host: localhost\r\n"
  17367. "\r\n";
  17368. std::string resp1;
  17369. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17370. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17371. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17372. "Host: localhost\r\n"
  17373. "Connection: close\r\n"
  17374. "\r\n";
  17375. std::string resp2;
  17376. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17377. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17378. EXPECT_EQ(2, delete_count.load());
  17379. }
  17380. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17381. Server svr;
  17382. svr.Post("/ingest", [&](const Request &, Response &res,
  17383. const ContentReader &content_reader) {
  17384. auto consumed = content_reader([](const char *, size_t) { return false; });
  17385. EXPECT_FALSE(consumed);
  17386. res.status = StatusCode::Conflict_409;
  17387. res.set_header("Connection", "close");
  17388. });
  17389. auto port = svr.bind_to_any_port(HOST);
  17390. thread t = thread([&] { svr.listen_after_bind(); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. t.join();
  17394. });
  17395. svr.wait_until_ready();
  17396. auto error = Error::Success;
  17397. auto sock = detail::create_client_socket(
  17398. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17399. /*connection_timeout_sec=*/2, 0,
  17400. /*read_timeout_sec=*/1, 0,
  17401. /*write_timeout_sec=*/2, 0, std::string(), error);
  17402. ASSERT_NE(INVALID_SOCKET, sock);
  17403. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17404. std::string request = "POST /ingest HTTP/1.1\r\n"
  17405. "Host: localhost\r\n"
  17406. "Transfer-Encoding: chunked\r\n"
  17407. "\r\n"
  17408. "4\r\n"
  17409. "data\r\n";
  17410. auto sent = send(sock, request.data(), request.size(), 0);
  17411. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17412. std::string response;
  17413. ssize_t received = 0;
  17414. do {
  17415. char buf[4096];
  17416. received = recv(sock, buf, sizeof(buf), 0);
  17417. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17418. } while (received > 0);
  17419. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17420. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17421. EXPECT_EQ(0, received);
  17422. }
  17423. namespace no_proxy_test {
  17424. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17425. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17426. // calling listen().
  17427. class ScopedServer {
  17428. public:
  17429. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17430. ~ScopedServer() {
  17431. svr_.stop();
  17432. if (th_.joinable()) { th_.join(); }
  17433. }
  17434. Server &svr() { return svr_; }
  17435. int port() const { return port_; }
  17436. void listen() {
  17437. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17438. svr_.wait_until_ready();
  17439. }
  17440. private:
  17441. Server svr_;
  17442. std::thread th_;
  17443. int port_ = 0;
  17444. };
  17445. class ProxyAndTargetServers {
  17446. public:
  17447. ProxyAndTargetServers() {
  17448. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17449. proxy_hits_++;
  17450. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17451. res.set_content("via-proxy", "text/plain");
  17452. });
  17453. target_.Get(".*", [this](const Request &req, Response &res) {
  17454. target_hits_++;
  17455. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17456. res.set_content("direct", "text/plain");
  17457. });
  17458. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17459. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17460. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17461. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17462. proxy_mock_.wait_until_ready();
  17463. target_.wait_until_ready();
  17464. }
  17465. ~ProxyAndTargetServers() {
  17466. proxy_mock_.stop();
  17467. target_.stop();
  17468. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17469. if (target_thread_.joinable()) { target_thread_.join(); }
  17470. }
  17471. Server &proxy_mock() { return proxy_mock_; }
  17472. Server &target() { return target_; }
  17473. int proxy_port() const { return proxy_port_; }
  17474. int target_port() const { return target_port_; }
  17475. int proxy_hits() const { return proxy_hits_.load(); }
  17476. int target_hits() const { return target_hits_.load(); }
  17477. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17478. void reset_counters() {
  17479. proxy_hits_ = 0;
  17480. target_hits_ = 0;
  17481. last_had_proxy_authz_ = false;
  17482. }
  17483. private:
  17484. Server proxy_mock_;
  17485. Server target_;
  17486. std::thread proxy_thread_;
  17487. std::thread target_thread_;
  17488. int proxy_port_ = 0;
  17489. int target_port_ = 0;
  17490. std::atomic<int> proxy_hits_{0};
  17491. std::atomic<int> target_hits_{0};
  17492. std::atomic<bool> last_had_proxy_authz_{false};
  17493. };
  17494. inline std::unique_ptr<Client> make_client(const std::string &host,
  17495. ProxyAndTargetServers &s) {
  17496. auto cli = detail::make_unique<Client>(host, s.target_port());
  17497. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17498. cli->set_proxy("127.0.0.1", s.proxy_port());
  17499. return cli;
  17500. }
  17501. } // namespace no_proxy_test
  17502. using no_proxy_test::make_client;
  17503. using no_proxy_test::ProxyAndTargetServers;
  17504. TEST(NoProxyTest, ExactHostnameBypasses) {
  17505. ProxyAndTargetServers s;
  17506. auto cli = make_client("example.com", s);
  17507. cli->set_no_proxy({"example.com"});
  17508. auto res = cli->Get("/");
  17509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17510. EXPECT_EQ(0, s.proxy_hits());
  17511. EXPECT_EQ(1, s.target_hits());
  17512. }
  17513. TEST(NoProxyTest, SubdomainBypasses) {
  17514. ProxyAndTargetServers s;
  17515. auto cli = make_client("foo.example.com", s);
  17516. cli->set_no_proxy({"example.com"});
  17517. auto res = cli->Get("/");
  17518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17519. EXPECT_EQ(0, s.proxy_hits());
  17520. EXPECT_EQ(1, s.target_hits());
  17521. }
  17522. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17523. // Regression guard: "evilexample.com" must not be considered a subdomain
  17524. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17525. // check would let traffic bypass the proxy and leak credentials direct
  17526. // to the attacker host.
  17527. ProxyAndTargetServers s;
  17528. auto cli = make_client("evilexample.com", s);
  17529. cli->set_no_proxy({"example.com"});
  17530. auto res = cli->Get("/");
  17531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17532. EXPECT_GE(s.proxy_hits(), 1);
  17533. EXPECT_EQ(0, s.target_hits());
  17534. }
  17535. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17536. ProxyAndTargetServers s;
  17537. auto cli = make_client("example.com.evil.com", s);
  17538. cli->set_no_proxy({"example.com"});
  17539. auto res = cli->Get("/");
  17540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17541. EXPECT_GE(s.proxy_hits(), 1);
  17542. EXPECT_EQ(0, s.target_hits());
  17543. }
  17544. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17545. ProxyAndTargetServers s;
  17546. auto cli = make_client("example.com", s);
  17547. cli->set_no_proxy({".example.com"});
  17548. auto res = cli->Get("/");
  17549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17550. EXPECT_EQ(0, s.proxy_hits());
  17551. EXPECT_EQ(1, s.target_hits());
  17552. }
  17553. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17554. ProxyAndTargetServers s;
  17555. auto cli = make_client("Example.COM", s);
  17556. cli->set_no_proxy({"EXAMPLE.com"});
  17557. auto res = cli->Get("/");
  17558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17559. EXPECT_EQ(0, s.proxy_hits());
  17560. EXPECT_EQ(1, s.target_hits());
  17561. }
  17562. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17563. ProxyAndTargetServers s;
  17564. auto cli = make_client("example.com.", s);
  17565. cli->set_no_proxy({"example.com"});
  17566. auto res = cli->Get("/");
  17567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17568. EXPECT_EQ(0, s.proxy_hits());
  17569. EXPECT_EQ(1, s.target_hits());
  17570. }
  17571. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17572. // Trailing dots must be normalized on BOTH sides — host and entry.
  17573. // An implementation that only strips the host-side trailing dot would
  17574. // fail to match host "example.com" against entry "example.com." because
  17575. // a literal substring search would compare 11 chars against 12.
  17576. ProxyAndTargetServers s;
  17577. auto cli = make_client("example.com", s);
  17578. cli->set_no_proxy({"example.com."});
  17579. auto res = cli->Get("/");
  17580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17581. EXPECT_EQ(0, s.proxy_hits());
  17582. EXPECT_EQ(1, s.target_hits());
  17583. }
  17584. TEST(NoProxyTest, WildcardBypassesEverything) {
  17585. ProxyAndTargetServers s;
  17586. auto cli = make_client("anything.invalid.test", s);
  17587. cli->set_no_proxy({"*"});
  17588. auto res = cli->Get("/");
  17589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17590. EXPECT_EQ(0, s.proxy_hits());
  17591. EXPECT_EQ(1, s.target_hits());
  17592. }
  17593. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17594. ProxyAndTargetServers s;
  17595. Client cli("127.0.0.1", s.target_port());
  17596. cli.set_proxy("127.0.0.1", s.proxy_port());
  17597. cli.set_no_proxy({"127.0.0.1"});
  17598. auto res = cli.Get("/");
  17599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17600. EXPECT_EQ(0, s.proxy_hits());
  17601. EXPECT_EQ(1, s.target_hits());
  17602. }
  17603. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17604. ProxyAndTargetServers s;
  17605. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17606. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17607. cli.set_proxy("127.0.0.1", s.proxy_port());
  17608. cli.set_no_proxy({"::1"});
  17609. auto res = cli.Get("/");
  17610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17611. EXPECT_EQ(0, s.proxy_hits());
  17612. EXPECT_EQ(1, s.target_hits());
  17613. }
  17614. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17615. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17616. // must still be recognized as IPv6 for CIDR matching. Implementations
  17617. // that detect IPv6 only when the host begins with '[' would parse the
  17618. // host as a hostname and miss the match.
  17619. ProxyAndTargetServers s;
  17620. Client cli("fe80::1", s.target_port());
  17621. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17622. cli.set_proxy("127.0.0.1", s.proxy_port());
  17623. cli.set_no_proxy({"fe80::/10"});
  17624. auto res = cli.Get("/");
  17625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17626. EXPECT_EQ(0, s.proxy_hits());
  17627. EXPECT_EQ(1, s.target_hits());
  17628. }
  17629. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17630. ProxyAndTargetServers s;
  17631. Client cli("::1", s.target_port());
  17632. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17633. cli.set_proxy("127.0.0.1", s.proxy_port());
  17634. cli.set_no_proxy({"[::1]"});
  17635. auto res = cli.Get("/");
  17636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17637. EXPECT_EQ(0, s.proxy_hits());
  17638. EXPECT_EQ(1, s.target_hits());
  17639. }
  17640. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17641. ProxyAndTargetServers s;
  17642. Client cli("fe80::1", s.target_port());
  17643. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17644. cli.set_proxy("127.0.0.1", s.proxy_port());
  17645. cli.set_no_proxy({"[fe80::]/10"});
  17646. auto res = cli.Get("/");
  17647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17648. EXPECT_EQ(0, s.proxy_hits());
  17649. EXPECT_EQ(1, s.target_hits());
  17650. }
  17651. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17652. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17653. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17654. // tricks via address-family conversion.
  17655. ProxyAndTargetServers s;
  17656. Client cli("::ffff:127.0.0.1", s.target_port());
  17657. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17658. cli.set_proxy("127.0.0.1", s.proxy_port());
  17659. cli.set_no_proxy({"127.0.0.1"});
  17660. auto res = cli.Get("/");
  17661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17662. EXPECT_GE(s.proxy_hits(), 1);
  17663. EXPECT_EQ(0, s.target_hits());
  17664. }
  17665. TEST(NoProxyTest, IPv4CidrMatch) {
  17666. ProxyAndTargetServers s;
  17667. Client cli("127.0.0.1", s.target_port());
  17668. cli.set_proxy("127.0.0.1", s.proxy_port());
  17669. cli.set_no_proxy({"127.0.0.0/8"});
  17670. auto res = cli.Get("/");
  17671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17672. EXPECT_EQ(0, s.proxy_hits());
  17673. EXPECT_EQ(1, s.target_hits());
  17674. }
  17675. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17676. ProxyAndTargetServers s;
  17677. Client cli("127.0.0.1", s.target_port());
  17678. cli.set_proxy("127.0.0.1", s.proxy_port());
  17679. cli.set_no_proxy({"10.0.0.0/8"});
  17680. auto res = cli.Get("/");
  17681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17682. EXPECT_GE(s.proxy_hits(), 1);
  17683. EXPECT_EQ(0, s.target_hits());
  17684. }
  17685. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17686. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17687. // IPv4 target matches.
  17688. ProxyAndTargetServers s;
  17689. Client cli("127.0.0.1", s.target_port());
  17690. cli.set_proxy("127.0.0.1", s.proxy_port());
  17691. cli.set_no_proxy({"0.0.0.0/0"});
  17692. auto res = cli.Get("/");
  17693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17694. EXPECT_EQ(0, s.proxy_hits());
  17695. EXPECT_EQ(1, s.target_hits());
  17696. }
  17697. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17698. ProxyAndTargetServers s;
  17699. Client cli("127.0.0.1", s.target_port());
  17700. cli.set_proxy("127.0.0.1", s.proxy_port());
  17701. cli.set_no_proxy({"127.0.0.1"});
  17702. auto res = cli.Get("/");
  17703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17704. EXPECT_EQ(0, s.proxy_hits());
  17705. EXPECT_EQ(1, s.target_hits());
  17706. }
  17707. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17708. ProxyAndTargetServers s;
  17709. Client cli("127.0.0.1", s.target_port());
  17710. cli.set_proxy("127.0.0.1", s.proxy_port());
  17711. cli.set_no_proxy({"127.0.0.0/33"});
  17712. auto res = cli.Get("/");
  17713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17714. EXPECT_GE(s.proxy_hits(), 1);
  17715. EXPECT_EQ(0, s.target_hits());
  17716. }
  17717. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17718. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17719. ProxyAndTargetServers s;
  17720. Client cli("127.0.0.1", s.target_port());
  17721. cli.set_proxy("127.0.0.1", s.proxy_port());
  17722. cli.set_no_proxy({"127.0.0.1/"});
  17723. auto res = cli.Get("/");
  17724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17725. EXPECT_GE(s.proxy_hits(), 1);
  17726. EXPECT_EQ(0, s.target_hits());
  17727. }
  17728. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17729. ProxyAndTargetServers s;
  17730. auto cli = make_client("internal.corp", s);
  17731. cli->set_proxy_basic_auth("u", "p");
  17732. cli->set_no_proxy({"internal.corp"});
  17733. auto res = cli->Get("/");
  17734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17735. EXPECT_EQ(1, s.target_hits());
  17736. EXPECT_EQ(0, s.proxy_hits());
  17737. EXPECT_FALSE(s.last_had_proxy_authz())
  17738. << "Proxy-Authorization must not be sent direct to the target";
  17739. }
  17740. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17741. ProxyAndTargetServers s;
  17742. auto cli = make_client("public.example", s);
  17743. cli->set_proxy_basic_auth("u", "p");
  17744. cli->set_no_proxy({"internal.corp"}); // does not match
  17745. auto res = cli->Get("/");
  17746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17747. EXPECT_GE(s.proxy_hits(), 1);
  17748. EXPECT_TRUE(s.last_had_proxy_authz());
  17749. }
  17750. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17751. ProxyAndTargetServers s;
  17752. auto cli = make_client("anything.test", s);
  17753. auto res = cli->Get("/");
  17754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17755. EXPECT_GE(s.proxy_hits(), 1);
  17756. EXPECT_EQ(0, s.target_hits());
  17757. }
  17758. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17759. ProxyAndTargetServers s;
  17760. auto cli = make_client("example.com", s);
  17761. cli->set_no_proxy({"example.com:8080"});
  17762. auto res = cli->Get("/");
  17763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17764. EXPECT_GE(s.proxy_hits(), 1);
  17765. EXPECT_EQ(0, s.target_hits());
  17766. }
  17767. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17768. ProxyAndTargetServers s;
  17769. auto cli = make_client("anything.test", s);
  17770. cli->set_no_proxy({"", " ", "\t"});
  17771. auto res = cli->Get("/");
  17772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17773. EXPECT_GE(s.proxy_hits(), 1);
  17774. EXPECT_EQ(0, s.target_hits());
  17775. }
  17776. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17777. // An entry with leading/trailing whitespace must still match — env-style
  17778. // values are commonly pasted with stray spaces and an implementation
  17779. // that feeds the raw token directly to inet_pton would fail to match
  17780. // valid CIDRs because of the spaces.
  17781. ProxyAndTargetServers s;
  17782. Client cli("127.0.0.1", s.target_port());
  17783. cli.set_proxy("127.0.0.1", s.proxy_port());
  17784. cli.set_no_proxy({" 127.0.0.0/8 "});
  17785. auto res = cli.Get("/");
  17786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17787. EXPECT_EQ(0, s.proxy_hits());
  17788. EXPECT_EQ(1, s.target_hits());
  17789. }
  17790. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17791. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17792. // go direct and must NOT carry Proxy-Authorization.
  17793. std::atomic<int> proxy_hits{0};
  17794. std::atomic<int> target_hits{0};
  17795. std::atomic<bool> target_saw_authz{false};
  17796. no_proxy_test::ScopedServer proxy_mock, target;
  17797. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17798. proxy_hits++;
  17799. res.status = 302;
  17800. res.set_header("Location", "http://127.0.0.1:" +
  17801. std::to_string(target.port()) + "/landed");
  17802. });
  17803. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17804. target_hits++;
  17805. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17806. res.set_content("direct", "text/plain");
  17807. });
  17808. proxy_mock.listen();
  17809. target.listen();
  17810. Client cli("public.example", target.port());
  17811. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17812. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17813. cli.set_proxy_basic_auth("u", "p");
  17814. cli.set_no_proxy({"127.0.0.1"});
  17815. cli.set_follow_location(true);
  17816. auto res = cli.Get("/redir");
  17817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17818. EXPECT_GE(proxy_hits.load(), 1);
  17819. EXPECT_GE(target_hits.load(), 1);
  17820. EXPECT_FALSE(target_saw_authz.load());
  17821. }
  17822. #ifdef CPPHTTPLIB_SSL_ENABLED
  17823. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17824. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17825. // proxy creds would be sent to the (possibly hostile) origin.
  17826. std::atomic<int> target_hits{0};
  17827. std::atomic<bool> target_saw_proxy_authz{false};
  17828. no_proxy_test::ScopedServer target;
  17829. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17830. target_hits++;
  17831. if (req.has_header("Proxy-Authorization")) {
  17832. target_saw_proxy_authz = true;
  17833. }
  17834. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17835. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17836. "nonce=\"abc\", algorithm=MD5");
  17837. });
  17838. target.listen();
  17839. // The proxy address is set to the target's port: the bypass MUST kick in;
  17840. // if it doesn't, the test still routes "via proxy" to the same server and
  17841. // the Proxy-Authorization assertion below catches the leak.
  17842. Client cli("evil.example", target.port());
  17843. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17844. cli.set_proxy("127.0.0.1", target.port());
  17845. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17846. cli.set_no_proxy({"evil.example"});
  17847. auto res = cli.Get("/x");
  17848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17849. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17850. EXPECT_EQ(1, target_hits.load());
  17851. EXPECT_FALSE(target_saw_proxy_authz.load());
  17852. }
  17853. #endif
  17854. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17855. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17856. std::atomic<int> proxy_hits{0};
  17857. std::atomic<int> bypass_hits{0};
  17858. std::atomic<bool> proxy_saw_c_url{false};
  17859. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17860. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17861. proxy_hits++;
  17862. if (req.path.find("/start") != std::string::npos) {
  17863. res.status = 302;
  17864. res.set_header("Location", "http://127.0.0.1:" +
  17865. std::to_string(bypass_server.port()) +
  17866. "/middle");
  17867. return;
  17868. }
  17869. if (req.path.find("/end") != std::string::npos) {
  17870. proxy_saw_c_url = true;
  17871. res.set_content("c-via-proxy", "text/plain");
  17872. return;
  17873. }
  17874. res.set_content("unexpected", "text/plain");
  17875. });
  17876. // public.example's "advertised" port is arbitrary (the request never lands
  17877. // there — it goes through the proxy), but use a dynamic value to stay
  17878. // friendly with sharded parallel runs.
  17879. int public_port = bypass_server.port();
  17880. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17881. bypass_hits++;
  17882. res.status = 302;
  17883. res.set_header("Location", "http://public.example:" +
  17884. std::to_string(public_port) + "/end");
  17885. });
  17886. proxy_mock.listen();
  17887. bypass_server.listen();
  17888. Client cli("public.example", public_port);
  17889. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17890. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17891. cli.set_no_proxy({"127.0.0.1"});
  17892. cli.set_follow_location(true);
  17893. auto res = cli.Get("/start");
  17894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17895. EXPECT_EQ(StatusCode::OK_200, res->status);
  17896. EXPECT_EQ("c-via-proxy", res->body);
  17897. EXPECT_GE(proxy_hits.load(), 2);
  17898. EXPECT_GE(bypass_hits.load(), 1);
  17899. EXPECT_TRUE(proxy_saw_c_url.load());
  17900. }
  17901. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17902. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17903. // request reconnects to the correct endpoint.
  17904. std::atomic<int> proxy_hits{0};
  17905. std::atomic<int> target_hits{0};
  17906. no_proxy_test::ScopedServer proxy_mock, target;
  17907. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17908. proxy_hits++;
  17909. res.set_content("via-proxy", "text/plain");
  17910. });
  17911. target.svr().Get(".*", [&](const Request &, Response &res) {
  17912. target_hits++;
  17913. res.set_content("direct", "text/plain");
  17914. });
  17915. proxy_mock.listen();
  17916. target.listen();
  17917. Client cli("public.example", target.port());
  17918. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17919. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17920. cli.set_keep_alive(true);
  17921. auto res1 = cli.Get("/a");
  17922. ASSERT_TRUE(res1);
  17923. EXPECT_EQ("via-proxy", res1->body);
  17924. EXPECT_EQ(1, proxy_hits.load());
  17925. EXPECT_EQ(0, target_hits.load());
  17926. cli.set_no_proxy({"public.example"});
  17927. auto res2 = cli.Get("/b");
  17928. ASSERT_TRUE(res2);
  17929. EXPECT_EQ("direct", res2->body);
  17930. EXPECT_EQ(1, proxy_hits.load());
  17931. EXPECT_EQ(1, target_hits.load());
  17932. }
  17933. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17934. namespace proxy_tunnel_test {
  17935. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17936. class ScopedSSLServer {
  17937. public:
  17938. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17939. port_ = svr_.bind_to_any_port("127.0.0.1");
  17940. }
  17941. ~ScopedSSLServer() {
  17942. svr_.stop();
  17943. if (th_.joinable()) { th_.join(); }
  17944. }
  17945. SSLServer &svr() { return svr_; }
  17946. int port() const { return port_; }
  17947. void listen() {
  17948. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17949. svr_.wait_until_ready();
  17950. }
  17951. private:
  17952. SSLServer svr_;
  17953. std::thread th_;
  17954. int port_ = 0;
  17955. };
  17956. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17957. class ScopedConnectProxy {
  17958. public:
  17959. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17960. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17961. if (listen_fd_ < 0) { return; }
  17962. int yes = 1;
  17963. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17964. sockaddr_in a{};
  17965. a.sin_family = AF_INET;
  17966. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17967. a.sin_port = 0;
  17968. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17969. return;
  17970. }
  17971. socklen_t alen = sizeof(a);
  17972. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17973. 0) {
  17974. return;
  17975. }
  17976. port_ = ntohs(a.sin_port);
  17977. if (::listen(listen_fd_, 1) != 0) { return; }
  17978. th_ = std::thread([this] { run(); });
  17979. }
  17980. ~ScopedConnectProxy() {
  17981. stop_ = true;
  17982. if (listen_fd_ >= 0) {
  17983. ::shutdown(listen_fd_, SHUT_RDWR);
  17984. ::close(listen_fd_);
  17985. }
  17986. if (th_.joinable()) { th_.join(); }
  17987. }
  17988. int port() const { return port_; }
  17989. int connect_hits() const { return connect_hits_.load(); }
  17990. private:
  17991. void run() {
  17992. while (!stop_.load()) {
  17993. fd_set rfds;
  17994. FD_ZERO(&rfds);
  17995. FD_SET(listen_fd_, &rfds);
  17996. timeval tv{0, 100 * 1000};
  17997. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17998. if (sel <= 0) { continue; }
  17999. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  18000. if (client_fd < 0) { continue; }
  18001. std::string req;
  18002. char buf[2048];
  18003. while (req.find("\r\n\r\n") == std::string::npos) {
  18004. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  18005. if (n <= 0) { break; }
  18006. req.append(buf, static_cast<size_t>(n));
  18007. }
  18008. if (req.compare(0, 7, "CONNECT") != 0) {
  18009. ::close(client_fd);
  18010. continue;
  18011. }
  18012. connect_hits_++;
  18013. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  18014. ::send(client_fd, ok, std::strlen(ok), 0);
  18015. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  18016. sockaddr_in o{};
  18017. o.sin_family = AF_INET;
  18018. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18019. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  18020. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  18021. 0) {
  18022. ::close(client_fd);
  18023. ::close(origin_fd);
  18024. continue;
  18025. }
  18026. auto forward = [](int from, int to) {
  18027. char b[8192];
  18028. for (;;) {
  18029. ssize_t n = ::recv(from, b, sizeof(b), 0);
  18030. if (n <= 0) { break; }
  18031. ssize_t off = 0;
  18032. while (off < n) {
  18033. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  18034. if (s <= 0) {
  18035. off = n;
  18036. break;
  18037. }
  18038. off += s;
  18039. }
  18040. }
  18041. ::shutdown(to, SHUT_WR);
  18042. };
  18043. std::thread t1([&] { forward(client_fd, origin_fd); });
  18044. std::thread t2([&] { forward(origin_fd, client_fd); });
  18045. t1.join();
  18046. t2.join();
  18047. ::close(client_fd);
  18048. ::close(origin_fd);
  18049. }
  18050. }
  18051. int forward_port_ = -1;
  18052. int listen_fd_ = -1;
  18053. int port_ = 0;
  18054. std::thread th_;
  18055. std::atomic<bool> stop_{false};
  18056. std::atomic<int> connect_hits_{0};
  18057. };
  18058. } // namespace proxy_tunnel_test
  18059. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  18060. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  18061. // retry; otherwise proxy creds would be sent to the origin.
  18062. std::atomic<int> origin_hits{0};
  18063. std::atomic<bool> origin_saw_proxy_authz{false};
  18064. proxy_tunnel_test::ScopedSSLServer origin;
  18065. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  18066. origin_hits++;
  18067. if (req.has_header("Proxy-Authorization")) {
  18068. origin_saw_proxy_authz = true;
  18069. }
  18070. res.status = StatusCode::ProxyAuthenticationRequired_407;
  18071. res.set_header("Proxy-Authenticate",
  18072. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  18073. "algorithm=MD5");
  18074. });
  18075. origin.listen();
  18076. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  18077. ASSERT_NE(0, proxy.port());
  18078. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  18079. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  18080. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  18081. // and answer with its own status, making this test flaky.
  18082. SSLClient cli("127.0.0.1", origin.port());
  18083. cli.enable_server_certificate_verification(false);
  18084. cli.set_proxy("127.0.0.1", proxy.port());
  18085. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  18086. auto res = cli.Get("/x");
  18087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18088. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18089. EXPECT_EQ(1, origin_hits.load());
  18090. EXPECT_FALSE(origin_saw_proxy_authz.load());
  18091. EXPECT_EQ(1, proxy.connect_hits());
  18092. }
  18093. #endif