test.cc 648 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908
  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 <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  47. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  48. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  49. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  50. #else
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  52. #endif
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  54. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  55. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  56. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  57. #ifdef CPPHTTPLIB_SSL_ENABLED
  58. namespace httplib {
  59. namespace tls {
  60. // Declared here for the split build, where the TLS abstraction declarations
  61. // live below the split border; the definition is linked from httplib.cc.
  62. ca_store_t create_ca_store(const char *pem, size_t len);
  63. } // namespace tls
  64. } // namespace httplib
  65. #endif
  66. using namespace std;
  67. using namespace httplib;
  68. const char *HOST = "localhost";
  69. static int get_base_port() {
  70. const char *shard = getenv("GTEST_SHARD_INDEX");
  71. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  72. }
  73. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  74. // New standalone tests MUST use svr.bind_to_any_port() instead.
  75. const int PORT = get_base_port();
  76. const string LONG_QUERY_VALUE = string(25000, '@');
  77. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  78. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  79. const string TOO_LONG_QUERY_URL =
  80. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  81. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  82. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  83. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  84. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  85. return file.name == key;
  86. });
  87. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  88. return *it;
  89. #else
  90. if (it != items.end()) { return *it; }
  91. throw std::runtime_error("invalid multipart form data name error");
  92. #endif
  93. }
  94. static void read_file(const std::string &path, std::string &out) {
  95. std::ifstream fs(path, std::ios_base::binary);
  96. if (!fs) {
  97. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  98. return;
  99. #else
  100. throw std::runtime_error("File not found: " + path);
  101. #endif
  102. }
  103. fs.seekg(0, std::ios_base::end);
  104. auto size = fs.tellg();
  105. fs.seekg(0);
  106. out.resize(static_cast<size_t>(size));
  107. fs.read(&out[0], static_cast<std::streamsize>(size));
  108. }
  109. class UnixSocketTest : public ::testing::Test {
  110. protected:
  111. void TearDown() override { std::remove(pathname_.c_str()); }
  112. void client_GET(const std::string &addr) {
  113. httplib::Client cli{addr};
  114. cli.set_address_family(AF_UNIX);
  115. ASSERT_TRUE(cli.is_valid());
  116. const auto &result = cli.Get(pattern_);
  117. ASSERT_TRUE(result) << "error: " << result.error();
  118. const auto &resp = result.value();
  119. EXPECT_EQ(resp.status, StatusCode::OK_200);
  120. EXPECT_EQ(resp.body, content_);
  121. }
  122. static std::string make_sock_path() {
  123. const char *shard = getenv("GTEST_SHARD_INDEX");
  124. return shard ? std::string("./httplib-server-") + shard + ".sock"
  125. : "./httplib-server.sock";
  126. }
  127. const std::string pathname_{make_sock_path()};
  128. const std::string pattern_{"/hi"};
  129. const std::string content_{"Hello World!"};
  130. };
  131. TEST_F(UnixSocketTest, pathname) {
  132. httplib::Server svr;
  133. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  134. res.set_content(content_, "text/plain");
  135. });
  136. std::thread t{[&] {
  137. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  138. }};
  139. auto se = detail::scope_exit([&] {
  140. svr.stop();
  141. t.join();
  142. ASSERT_FALSE(svr.is_running());
  143. });
  144. svr.wait_until_ready();
  145. ASSERT_TRUE(svr.is_running());
  146. client_GET(pathname_);
  147. }
  148. #if defined(__linux__) || \
  149. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  150. TEST_F(UnixSocketTest, PeerPid) {
  151. httplib::Server svr;
  152. std::string remote_port_val;
  153. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  154. res.set_content(content_, "text/plain");
  155. remote_port_val = std::to_string(req.remote_port);
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. client_GET(pathname_);
  168. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  169. }
  170. #endif
  171. #ifdef __linux__
  172. TEST_F(UnixSocketTest, abstract) {
  173. constexpr char svr_path[]{"\x00httplib-server.sock"};
  174. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  175. httplib::Server svr;
  176. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  177. res.set_content(content_, "text/plain");
  178. });
  179. std::thread t{[&] {
  180. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  181. }};
  182. auto se = detail::scope_exit([&] {
  183. svr.stop();
  184. t.join();
  185. ASSERT_FALSE(svr.is_running());
  186. });
  187. svr.wait_until_ready();
  188. ASSERT_TRUE(svr.is_running());
  189. client_GET(abstract_addr);
  190. }
  191. #endif
  192. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  193. httplib::Server svr;
  194. std::string received_host_header;
  195. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  196. // Capture the Host header sent by the client
  197. auto host_iter = req.headers.find("Host");
  198. if (host_iter != req.headers.end()) {
  199. received_host_header = host_iter->second;
  200. }
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. // Test that Host header is automatically set to "localhost" for Unix socket
  214. // connections
  215. httplib::Client cli{pathname_};
  216. cli.set_address_family(AF_UNIX);
  217. ASSERT_TRUE(cli.is_valid());
  218. const auto &result = cli.Get(pattern_);
  219. ASSERT_TRUE(result) << "error: " << result.error();
  220. const auto &resp = result.value();
  221. EXPECT_EQ(resp.status, StatusCode::OK_200);
  222. EXPECT_EQ(resp.body, content_);
  223. // Verify that Host header was automatically set to "localhost"
  224. EXPECT_EQ(received_host_header, "localhost");
  225. }
  226. #ifndef _WIN32
  227. TEST(SocketStream, wait_writable_UNIX) {
  228. int fds[2];
  229. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  230. const auto asSocketStream = [&](socket_t fd,
  231. std::function<bool(Stream &)> func) {
  232. return detail::process_client_socket(
  233. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  234. };
  235. asSocketStream(fds[0], [&](Stream &s0) {
  236. EXPECT_EQ(s0.socket(), fds[0]);
  237. EXPECT_TRUE(s0.wait_writable());
  238. EXPECT_TRUE(s0.is_peer_alive());
  239. EXPECT_EQ(0, close(fds[1]));
  240. EXPECT_FALSE(s0.is_peer_alive());
  241. return true;
  242. });
  243. EXPECT_EQ(0, close(fds[0]));
  244. }
  245. TEST(SocketStream, wait_writable_INET) {
  246. sockaddr_in addr;
  247. memset(&addr, 0, sizeof(addr));
  248. addr.sin_family = AF_INET;
  249. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  250. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  251. int disconnected_svr_sock = -1;
  252. std::thread svr{[&] {
  253. const int s = socket(AF_INET, SOCK_STREAM, 0);
  254. ASSERT_LE(0, s);
  255. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  256. ASSERT_EQ(0, listen(s, 1));
  257. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  258. ASSERT_EQ(0, close(s));
  259. }};
  260. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  261. std::thread cli{[&] {
  262. const int s = socket(AF_INET, SOCK_STREAM, 0);
  263. ASSERT_LE(0, s);
  264. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  265. ASSERT_EQ(0, close(s));
  266. }};
  267. cli.join();
  268. svr.join();
  269. ASSERT_NE(disconnected_svr_sock, -1);
  270. const auto asSocketStream = [&](socket_t fd,
  271. std::function<bool(Stream &)> func) {
  272. return detail::process_client_socket(
  273. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  274. };
  275. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  276. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  277. // wait_writable() returns true because select_write() only checks if the
  278. // send buffer has space. Peer disconnection is detected later by send().
  279. EXPECT_TRUE(ss.wait_writable());
  280. return true;
  281. });
  282. ASSERT_EQ(0, close(disconnected_svr_sock));
  283. }
  284. #endif // #ifndef _WIN32
  285. TEST(SetSocketOptTest, TcpNoDelay) {
  286. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  287. ASSERT_NE(sock, INVALID_SOCKET);
  288. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  289. int val = 0;
  290. socklen_t len = sizeof(val);
  291. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  292. reinterpret_cast<char *>(&val), &len));
  293. EXPECT_NE(val, 0);
  294. detail::close_socket(sock);
  295. }
  296. TEST(ClientTest, MoveConstructible) {
  297. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  298. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  299. }
  300. TEST(ClientTest, MoveAssignable) {
  301. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  302. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  303. }
  304. #ifdef _WIN32
  305. TEST(StartupTest, WSAStartup) {
  306. WSADATA wsaData;
  307. int ret = WSAStartup(0x0002, &wsaData);
  308. ASSERT_EQ(0, ret);
  309. }
  310. #endif
  311. TEST(DecodePathTest, PercentCharacter) {
  312. EXPECT_EQ(
  313. decode_path_component(
  314. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  315. U8("descrip=Gastos áéíóúñÑ 6"));
  316. }
  317. TEST(DecodePathTest, PercentCharacterNUL) {
  318. string expected;
  319. expected.push_back('x');
  320. expected.push_back('\0');
  321. expected.push_back('x');
  322. EXPECT_EQ(decode_path_component("x%00x"), expected);
  323. }
  324. TEST(DecodePathTest, UnicodeEncoding) {
  325. // %u0041 = 'A' (1-byte UTF-8)
  326. EXPECT_EQ("A", decode_path_component("%u0041"));
  327. // %u00E9 = 'é' (2-byte UTF-8)
  328. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  329. // %u3042 = 'あ' (3-byte UTF-8)
  330. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  331. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  332. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  333. // %uD800 = surrogate (invalid, silently dropped)
  334. EXPECT_EQ("", decode_path_component("%uD800"));
  335. }
  336. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  337. // A sign or whitespace inside the two-character escape window must not be
  338. // accepted as a valid percent-encoding; the sequence is passed through
  339. // literally, matching decode_uri_component / decode_path_component.
  340. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  341. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  342. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  343. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  344. // Well-formed escapes still decode.
  345. EXPECT_EQ("-", decode_query_component("%2D", false));
  346. EXPECT_EQ("A", decode_query_component("%41", false));
  347. }
  348. TEST(SanitizeFilenameTest, VariousPatterns) {
  349. // Path traversal
  350. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  351. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  352. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  353. // Normal and edge cases
  354. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  355. EXPECT_EQ("filename.txt",
  356. httplib::sanitize_filename("/path/to/filename.txt"));
  357. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  358. EXPECT_EQ("", httplib::sanitize_filename(".."));
  359. EXPECT_EQ("", httplib::sanitize_filename(""));
  360. // Null bytes stripped
  361. EXPECT_EQ("safe.txt",
  362. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  363. // Whitespace-only rejected
  364. EXPECT_EQ("", httplib::sanitize_filename(" "));
  365. }
  366. // Forward declaration (see the base64_encode note below): split builds move the
  367. // definition into httplib.cc, so re-declaring it here lets the test link.
  368. namespace httplib {
  369. namespace detail {
  370. bool is_chunked_transfer_encoding(const Headers &headers);
  371. } // namespace detail
  372. } // namespace httplib
  373. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  374. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  375. auto make = [](std::initializer_list<const char *> lines) {
  376. Headers h;
  377. for (auto te : lines) {
  378. if (te) { h.emplace("Transfer-Encoding", te); }
  379. }
  380. return h;
  381. };
  382. // Sole coding, matched case-insensitively.
  383. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  384. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  386. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  388. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  390. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  391. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  392. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  395. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  396. // portable, so any line naming chunked is treated as chunked (fail safe).
  397. // The result must not depend on the order the lines were added.
  398. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  399. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  401. }
  402. // Forward declaration: in split builds split.py strips `inline` and moves the
  403. // definition into httplib.cc, so detail::base64_encode is not visible from the
  404. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  405. // in both header-only and split builds.
  406. namespace httplib {
  407. namespace detail {
  408. std::string base64_encode(const std::string &in);
  409. } // namespace detail
  410. } // namespace httplib
  411. TEST(Base64EncodeTest, KnownAnswers) {
  412. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  413. // where the accumulator's top bit is already set before the next shift.
  414. EXPECT_EQ("", detail::base64_encode(""));
  415. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  416. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  417. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  418. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  419. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  420. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  421. // High bytes keep the top bit set across several rounds.
  422. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  423. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  424. }
  425. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  426. string unescapedCharacters = "-_.!~*'()";
  427. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  428. }
  429. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  430. string reservedCharacters = ";,/?:@&=+$";
  431. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  432. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  433. }
  434. TEST(ClientQueryOrder, PreserveOrder) {
  435. // This test reproduces Issue #2259: client may reorder query parameters
  436. // when sending a GET request. The expected behavior is that the client
  437. // preserves the original query string order when the caller supplied it
  438. // as part of the path.
  439. Server svr;
  440. svr.Get("/", [&](const Request &req, Response &res) {
  441. // Echo back the raw target so the test can assert ordering
  442. res.set_content(req.target, "text/plain");
  443. });
  444. std::thread t{[&] { svr.listen(HOST, PORT); }};
  445. auto se = detail::scope_exit([&] {
  446. svr.stop();
  447. t.join();
  448. ASSERT_FALSE(svr.is_running());
  449. });
  450. svr.wait_until_ready();
  451. Client cli(HOST, PORT);
  452. ASSERT_TRUE(cli.is_valid());
  453. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  454. auto res = cli.Get(original);
  455. ASSERT_TRUE(res);
  456. // Expect the echoed target to exactly match the original path (order
  457. // preserved)
  458. EXPECT_EQ(res->body, original);
  459. }
  460. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  461. string chineseCharacters = U8("中国語");
  462. string russianCharacters = U8("дом");
  463. string brazilianCharacters = U8("óculos");
  464. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  465. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  466. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  467. "%D0%B4%D0%BE%D0%BC");
  468. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  469. }
  470. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  471. string unescapedCharacters = "-_.!~*'()";
  472. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  473. }
  474. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  475. string reservedCharacters = ";,/?:@&=+$";
  476. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  477. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  478. }
  479. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  480. string chineseCharacters = U8("中国語");
  481. string russianCharacters = U8("дом");
  482. string brazilianCharacters = U8("óculos");
  483. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  484. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  485. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  486. "%D0%B4%D0%BE%D0%BC");
  487. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  488. }
  489. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  490. // Issue #2082 use case: encoding path component with ampersand
  491. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  492. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  493. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  494. }
  495. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  496. string unescapedCharacters = "-_.!~*'()";
  497. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  498. }
  499. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  500. string reservedCharacters = ";,/?:@&=+$#";
  501. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  502. }
  503. TEST(EncodeUriTest, TestUTF8Characters) {
  504. string chineseCharacters = U8("中国語");
  505. string russianCharacters = U8("дом");
  506. string brazilianCharacters = U8("óculos");
  507. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  508. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  509. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  510. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  511. }
  512. TEST(EncodeUriTest, TestCompleteUri) {
  513. string uri =
  514. "https://example.com/path/to/resource?query=value&param=test#fragment";
  515. EXPECT_EQ(
  516. httplib::encode_uri(uri),
  517. "https://example.com/path/to/resource?query=value&param=test#fragment");
  518. }
  519. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  520. string uri =
  521. "https://example.com/path with spaces/file name.html?q=hello world";
  522. EXPECT_EQ(httplib::encode_uri(uri),
  523. "https://example.com/path%20with%20spaces/"
  524. "file%20name.html?q=hello%20world");
  525. }
  526. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  527. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  528. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  529. }
  530. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  531. string unescapedCharacters = "-_.!~*'()";
  532. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  533. }
  534. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  535. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  536. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  537. string encodedBrazilian = "%C3%B3culos";
  538. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  539. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  540. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  541. }
  542. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  543. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  544. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  545. "Piri Tommy Villiers - on & on");
  546. }
  547. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  548. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  549. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  550. }
  551. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  552. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  553. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  554. }
  555. TEST(DecodeUriTest, TestUTF8Characters) {
  556. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  557. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  558. string encodedBrazilian = "%C3%B3culos";
  559. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  560. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  561. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  562. }
  563. TEST(DecodeUriTest, TestCompleteUri) {
  564. string encodedUri = "https://example.com/path%20with%20spaces/"
  565. "file%20name.html?q=hello%20world";
  566. EXPECT_EQ(
  567. httplib::decode_uri(encodedUri),
  568. "https://example.com/path with spaces/file name.html?q=hello world");
  569. }
  570. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  571. string original =
  572. "https://example.com/path with spaces/file name.html?q=hello world";
  573. string encoded = httplib::encode_uri(original);
  574. string decoded = httplib::decode_uri(encoded);
  575. EXPECT_EQ(decoded, original);
  576. }
  577. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  578. string original = "Piri Tommy Villiers - on & on";
  579. string encoded = httplib::encode_uri_component(original);
  580. string decoded = httplib::decode_uri_component(encoded);
  581. EXPECT_EQ(decoded, original);
  582. }
  583. TEST(TrimTests, TrimStringTests) {
  584. EXPECT_EQ("abc", detail::trim_copy("abc"));
  585. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  586. EXPECT_TRUE(detail::trim_copy("").empty());
  587. }
  588. TEST(AsciiTest, LocaleIndependentClassification) {
  589. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  590. // which consult the global C locale: std::isalnum(0xC5) can return true
  591. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  592. // helpers must classify every byte by the ASCII grammar alone.
  593. for (int i = 0; i < 256; i++) {
  594. auto c = static_cast<char>(i);
  595. auto is_digit = i >= '0' && i <= '9';
  596. auto is_upper = i >= 'A' && i <= 'Z';
  597. auto is_lower = i >= 'a' && i <= 'z';
  598. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  599. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  600. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  601. << "byte " << i;
  602. }
  603. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  604. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  605. // Non-ASCII bytes must be percent-encoded, never passed through as
  606. // alphanumeric.
  607. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  608. }
  609. TEST(FromCharsTest, Double) {
  610. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  611. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  612. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  613. auto parse = [](const std::string &s, double &v) {
  614. return detail::from_chars(s.data(), s.data() + s.size(), v);
  615. };
  616. double v = -1.0;
  617. // Representative quality values.
  618. EXPECT_EQ(parse("0", v).ec, std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.0);
  620. EXPECT_EQ(parse("1", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 1.0);
  622. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  623. EXPECT_DOUBLE_EQ(v, 0.8);
  624. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  625. EXPECT_DOUBLE_EQ(v, 0.001);
  626. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  627. EXPECT_DOUBLE_EQ(v, 1.0);
  628. // A missing integer or fractional part is tolerated.
  629. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  630. EXPECT_DOUBLE_EQ(v, 0.5);
  631. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 5.0);
  633. // Values outside [0, 1] still parse; the caller range-checks them.
  634. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  635. EXPECT_DOUBLE_EQ(v, 123.456);
  636. // Stops at the first byte that is not part of the number and reports where.
  637. std::string trailing = "0.9, text/html";
  638. auto r = parse(trailing, v);
  639. EXPECT_EQ(r.ec, std::errc{});
  640. EXPECT_DOUBLE_EQ(v, 0.9);
  641. EXPECT_EQ(*r.ptr, ',');
  642. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  643. // outright, and an 'e'/'E' simply ends the number.
  644. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  645. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  646. std::string exp_input = "1.5e3";
  647. r = parse(exp_input, v);
  648. EXPECT_EQ(r.ec, std::errc{});
  649. EXPECT_DOUBLE_EQ(v, 1.5);
  650. EXPECT_EQ(*r.ptr, 'e');
  651. // Invalid inputs.
  652. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  653. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  654. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  655. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  657. // Pathological but well-formed inputs must stay bounded (no overflow, no
  658. // out-of-bounds table access) and stay within [0, 1] for the caller.
  659. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  660. std::errc{});
  661. EXPECT_DOUBLE_EQ(v, 0.0);
  662. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  663. std::errc{});
  664. EXPECT_GE(v, 0.0);
  665. EXPECT_LE(v, 1.0);
  666. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  667. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  668. }
  669. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  670. // Simple case without quality values
  671. std::vector<std::string> result1;
  672. EXPECT_TRUE(detail::parse_accept_header(
  673. "text/html,application/json,text/plain", result1));
  674. EXPECT_EQ(result1.size(), 3U);
  675. EXPECT_EQ(result1[0], "text/html");
  676. EXPECT_EQ(result1[1], "application/json");
  677. EXPECT_EQ(result1[2], "text/plain");
  678. // With quality values
  679. std::vector<std::string> result2;
  680. EXPECT_TRUE(detail::parse_accept_header(
  681. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  682. EXPECT_EQ(result2.size(), 3U);
  683. EXPECT_EQ(result2[0], "application/json"); // highest q value
  684. EXPECT_EQ(result2[1], "text/html");
  685. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  686. }
  687. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  688. // Mixed with and without quality values
  689. std::vector<std::string> result;
  690. EXPECT_TRUE(detail::parse_accept_header(
  691. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  692. EXPECT_EQ(result.size(), 3U);
  693. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  694. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  695. EXPECT_EQ(result[2], "application/json"); // q=0.5
  696. }
  697. TEST(ParseAcceptHeaderTest, EdgeCases) {
  698. // Empty header
  699. std::vector<std::string> empty_result;
  700. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  701. EXPECT_TRUE(empty_result.empty());
  702. // Single type
  703. std::vector<std::string> single_result;
  704. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  705. EXPECT_EQ(single_result.size(), 1U);
  706. EXPECT_EQ(single_result[0], "application/json");
  707. // Wildcard types
  708. std::vector<std::string> wildcard_result;
  709. EXPECT_TRUE(detail::parse_accept_header(
  710. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  711. EXPECT_EQ(wildcard_result.size(), 3U);
  712. EXPECT_EQ(wildcard_result[0], "application/json");
  713. EXPECT_EQ(wildcard_result[1], "text/*");
  714. EXPECT_EQ(wildcard_result[2], "*/*");
  715. }
  716. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  717. // Common browser Accept header
  718. std::vector<std::string> browser_result;
  719. EXPECT_TRUE(
  720. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  721. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  722. browser_result));
  723. EXPECT_EQ(browser_result.size(), 6U);
  724. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  725. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  726. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  727. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  728. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  729. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  730. // API client header
  731. std::vector<std::string> api_result;
  732. EXPECT_TRUE(detail::parse_accept_header(
  733. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  734. api_result));
  735. EXPECT_EQ(api_result.size(), 3U);
  736. EXPECT_EQ(api_result[0], "application/json");
  737. EXPECT_EQ(api_result[1], "application/xml");
  738. EXPECT_EQ(api_result[2], "text/plain");
  739. }
  740. TEST(ParseAcceptHeaderTest, SpecialCases) {
  741. // Quality value with 3 decimal places
  742. std::vector<std::string> decimal_result;
  743. EXPECT_TRUE(detail::parse_accept_header(
  744. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  745. EXPECT_EQ(decimal_result.size(), 2U);
  746. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  747. EXPECT_EQ(decimal_result[1], "text/html");
  748. // Zero quality (should still be included but with lowest priority)
  749. std::vector<std::string> zero_q_result;
  750. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  751. zero_q_result));
  752. EXPECT_EQ(zero_q_result.size(), 2U);
  753. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  754. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  755. // No spaces around commas
  756. std::vector<std::string> no_space_result;
  757. EXPECT_TRUE(detail::parse_accept_header(
  758. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  759. no_space_result));
  760. EXPECT_EQ(no_space_result.size(), 3U);
  761. EXPECT_EQ(no_space_result[0], "text/html");
  762. EXPECT_EQ(no_space_result[1], "application/json");
  763. EXPECT_EQ(no_space_result[2], "text/plain");
  764. }
  765. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  766. // Quality values always use '.' as the decimal separator, so parsing must
  767. // not depend on the process locale. An embedding application may have
  768. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  769. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  770. std::string saved = cur ? cur : "C";
  771. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  772. "fr_FR.UTF-8"};
  773. bool switched = false;
  774. for (const auto loc : comma_locales) {
  775. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  776. std::localeconv()->decimal_point[0] == ',') {
  777. switched = true;
  778. break;
  779. }
  780. }
  781. if (!switched) {
  782. std::setlocale(LC_NUMERIC, saved.c_str());
  783. GTEST_SKIP() << "no comma-decimal locale available on this host";
  784. }
  785. // The higher-weighted type appears later in the list, so a correct parse
  786. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  787. // sensitive parse reads both weights as 0 and leaves the original order.
  788. std::vector<std::string> result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "application/json;q=0.1,text/html;q=0.9", result));
  791. ASSERT_EQ(result.size(), 2U);
  792. EXPECT_EQ(result[0], "text/html");
  793. EXPECT_EQ(result[1], "application/json");
  794. std::setlocale(LC_NUMERIC, saved.c_str());
  795. }
  796. TEST(ParseAcceptHeaderTest, InvalidCases) {
  797. std::vector<std::string> result;
  798. // Invalid quality value (> 1.0)
  799. EXPECT_FALSE(
  800. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  801. // Invalid quality value (< 0.0)
  802. EXPECT_FALSE(
  803. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  804. // Invalid quality value (not a number)
  805. EXPECT_FALSE(detail::parse_accept_header(
  806. "text/html;q=invalid,application/json", result));
  807. // Empty quality value
  808. EXPECT_FALSE(
  809. detail::parse_accept_header("text/html;q=,application/json", result));
  810. // Invalid media type format (no slash and not wildcard)
  811. EXPECT_FALSE(
  812. detail::parse_accept_header("invalidtype,application/json", result));
  813. // Empty media type
  814. result.clear();
  815. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  816. // Only commas
  817. result.clear();
  818. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  819. // Valid cases should still work
  820. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  821. EXPECT_EQ(result.size(), 1U);
  822. EXPECT_EQ(result[0], "*/*");
  823. EXPECT_TRUE(detail::parse_accept_header("*", result));
  824. EXPECT_EQ(result.size(), 1U);
  825. EXPECT_EQ(result[0], "*");
  826. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  827. EXPECT_EQ(result.size(), 1U);
  828. EXPECT_EQ(result[0], "text/*");
  829. }
  830. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  831. Server svr;
  832. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  833. EXPECT_EQ(req.accept_content_types.size(), 3U);
  834. EXPECT_EQ(req.accept_content_types[0], "application/json");
  835. EXPECT_EQ(req.accept_content_types[1], "text/html");
  836. EXPECT_EQ(req.accept_content_types[2], "*/*");
  837. res.set_content("ok", "text/plain");
  838. });
  839. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  840. EXPECT_TRUE(false);
  841. res.set_content("bad request", "text/plain");
  842. });
  843. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  844. auto se = detail::scope_exit([&] {
  845. svr.stop();
  846. listen_thread.join();
  847. ASSERT_FALSE(svr.is_running());
  848. });
  849. svr.wait_until_ready();
  850. Client cli("localhost", PORT);
  851. {
  852. auto res = cli.Get(
  853. "/accept_ok",
  854. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  855. ASSERT_TRUE(res);
  856. EXPECT_EQ(StatusCode::OK_200, res->status);
  857. }
  858. {
  859. auto res = cli.Get("/accept_bad_request",
  860. Headers{{"Accept", "text/html;q=abc,application/json"}});
  861. ASSERT_TRUE(res);
  862. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  863. }
  864. }
  865. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  866. Server svr;
  867. svr.Get("/", [](const Request & /*req*/, Response &res) {
  868. res.set_content("ok", "text/plain");
  869. });
  870. std::atomic<int> start_count{0};
  871. std::atomic<bool> running_when_called{false};
  872. svr.set_start_handler([&]() {
  873. running_when_called = svr.is_running();
  874. start_count++;
  875. });
  876. auto port = svr.bind_to_any_port(HOST);
  877. std::thread t([&]() { svr.listen_after_bind(); });
  878. auto se = detail::scope_exit([&] {
  879. svr.stop();
  880. t.join();
  881. ASSERT_FALSE(svr.is_running());
  882. });
  883. svr.wait_until_ready();
  884. // A successful request proves the accept loop is running, which the start
  885. // handler precedes; so by now the handler must have run exactly once.
  886. Client cli(HOST, port);
  887. cli.set_connection_timeout(std::chrono::seconds(5));
  888. auto res = cli.Get("/");
  889. ASSERT_TRUE(res);
  890. EXPECT_EQ(StatusCode::OK_200, res->status);
  891. EXPECT_EQ(1, start_count.load());
  892. EXPECT_TRUE(running_when_called.load());
  893. }
  894. TEST(DivideTest, DivideStringTests) {
  895. auto divide = [](const std::string &str, char d) {
  896. std::string lhs;
  897. std::string rhs;
  898. detail::divide(str, d,
  899. [&](const char *lhs_data, std::size_t lhs_size,
  900. const char *rhs_data, std::size_t rhs_size) {
  901. lhs.assign(lhs_data, lhs_size);
  902. rhs.assign(rhs_data, rhs_size);
  903. });
  904. return std::make_pair(std::move(lhs), std::move(rhs));
  905. };
  906. {
  907. const auto res = divide("", '=');
  908. EXPECT_EQ(res.first, "");
  909. EXPECT_EQ(res.second, "");
  910. }
  911. {
  912. const auto res = divide("=", '=');
  913. EXPECT_EQ(res.first, "");
  914. EXPECT_EQ(res.second, "");
  915. }
  916. {
  917. const auto res = divide(" ", '=');
  918. EXPECT_EQ(res.first, " ");
  919. EXPECT_EQ(res.second, "");
  920. }
  921. {
  922. const auto res = divide("a", '=');
  923. EXPECT_EQ(res.first, "a");
  924. EXPECT_EQ(res.second, "");
  925. }
  926. {
  927. const auto res = divide("a=", '=');
  928. EXPECT_EQ(res.first, "a");
  929. EXPECT_EQ(res.second, "");
  930. }
  931. {
  932. const auto res = divide("=b", '=');
  933. EXPECT_EQ(res.first, "");
  934. EXPECT_EQ(res.second, "b");
  935. }
  936. {
  937. const auto res = divide("a=b", '=');
  938. EXPECT_EQ(res.first, "a");
  939. EXPECT_EQ(res.second, "b");
  940. }
  941. {
  942. const auto res = divide("a=b=", '=');
  943. EXPECT_EQ(res.first, "a");
  944. EXPECT_EQ(res.second, "b=");
  945. }
  946. {
  947. const auto res = divide("a=b=c", '=');
  948. EXPECT_EQ(res.first, "a");
  949. EXPECT_EQ(res.second, "b=c");
  950. }
  951. }
  952. TEST(SplitTest, ParseQueryString) {
  953. string s = "key1=val1&key2=val2&key3=val3";
  954. Params dic;
  955. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  956. [&](const char *b, const char *e) {
  957. string key, val;
  958. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  959. if (key.empty()) {
  960. key.assign(b2, e2);
  961. } else {
  962. val.assign(b2, e2);
  963. }
  964. });
  965. dic.emplace(key, val);
  966. });
  967. EXPECT_EQ("val1", dic.find("key1")->second);
  968. EXPECT_EQ("val2", dic.find("key2")->second);
  969. EXPECT_EQ("val3", dic.find("key3")->second);
  970. }
  971. TEST(SplitTest, ParseInvalidQueryTests) {
  972. {
  973. string s = " ";
  974. Params dict;
  975. detail::parse_query_text(s, dict);
  976. EXPECT_TRUE(dict.empty());
  977. }
  978. {
  979. string s = " = =";
  980. Params dict;
  981. detail::parse_query_text(s, dict);
  982. EXPECT_TRUE(dict.empty());
  983. }
  984. }
  985. TEST(ParseQueryTest, ParseQueryString) {
  986. {
  987. std::string s = "key1=val1&key2=val2&key3=val3";
  988. Params dic;
  989. detail::parse_query_text(s, dic);
  990. EXPECT_EQ("val1", dic.find("key1")->second);
  991. EXPECT_EQ("val2", dic.find("key2")->second);
  992. EXPECT_EQ("val3", dic.find("key3")->second);
  993. }
  994. {
  995. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  996. Params dic;
  997. detail::parse_query_text(s, dic);
  998. EXPECT_EQ("", dic.find("key1")->second);
  999. EXPECT_EQ("val1", dic.find("key2")->second);
  1000. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1001. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1002. }
  1003. }
  1004. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1005. Params dic;
  1006. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1007. dic.emplace("key1", "val1");
  1008. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1009. dic.emplace("key2", "val2");
  1010. dic.emplace("key3", "val3");
  1011. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1012. }
  1013. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1014. string content_type = "multipart/form-data; boundary=something";
  1015. string boundary;
  1016. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1017. EXPECT_TRUE(ret);
  1018. EXPECT_EQ(boundary, "something");
  1019. }
  1020. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1021. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1022. string boundary;
  1023. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1024. EXPECT_TRUE(ret);
  1025. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1026. }
  1027. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1028. string content_type =
  1029. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1030. string boundary;
  1031. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1032. EXPECT_TRUE(ret);
  1033. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1034. }
  1035. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1036. string content_type =
  1037. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1038. string boundary;
  1039. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1040. EXPECT_TRUE(ret);
  1041. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1042. }
  1043. TEST(GetHeaderValueTest, DefaultValue) {
  1044. Headers headers = {{"Dummy", "Dummy"}};
  1045. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1046. EXPECT_STREQ("text/plain", val);
  1047. }
  1048. TEST(GetHeaderValueTest, DefaultValueInt) {
  1049. Headers headers = {{"Dummy", "Dummy"}};
  1050. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1051. EXPECT_EQ(100ull, val);
  1052. }
  1053. TEST(GetHeaderValueTest, RegularValue) {
  1054. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1055. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1056. EXPECT_STREQ("text/html", val);
  1057. }
  1058. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1059. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1060. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1061. EXPECT_STREQ("text/html", val);
  1062. }
  1063. TEST(GetHeaderValueTest, SetContent) {
  1064. Response res;
  1065. res.set_content("html", "text/html");
  1066. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1067. res.set_content("text", "text/plain");
  1068. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1069. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1070. }
  1071. TEST(GetHeaderValueTest, RegularValueInt) {
  1072. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1073. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1074. EXPECT_EQ(100ull, val);
  1075. }
  1076. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1077. Headers headers = {{"Content-Length", "x"}};
  1078. auto is_invalid_value = false;
  1079. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1080. is_invalid_value);
  1081. EXPECT_EQ(0ull, val);
  1082. EXPECT_TRUE(is_invalid_value);
  1083. }
  1084. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1085. // An all-digit value that overflows size_t must be reported as invalid, not
  1086. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1087. // a large length to a small one on 32-bit builds, leaving the framing length
  1088. // wrong while is_invalid_value stayed false.
  1089. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1090. auto is_invalid_value = false;
  1091. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1092. is_invalid_value);
  1093. EXPECT_TRUE(is_invalid_value);
  1094. // A well-formed length is unaffected.
  1095. Headers ok = {{"Content-Length", "1234"}};
  1096. is_invalid_value = false;
  1097. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1098. is_invalid_value);
  1099. EXPECT_EQ(1234ull, val);
  1100. EXPECT_FALSE(is_invalid_value);
  1101. }
  1102. TEST(GetHeaderValueTest, Range) {
  1103. {
  1104. Headers headers = {make_range_header({{1, -1}})};
  1105. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1106. EXPECT_STREQ("bytes=1-", val);
  1107. }
  1108. {
  1109. Headers headers = {make_range_header({{-1, 1}})};
  1110. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1111. EXPECT_STREQ("bytes=-1", val);
  1112. }
  1113. {
  1114. Headers headers = {make_range_header({{1, 10}})};
  1115. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1116. EXPECT_STREQ("bytes=1-10", val);
  1117. }
  1118. {
  1119. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1120. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1121. EXPECT_STREQ("bytes=1-10, 100-", val);
  1122. }
  1123. {
  1124. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1125. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1126. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1127. }
  1128. {
  1129. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1130. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1131. EXPECT_STREQ("bytes=0-0, -1", val);
  1132. }
  1133. }
  1134. TEST(ParseHeaderValueTest, Range) {
  1135. {
  1136. Ranges ranges;
  1137. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1138. EXPECT_TRUE(ret);
  1139. EXPECT_EQ(1u, ranges.size());
  1140. EXPECT_EQ(1u, ranges[0].first);
  1141. EXPECT_EQ(-1, ranges[0].second);
  1142. }
  1143. {
  1144. Ranges ranges;
  1145. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1146. EXPECT_TRUE(ret);
  1147. EXPECT_EQ(1u, ranges.size());
  1148. EXPECT_EQ(-1, ranges[0].first);
  1149. EXPECT_EQ(1u, ranges[0].second);
  1150. }
  1151. {
  1152. Ranges ranges;
  1153. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1154. EXPECT_TRUE(ret);
  1155. EXPECT_EQ(1u, ranges.size());
  1156. EXPECT_EQ(1u, ranges[0].first);
  1157. EXPECT_EQ(10u, ranges[0].second);
  1158. }
  1159. {
  1160. Ranges ranges;
  1161. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1162. EXPECT_FALSE(ret);
  1163. }
  1164. {
  1165. Ranges ranges;
  1166. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1167. EXPECT_TRUE(ret);
  1168. EXPECT_EQ(2u, ranges.size());
  1169. EXPECT_EQ(1u, ranges[0].first);
  1170. EXPECT_EQ(10u, ranges[0].second);
  1171. EXPECT_EQ(100u, ranges[1].first);
  1172. EXPECT_EQ(-1, ranges[1].second);
  1173. }
  1174. {
  1175. Ranges ranges;
  1176. auto ret =
  1177. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1178. EXPECT_TRUE(ret);
  1179. EXPECT_EQ(3u, ranges.size());
  1180. EXPECT_EQ(1u, ranges[0].first);
  1181. EXPECT_EQ(10u, ranges[0].second);
  1182. EXPECT_EQ(100u, ranges[1].first);
  1183. EXPECT_EQ(200u, ranges[1].second);
  1184. EXPECT_EQ(300u, ranges[2].first);
  1185. EXPECT_EQ(400u, ranges[2].second);
  1186. }
  1187. {
  1188. Ranges ranges;
  1189. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1190. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1191. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1192. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1193. EXPECT_FALSE(detail::parse_range_header("bytes= ", 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=a-b", ranges));
  1198. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1199. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1200. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1201. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1202. EXPECT_TRUE(ranges.empty());
  1203. }
  1204. }
  1205. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1206. Request req;
  1207. req.set_header("Accept-Encoding", "gzip");
  1208. Response res;
  1209. res.set_header("Content-Type", "text/plain");
  1210. auto ret = detail::encoding_type(req, res);
  1211. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1212. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1213. #else
  1214. EXPECT_TRUE(ret == detail::EncodingType::None);
  1215. #endif
  1216. }
  1217. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1218. Request req;
  1219. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1220. Response res;
  1221. res.set_header("Content-Type", "text/plain");
  1222. auto ret = detail::encoding_type(req, res);
  1223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1224. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1225. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1226. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1227. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1228. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1229. #else
  1230. EXPECT_TRUE(ret == detail::EncodingType::None);
  1231. #endif
  1232. }
  1233. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1234. Request req;
  1235. req.set_header("Accept-Encoding",
  1236. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1237. Response res;
  1238. res.set_header("Content-Type", "text/plain");
  1239. auto ret = detail::encoding_type(req, res);
  1240. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1241. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1242. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1243. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1244. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1245. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1246. #else
  1247. EXPECT_TRUE(ret == detail::EncodingType::None);
  1248. #endif
  1249. }
  1250. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1251. // All supported encodings rejected with q=0 should return None
  1252. Request req;
  1253. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1254. Response res;
  1255. res.set_header("Content-Type", "text/plain");
  1256. auto ret = detail::encoding_type(req, res);
  1257. EXPECT_TRUE(ret == detail::EncodingType::None);
  1258. }
  1259. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1260. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1261. Request req;
  1262. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1263. Response res;
  1264. res.set_header("Content-Type", "text/plain");
  1265. auto ret = detail::encoding_type(req, res);
  1266. EXPECT_TRUE(ret == detail::EncodingType::None);
  1267. }
  1268. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1269. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1270. Request req;
  1271. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1272. Response res;
  1273. res.set_header("Content-Type", "text/plain");
  1274. auto ret = detail::encoding_type(req, res);
  1275. EXPECT_TRUE(ret == detail::EncodingType::None);
  1276. }
  1277. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1278. // RFC 7231: Accept-Encoding values are case-insensitive
  1279. Request req;
  1280. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1281. Response res;
  1282. res.set_header("Content-Type", "text/plain");
  1283. auto ret = detail::encoding_type(req, res);
  1284. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1285. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1286. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1287. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1288. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1289. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1290. #else
  1291. EXPECT_TRUE(ret == detail::EncodingType::None);
  1292. #endif
  1293. }
  1294. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1295. // q value should determine priority, not hardcoded order
  1296. Request req;
  1297. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1298. Response res;
  1299. res.set_header("Content-Type", "text/plain");
  1300. auto ret = detail::encoding_type(req, res);
  1301. // gzip has highest q=1.0, so it should be selected even though
  1302. // br and zstd are also supported
  1303. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1304. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1305. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1306. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1307. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1308. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1309. #else
  1310. EXPECT_TRUE(ret == detail::EncodingType::None);
  1311. #endif
  1312. }
  1313. TEST(BufferStreamTest, read) {
  1314. detail::BufferStream strm1;
  1315. Stream &strm = strm1;
  1316. EXPECT_EQ(5, strm.write("hello"));
  1317. char buf[512];
  1318. EXPECT_EQ(2, strm.read(buf, 2));
  1319. EXPECT_EQ('h', buf[0]);
  1320. EXPECT_EQ('e', buf[1]);
  1321. EXPECT_EQ(2, strm.read(buf, 2));
  1322. EXPECT_EQ('l', buf[0]);
  1323. EXPECT_EQ('l', buf[1]);
  1324. EXPECT_EQ(1, strm.read(buf, 1));
  1325. EXPECT_EQ('o', buf[0]);
  1326. EXPECT_EQ(0, strm.read(buf, 1));
  1327. }
  1328. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1329. auto host = "www.httpwatch.com";
  1330. auto ip = hosted_at(host);
  1331. EXPECT_EQ("23.96.13.243", ip);
  1332. std::vector<std::string> addrs;
  1333. hosted_at(host, addrs);
  1334. EXPECT_EQ(1u, addrs.size());
  1335. }
  1336. #if 0 // It depends on each test environment...
  1337. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1338. auto host = "www.youtube.com";
  1339. std::vector<std::string> addrs;
  1340. hosted_at(host, addrs);
  1341. EXPECT_EQ(20u, addrs.size());
  1342. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1343. EXPECT_TRUE(it != addrs.end());
  1344. }
  1345. #endif
  1346. class ChunkedEncodingTest : public ::testing::Test {
  1347. protected:
  1348. ChunkedEncodingTest()
  1349. : cli_(HOST, PORT)
  1350. #ifdef CPPHTTPLIB_SSL_ENABLED
  1351. ,
  1352. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1353. #endif
  1354. {
  1355. cli_.set_connection_timeout(2);
  1356. #ifdef CPPHTTPLIB_SSL_ENABLED
  1357. cli_.enable_server_certificate_verification(false);
  1358. #endif
  1359. }
  1360. virtual void SetUp() {
  1361. read_file("./image.jpg", image_data_);
  1362. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1363. res.set_content("Hello World!", "text/plain");
  1364. });
  1365. svr_.Get(
  1366. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1367. res.set_chunked_content_provider(
  1368. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1369. size_t remaining = image_data_.size() - offset;
  1370. if (remaining == 0) {
  1371. sink.done();
  1372. } else {
  1373. constexpr size_t CHUNK_SIZE = 1024;
  1374. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1375. sink.write(&image_data_[offset], send_size);
  1376. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1377. }
  1378. return true;
  1379. });
  1380. });
  1381. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1382. svr_.wait_until_ready();
  1383. }
  1384. virtual void TearDown() {
  1385. svr_.stop();
  1386. if (!request_threads_.empty()) {
  1387. std::this_thread::sleep_for(std::chrono::seconds(1));
  1388. for (auto &t : request_threads_) {
  1389. t.join();
  1390. }
  1391. }
  1392. t_.join();
  1393. }
  1394. #ifdef CPPHTTPLIB_SSL_ENABLED
  1395. SSLClient cli_;
  1396. SSLServer svr_;
  1397. #else
  1398. Client cli_;
  1399. Server svr_;
  1400. #endif
  1401. thread t_;
  1402. std::vector<thread> request_threads_;
  1403. std::string image_data_;
  1404. };
  1405. TEST_F(ChunkedEncodingTest, NormalGet) {
  1406. auto res = cli_.Get("/chunked");
  1407. ASSERT_TRUE(res);
  1408. std::string out;
  1409. read_file("./image.jpg", out);
  1410. EXPECT_EQ(StatusCode::OK_200, res->status);
  1411. EXPECT_EQ(out, res->body);
  1412. }
  1413. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1414. std::string body;
  1415. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1416. body.append(data, data_length);
  1417. return true;
  1418. });
  1419. ASSERT_TRUE(res);
  1420. std::string out;
  1421. read_file("./image.jpg", out);
  1422. EXPECT_EQ(StatusCode::OK_200, res->status);
  1423. EXPECT_EQ(out, body);
  1424. }
  1425. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1426. std::string body;
  1427. auto res = cli_.Get(
  1428. "/chunked",
  1429. [&](const Response &response) {
  1430. EXPECT_EQ(StatusCode::OK_200, response.status);
  1431. return true;
  1432. },
  1433. [&](const char *data, size_t data_length) {
  1434. body.append(data, data_length);
  1435. return true;
  1436. });
  1437. ASSERT_TRUE(res);
  1438. std::string out;
  1439. read_file("./image.jpg", out);
  1440. EXPECT_EQ(StatusCode::OK_200, res->status);
  1441. EXPECT_EQ(out, body);
  1442. }
  1443. TEST(RangeTest, FromHTTPBin_Online) {
  1444. auto host = "httpbingo.org";
  1445. auto path = std::string{"/range/32"};
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 443;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 80;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(5);
  1454. {
  1455. auto res = cli.Get(path);
  1456. ASSERT_TRUE(res);
  1457. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1458. EXPECT_EQ(StatusCode::OK_200, res->status);
  1459. }
  1460. {
  1461. Headers headers = {make_range_header({{1, -1}})};
  1462. auto res = cli.Get(path, headers);
  1463. ASSERT_TRUE(res);
  1464. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1466. }
  1467. {
  1468. Headers headers = {make_range_header({{1, 10}})};
  1469. auto res = cli.Get(path, headers);
  1470. ASSERT_TRUE(res);
  1471. EXPECT_EQ("bcdefghijk", res->body);
  1472. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1473. }
  1474. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1475. // entire resource, while the original httpbin returned 200. Both are
  1476. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1477. {
  1478. Headers headers = {make_range_header({{0, 31}})};
  1479. auto res = cli.Get(path, headers);
  1480. ASSERT_TRUE(res);
  1481. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1482. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1483. res->status == StatusCode::PartialContent_206);
  1484. }
  1485. {
  1486. Headers headers = {make_range_header({{0, -1}})};
  1487. auto res = cli.Get(path, headers);
  1488. ASSERT_TRUE(res);
  1489. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1490. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1491. res->status == StatusCode::PartialContent_206);
  1492. }
  1493. // go-httpbin returns 206 with clamped range for over-range requests,
  1494. // while the original httpbin returned 416. Both behaviors are observed
  1495. // in real servers, so we only verify the request succeeds.
  1496. {
  1497. Headers headers = {make_range_header({{0, 32}})};
  1498. auto res = cli.Get(path, headers);
  1499. ASSERT_TRUE(res);
  1500. }
  1501. }
  1502. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1503. auto host = "unresolvableaddress.local";
  1504. auto path = std::string{"/"};
  1505. #ifdef CPPHTTPLIB_SSL_ENABLED
  1506. auto port = 443;
  1507. SSLClient cli(host, port);
  1508. #else
  1509. auto port = 80;
  1510. Client cli(host, port);
  1511. #endif
  1512. cli.set_connection_timeout(1);
  1513. {
  1514. auto res = cli.Get(path);
  1515. ASSERT_FALSE(res);
  1516. }
  1517. std::this_thread::sleep_for(std::chrono::seconds(8));
  1518. }
  1519. #if defined(__linux__) && defined(__GLIBC__) && \
  1520. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1521. // Forward declaration: in split builds split.py strips `inline` and moves the
  1522. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1523. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1524. // against the symbol in both header-only and split builds.
  1525. namespace httplib {
  1526. namespace detail {
  1527. int getaddrinfo_with_timeout(const char *node, const char *service,
  1528. const struct addrinfo *hints,
  1529. struct addrinfo **res, time_t timeout_sec);
  1530. } // namespace detail
  1531. } // namespace httplib
  1532. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1533. //
  1534. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1535. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1536. // gai_suspend() call hits the connection timeout the function calls
  1537. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1538. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1539. // still alive and still references the now-destroyed stack frame.
  1540. //
  1541. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1542. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1543. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1544. // and runs them in a container.
  1545. namespace {
  1546. bool should_run_issue_2431_tests() {
  1547. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1548. return v && *v && std::string(v) != "0";
  1549. }
  1550. std::string unique_unresolvable_host(int n) {
  1551. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1552. // glibc still asks the configured nameserver — which is exactly the path
  1553. // we want to exercise. A unique label per call avoids the resolver cache.
  1554. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1555. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1556. std::to_string(n) + ".invalid";
  1557. }
  1558. } // namespace
  1559. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1560. if (!should_run_issue_2431_tests()) {
  1561. GTEST_SKIP()
  1562. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1563. }
  1564. for (int i = 0; i < 8; ++i) {
  1565. struct addrinfo hints;
  1566. memset(&hints, 0, sizeof(hints));
  1567. hints.ai_family = AF_UNSPEC;
  1568. hints.ai_socktype = SOCK_STREAM;
  1569. auto host = unique_unresolvable_host(i);
  1570. struct addrinfo *result = nullptr;
  1571. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1572. &result, /*timeout_sec=*/1);
  1573. if (rc == 0 && result) { freeaddrinfo(result); }
  1574. }
  1575. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1576. // stack region they still believe holds their gaicb.
  1577. std::this_thread::sleep_for(std::chrono::seconds(3));
  1578. }
  1579. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1580. if (!should_run_issue_2431_tests()) {
  1581. GTEST_SKIP()
  1582. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1583. }
  1584. std::atomic<bool> stop{false};
  1585. std::vector<std::thread> threads;
  1586. for (int t = 0; t < 8; ++t) {
  1587. threads.emplace_back([t, &stop] {
  1588. int i = 0;
  1589. while (!stop.load(std::memory_order_relaxed)) {
  1590. struct addrinfo hints;
  1591. memset(&hints, 0, sizeof(hints));
  1592. hints.ai_family = AF_UNSPEC;
  1593. hints.ai_socktype = SOCK_STREAM;
  1594. auto host = unique_unresolvable_host(t * 100000 + i++);
  1595. struct addrinfo *result = nullptr;
  1596. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1597. &result, /*timeout_sec=*/1);
  1598. if (rc == 0 && result) { freeaddrinfo(result); }
  1599. }
  1600. });
  1601. }
  1602. std::this_thread::sleep_for(std::chrono::seconds(8));
  1603. stop.store(true, std::memory_order_relaxed);
  1604. for (auto &th : threads) {
  1605. th.join();
  1606. }
  1607. std::this_thread::sleep_for(std::chrono::seconds(3));
  1608. }
  1609. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1610. if (!should_run_issue_2431_tests()) {
  1611. GTEST_SKIP()
  1612. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1613. }
  1614. std::atomic<bool> stop{false};
  1615. std::vector<std::thread> threads;
  1616. for (int t = 0; t < 8; ++t) {
  1617. threads.emplace_back([t, &stop] {
  1618. int i = 0;
  1619. while (!stop.load(std::memory_order_relaxed)) {
  1620. auto host = unique_unresolvable_host(t * 100000 + i++);
  1621. Client cli(host, 80);
  1622. cli.set_connection_timeout(1, 0);
  1623. cli.set_read_timeout(1, 0);
  1624. cli.set_write_timeout(1, 0);
  1625. (void)cli.Get("/");
  1626. }
  1627. });
  1628. }
  1629. std::this_thread::sleep_for(std::chrono::seconds(8));
  1630. stop.store(true, std::memory_order_relaxed);
  1631. for (auto &th : threads) {
  1632. th.join();
  1633. }
  1634. std::this_thread::sleep_for(std::chrono::seconds(3));
  1635. }
  1636. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1637. TEST(ConnectionErrorTest, InvalidHost) {
  1638. auto host = "-abcde.com";
  1639. #ifdef CPPHTTPLIB_SSL_ENABLED
  1640. auto port = 443;
  1641. SSLClient cli(host, port);
  1642. #else
  1643. auto port = 80;
  1644. Client cli(host, port);
  1645. #endif
  1646. cli.set_connection_timeout(std::chrono::seconds(2));
  1647. auto res = cli.Get("/");
  1648. ASSERT_TRUE(!res);
  1649. EXPECT_EQ(Error::Connection, res.error());
  1650. }
  1651. TEST(ConnectionErrorTest, InvalidHost2) {
  1652. auto host = "httpcan.org/";
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. SSLClient cli(host);
  1655. #else
  1656. Client cli(host);
  1657. #endif
  1658. cli.set_connection_timeout(std::chrono::seconds(2));
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(!res);
  1661. EXPECT_EQ(Error::Connection, res.error());
  1662. }
  1663. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1664. auto host = "httpcan.org/";
  1665. #ifdef CPPHTTPLIB_SSL_ENABLED
  1666. SSLClient cli(host);
  1667. #else
  1668. Client cli(host);
  1669. #endif
  1670. cli.set_connection_timeout(std::chrono::seconds(2));
  1671. auto res = cli.Get("/");
  1672. ASSERT_TRUE(!res);
  1673. stringstream s;
  1674. s << "error code: " << res.error();
  1675. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1676. }
  1677. TEST(ConnectionErrorTest, InvalidPort) {
  1678. auto host = "localhost";
  1679. auto port = 44380;
  1680. #ifdef CPPHTTPLIB_SSL_ENABLED
  1681. SSLClient cli(host, port);
  1682. #else
  1683. Client cli(host, port);
  1684. #endif
  1685. cli.set_connection_timeout(std::chrono::seconds(2));
  1686. auto res = cli.Get("/");
  1687. ASSERT_TRUE(!res);
  1688. EXPECT_TRUE(Error::Connection == res.error() ||
  1689. Error::ConnectionTimeout == res.error());
  1690. }
  1691. TEST(ConnectionErrorTest, Timeout_Online) {
  1692. auto host = "google.com";
  1693. #ifdef CPPHTTPLIB_SSL_ENABLED
  1694. auto port = 44380;
  1695. SSLClient cli(host, port);
  1696. #else
  1697. auto port = 8080;
  1698. Client cli(host, port);
  1699. #endif
  1700. cli.set_connection_timeout(std::chrono::seconds(2));
  1701. // only probe one address type so that the error reason
  1702. // correlates to the timed-out IPv4, not the unsupported
  1703. // IPv6 connection attempt
  1704. cli.set_address_family(AF_INET);
  1705. auto res = cli.Get("/");
  1706. ASSERT_TRUE(!res);
  1707. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1708. }
  1709. TEST(CancelTest, NoCancel_Online) {
  1710. auto host = "httpbingo.org";
  1711. auto path = std::string{"/range/32"};
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. auto port = 443;
  1714. SSLClient cli(host, port);
  1715. #else
  1716. auto port = 80;
  1717. Client cli(host, port);
  1718. #endif
  1719. cli.set_connection_timeout(std::chrono::seconds(5));
  1720. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1723. EXPECT_EQ(StatusCode::OK_200, res->status);
  1724. }
  1725. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1726. // Use /bytes with a large payload so that the DownloadProgress callback
  1727. // (which only fires for Content-Length responses) is invoked before the
  1728. // entire body is received, giving cancellation a chance to fire.
  1729. auto host = "httpbingo.org";
  1730. auto path = std::string{"/bytes/524288"};
  1731. #ifdef CPPHTTPLIB_SSL_ENABLED
  1732. auto port = 443;
  1733. SSLClient cli(host, port);
  1734. #else
  1735. auto port = 80;
  1736. Client cli(host, port);
  1737. #endif
  1738. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1739. cli.set_connection_timeout(std::chrono::seconds(5));
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayload_Online) {
  1744. auto host = "httpbingo.org";
  1745. auto path = std::string{"/bytes/524288"};
  1746. #ifdef CPPHTTPLIB_SSL_ENABLED
  1747. auto port = 443;
  1748. SSLClient cli(host, port);
  1749. #else
  1750. auto port = 80;
  1751. Client cli(host, port);
  1752. #endif
  1753. cli.set_connection_timeout(std::chrono::seconds(5));
  1754. uint32_t count = 0;
  1755. auto res =
  1756. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::Canceled, res.error());
  1759. }
  1760. TEST(CancelTest, NoCancelPost) {
  1761. Server svr;
  1762. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1763. res.set_content("Hello World!", "text/plain");
  1764. });
  1765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1766. auto se = detail::scope_exit([&] {
  1767. svr.stop();
  1768. thread.join();
  1769. ASSERT_FALSE(svr.is_running());
  1770. });
  1771. svr.wait_until_ready();
  1772. Client cli(HOST, PORT);
  1773. cli.set_connection_timeout(std::chrono::seconds(5));
  1774. auto res =
  1775. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1776. "application/json", [](uint64_t, uint64_t) { return true; });
  1777. ASSERT_TRUE(res);
  1778. EXPECT_EQ("Hello World!", res->body);
  1779. EXPECT_EQ(StatusCode::OK_200, res->status);
  1780. }
  1781. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1782. Server svr;
  1783. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1784. res.set_content("Hello World!", "text/plain");
  1785. });
  1786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1787. auto se = detail::scope_exit([&] {
  1788. svr.stop();
  1789. thread.join();
  1790. ASSERT_FALSE(svr.is_running());
  1791. });
  1792. svr.wait_until_ready();
  1793. Client cli(HOST, PORT);
  1794. cli.set_connection_timeout(std::chrono::seconds(5));
  1795. auto res =
  1796. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1797. "application/json", [](uint64_t, uint64_t) { return false; });
  1798. ASSERT_TRUE(!res);
  1799. EXPECT_EQ(Error::Canceled, res.error());
  1800. }
  1801. TEST(CancelTest, WithCancelLargePayloadPost) {
  1802. Server svr;
  1803. svr.set_payload_max_length(200 * 1024 * 1024);
  1804. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1805. res.set_content(LARGE_DATA, "text/plain");
  1806. });
  1807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1808. auto se = detail::scope_exit([&] {
  1809. svr.stop();
  1810. thread.join();
  1811. ASSERT_FALSE(svr.is_running());
  1812. });
  1813. svr.wait_until_ready();
  1814. Client cli(HOST, PORT);
  1815. cli.set_payload_max_length(200 * 1024 * 1024);
  1816. cli.set_connection_timeout(std::chrono::seconds(5));
  1817. auto res =
  1818. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1819. "application/json", [](uint64_t, uint64_t) { return false; });
  1820. ASSERT_TRUE(!res);
  1821. EXPECT_EQ(Error::Canceled, res.error());
  1822. }
  1823. TEST(CancelTest, NoCancelPut) {
  1824. Server svr;
  1825. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1826. res.set_content("Hello World!", "text/plain");
  1827. });
  1828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1829. auto se = detail::scope_exit([&] {
  1830. svr.stop();
  1831. thread.join();
  1832. ASSERT_FALSE(svr.is_running());
  1833. });
  1834. svr.wait_until_ready();
  1835. Client cli(HOST, PORT);
  1836. cli.set_connection_timeout(std::chrono::seconds(5));
  1837. auto res =
  1838. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1839. "application/json", [](uint64_t, uint64_t) { return true; });
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ("Hello World!", res->body);
  1842. EXPECT_EQ(StatusCode::OK_200, res->status);
  1843. }
  1844. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1845. Server svr;
  1846. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("Hello World!", "text/plain");
  1848. });
  1849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1850. auto se = detail::scope_exit([&] {
  1851. svr.stop();
  1852. thread.join();
  1853. ASSERT_FALSE(svr.is_running());
  1854. });
  1855. svr.wait_until_ready();
  1856. Client cli(HOST, PORT);
  1857. cli.set_connection_timeout(std::chrono::seconds(5));
  1858. auto res =
  1859. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1860. "application/json", [](uint64_t, uint64_t) { return false; });
  1861. ASSERT_TRUE(!res);
  1862. EXPECT_EQ(Error::Canceled, res.error());
  1863. }
  1864. TEST(CancelTest, WithCancelLargePayloadPut) {
  1865. Server svr;
  1866. svr.set_payload_max_length(200 * 1024 * 1024);
  1867. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1868. res.set_content(LARGE_DATA, "text/plain");
  1869. });
  1870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1871. auto se = detail::scope_exit([&] {
  1872. svr.stop();
  1873. thread.join();
  1874. ASSERT_FALSE(svr.is_running());
  1875. });
  1876. svr.wait_until_ready();
  1877. Client cli(HOST, PORT);
  1878. cli.set_payload_max_length(200 * 1024 * 1024);
  1879. cli.set_connection_timeout(std::chrono::seconds(5));
  1880. auto res =
  1881. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1882. "application/json", [](uint64_t, uint64_t) { return false; });
  1883. ASSERT_TRUE(!res);
  1884. EXPECT_EQ(Error::Canceled, res.error());
  1885. }
  1886. TEST(CancelTest, NoCancelPatch) {
  1887. Server svr;
  1888. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("Hello World!", "text/plain");
  1890. });
  1891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1892. auto se = detail::scope_exit([&] {
  1893. svr.stop();
  1894. thread.join();
  1895. ASSERT_FALSE(svr.is_running());
  1896. });
  1897. svr.wait_until_ready();
  1898. Client cli(HOST, PORT);
  1899. cli.set_connection_timeout(std::chrono::seconds(5));
  1900. auto res =
  1901. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1902. "application/json", [](uint64_t, uint64_t) { return true; });
  1903. ASSERT_TRUE(res);
  1904. EXPECT_EQ("Hello World!", res->body);
  1905. EXPECT_EQ(StatusCode::OK_200, res->status);
  1906. }
  1907. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1908. Server svr;
  1909. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1910. res.set_content("Hello World!", "text/plain");
  1911. });
  1912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1913. auto se = detail::scope_exit([&] {
  1914. svr.stop();
  1915. thread.join();
  1916. ASSERT_FALSE(svr.is_running());
  1917. });
  1918. svr.wait_until_ready();
  1919. Client cli(HOST, PORT);
  1920. cli.set_connection_timeout(std::chrono::seconds(5));
  1921. auto res =
  1922. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1923. "application/json", [](uint64_t, uint64_t) { return false; });
  1924. ASSERT_TRUE(!res);
  1925. EXPECT_EQ(Error::Canceled, res.error());
  1926. }
  1927. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1928. Server svr;
  1929. svr.set_payload_max_length(200 * 1024 * 1024);
  1930. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1931. res.set_content(LARGE_DATA, "text/plain");
  1932. });
  1933. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1934. auto se = detail::scope_exit([&] {
  1935. svr.stop();
  1936. thread.join();
  1937. ASSERT_FALSE(svr.is_running());
  1938. });
  1939. svr.wait_until_ready();
  1940. Client cli(HOST, PORT);
  1941. cli.set_payload_max_length(200 * 1024 * 1024);
  1942. cli.set_connection_timeout(std::chrono::seconds(5));
  1943. auto res =
  1944. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1945. "application/json", [](uint64_t, uint64_t) { return false; });
  1946. ASSERT_TRUE(!res);
  1947. EXPECT_EQ(Error::Canceled, res.error());
  1948. }
  1949. TEST(CancelTest, NoCancelDelete) {
  1950. Server svr;
  1951. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1952. res.set_content("Hello World!", "text/plain");
  1953. });
  1954. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1955. auto se = detail::scope_exit([&] {
  1956. svr.stop();
  1957. thread.join();
  1958. ASSERT_FALSE(svr.is_running());
  1959. });
  1960. svr.wait_until_ready();
  1961. Client cli(HOST, PORT);
  1962. cli.set_connection_timeout(std::chrono::seconds(5));
  1963. auto res =
  1964. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1965. "application/json", [](uint64_t, uint64_t) { return true; });
  1966. ASSERT_TRUE(res);
  1967. EXPECT_EQ("Hello World!", res->body);
  1968. EXPECT_EQ(StatusCode::OK_200, res->status);
  1969. }
  1970. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1971. Server svr;
  1972. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1973. res.set_content("Hello World!", "text/plain");
  1974. });
  1975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1976. auto se = detail::scope_exit([&] {
  1977. svr.stop();
  1978. thread.join();
  1979. ASSERT_FALSE(svr.is_running());
  1980. });
  1981. svr.wait_until_ready();
  1982. Client cli(HOST, PORT);
  1983. cli.set_connection_timeout(std::chrono::seconds(5));
  1984. auto res =
  1985. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1986. "application/json", [](uint64_t, uint64_t) { return false; });
  1987. ASSERT_TRUE(!res);
  1988. EXPECT_EQ(Error::Canceled, res.error());
  1989. }
  1990. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1991. Server svr;
  1992. svr.set_payload_max_length(200 * 1024 * 1024);
  1993. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1994. res.set_content(LARGE_DATA, "text/plain");
  1995. });
  1996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1997. auto se = detail::scope_exit([&] {
  1998. svr.stop();
  1999. thread.join();
  2000. ASSERT_FALSE(svr.is_running());
  2001. });
  2002. svr.wait_until_ready();
  2003. Client cli(HOST, PORT);
  2004. cli.set_payload_max_length(200 * 1024 * 1024);
  2005. cli.set_connection_timeout(std::chrono::seconds(5));
  2006. auto res =
  2007. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2008. "application/json", [](uint64_t, uint64_t) { return false; });
  2009. ASSERT_TRUE(!res);
  2010. EXPECT_EQ(Error::Canceled, res.error());
  2011. }
  2012. static std::string remove_whitespace(const std::string &input) {
  2013. std::string output;
  2014. output.reserve(input.size());
  2015. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2016. [](unsigned char c) { return !std::isspace(c); });
  2017. return output;
  2018. }
  2019. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2020. auto host = "httpbingo.org";
  2021. auto path = std::string{"/basic-auth/hello/world"};
  2022. #ifdef CPPHTTPLIB_SSL_ENABLED
  2023. auto port = 443;
  2024. SSLClient cli(host, port);
  2025. #else
  2026. auto port = 80;
  2027. Client cli(host, port);
  2028. #endif
  2029. {
  2030. auto res = cli.Get(path);
  2031. ASSERT_TRUE(res);
  2032. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2033. }
  2034. {
  2035. auto res = cli.Get(
  2036. path, Headers{make_basic_authentication_header("hello", "world")});
  2037. ASSERT_TRUE(res);
  2038. auto body = remove_whitespace(res->body);
  2039. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2040. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2041. EXPECT_EQ(StatusCode::OK_200, res->status);
  2042. }
  2043. {
  2044. cli.set_basic_auth("hello", "world");
  2045. auto res = cli.Get(path);
  2046. ASSERT_TRUE(res);
  2047. auto body = remove_whitespace(res->body);
  2048. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2049. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2050. EXPECT_EQ(StatusCode::OK_200, res->status);
  2051. }
  2052. {
  2053. cli.set_basic_auth("hello", "bad");
  2054. auto res = cli.Get(path);
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2057. }
  2058. {
  2059. cli.set_basic_auth("bad", "world");
  2060. auto res = cli.Get(path);
  2061. ASSERT_TRUE(res);
  2062. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2063. }
  2064. }
  2065. #ifdef CPPHTTPLIB_SSL_ENABLED
  2066. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2067. auto host = "httpbingo.org";
  2068. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2069. auto paths = std::vector<std::string>{
  2070. "/digest-auth/auth/hello/world/MD5",
  2071. "/digest-auth/auth/hello/world/SHA-256",
  2072. };
  2073. auto port = 443;
  2074. SSLClient cli(host, port);
  2075. {
  2076. auto res = cli.Get(unauth_path);
  2077. ASSERT_TRUE(res);
  2078. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2079. }
  2080. {
  2081. cli.set_digest_auth("hello", "world");
  2082. for (const auto &path : paths) {
  2083. auto res = cli.Get(path.c_str());
  2084. ASSERT_TRUE(res);
  2085. auto body = remove_whitespace(res->body);
  2086. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2087. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2088. EXPECT_EQ(StatusCode::OK_200, res->status);
  2089. }
  2090. cli.set_digest_auth("hello", "bad");
  2091. for (const auto &path : paths) {
  2092. auto res = cli.Get(path.c_str());
  2093. ASSERT_TRUE(res);
  2094. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2095. }
  2096. }
  2097. }
  2098. #endif
  2099. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2100. auto host = "google.com";
  2101. auto another_host = "example.com";
  2102. auto wrong_ip = "0.0.0.0";
  2103. #ifdef CPPHTTPLIB_SSL_ENABLED
  2104. SSLClient cli(host);
  2105. #else
  2106. Client cli(host);
  2107. #endif
  2108. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2109. auto res = cli.Get("/");
  2110. ASSERT_TRUE(res);
  2111. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2112. }
  2113. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2114. auto host = "google.com";
  2115. auto wrong_ip = "0.0.0.0";
  2116. #ifdef CPPHTTPLIB_SSL_ENABLED
  2117. SSLClient cli(host);
  2118. #else
  2119. Client cli(host);
  2120. #endif
  2121. cli.set_hostname_addr_map({{host, wrong_ip}});
  2122. auto res = cli.Get("/");
  2123. ASSERT_TRUE(!res);
  2124. EXPECT_EQ(Error::Connection, res.error());
  2125. }
  2126. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2127. auto host = "httpbingo.org";
  2128. auto path = std::string{"/absolute-redirect/3"};
  2129. #ifdef CPPHTTPLIB_SSL_ENABLED
  2130. SSLClient cli(host);
  2131. #else
  2132. Client cli(host);
  2133. #endif
  2134. cli.set_follow_location(true);
  2135. auto res = cli.Get(path);
  2136. ASSERT_TRUE(res);
  2137. EXPECT_EQ(StatusCode::OK_200, res->status);
  2138. }
  2139. TEST(RedirectTest, Redirect_Online) {
  2140. auto host = "httpbingo.org";
  2141. auto path = std::string{"/redirect/3"};
  2142. #ifdef CPPHTTPLIB_SSL_ENABLED
  2143. SSLClient cli(host);
  2144. #else
  2145. Client cli(host);
  2146. #endif
  2147. cli.set_follow_location(true);
  2148. auto res = cli.Get(path);
  2149. ASSERT_TRUE(res);
  2150. EXPECT_EQ(StatusCode::OK_200, res->status);
  2151. }
  2152. TEST(RelativeRedirectTest, Redirect_Online) {
  2153. auto host = "httpbingo.org";
  2154. auto path = std::string{"/relative-redirect/3"};
  2155. #ifdef CPPHTTPLIB_SSL_ENABLED
  2156. SSLClient cli(host);
  2157. #else
  2158. Client cli(host);
  2159. #endif
  2160. cli.set_follow_location(true);
  2161. auto res = cli.Get(path);
  2162. ASSERT_TRUE(res);
  2163. EXPECT_EQ(StatusCode::OK_200, res->status);
  2164. }
  2165. TEST(TooManyRedirectTest, Redirect_Online) {
  2166. auto host = "httpbingo.org";
  2167. auto path = std::string{"/redirect/21"};
  2168. #ifdef CPPHTTPLIB_SSL_ENABLED
  2169. SSLClient cli(host);
  2170. #else
  2171. Client cli(host);
  2172. #endif
  2173. cli.set_follow_location(true);
  2174. auto res = cli.Get(path);
  2175. ASSERT_TRUE(!res);
  2176. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2177. }
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. TEST(YahooRedirectTest, Redirect_Online) {
  2180. Client cli("yahoo.com");
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(res);
  2183. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2184. cli.set_follow_location(true);
  2185. res = cli.Get("/");
  2186. ASSERT_TRUE(res);
  2187. EXPECT_EQ(StatusCode::OK_200, res->status);
  2188. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2189. }
  2190. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2191. #define REDIR_HOST "httpbingo.org"
  2192. #define REDIR_PATH "/redirect-to"
  2193. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2194. SSLClient cli(REDIR_HOST);
  2195. cli.set_follow_location(true);
  2196. auto res =
  2197. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2198. ASSERT_TRUE(res);
  2199. EXPECT_EQ(StatusCode::OK_200, res->status);
  2200. }
  2201. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2202. SSLClient cli(REDIR_HOST);
  2203. cli.set_follow_location(true);
  2204. Params params;
  2205. params.emplace("url", "http://example.com");
  2206. params.emplace("status_code", "302");
  2207. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2208. ASSERT_TRUE(res);
  2209. EXPECT_EQ(StatusCode::OK_200, res->status);
  2210. }
  2211. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2212. SSLClient cli(REDIR_HOST);
  2213. cli.set_follow_location(true);
  2214. Params params;
  2215. params.emplace("url", "http://example.com");
  2216. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2217. ASSERT_TRUE(res);
  2218. EXPECT_EQ(StatusCode::OK_200, res->status);
  2219. }
  2220. TEST(UrlWithSpace, Redirect_Online) {
  2221. SSLClient cli("edge.forgecdn.net");
  2222. cli.set_follow_location(true);
  2223. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2224. ASSERT_TRUE(res);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2227. }
  2228. #endif
  2229. #if !defined(_WIN32) && !defined(_WIN64)
  2230. TEST(ReceiveSignals, Signal) {
  2231. auto setupSignalHandlers = []() {
  2232. struct sigaction act;
  2233. sigemptyset(&act.sa_mask);
  2234. act.sa_flags = SA_SIGINFO;
  2235. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2236. switch (sig) {
  2237. case SIGINT:
  2238. default: break;
  2239. }
  2240. };
  2241. ::sigaction(SIGINT, &act, nullptr);
  2242. };
  2243. Server svr;
  2244. int port = 0;
  2245. auto thread = std::thread([&]() {
  2246. setupSignalHandlers();
  2247. port = svr.bind_to_any_port(HOST);
  2248. svr.listen_after_bind();
  2249. });
  2250. auto se = detail::scope_exit([&] {
  2251. svr.stop();
  2252. thread.join();
  2253. ASSERT_FALSE(svr.is_running());
  2254. });
  2255. svr.wait_until_ready();
  2256. ASSERT_TRUE(svr.is_running());
  2257. pthread_kill(thread.native_handle(), SIGINT);
  2258. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2259. ASSERT_TRUE(svr.is_running());
  2260. }
  2261. #endif
  2262. TEST(RedirectToDifferentPort, Redirect) {
  2263. Server svr1;
  2264. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2265. res.set_content("Hello World!", "text/plain");
  2266. });
  2267. int svr1_port = 0;
  2268. auto thread1 = std::thread([&]() {
  2269. svr1_port = svr1.bind_to_any_port(HOST);
  2270. svr1.listen_after_bind();
  2271. });
  2272. Server svr2;
  2273. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2274. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2275. });
  2276. int svr2_port = 0;
  2277. auto thread2 = std::thread([&]() {
  2278. svr2_port = svr2.bind_to_any_port(HOST);
  2279. svr2.listen_after_bind();
  2280. });
  2281. auto se = detail::scope_exit([&] {
  2282. svr2.stop();
  2283. thread2.join();
  2284. svr1.stop();
  2285. thread1.join();
  2286. ASSERT_FALSE(svr2.is_running());
  2287. ASSERT_FALSE(svr1.is_running());
  2288. });
  2289. svr1.wait_until_ready();
  2290. svr2.wait_until_ready();
  2291. Client cli("localhost", svr2_port);
  2292. cli.set_follow_location(true);
  2293. auto res = cli.Get("/2");
  2294. ASSERT_TRUE(res);
  2295. EXPECT_EQ(StatusCode::OK_200, res->status);
  2296. EXPECT_EQ("Hello World!", res->body);
  2297. }
  2298. static void
  2299. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2300. Server svr1;
  2301. std::string captured_authorization;
  2302. svr1.Get("/target", [&](const Request &req, Response &res) {
  2303. captured_authorization = req.get_header_value("Authorization");
  2304. res.set_content("OK", "text/plain");
  2305. });
  2306. int svr1_port = 0;
  2307. auto thread1 = std::thread([&]() {
  2308. svr1_port = svr1.bind_to_any_port(HOST);
  2309. svr1.listen_after_bind();
  2310. });
  2311. Server svr2;
  2312. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2313. res.set_redirect(
  2314. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2315. });
  2316. int svr2_port = 0;
  2317. auto thread2 = std::thread([&]() {
  2318. svr2_port = svr2.bind_to_any_port(HOST);
  2319. svr2.listen_after_bind();
  2320. });
  2321. auto se = detail::scope_exit([&] {
  2322. svr2.stop();
  2323. thread2.join();
  2324. svr1.stop();
  2325. thread1.join();
  2326. ASSERT_FALSE(svr2.is_running());
  2327. ASSERT_FALSE(svr1.is_running());
  2328. });
  2329. svr1.wait_until_ready();
  2330. svr2.wait_until_ready();
  2331. Client cli("localhost", svr2_port);
  2332. cli.set_follow_location(true);
  2333. set_auth(cli);
  2334. auto res = cli.Get("/redir");
  2335. ASSERT_TRUE(res);
  2336. EXPECT_EQ(StatusCode::OK_200, res->status);
  2337. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2338. EXPECT_TRUE(captured_authorization.empty());
  2339. }
  2340. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2341. TestDoNotForwardCredentialsOnRedirect(
  2342. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2343. }
  2344. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2345. TestDoNotForwardCredentialsOnRedirect(
  2346. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2347. }
  2348. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2349. Server svr1;
  2350. std::string captured_cookie;
  2351. bool target_hit = false;
  2352. svr1.Get("/target", [&](const Request &req, Response &res) {
  2353. captured_cookie = req.get_header_value("Cookie");
  2354. target_hit = true;
  2355. res.set_content("OK", "text/plain");
  2356. });
  2357. int svr1_port = 0;
  2358. auto thread1 = std::thread([&]() {
  2359. svr1_port = svr1.bind_to_any_port(HOST);
  2360. svr1.listen_after_bind();
  2361. });
  2362. Server svr2;
  2363. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2364. res.set_redirect(
  2365. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2366. });
  2367. int svr2_port = 0;
  2368. auto thread2 = std::thread([&]() {
  2369. svr2_port = svr2.bind_to_any_port(HOST);
  2370. svr2.listen_after_bind();
  2371. });
  2372. auto se = detail::scope_exit([&] {
  2373. svr2.stop();
  2374. thread2.join();
  2375. svr1.stop();
  2376. thread1.join();
  2377. ASSERT_FALSE(svr2.is_running());
  2378. ASSERT_FALSE(svr1.is_running());
  2379. });
  2380. svr1.wait_until_ready();
  2381. svr2.wait_until_ready();
  2382. Client cli("localhost", svr2_port);
  2383. cli.set_follow_location(true);
  2384. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2385. auto res = cli.Get("/redir", headers);
  2386. ASSERT_TRUE(res);
  2387. EXPECT_EQ(StatusCode::OK_200, res->status);
  2388. EXPECT_TRUE(target_hit);
  2389. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2390. EXPECT_TRUE(captured_cookie.empty());
  2391. }
  2392. TEST(RedirectToSamePort, ForwardCookie) {
  2393. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2394. // header so that ordinary session flows keep working.
  2395. Server svr;
  2396. std::string captured_cookie;
  2397. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2398. res.set_redirect("/target", 302);
  2399. });
  2400. svr.Get("/target", [&](const Request &req, Response &res) {
  2401. captured_cookie = req.get_header_value("Cookie");
  2402. res.set_content("OK", "text/plain");
  2403. });
  2404. auto port = svr.bind_to_any_port(HOST);
  2405. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2406. auto se = detail::scope_exit([&] {
  2407. svr.stop();
  2408. thread.join();
  2409. ASSERT_FALSE(svr.is_running());
  2410. });
  2411. svr.wait_until_ready();
  2412. Client cli(HOST, port);
  2413. cli.set_follow_location(true);
  2414. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2415. auto res = cli.Get("/redir", headers);
  2416. ASSERT_TRUE(res);
  2417. EXPECT_EQ(StatusCode::OK_200, res->status);
  2418. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2419. }
  2420. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2421. Server svr;
  2422. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2423. // Port number that overflows int — should not crash
  2424. res.set_redirect("http://localhost:99999999999999999999/target");
  2425. });
  2426. auto port = svr.bind_to_any_port(HOST);
  2427. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2428. auto se = detail::scope_exit([&] {
  2429. svr.stop();
  2430. thread.join();
  2431. ASSERT_FALSE(svr.is_running());
  2432. });
  2433. svr.wait_until_ready();
  2434. Client cli(HOST, port);
  2435. cli.set_follow_location(true);
  2436. auto res = cli.Get("/redir");
  2437. // Should fail gracefully, not crash (no valid response due to bad port)
  2438. EXPECT_FALSE(res);
  2439. }
  2440. TEST(RedirectFromPageWithContent, Redirect) {
  2441. Server svr;
  2442. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2443. res.set_content("___", "text/plain");
  2444. res.set_redirect("/2");
  2445. });
  2446. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2447. res.set_content("Hello World!", "text/plain");
  2448. });
  2449. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2450. auto se = detail::scope_exit([&] {
  2451. svr.stop();
  2452. th.join();
  2453. ASSERT_FALSE(svr.is_running());
  2454. });
  2455. svr.wait_until_ready();
  2456. {
  2457. Client cli("localhost", PORT);
  2458. cli.set_follow_location(true);
  2459. std::string body;
  2460. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2461. body.append(data, data_length);
  2462. return true;
  2463. });
  2464. ASSERT_TRUE(res);
  2465. EXPECT_EQ(StatusCode::OK_200, res->status);
  2466. EXPECT_EQ("Hello World!", body);
  2467. }
  2468. {
  2469. Client cli("localhost", PORT);
  2470. std::string body;
  2471. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2472. body.append(data, data_length);
  2473. return true;
  2474. });
  2475. ASSERT_TRUE(res);
  2476. EXPECT_EQ(StatusCode::Found_302, res->status);
  2477. EXPECT_EQ("___", body);
  2478. }
  2479. }
  2480. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2481. Server svr;
  2482. auto port_str = std::to_string(PORT);
  2483. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2484. auto expected_host = "[::1]:" + port_str;
  2485. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2486. res.set_content("___", "text/plain");
  2487. // res.set_redirect("/2");
  2488. res.set_redirect(redirect_url);
  2489. });
  2490. svr.Get("/2", [&](const Request &req, Response &res) {
  2491. auto host_header = req.headers.find("Host");
  2492. ASSERT_TRUE(host_header != req.headers.end());
  2493. EXPECT_EQ(expected_host, host_header->second);
  2494. res.set_content("Hello World!", "text/plain");
  2495. });
  2496. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2497. auto se = detail::scope_exit([&] {
  2498. svr.stop();
  2499. th.join();
  2500. ASSERT_FALSE(svr.is_running());
  2501. });
  2502. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2503. // actually starts anything, so the condition !svr.is_running() will
  2504. // always remain true, and the loop never stops.
  2505. // This basically counts how many milliseconds have passed since the
  2506. // call to svr.listen(), and if after 5 seconds nothing started yet
  2507. // aborts the test.
  2508. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2509. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2510. ASSERT_LT(milliseconds, 5000U);
  2511. }
  2512. {
  2513. Client cli("::1", PORT);
  2514. cli.set_follow_location(true);
  2515. std::string body;
  2516. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2517. body.append(data, data_length);
  2518. return true;
  2519. });
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::OK_200, res->status);
  2522. EXPECT_EQ("Hello World!", body);
  2523. }
  2524. {
  2525. Client cli("::1", PORT);
  2526. std::string body;
  2527. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2528. body.append(data, data_length);
  2529. return true;
  2530. });
  2531. ASSERT_TRUE(res);
  2532. EXPECT_EQ(StatusCode::Found_302, res->status);
  2533. EXPECT_EQ("___", body);
  2534. }
  2535. }
  2536. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2537. Server svr;
  2538. svr.Get("/foo", [](const Request &req, Response &res) {
  2539. auto a = req.params.find("a");
  2540. if (a != req.params.end()) {
  2541. res.set_content((*a).second, "text/plain");
  2542. res.status = StatusCode::OK_200;
  2543. } else {
  2544. res.status = StatusCode::BadRequest_400;
  2545. }
  2546. });
  2547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2548. auto se = detail::scope_exit([&] {
  2549. svr.stop();
  2550. thread.join();
  2551. ASSERT_FALSE(svr.is_running());
  2552. });
  2553. svr.wait_until_ready();
  2554. {
  2555. Client cli(HOST, PORT);
  2556. cli.set_path_encode(false);
  2557. auto res = cli.Get("/foo?a=explicitly+encoded");
  2558. ASSERT_TRUE(res);
  2559. EXPECT_EQ(StatusCode::OK_200, res->status);
  2560. // This expects it back with a space, as the `+` won't have been
  2561. // url-encoded, and server-side the params get decoded turning `+`
  2562. // into spaces.
  2563. EXPECT_EQ("explicitly encoded", res->body);
  2564. }
  2565. }
  2566. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2567. // When path encoding is disabled the client must transmit the supplied
  2568. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2569. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2570. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2571. // than a space (0x20). Assert on the raw wire target to catch this.
  2572. Server svr;
  2573. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2574. svr.Get("/foo", [&](const Request &req, Response &res) {
  2575. EXPECT_EQ(expected_target, req.target);
  2576. res.status = StatusCode::OK_200;
  2577. });
  2578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2579. auto se = detail::scope_exit([&] {
  2580. svr.stop();
  2581. thread.join();
  2582. ASSERT_FALSE(svr.is_running());
  2583. });
  2584. svr.wait_until_ready();
  2585. {
  2586. Client cli(HOST, PORT);
  2587. cli.set_path_encode(false);
  2588. auto res = cli.Get(expected_target.c_str());
  2589. ASSERT_TRUE(res);
  2590. EXPECT_EQ(StatusCode::OK_200, res->status);
  2591. }
  2592. }
  2593. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2594. Server svr;
  2595. svr.Get("/", [](const Request &req, Response &) {
  2596. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. {
  2606. Client cli(HOST, PORT);
  2607. cli.set_path_encode(false);
  2608. auto res = cli.Get("/?something=%0A");
  2609. ASSERT_TRUE(res);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. }
  2613. TEST(BindServerTest, BindDualStack) {
  2614. Server svr;
  2615. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2616. res.set_content("Hello World!", "text/plain");
  2617. });
  2618. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2619. auto se = detail::scope_exit([&] {
  2620. svr.stop();
  2621. thread.join();
  2622. ASSERT_FALSE(svr.is_running());
  2623. });
  2624. svr.wait_until_ready();
  2625. {
  2626. Client cli("127.0.0.1", PORT);
  2627. auto res = cli.Get("/1");
  2628. ASSERT_TRUE(res);
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. EXPECT_EQ("Hello World!", res->body);
  2631. }
  2632. {
  2633. Client cli("::1", PORT);
  2634. auto res = cli.Get("/1");
  2635. ASSERT_TRUE(res);
  2636. EXPECT_EQ(StatusCode::OK_200, res->status);
  2637. EXPECT_EQ("Hello World!", res->body);
  2638. }
  2639. }
  2640. TEST(BindServerTest, BindAndListenSeparately) {
  2641. Server svr;
  2642. int port = svr.bind_to_any_port("0.0.0.0");
  2643. ASSERT_TRUE(svr.is_valid());
  2644. ASSERT_TRUE(port > 0);
  2645. svr.stop();
  2646. }
  2647. #ifdef CPPHTTPLIB_SSL_ENABLED
  2648. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2650. CLIENT_CA_CERT_DIR);
  2651. int port = svr.bind_to_any_port("0.0.0.0");
  2652. ASSERT_TRUE(svr.is_valid());
  2653. ASSERT_TRUE(port > 0);
  2654. svr.stop();
  2655. }
  2656. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2657. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2658. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2659. int port = svr.bind_to_any_port("0.0.0.0");
  2660. ASSERT_TRUE(svr.is_valid());
  2661. ASSERT_TRUE(port > 0);
  2662. svr.stop();
  2663. }
  2664. TEST(BindServerTest, UpdateCertsPem) {
  2665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2666. int port = svr.bind_to_any_port("0.0.0.0");
  2667. ASSERT_TRUE(svr.is_valid());
  2668. ASSERT_TRUE(port > 0);
  2669. // Read PEM files
  2670. std::string cert_pem, key_pem, ca_pem;
  2671. read_file(SERVER_CERT_FILE, cert_pem);
  2672. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2673. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2674. // Update server certificates using PEM API
  2675. ASSERT_TRUE(
  2676. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2677. ASSERT_TRUE(svr.is_valid());
  2678. svr.stop();
  2679. }
  2680. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2681. // Start server with client CA (enables client auth)
  2682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2683. ASSERT_TRUE(svr.is_valid());
  2684. bool handler_called = false;
  2685. svr.Get("/test", [&](const Request &req, Response &res) {
  2686. handler_called = true;
  2687. // Verify client certificate is present
  2688. auto cert = req.peer_cert();
  2689. EXPECT_TRUE(static_cast<bool>(cert));
  2690. res.set_content("ok", "text/plain");
  2691. });
  2692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. t.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. // Read PEM files
  2700. std::string cert_pem, key_pem, ca_pem;
  2701. read_file(SERVER_CERT_FILE, cert_pem);
  2702. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2703. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2704. // Update server certificates and client CA using PEM API while server running
  2705. ASSERT_TRUE(
  2706. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2707. // Connect with client certificate
  2708. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2709. cli.enable_server_certificate_verification(false);
  2710. cli.set_connection_timeout(30);
  2711. auto res = cli.Get("/test");
  2712. ASSERT_TRUE(res);
  2713. ASSERT_EQ(StatusCode::OK_200, res->status);
  2714. ASSERT_TRUE(handler_called);
  2715. EXPECT_EQ("ok", res->body);
  2716. }
  2717. #endif
  2718. TEST(ErrorHandlerTest, ContentLength) {
  2719. Server svr;
  2720. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2721. res.status = StatusCode::OK_200;
  2722. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2723. "text/html"); // <= Content-Length still 13
  2724. });
  2725. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2726. res.set_content("Hello World!\n", "text/plain");
  2727. res.status = 524;
  2728. });
  2729. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2730. auto se = detail::scope_exit([&] {
  2731. svr.stop();
  2732. thread.join();
  2733. ASSERT_FALSE(svr.is_running());
  2734. });
  2735. svr.wait_until_ready();
  2736. {
  2737. Client cli(HOST, PORT);
  2738. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2739. ASSERT_TRUE(res);
  2740. EXPECT_EQ(StatusCode::OK_200, res->status);
  2741. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2742. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2743. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2744. }
  2745. }
  2746. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2747. TEST(ExceptionTest, WithoutExceptionHandler) {
  2748. Server svr;
  2749. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2750. throw std::runtime_error("exception...");
  2751. });
  2752. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2753. throw std::runtime_error("exception\r\n...");
  2754. });
  2755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. listen_thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli("localhost", PORT);
  2763. {
  2764. auto res = cli.Get("/exception");
  2765. ASSERT_TRUE(res);
  2766. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2767. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2768. }
  2769. {
  2770. auto res = cli.Get("/unknown");
  2771. ASSERT_TRUE(res);
  2772. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2773. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2774. }
  2775. }
  2776. TEST(ExceptionTest, WithExceptionHandler) {
  2777. Server svr;
  2778. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2779. std::exception_ptr ep) {
  2780. EXPECT_FALSE(ep == nullptr);
  2781. try {
  2782. std::rethrow_exception(ep);
  2783. } catch (std::exception &e) {
  2784. EXPECT_EQ("abc", std::string(e.what()));
  2785. } catch (...) {}
  2786. res.status = StatusCode::InternalServerError_500;
  2787. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2788. "text/html"); // <= Content-Length still 13 at this point
  2789. });
  2790. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2791. res.set_content("Hello World!\n", "text/plain");
  2792. throw std::runtime_error("abc");
  2793. });
  2794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2795. auto se = detail::scope_exit([&] {
  2796. svr.stop();
  2797. thread.join();
  2798. ASSERT_FALSE(svr.is_running());
  2799. });
  2800. svr.wait_until_ready();
  2801. for (size_t i = 0; i < 10; i++) {
  2802. Client cli(HOST, PORT);
  2803. for (size_t j = 0; j < 100; j++) {
  2804. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2805. ASSERT_TRUE(res);
  2806. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2807. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2808. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2809. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2810. }
  2811. cli.set_keep_alive(true);
  2812. for (size_t j = 0; j < 100; j++) {
  2813. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2814. ASSERT_TRUE(res);
  2815. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2816. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2817. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2818. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2819. }
  2820. }
  2821. }
  2822. TEST(ExceptionTest, AndErrorHandler) {
  2823. Server svr;
  2824. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2825. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2826. });
  2827. svr.set_exception_handler(
  2828. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2829. EXPECT_FALSE(ep == nullptr);
  2830. try {
  2831. std::rethrow_exception(ep);
  2832. } catch (std::exception &e) {
  2833. res.set_content(e.what(), "text/html");
  2834. } catch (...) {}
  2835. res.status = StatusCode::InternalServerError_500;
  2836. });
  2837. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2838. throw std::runtime_error("EXCEPTION");
  2839. });
  2840. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2841. res.set_content("ERROR", "text/html");
  2842. res.status = StatusCode::InternalServerError_500;
  2843. });
  2844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. thread.join();
  2848. ASSERT_FALSE(svr.is_running());
  2849. });
  2850. svr.wait_until_ready();
  2851. Client cli(HOST, PORT);
  2852. {
  2853. auto res = cli.Get("/exception");
  2854. ASSERT_TRUE(res);
  2855. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2856. EXPECT_EQ("EXCEPTION", res->body);
  2857. }
  2858. {
  2859. auto res = cli.Get("/error");
  2860. ASSERT_TRUE(res);
  2861. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2862. EXPECT_EQ("ERROR", res->body);
  2863. }
  2864. {
  2865. auto res = cli.Get("/invalid");
  2866. ASSERT_TRUE(res);
  2867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2868. EXPECT_EQ("NOT_FOUND", res->body);
  2869. }
  2870. }
  2871. #endif
  2872. TEST(NoContentTest, ContentLength) {
  2873. Server svr;
  2874. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2875. res.status = StatusCode::NoContent_204;
  2876. });
  2877. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2878. auto se = detail::scope_exit([&] {
  2879. svr.stop();
  2880. thread.join();
  2881. ASSERT_FALSE(svr.is_running());
  2882. });
  2883. svr.wait_until_ready();
  2884. {
  2885. Client cli(HOST, PORT);
  2886. auto res = cli.Get("/hi");
  2887. ASSERT_TRUE(res);
  2888. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2889. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2890. }
  2891. }
  2892. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2893. #ifdef CPPHTTPLIB_SSL_ENABLED
  2894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2895. ASSERT_TRUE(svr.is_valid());
  2896. #else
  2897. Server svr;
  2898. #endif
  2899. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2900. if (req.path == "/routing_handler") {
  2901. res.set_header("PRE_ROUTING", "on");
  2902. res.set_content("Routing Handler", "text/plain");
  2903. return httplib::Server::HandlerResponse::Handled;
  2904. }
  2905. return httplib::Server::HandlerResponse::Unhandled;
  2906. });
  2907. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2908. res.set_content("Error", "text/html");
  2909. });
  2910. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2911. if (req.path == "/routing_handler") {
  2912. res.set_header("POST_ROUTING", "on");
  2913. }
  2914. });
  2915. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2916. res.set_content("Hello World!\n", "text/plain");
  2917. });
  2918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2919. auto se = detail::scope_exit([&] {
  2920. svr.stop();
  2921. thread.join();
  2922. ASSERT_FALSE(svr.is_running());
  2923. });
  2924. svr.wait_until_ready();
  2925. {
  2926. #ifdef CPPHTTPLIB_SSL_ENABLED
  2927. SSLClient cli(HOST, PORT);
  2928. cli.enable_server_certificate_verification(false);
  2929. #else
  2930. Client cli(HOST, PORT);
  2931. #endif
  2932. auto res = cli.Get("/routing_handler");
  2933. ASSERT_TRUE(res);
  2934. EXPECT_EQ(StatusCode::OK_200, res->status);
  2935. EXPECT_EQ("Routing Handler", res->body);
  2936. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2937. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2938. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2939. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2940. }
  2941. {
  2942. #ifdef CPPHTTPLIB_SSL_ENABLED
  2943. SSLClient cli(HOST, PORT);
  2944. cli.enable_server_certificate_verification(false);
  2945. #else
  2946. Client cli(HOST, PORT);
  2947. #endif
  2948. auto res = cli.Get("/hi");
  2949. ASSERT_TRUE(res);
  2950. EXPECT_EQ(StatusCode::OK_200, res->status);
  2951. EXPECT_EQ("Hello World!\n", res->body);
  2952. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2953. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2954. }
  2955. {
  2956. #ifdef CPPHTTPLIB_SSL_ENABLED
  2957. SSLClient cli(HOST, PORT);
  2958. cli.enable_server_certificate_verification(false);
  2959. #else
  2960. Client cli(HOST, PORT);
  2961. #endif
  2962. auto res = cli.Get("/aaa");
  2963. ASSERT_TRUE(res);
  2964. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2965. EXPECT_EQ("Error", res->body);
  2966. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2967. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2968. }
  2969. }
  2970. TEST(RequestHandlerTest, PreRequestHandler) {
  2971. auto route_path = "/user/:user";
  2972. Server svr;
  2973. svr.Get("/hi", [](const Request &, Response &res) {
  2974. res.set_content("hi", "text/plain");
  2975. });
  2976. svr.Get(route_path, [](const Request &req, Response &res) {
  2977. res.set_content(req.path_params.at("user"), "text/plain");
  2978. });
  2979. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2980. if (req.matched_route == route_path) {
  2981. auto user = req.path_params.at("user");
  2982. if (user != "john") {
  2983. res.status = StatusCode::Forbidden_403;
  2984. res.set_content("error", "text/html");
  2985. return Server::HandlerResponse::Handled;
  2986. }
  2987. }
  2988. return Server::HandlerResponse::Unhandled;
  2989. });
  2990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2991. auto se = detail::scope_exit([&] {
  2992. svr.stop();
  2993. thread.join();
  2994. ASSERT_FALSE(svr.is_running());
  2995. });
  2996. svr.wait_until_ready();
  2997. Client cli(HOST, PORT);
  2998. {
  2999. auto res = cli.Get("/hi");
  3000. ASSERT_TRUE(res);
  3001. EXPECT_EQ(StatusCode::OK_200, res->status);
  3002. EXPECT_EQ("hi", res->body);
  3003. }
  3004. {
  3005. auto res = cli.Get("/user/john");
  3006. ASSERT_TRUE(res);
  3007. EXPECT_EQ(StatusCode::OK_200, res->status);
  3008. EXPECT_EQ("john", res->body);
  3009. }
  3010. {
  3011. auto res = cli.Get("/user/invalid-user");
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3014. EXPECT_EQ("error", res->body);
  3015. }
  3016. }
  3017. // The pre-request handler must run before the request body is read, so a
  3018. // rejected request never forces the server to buffer a (potentially large)
  3019. // body. Here the posted body is larger than the payload limit: if the body
  3020. // were read first the server would answer 413, but because the pre-request
  3021. // handler runs first it answers 403 and the body is never read.
  3022. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3023. Server svr;
  3024. svr.set_payload_max_length(8);
  3025. auto handler_ran = false;
  3026. svr.Post("/reject", [&](const Request &req, Response &res) {
  3027. handler_ran = true;
  3028. res.set_content(req.body, "text/plain");
  3029. });
  3030. svr.Post("/accept", [](const Request &req, Response &res) {
  3031. res.set_content(req.body, "text/plain");
  3032. });
  3033. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3034. if (req.matched_route == "/reject") {
  3035. res.status = StatusCode::Forbidden_403;
  3036. res.set_content("denied", "text/plain");
  3037. return Server::HandlerResponse::Handled;
  3038. }
  3039. return Server::HandlerResponse::Unhandled;
  3040. });
  3041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. thread.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. Client cli(HOST, PORT);
  3049. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3050. // rejects with 403 before the body is read, so 413 is never reached.
  3051. {
  3052. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3053. ASSERT_TRUE(res);
  3054. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3055. EXPECT_EQ("denied", res->body);
  3056. EXPECT_FALSE(handler_ran);
  3057. }
  3058. // An approved route still reads the body and enforces the payload limit.
  3059. {
  3060. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3061. ASSERT_TRUE(res);
  3062. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3063. }
  3064. }
  3065. TEST(UserDataTest, BasicOperations) {
  3066. httplib::UserData ud;
  3067. // Initially empty
  3068. EXPECT_FALSE(ud.has("key"));
  3069. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3070. // set and get
  3071. ud.set("key", 42);
  3072. EXPECT_TRUE(ud.has("key"));
  3073. auto *p = ud.get<int>("key");
  3074. ASSERT_NE(nullptr, p);
  3075. EXPECT_EQ(42, *p);
  3076. // Type mismatch → nullptr
  3077. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3078. // Overwrite with different type
  3079. ud.set("key", std::string("hello"));
  3080. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3081. auto *s = ud.get<std::string>("key");
  3082. ASSERT_NE(nullptr, s);
  3083. EXPECT_EQ("hello", *s);
  3084. // erase
  3085. ud.erase("key");
  3086. EXPECT_FALSE(ud.has("key"));
  3087. // clear
  3088. ud.set("a", 1);
  3089. ud.set("b", 2);
  3090. ud.clear();
  3091. EXPECT_FALSE(ud.has("a"));
  3092. EXPECT_FALSE(ud.has("b"));
  3093. }
  3094. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3095. struct AuthCtx {
  3096. std::string user_id;
  3097. };
  3098. Server svr;
  3099. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3100. res.user_data.set("auth", AuthCtx{"alice"});
  3101. return Server::HandlerResponse::Unhandled;
  3102. });
  3103. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3104. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3105. ASSERT_NE(nullptr, ctx);
  3106. res.set_content("Hello " + ctx->user_id, "text/plain");
  3107. });
  3108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3109. auto se = detail::scope_exit([&] {
  3110. svr.stop();
  3111. thread.join();
  3112. ASSERT_FALSE(svr.is_running());
  3113. });
  3114. svr.wait_until_ready();
  3115. Client cli(HOST, PORT);
  3116. auto res = cli.Get("/me");
  3117. ASSERT_TRUE(res);
  3118. EXPECT_EQ(StatusCode::OK_200, res->status);
  3119. EXPECT_EQ("Hello alice", res->body);
  3120. }
  3121. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3122. struct RoleCtx {
  3123. std::string role;
  3124. };
  3125. Server svr;
  3126. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3127. res.user_data.set("role", RoleCtx{"admin"});
  3128. return Server::HandlerResponse::Unhandled;
  3129. });
  3130. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3131. auto *ctx = res.user_data.get<RoleCtx>("role");
  3132. ASSERT_NE(nullptr, ctx);
  3133. res.set_content(ctx->role, "text/plain");
  3134. });
  3135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3136. auto se = detail::scope_exit([&] {
  3137. svr.stop();
  3138. thread.join();
  3139. ASSERT_FALSE(svr.is_running());
  3140. });
  3141. svr.wait_until_ready();
  3142. Client cli(HOST, PORT);
  3143. auto res = cli.Get("/role");
  3144. ASSERT_TRUE(res);
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ("admin", res->body);
  3147. }
  3148. TEST(InvalidFormatTest, StatusCode) {
  3149. Server svr;
  3150. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3151. res.set_content("Hello World!\n", "text/plain");
  3152. res.status = 9999; // Status should be a three-digit code...
  3153. });
  3154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3155. auto se = detail::scope_exit([&] {
  3156. svr.stop();
  3157. thread.join();
  3158. ASSERT_FALSE(svr.is_running());
  3159. });
  3160. svr.wait_until_ready();
  3161. {
  3162. Client cli(HOST, PORT);
  3163. auto res = cli.Get("/hi");
  3164. ASSERT_FALSE(res);
  3165. }
  3166. }
  3167. TEST(URLFragmentTest, WithFragment) {
  3168. Server svr;
  3169. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3170. EXPECT_TRUE(req.target == "/hi");
  3171. });
  3172. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3173. auto se = detail::scope_exit([&] {
  3174. svr.stop();
  3175. thread.join();
  3176. ASSERT_FALSE(svr.is_running());
  3177. });
  3178. svr.wait_until_ready();
  3179. {
  3180. Client cli(HOST, PORT);
  3181. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3182. EXPECT_TRUE(res);
  3183. EXPECT_EQ(StatusCode::OK_200, res->status);
  3184. res = cli.Get("/hi%23key1=val1=key2=val2");
  3185. EXPECT_TRUE(res);
  3186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3187. }
  3188. }
  3189. TEST(HeaderWriter, SetHeaderWriter) {
  3190. Server svr;
  3191. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3192. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3193. return detail::write_headers(strm, hdrs);
  3194. });
  3195. svr.Get("/hi", [](const Request &req, Response &res) {
  3196. auto it = req.headers.find("CustomClientHeader");
  3197. EXPECT_TRUE(it != req.headers.end());
  3198. EXPECT_EQ(it->second, "CustomClientValue");
  3199. res.set_content("Hello World!\n", "text/plain");
  3200. });
  3201. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3202. auto se = detail::scope_exit([&] {
  3203. svr.stop();
  3204. thread.join();
  3205. ASSERT_FALSE(svr.is_running());
  3206. });
  3207. svr.wait_until_ready();
  3208. {
  3209. Client cli(HOST, PORT);
  3210. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3211. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3212. return detail::write_headers(strm, hdrs);
  3213. });
  3214. auto res = cli.Get("/hi");
  3215. EXPECT_TRUE(res);
  3216. EXPECT_EQ(StatusCode::OK_200, res->status);
  3217. auto it = res->headers.find("CustomServerHeader");
  3218. EXPECT_TRUE(it != res->headers.end());
  3219. EXPECT_EQ(it->second, "CustomServerValue");
  3220. }
  3221. }
  3222. class ServerTest : public ::testing::Test {
  3223. protected:
  3224. ServerTest()
  3225. : cli_(HOST, PORT)
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. ,
  3228. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3229. #endif
  3230. {
  3231. #ifdef CPPHTTPLIB_SSL_ENABLED
  3232. cli_.enable_server_certificate_verification(false);
  3233. #endif
  3234. // Allow LARGE_DATA (100MB) responses
  3235. cli_.set_payload_max_length(200 * 1024 * 1024);
  3236. }
  3237. virtual void SetUp() {
  3238. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3239. svr_.set_payload_max_length(200 * 1024 * 1024);
  3240. svr_.set_mount_point("/", "./www");
  3241. svr_.set_mount_point("/mount", "./www2");
  3242. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3243. svr_.Get("/hi",
  3244. [&](const Request & /*req*/, Response &res) {
  3245. res.set_content("Hello World!", "text/plain");
  3246. })
  3247. .Get("/file_content",
  3248. [&](const Request & /*req*/, Response &res) {
  3249. res.set_file_content("./www/dir/test.html");
  3250. })
  3251. .Get("/file_content_with_content_type",
  3252. [&](const Request & /*req*/, Response &res) {
  3253. res.set_file_content("./www/file", "text/plain");
  3254. })
  3255. .Get("/invalid_file_content",
  3256. [&](const Request & /*req*/, Response &res) {
  3257. res.set_file_content("./www/dir/invalid_file_path");
  3258. })
  3259. .Get("/http_response_splitting",
  3260. [&](const Request & /*req*/, Response &res) {
  3261. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3262. EXPECT_EQ(0U, res.headers.size());
  3263. EXPECT_FALSE(res.has_header("a"));
  3264. res.set_header("a", "1\nSet-Cookie: a=1");
  3265. EXPECT_EQ(0U, res.headers.size());
  3266. EXPECT_FALSE(res.has_header("a"));
  3267. res.set_header("a", "1\rSet-Cookie: a=1");
  3268. EXPECT_EQ(0U, res.headers.size());
  3269. EXPECT_FALSE(res.has_header("a"));
  3270. res.set_header("a\r\nb", "0");
  3271. EXPECT_EQ(0U, res.headers.size());
  3272. EXPECT_FALSE(res.has_header("a"));
  3273. res.set_header("a\rb", "0");
  3274. EXPECT_EQ(0U, res.headers.size());
  3275. EXPECT_FALSE(res.has_header("a"));
  3276. res.set_header("a\nb", "0");
  3277. EXPECT_EQ(0U, res.headers.size());
  3278. EXPECT_FALSE(res.has_header("a"));
  3279. res.set_redirect("1\r\nSet-Cookie: a=1");
  3280. EXPECT_EQ(0U, res.headers.size());
  3281. EXPECT_FALSE(res.has_header("Location"));
  3282. })
  3283. .Get("/slow",
  3284. [&](const Request & /*req*/, Response &res) {
  3285. std::this_thread::sleep_for(std::chrono::seconds(4));
  3286. res.set_content("slow", "text/plain");
  3287. })
  3288. #if 0
  3289. .Post("/slowpost",
  3290. [&](const Request & /*req*/, Response &res) {
  3291. std::this_thread::sleep_for(std::chrono::seconds(2));
  3292. res.set_content("slow", "text/plain");
  3293. })
  3294. #endif
  3295. .Get("/remote_addr",
  3296. [&](const Request &req, Response &res) {
  3297. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3298. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3299. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3300. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3301. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3302. #endif
  3303. res.set_content(req.remote_addr, "text/plain");
  3304. })
  3305. .Get("/local_addr",
  3306. [&](const Request &req, Response &res) {
  3307. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3308. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3309. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3310. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3311. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3312. #endif
  3313. auto local_addr = req.local_addr;
  3314. auto local_port = std::to_string(req.local_port);
  3315. res.set_content(local_addr.append(":").append(local_port),
  3316. "text/plain");
  3317. })
  3318. .Get("/endwith%",
  3319. [&](const Request & /*req*/, Response &res) {
  3320. res.set_content("Hello World!", "text/plain");
  3321. })
  3322. .Get("/a\\+\\+b",
  3323. [&](const Request &req, Response &res) {
  3324. ASSERT_TRUE(req.has_param("a +b"));
  3325. auto val = req.get_param_value("a +b");
  3326. res.set_content(val, "text/plain");
  3327. })
  3328. .Get("/", [&](const Request & /*req*/,
  3329. Response &res) { res.set_redirect("/hi"); })
  3330. .Post("/1",
  3331. [](const Request & /*req*/, Response &res) {
  3332. res.set_redirect("/2", StatusCode::SeeOther_303);
  3333. })
  3334. .Get("/2",
  3335. [](const Request & /*req*/, Response &res) {
  3336. res.set_content("redirected.", "text/plain");
  3337. res.status = StatusCode::OK_200;
  3338. })
  3339. .Post("/person",
  3340. [&](const Request &req, Response &res) {
  3341. if (req.has_param("name") && req.has_param("note")) {
  3342. persons_[req.get_param_value("name")] =
  3343. req.get_param_value("note");
  3344. } else {
  3345. res.status = StatusCode::BadRequest_400;
  3346. }
  3347. })
  3348. .Put("/person",
  3349. [&](const Request &req, Response &res) {
  3350. if (req.has_param("name") && req.has_param("note")) {
  3351. persons_[req.get_param_value("name")] =
  3352. req.get_param_value("note");
  3353. } else {
  3354. res.status = StatusCode::BadRequest_400;
  3355. }
  3356. })
  3357. .Get("/person/(.*)",
  3358. [&](const Request &req, Response &res) {
  3359. string name = req.matches[1];
  3360. if (persons_.find(name) != persons_.end()) {
  3361. auto note = persons_[name];
  3362. res.set_content(note, "text/plain");
  3363. } else {
  3364. res.status = StatusCode::NotFound_404;
  3365. }
  3366. })
  3367. .Delete("/person",
  3368. [&](const Request &req, Response &res) {
  3369. if (req.has_param("name")) {
  3370. string name = req.get_param_value("name");
  3371. if (persons_.find(name) != persons_.end()) {
  3372. persons_.erase(name);
  3373. res.set_content("DELETED", "text/plain");
  3374. } else {
  3375. res.status = StatusCode::NotFound_404;
  3376. }
  3377. } else {
  3378. res.status = StatusCode::BadRequest_400;
  3379. }
  3380. })
  3381. .Post("/x-www-form-urlencoded-json",
  3382. [&](const Request &req, Response &res) {
  3383. auto json = req.get_param_value("json");
  3384. ASSERT_EQ(JSON_DATA, json);
  3385. res.set_content(json, "appliation/json");
  3386. res.status = StatusCode::OK_200;
  3387. })
  3388. .Get("/streamed-chunked",
  3389. [&](const Request & /*req*/, Response &res) {
  3390. res.set_chunked_content_provider(
  3391. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3392. sink.os << "123";
  3393. sink.os << "456";
  3394. sink.os << "789";
  3395. sink.done();
  3396. return true;
  3397. });
  3398. })
  3399. .Get("/streamed-chunked-with-prohibited-trailer",
  3400. [&](const Request & /*req*/, Response &res) {
  3401. auto i = new int(0);
  3402. // Declare both a prohibited trailer (Content-Length) and an
  3403. // allowed one
  3404. res.set_header("Trailer", "Content-Length, X-Allowed");
  3405. res.set_chunked_content_provider(
  3406. "text/plain",
  3407. [i](size_t /*offset*/, DataSink &sink) {
  3408. switch (*i) {
  3409. case 0: sink.os << "123"; break;
  3410. case 1: sink.os << "456"; break;
  3411. case 2: sink.os << "789"; break;
  3412. case 3: {
  3413. sink.done_with_trailer(
  3414. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3415. } break;
  3416. }
  3417. (*i)++;
  3418. return true;
  3419. },
  3420. [i](bool success) {
  3421. EXPECT_TRUE(success);
  3422. delete i;
  3423. });
  3424. })
  3425. .Get("/streamed-chunked2",
  3426. [&](const Request & /*req*/, Response &res) {
  3427. auto i = new int(0);
  3428. res.set_chunked_content_provider(
  3429. "text/plain",
  3430. [i](size_t /*offset*/, DataSink &sink) {
  3431. switch (*i) {
  3432. case 0: sink.os << "123"; break;
  3433. case 1: sink.os << "456"; break;
  3434. case 2: sink.os << "789"; break;
  3435. case 3: sink.done(); break;
  3436. }
  3437. (*i)++;
  3438. return true;
  3439. },
  3440. [i](bool success) {
  3441. EXPECT_TRUE(success);
  3442. delete i;
  3443. });
  3444. })
  3445. .Get("/streamed-chunked-with-trailer",
  3446. [&](const Request & /*req*/, Response &res) {
  3447. auto i = new int(0);
  3448. res.set_header("Trailer", "Dummy1, Dummy2");
  3449. res.set_chunked_content_provider(
  3450. "text/plain",
  3451. [i](size_t /*offset*/, DataSink &sink) {
  3452. switch (*i) {
  3453. case 0: sink.os << "123"; break;
  3454. case 1: sink.os << "456"; break;
  3455. case 2: sink.os << "789"; break;
  3456. case 3: {
  3457. sink.done_with_trailer(
  3458. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3459. } break;
  3460. }
  3461. (*i)++;
  3462. return true;
  3463. },
  3464. [i](bool success) {
  3465. EXPECT_TRUE(success);
  3466. delete i;
  3467. });
  3468. })
  3469. .Get("/streamed",
  3470. [&](const Request & /*req*/, Response &res) {
  3471. res.set_content_provider(
  3472. 6, "text/plain",
  3473. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3474. sink.os << (offset < 3 ? "a" : "b");
  3475. return true;
  3476. });
  3477. })
  3478. .Get("/streamed-without-length",
  3479. [&](const Request & /*req*/, Response &res) {
  3480. auto data = new std::string("abcdefg");
  3481. res.set_content_provider(
  3482. "text/plain",
  3483. [data](size_t offset, DataSink &sink) {
  3484. if (offset < data->size()) {
  3485. sink.os << data->substr(offset);
  3486. }
  3487. sink.done();
  3488. return true;
  3489. },
  3490. [data](bool success) {
  3491. EXPECT_TRUE(success);
  3492. delete data;
  3493. });
  3494. })
  3495. .Get("/streamed-with-range",
  3496. [&](const Request &req, Response &res) {
  3497. auto data = new std::string("abcdefg");
  3498. res.set_content_provider(
  3499. data->size(), "text/plain",
  3500. [data](size_t offset, size_t length, DataSink &sink) {
  3501. size_t DATA_CHUNK_SIZE = 4;
  3502. const auto &d = *data;
  3503. auto out_len =
  3504. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3505. auto ret =
  3506. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3507. EXPECT_TRUE(ret);
  3508. return true;
  3509. },
  3510. [data, &req](bool success) {
  3511. EXPECT_EQ(success, !req.has_param("error"));
  3512. delete data;
  3513. });
  3514. })
  3515. .Get("/streamed-cancel",
  3516. [&](const Request & /*req*/, Response &res) {
  3517. res.set_content_provider(
  3518. size_t(-1), "text/plain",
  3519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3520. sink.os << "data_chunk";
  3521. return true;
  3522. });
  3523. })
  3524. .Get("/regex-with-delimiter",
  3525. [&](const Request &req, Response & /*res*/) {
  3526. ASSERT_TRUE(req.has_param("key"));
  3527. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3528. })
  3529. .Get("/with-range",
  3530. [&](const Request & /*req*/, Response &res) {
  3531. res.set_content("abcdefg", "text/plain");
  3532. })
  3533. .Get("/test-start-time",
  3534. [&](const Request &req, Response & /*res*/) {
  3535. EXPECT_NE(req.start_time_,
  3536. std::chrono::steady_clock::time_point::min());
  3537. })
  3538. .Get("/with-range-customized-response",
  3539. [&](const Request & /*req*/, Response &res) {
  3540. res.status = StatusCode::BadRequest_400;
  3541. res.set_content(JSON_DATA, "application/json");
  3542. })
  3543. .Post("/chunked",
  3544. [&](const Request &req, Response & /*res*/) {
  3545. EXPECT_EQ(req.body, "dechunked post body");
  3546. })
  3547. .Post("/large-chunked",
  3548. [&](const Request &req, Response & /*res*/) {
  3549. std::string expected(6 * 30 * 1024u, 'a');
  3550. EXPECT_EQ(req.body, expected);
  3551. })
  3552. .Post("/multipart",
  3553. [&](const Request &req, Response & /*res*/) {
  3554. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3555. req.form.get_field_count("text2") +
  3556. req.form.get_field_count("file3") +
  3557. req.form.get_field_count("file4"));
  3558. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3559. req.form.get_file_count("file2"));
  3560. ASSERT_TRUE(!req.form.has_file("???"));
  3561. ASSERT_TRUE(!req.form.has_field("???"));
  3562. ASSERT_TRUE(req.body.empty());
  3563. {
  3564. const auto &text = req.form.get_field("text1");
  3565. EXPECT_EQ("text default", text);
  3566. }
  3567. {
  3568. const auto &text = req.form.get_field("text2");
  3569. EXPECT_EQ("aωb", text);
  3570. }
  3571. {
  3572. const auto &file = req.form.get_file("file1");
  3573. EXPECT_EQ("hello.txt", file.filename);
  3574. EXPECT_EQ("text/plain", file.content_type);
  3575. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3576. }
  3577. {
  3578. const auto &file = req.form.get_file("file2");
  3579. EXPECT_EQ("world.json", file.filename);
  3580. EXPECT_EQ("application/json", file.content_type);
  3581. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3582. }
  3583. {
  3584. const auto &text = req.form.get_field("file3");
  3585. EXPECT_EQ(0u, text.size());
  3586. }
  3587. {
  3588. const auto &text = req.form.get_field("file4");
  3589. EXPECT_EQ(0u, text.size());
  3590. }
  3591. })
  3592. .Post("/multipart/multi_file_values",
  3593. [&](const Request &req, Response & /*res*/) {
  3594. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3595. req.form.get_field_count("multi_text1"));
  3596. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3597. ASSERT_TRUE(!req.form.has_file("???"));
  3598. ASSERT_TRUE(!req.form.has_field("???"));
  3599. ASSERT_TRUE(req.body.empty());
  3600. {
  3601. const auto &text = req.form.get_field("text");
  3602. EXPECT_EQ("default text", text);
  3603. }
  3604. {
  3605. const auto &text1_values = req.form.get_fields("multi_text1");
  3606. EXPECT_EQ(2u, text1_values.size());
  3607. EXPECT_EQ("aaaaa", text1_values[0]);
  3608. EXPECT_EQ("bbbbb", text1_values[1]);
  3609. }
  3610. {
  3611. const auto &file1_values = req.form.get_files("multi_file1");
  3612. EXPECT_EQ(2u, file1_values.size());
  3613. auto file1 = file1_values[0];
  3614. EXPECT_EQ(file1.filename, "hello.txt");
  3615. EXPECT_EQ(file1.content_type, "text/plain");
  3616. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3617. auto file2 = file1_values[1];
  3618. EXPECT_EQ(file2.filename, "world.json");
  3619. EXPECT_EQ(file2.content_type, "application/json");
  3620. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3621. }
  3622. })
  3623. .Post("/empty",
  3624. [&](const Request &req, Response &res) {
  3625. EXPECT_EQ(req.body, "");
  3626. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3627. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3628. res.set_content("empty", "text/plain");
  3629. })
  3630. .Post("/empty-no-content-type",
  3631. [&](const Request &req, Response &res) {
  3632. EXPECT_EQ(req.body, "");
  3633. EXPECT_FALSE(req.has_header("Content-Type"));
  3634. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3635. res.set_content("empty-no-content-type", "text/plain");
  3636. })
  3637. .Post("/path-only",
  3638. [&](const Request &req, Response &res) {
  3639. EXPECT_EQ(req.body, "");
  3640. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3641. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3642. res.set_content("path-only", "text/plain");
  3643. })
  3644. .Post("/path-headers-only",
  3645. [&](const Request &req, Response &res) {
  3646. EXPECT_EQ(req.body, "");
  3647. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3648. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3649. EXPECT_EQ("world", req.get_header_value("hello"));
  3650. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3651. res.set_content("path-headers-only", "text/plain");
  3652. })
  3653. .Post("/post-large",
  3654. [&](const Request &req, Response &res) {
  3655. EXPECT_EQ(req.body, LARGE_DATA);
  3656. res.set_content(req.body, "text/plain");
  3657. })
  3658. .Post("/post-loopback",
  3659. [&](const Request &, Response &res,
  3660. ContentReader const &content_reader) {
  3661. std::string body;
  3662. content_reader([&](const char *data, size_t data_length) {
  3663. body.append(data, data_length);
  3664. return true;
  3665. });
  3666. res.set_content(body, "text/plain");
  3667. })
  3668. .Put("/put-loopback",
  3669. [&](const Request &, Response &res,
  3670. ContentReader const &content_reader) {
  3671. std::string body;
  3672. content_reader([&](const char *data, size_t data_length) {
  3673. body.append(data, data_length);
  3674. return true;
  3675. });
  3676. res.set_content(body, "text/plain");
  3677. })
  3678. .Patch("/patch-loopback",
  3679. [&](const Request &, Response &res,
  3680. ContentReader const &content_reader) {
  3681. std::string body;
  3682. content_reader([&](const char *data, size_t data_length) {
  3683. body.append(data, data_length);
  3684. return true;
  3685. });
  3686. res.set_content(body, "text/plain");
  3687. })
  3688. .Put("/empty-no-content-type",
  3689. [&](const Request &req, Response &res) {
  3690. EXPECT_EQ(req.body, "");
  3691. EXPECT_FALSE(req.has_header("Content-Type"));
  3692. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3693. res.set_content("empty-no-content-type", "text/plain");
  3694. })
  3695. .Put("/put",
  3696. [&](const Request &req, Response &res) {
  3697. EXPECT_EQ(req.body, "PUT");
  3698. res.set_content(req.body, "text/plain");
  3699. })
  3700. .Put("/put-large",
  3701. [&](const Request &req, Response &res) {
  3702. EXPECT_EQ(req.body, LARGE_DATA);
  3703. res.set_content(req.body, "text/plain");
  3704. })
  3705. .Patch("/patch",
  3706. [&](const Request &req, Response &res) {
  3707. EXPECT_EQ(req.body, "PATCH");
  3708. res.set_content(req.body, "text/plain");
  3709. })
  3710. .Delete("/delete",
  3711. [&](const Request & /*req*/, Response &res) {
  3712. res.set_content("DELETE", "text/plain");
  3713. })
  3714. .Delete("/delete-body",
  3715. [&](const Request &req, Response &res) {
  3716. EXPECT_EQ(req.body, "content");
  3717. res.set_content(req.body, "text/plain");
  3718. })
  3719. .Options(R"(\*)",
  3720. [&](const Request & /*req*/, Response &res) {
  3721. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3722. })
  3723. .Get("/request-target",
  3724. [&](const Request &req, Response & /*res*/) {
  3725. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3726. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3727. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3728. })
  3729. .Get("/long-query-value",
  3730. [&](const Request &req, Response & /*res*/) {
  3731. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3732. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3733. })
  3734. .Get("/too-long-query-value",
  3735. [&](const Request &req, Response & /*res*/) {
  3736. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3737. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3738. })
  3739. .Get("/array-param",
  3740. [&](const Request &req, Response & /*res*/) {
  3741. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3742. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3743. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3744. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3745. })
  3746. .Get("/array-param-values",
  3747. [&](const Request &req, Response & /*res*/) {
  3748. auto values = req.get_param_values("array");
  3749. EXPECT_EQ(3u, values.size());
  3750. EXPECT_EQ("value1", values[0]);
  3751. EXPECT_EQ("value2", values[1]);
  3752. EXPECT_EQ("value3", values[2]);
  3753. auto empty = req.get_param_values("nonexistent");
  3754. EXPECT_TRUE(empty.empty());
  3755. })
  3756. .Post("/validate-no-multiple-headers",
  3757. [&](const Request &req, Response & /*res*/) {
  3758. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3759. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3760. })
  3761. .Post("/content_receiver",
  3762. [&](const Request &req, Response &res,
  3763. const ContentReader &content_reader) {
  3764. if (req.is_multipart_form_data()) {
  3765. std::vector<FormData> items;
  3766. content_reader(
  3767. [&](const FormData &file) {
  3768. items.push_back(file);
  3769. return true;
  3770. },
  3771. [&](const char *data, size_t data_length) {
  3772. items.back().content.append(data, data_length);
  3773. return true;
  3774. });
  3775. EXPECT_EQ(5u, items.size());
  3776. {
  3777. const auto &file = get_file_value(items, "text1");
  3778. EXPECT_TRUE(file.filename.empty());
  3779. EXPECT_EQ("text default", file.content);
  3780. }
  3781. {
  3782. const auto &file = get_file_value(items, "text2");
  3783. EXPECT_TRUE(file.filename.empty());
  3784. EXPECT_EQ("aωb", file.content);
  3785. }
  3786. {
  3787. const auto &file = get_file_value(items, "file1");
  3788. EXPECT_EQ("hello.txt", file.filename);
  3789. EXPECT_EQ("text/plain", file.content_type);
  3790. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3791. }
  3792. {
  3793. const auto &file = get_file_value(items, "file2");
  3794. EXPECT_EQ("world.json", file.filename);
  3795. EXPECT_EQ("application/json", file.content_type);
  3796. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3797. }
  3798. {
  3799. const auto &file = get_file_value(items, "file3");
  3800. EXPECT_TRUE(file.filename.empty());
  3801. EXPECT_EQ("application/octet-stream", file.content_type);
  3802. EXPECT_EQ(0u, file.content.size());
  3803. }
  3804. } else {
  3805. std::string body;
  3806. content_reader([&](const char *data, size_t data_length) {
  3807. EXPECT_EQ(7U, data_length);
  3808. body.append(data, data_length);
  3809. return true;
  3810. });
  3811. EXPECT_EQ(body, "content");
  3812. res.set_content(body, "text/plain");
  3813. }
  3814. })
  3815. .Put("/content_receiver",
  3816. [&](const Request & /*req*/, Response &res,
  3817. const ContentReader &content_reader) {
  3818. std::string body;
  3819. content_reader([&](const char *data, size_t data_length) {
  3820. body.append(data, data_length);
  3821. return true;
  3822. });
  3823. EXPECT_EQ(body, "content");
  3824. res.set_content(body, "text/plain");
  3825. })
  3826. .Patch("/content_receiver",
  3827. [&](const Request & /*req*/, Response &res,
  3828. const ContentReader &content_reader) {
  3829. std::string body;
  3830. content_reader([&](const char *data, size_t data_length) {
  3831. body.append(data, data_length);
  3832. return true;
  3833. });
  3834. EXPECT_EQ(body, "content");
  3835. res.set_content(body, "text/plain");
  3836. })
  3837. .Post("/query-string-and-body",
  3838. [&](const Request &req, Response & /*res*/) {
  3839. ASSERT_TRUE(req.has_param("key"));
  3840. EXPECT_EQ(req.get_param_value("key"), "value");
  3841. EXPECT_EQ(req.body, "content");
  3842. })
  3843. .Get("/last-request",
  3844. [&](const Request &req, Response & /*res*/) {
  3845. EXPECT_EQ("close", req.get_header_value("Connection"));
  3846. })
  3847. .Get(R"(/redirect/(\d+))",
  3848. [&](const Request &req, Response &res) {
  3849. auto num = std::stoi(req.matches[1]) + 1;
  3850. std::string url = "/redirect/" + std::to_string(num);
  3851. res.set_redirect(url);
  3852. })
  3853. .Post("/binary",
  3854. [&](const Request &req, Response &res) {
  3855. EXPECT_EQ(4U, req.body.size());
  3856. EXPECT_EQ("application/octet-stream",
  3857. req.get_header_value("Content-Type"));
  3858. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3859. res.set_content(req.body, "application/octet-stream");
  3860. })
  3861. .Put("/binary",
  3862. [&](const Request &req, Response &res) {
  3863. EXPECT_EQ(4U, req.body.size());
  3864. EXPECT_EQ("application/octet-stream",
  3865. req.get_header_value("Content-Type"));
  3866. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3867. res.set_content(req.body, "application/octet-stream");
  3868. })
  3869. .Patch("/binary",
  3870. [&](const Request &req, Response &res) {
  3871. EXPECT_EQ(4U, req.body.size());
  3872. EXPECT_EQ("application/octet-stream",
  3873. req.get_header_value("Content-Type"));
  3874. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3875. res.set_content(req.body, "application/octet-stream");
  3876. })
  3877. .Delete("/binary",
  3878. [&](const Request &req, Response &res) {
  3879. EXPECT_EQ(4U, req.body.size());
  3880. EXPECT_EQ("application/octet-stream",
  3881. req.get_header_value("Content-Type"));
  3882. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3883. res.set_content(req.body, "application/octet-stream");
  3884. })
  3885. .Get("/issue1772",
  3886. [&](const Request & /*req*/, Response &res) {
  3887. res.status = 401;
  3888. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3889. })
  3890. .Delete("/issue609",
  3891. [](const httplib::Request &, httplib::Response &res,
  3892. const httplib::ContentReader &) {
  3893. res.set_content("ok", "text/plain");
  3894. })
  3895. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3896. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3897. .Get("/compress",
  3898. [&](const Request & /*req*/, Response &res) {
  3899. res.set_content(
  3900. "12345678901234567890123456789012345678901234567890123456789"
  3901. "01234567890123456789012345678901234567890",
  3902. "text/plain");
  3903. })
  3904. .Get("/compress-with-charset",
  3905. [&](const Request & /*req*/, Response &res) {
  3906. res.set_content(
  3907. "12345678901234567890123456789012345678901234567890123456789"
  3908. "01234567890123456789012345678901234567890",
  3909. "application/json; charset=utf-8");
  3910. })
  3911. .Get("/nocompress",
  3912. [&](const Request & /*req*/, Response &res) {
  3913. res.set_content(
  3914. "12345678901234567890123456789012345678901234567890123456789"
  3915. "01234567890123456789012345678901234567890",
  3916. "application/octet-stream");
  3917. })
  3918. .Post("/compress-multipart",
  3919. [&](const Request &req, Response & /*res*/) {
  3920. EXPECT_EQ(2u, req.form.fields.size());
  3921. ASSERT_TRUE(!req.form.has_field("???"));
  3922. {
  3923. const auto &text = req.form.get_field("key1");
  3924. EXPECT_EQ("test", text);
  3925. }
  3926. {
  3927. const auto &text = req.form.get_field("key2");
  3928. EXPECT_EQ("--abcdefg123", text);
  3929. }
  3930. })
  3931. #endif
  3932. ;
  3933. persons_["john"] = "programmer";
  3934. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3935. svr_.wait_until_ready();
  3936. }
  3937. virtual void TearDown() {
  3938. svr_.stop();
  3939. if (!request_threads_.empty()) {
  3940. std::this_thread::sleep_for(std::chrono::seconds(1));
  3941. for (auto &t : request_threads_) {
  3942. t.join();
  3943. }
  3944. }
  3945. t_.join();
  3946. }
  3947. map<string, string> persons_;
  3948. #ifdef CPPHTTPLIB_SSL_ENABLED
  3949. SSLClient cli_;
  3950. SSLServer svr_;
  3951. #else
  3952. Client cli_;
  3953. Server svr_;
  3954. #endif
  3955. thread t_;
  3956. std::vector<thread> request_threads_;
  3957. };
  3958. TEST_F(ServerTest, GetMethod200) {
  3959. auto res = cli_.Get("/hi");
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ("HTTP/1.1", res->version);
  3962. EXPECT_EQ(StatusCode::OK_200, res->status);
  3963. EXPECT_EQ("OK", res->reason);
  3964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3965. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3966. EXPECT_EQ("Hello World!", res->body);
  3967. }
  3968. TEST_F(ServerTest, GetEmptyFile) {
  3969. auto res = cli_.Get("/empty_file");
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3974. EXPECT_EQ("", res->body);
  3975. }
  3976. TEST_F(ServerTest, GetFileContent) {
  3977. auto res = cli_.Get("/file_content");
  3978. ASSERT_TRUE(res);
  3979. EXPECT_EQ(StatusCode::OK_200, res->status);
  3980. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3981. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3982. EXPECT_EQ("test.html", res->body);
  3983. }
  3984. TEST_F(ServerTest, GetFileContentWithRange) {
  3985. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3986. ASSERT_TRUE(res);
  3987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3988. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3989. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3990. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3991. EXPECT_EQ("est", res->body);
  3992. }
  3993. TEST_F(ServerTest, GetFileContentWithContentType) {
  3994. auto res = cli_.Get("/file_content_with_content_type");
  3995. ASSERT_TRUE(res);
  3996. EXPECT_EQ(StatusCode::OK_200, res->status);
  3997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3998. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3999. EXPECT_EQ("file\n", res->body);
  4000. }
  4001. TEST_F(ServerTest, GetInvalidFileContent) {
  4002. auto res = cli_.Get("/invalid_file_content");
  4003. ASSERT_TRUE(res);
  4004. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4005. }
  4006. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4007. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ("HTTP/1.1", res->version);
  4010. EXPECT_EQ(StatusCode::OK_200, res->status);
  4011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4012. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4013. EXPECT_EQ("Hello World!", res->body);
  4014. }
  4015. TEST_F(ServerTest, GetMethod302) {
  4016. auto res = cli_.Get("/");
  4017. ASSERT_TRUE(res);
  4018. EXPECT_EQ(StatusCode::Found_302, res->status);
  4019. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4020. }
  4021. TEST_F(ServerTest, GetMethod302Redirect) {
  4022. cli_.set_follow_location(true);
  4023. auto res = cli_.Get("/");
  4024. ASSERT_TRUE(res);
  4025. EXPECT_EQ(StatusCode::OK_200, res->status);
  4026. EXPECT_EQ("Hello World!", res->body);
  4027. EXPECT_EQ("/hi", res->location);
  4028. }
  4029. TEST_F(ServerTest, GetMethod404) {
  4030. auto res = cli_.Get("/invalid");
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4033. }
  4034. TEST_F(ServerTest, HeadMethod200) {
  4035. auto res = cli_.Head("/hi");
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4039. EXPECT_TRUE(res->body.empty());
  4040. }
  4041. TEST_F(ServerTest, HeadMethod200Static) {
  4042. auto res = cli_.Head("/mount/dir/index.html");
  4043. ASSERT_TRUE(res);
  4044. EXPECT_EQ(StatusCode::OK_200, res->status);
  4045. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4046. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4047. EXPECT_TRUE(res->body.empty());
  4048. }
  4049. TEST_F(ServerTest, HeadMethod404) {
  4050. auto res = cli_.Head("/invalid");
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4053. EXPECT_TRUE(res->body.empty());
  4054. }
  4055. TEST_F(ServerTest, GetMethodPersonJohn) {
  4056. auto res = cli_.Get("/person/john");
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::OK_200, res->status);
  4059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4060. EXPECT_EQ("programmer", res->body);
  4061. }
  4062. TEST_F(ServerTest, PostMethod1) {
  4063. auto res = cli_.Get("/person/john1");
  4064. ASSERT_TRUE(res);
  4065. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4066. res = cli_.Post("/person", "name=john1&note=coder",
  4067. "application/x-www-form-urlencoded");
  4068. ASSERT_TRUE(res);
  4069. ASSERT_EQ(StatusCode::OK_200, res->status);
  4070. res = cli_.Get("/person/john1");
  4071. ASSERT_TRUE(res);
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4074. ASSERT_EQ("coder", res->body);
  4075. }
  4076. TEST_F(ServerTest, PostMethod2) {
  4077. auto res = cli_.Get("/person/john2");
  4078. ASSERT_TRUE(res);
  4079. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4080. Params params;
  4081. params.emplace("name", "john2");
  4082. params.emplace("note", "coder");
  4083. res = cli_.Post("/person", params);
  4084. ASSERT_TRUE(res);
  4085. ASSERT_EQ(StatusCode::OK_200, res->status);
  4086. res = cli_.Get("/person/john2");
  4087. ASSERT_TRUE(res);
  4088. ASSERT_EQ(StatusCode::OK_200, res->status);
  4089. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4090. ASSERT_EQ("coder", res->body);
  4091. }
  4092. TEST_F(ServerTest, PutMethod3) {
  4093. auto res = cli_.Get("/person/john3");
  4094. ASSERT_TRUE(res);
  4095. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4096. Params params;
  4097. params.emplace("name", "john3");
  4098. params.emplace("note", "coder");
  4099. res = cli_.Put("/person", params);
  4100. ASSERT_TRUE(res);
  4101. ASSERT_EQ(StatusCode::OK_200, res->status);
  4102. res = cli_.Get("/person/john3");
  4103. ASSERT_TRUE(res);
  4104. ASSERT_EQ(StatusCode::OK_200, res->status);
  4105. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4106. ASSERT_EQ("coder", res->body);
  4107. }
  4108. TEST_F(ServerTest, DeleteMethod1) {
  4109. auto res = cli_.Get("/person/john4");
  4110. ASSERT_TRUE(res);
  4111. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4112. Params params;
  4113. params.emplace("name", "john4");
  4114. params.emplace("note", "coder");
  4115. res = cli_.Post("/person", params);
  4116. ASSERT_TRUE(res);
  4117. ASSERT_EQ(StatusCode::OK_200, res->status);
  4118. res = cli_.Get("/person/john4");
  4119. ASSERT_TRUE(res);
  4120. ASSERT_EQ(StatusCode::OK_200, res->status);
  4121. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4122. ASSERT_EQ("coder", res->body);
  4123. Params delete_params;
  4124. delete_params.emplace("name", "john4");
  4125. res = cli_.Delete("/person", delete_params);
  4126. ASSERT_TRUE(res);
  4127. ASSERT_EQ(StatusCode::OK_200, res->status);
  4128. ASSERT_EQ("DELETED", res->body);
  4129. res = cli_.Get("/person/john4");
  4130. ASSERT_TRUE(res);
  4131. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4132. }
  4133. TEST_F(ServerTest, DeleteMethod2) {
  4134. auto res = cli_.Get("/person/john5");
  4135. ASSERT_TRUE(res);
  4136. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4137. Params params;
  4138. params.emplace("name", "john5");
  4139. params.emplace("note", "developer");
  4140. res = cli_.Post("/person", params);
  4141. ASSERT_TRUE(res);
  4142. ASSERT_EQ(StatusCode::OK_200, res->status);
  4143. res = cli_.Get("/person/john5");
  4144. ASSERT_TRUE(res);
  4145. ASSERT_EQ(StatusCode::OK_200, res->status);
  4146. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4147. ASSERT_EQ("developer", res->body);
  4148. Params delete_params;
  4149. delete_params.emplace("name", "john5");
  4150. Headers headers;
  4151. headers.emplace("Custom-Header", "test-value");
  4152. res = cli_.Delete("/person", headers, delete_params);
  4153. ASSERT_TRUE(res);
  4154. ASSERT_EQ(StatusCode::OK_200, res->status);
  4155. ASSERT_EQ("DELETED", res->body);
  4156. res = cli_.Get("/person/john5");
  4157. ASSERT_TRUE(res);
  4158. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4159. }
  4160. TEST_F(ServerTest, DeleteMethod3) {
  4161. auto res = cli_.Get("/person/john6");
  4162. ASSERT_TRUE(res);
  4163. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4164. Params params;
  4165. params.emplace("name", "john6");
  4166. params.emplace("note", "tester");
  4167. res = cli_.Post("/person", params);
  4168. ASSERT_TRUE(res);
  4169. ASSERT_EQ(StatusCode::OK_200, res->status);
  4170. res = cli_.Get("/person/john6");
  4171. ASSERT_TRUE(res);
  4172. ASSERT_EQ(StatusCode::OK_200, res->status);
  4173. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4174. ASSERT_EQ("tester", res->body);
  4175. Params delete_params;
  4176. delete_params.emplace("name", "john6");
  4177. Headers headers;
  4178. headers.emplace("Custom-Header", "test-value");
  4179. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4180. ASSERT_TRUE(res);
  4181. ASSERT_EQ(StatusCode::OK_200, res->status);
  4182. ASSERT_EQ("DELETED", res->body);
  4183. res = cli_.Get("/person/john6");
  4184. ASSERT_TRUE(res);
  4185. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4186. }
  4187. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4188. Params params;
  4189. params.emplace("json", JSON_DATA);
  4190. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4191. ASSERT_TRUE(res);
  4192. ASSERT_EQ(StatusCode::OK_200, res->status);
  4193. ASSERT_EQ(JSON_DATA, res->body);
  4194. }
  4195. TEST_F(ServerTest, PostEmptyContent) {
  4196. auto res = cli_.Post("/empty", "", "text/plain");
  4197. ASSERT_TRUE(res);
  4198. ASSERT_EQ(StatusCode::OK_200, res->status);
  4199. ASSERT_EQ("empty", res->body);
  4200. }
  4201. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4202. auto res = cli_.Post("/empty-no-content-type");
  4203. ASSERT_TRUE(res);
  4204. ASSERT_EQ(StatusCode::OK_200, res->status);
  4205. ASSERT_EQ("empty-no-content-type", res->body);
  4206. }
  4207. TEST_F(ServerTest, PostPathOnly) {
  4208. auto res = cli_.Post("/path-only");
  4209. ASSERT_TRUE(res);
  4210. ASSERT_EQ(StatusCode::OK_200, res->status);
  4211. ASSERT_EQ("path-only", res->body);
  4212. }
  4213. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4214. auto res = cli_.Post("/path-headers-only",
  4215. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4216. ASSERT_TRUE(res);
  4217. ASSERT_EQ(StatusCode::OK_200, res->status);
  4218. ASSERT_EQ("path-headers-only", res->body);
  4219. }
  4220. TEST_F(ServerTest, PostLarge) {
  4221. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4222. ASSERT_TRUE(res);
  4223. ASSERT_EQ(StatusCode::OK_200, res->status);
  4224. EXPECT_EQ(LARGE_DATA, res->body);
  4225. }
  4226. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4227. auto res = cli_.Put("/empty-no-content-type");
  4228. ASSERT_TRUE(res);
  4229. ASSERT_EQ(StatusCode::OK_200, res->status);
  4230. ASSERT_EQ("empty-no-content-type", res->body);
  4231. }
  4232. TEST_F(ServerTest, GetMethodDir) {
  4233. auto res = cli_.Get("/dir/");
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4237. auto body = R"(<html>
  4238. <head>
  4239. </head>
  4240. <body>
  4241. <a href="/dir/test.html">Test</a>
  4242. <a href="/hi">hi</a>
  4243. </body>
  4244. </html>
  4245. )";
  4246. EXPECT_EQ(body, res->body);
  4247. }
  4248. TEST_F(ServerTest, GetMethodDirTest) {
  4249. auto res = cli_.Get("/dir/test.html");
  4250. ASSERT_TRUE(res);
  4251. EXPECT_EQ(StatusCode::OK_200, res->status);
  4252. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4253. EXPECT_EQ("test.html", res->body);
  4254. }
  4255. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4256. auto res = cli_.Get("/dir/../dir/test.html");
  4257. ASSERT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4260. EXPECT_EQ("test.html", res->body);
  4261. }
  4262. TEST_F(ServerTest, GetMethodInvalidPath) {
  4263. auto res = cli_.Get("/dir/../test.html");
  4264. ASSERT_TRUE(res);
  4265. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4266. }
  4267. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4268. auto res = cli_.Get("/../www/dir/test.html");
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4271. }
  4272. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4273. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4274. ASSERT_TRUE(res);
  4275. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4276. }
  4277. TEST_F(ServerTest, GetMethodDirMountTest) {
  4278. auto res = cli_.Get("/mount/dir/test.html");
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::OK_200, res->status);
  4281. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4282. EXPECT_EQ("test.html", res->body);
  4283. }
  4284. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4285. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4286. ASSERT_TRUE(res);
  4287. EXPECT_EQ(StatusCode::OK_200, res->status);
  4288. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4289. EXPECT_EQ("test.html", res->body);
  4290. }
  4291. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4292. auto res = cli_.Get("/mount/dir/../test.html");
  4293. ASSERT_TRUE(res);
  4294. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4295. }
  4296. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4297. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4298. ASSERT_TRUE(res);
  4299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4300. }
  4301. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4302. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4305. }
  4306. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4307. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4310. }
  4311. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4312. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4313. ASSERT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4315. }
  4316. TEST_F(ServerTest, PostMethod303) {
  4317. auto res = cli_.Post("/1", "body", "text/plain");
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4320. EXPECT_EQ("/2", res->get_header_value("Location"));
  4321. }
  4322. TEST_F(ServerTest, PostMethod303Redirect) {
  4323. cli_.set_follow_location(true);
  4324. auto res = cli_.Post("/1", "body", "text/plain");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ("redirected.", res->body);
  4328. EXPECT_EQ("/2", res->location);
  4329. }
  4330. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4331. auto res = cli_.Get("/dir/test.abcde");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4335. EXPECT_EQ("abcde", res->body);
  4336. }
  4337. TEST_F(ServerTest, StaticFileRange) {
  4338. auto res =
  4339. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4340. ASSERT_TRUE(res);
  4341. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4342. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4343. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4344. EXPECT_EQ(true, res->has_header("Content-Range"));
  4345. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4346. EXPECT_EQ(std::string("cd"), res->body);
  4347. }
  4348. TEST_F(ServerTest, StaticFileRanges) {
  4349. auto res = cli_.Get("/dir/test.abcde",
  4350. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4353. EXPECT_TRUE(
  4354. res->get_header_value("Content-Type")
  4355. .find(
  4356. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4357. 0);
  4358. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4359. }
  4360. TEST_F(ServerTest, StaticFileRangeHead) {
  4361. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4362. ASSERT_TRUE(res);
  4363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4364. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4365. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4366. EXPECT_EQ(true, res->has_header("Content-Range"));
  4367. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4368. }
  4369. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4370. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4371. ASSERT_TRUE(res);
  4372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4374. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4375. EXPECT_EQ(true, res->has_header("Content-Range"));
  4376. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4377. res->get_header_value("Content-Range"));
  4378. EXPECT_EQ("LAST\n", res->body);
  4379. }
  4380. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4381. auto res =
  4382. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4383. ASSERT_TRUE(res);
  4384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4386. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4389. }
  4390. TEST_F(ServerTest, StaticFileBigFile) {
  4391. auto res = cli_.Get("/dir/1MB.txt");
  4392. ASSERT_TRUE(res);
  4393. EXPECT_EQ(StatusCode::OK_200, res->status);
  4394. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4395. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4396. }
  4397. TEST_F(ServerTest, InvalidBaseDirMount) {
  4398. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4399. }
  4400. TEST_F(ServerTest, Binary) {
  4401. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4402. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4403. "application/octet-stream");
  4404. ASSERT_TRUE(res);
  4405. ASSERT_EQ(StatusCode::OK_200, res->status);
  4406. ASSERT_EQ(4U, res->body.size());
  4407. res = cli_.Put("/binary", binary.data(), binary.size(),
  4408. "application/octet-stream");
  4409. ASSERT_TRUE(res);
  4410. ASSERT_EQ(StatusCode::OK_200, res->status);
  4411. ASSERT_EQ(4U, res->body.size());
  4412. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4413. "application/octet-stream");
  4414. ASSERT_TRUE(res);
  4415. ASSERT_EQ(StatusCode::OK_200, res->status);
  4416. ASSERT_EQ(4U, res->body.size());
  4417. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4418. "application/octet-stream");
  4419. ASSERT_TRUE(res);
  4420. ASSERT_EQ(StatusCode::OK_200, res->status);
  4421. ASSERT_EQ(4U, res->body.size());
  4422. }
  4423. TEST_F(ServerTest, BinaryString) {
  4424. auto binary = std::string("\x00\x01\x02\x03", 4);
  4425. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4426. ASSERT_TRUE(res);
  4427. ASSERT_EQ(StatusCode::OK_200, res->status);
  4428. ASSERT_EQ(4U, res->body.size());
  4429. res = cli_.Put("/binary", binary, "application/octet-stream");
  4430. ASSERT_TRUE(res);
  4431. ASSERT_EQ(StatusCode::OK_200, res->status);
  4432. ASSERT_EQ(4U, res->body.size());
  4433. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4434. ASSERT_TRUE(res);
  4435. ASSERT_EQ(StatusCode::OK_200, res->status);
  4436. ASSERT_EQ(4U, res->body.size());
  4437. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4438. ASSERT_TRUE(res);
  4439. ASSERT_EQ(StatusCode::OK_200, res->status);
  4440. ASSERT_EQ(4U, res->body.size());
  4441. }
  4442. TEST_F(ServerTest, EmptyRequest) {
  4443. auto res = cli_.Get("");
  4444. ASSERT_TRUE(!res);
  4445. EXPECT_EQ(Error::Connection, res.error());
  4446. }
  4447. TEST_F(ServerTest, LongRequest) {
  4448. std::string request;
  4449. for (size_t i = 0; i < 545; i++) {
  4450. request += "/TooLongRequest";
  4451. }
  4452. request += "OK";
  4453. auto res = cli_.Get(request.c_str());
  4454. ASSERT_TRUE(res);
  4455. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4456. }
  4457. TEST_F(ServerTest, TooLongRequest) {
  4458. std::string request;
  4459. for (size_t i = 0; i < 546; i++) {
  4460. request += "/TooLongRequest";
  4461. }
  4462. request += "_NG";
  4463. auto start = std::chrono::high_resolution_clock::now();
  4464. cli_.set_keep_alive(true);
  4465. auto res = cli_.Get(request.c_str());
  4466. auto end = std::chrono::high_resolution_clock::now();
  4467. auto elapsed =
  4468. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4469. .count();
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4472. EXPECT_LE(elapsed, 1000);
  4473. EXPECT_EQ("close", res->get_header_value("Connection"));
  4474. EXPECT_FALSE(cli_.is_socket_open());
  4475. }
  4476. TEST_F(ServerTest, AlmostTooLongRequest) {
  4477. // test for #2046 - URI length check shouldn't include other content on req
  4478. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4479. // leading /, space, HTTP/1.1)
  4480. std::string request =
  4481. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4482. auto res = cli_.Get(request.c_str());
  4483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4485. }
  4486. TEST_F(ServerTest, LongHeader) {
  4487. Request req;
  4488. req.method = "GET";
  4489. req.path = "/hi";
  4490. std::string host_and_port;
  4491. host_and_port += HOST;
  4492. host_and_port += ":";
  4493. host_and_port += std::to_string(PORT);
  4494. req.headers.emplace("Host", host_and_port.c_str());
  4495. req.headers.emplace("Accept", "*/*");
  4496. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4497. req.headers.emplace(
  4498. "Header-Name",
  4499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4527. "@@@@@@@@@@@@@@@@");
  4528. auto res = std::make_shared<Response>();
  4529. auto error = Error::Success;
  4530. auto ret = cli_.send(req, *res, error);
  4531. ASSERT_TRUE(ret);
  4532. EXPECT_EQ(StatusCode::OK_200, res->status);
  4533. }
  4534. TEST_F(ServerTest, LongQueryValue) {
  4535. auto start = std::chrono::high_resolution_clock::now();
  4536. cli_.set_keep_alive(true);
  4537. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4538. auto end = std::chrono::high_resolution_clock::now();
  4539. auto elapsed =
  4540. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4541. .count();
  4542. ASSERT_TRUE(res);
  4543. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4544. EXPECT_LE(elapsed, 1000);
  4545. EXPECT_EQ("close", res->get_header_value("Connection"));
  4546. EXPECT_FALSE(cli_.is_socket_open());
  4547. }
  4548. TEST_F(ServerTest, TooLongQueryValue) {
  4549. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4550. ASSERT_FALSE(res);
  4551. EXPECT_EQ(Error::Read, res.error());
  4552. }
  4553. TEST_F(ServerTest, TooLongHeader) {
  4554. Request req;
  4555. req.method = "GET";
  4556. req.path = "/hi";
  4557. std::string host_and_port;
  4558. host_and_port += HOST;
  4559. host_and_port += ":";
  4560. host_and_port += std::to_string(PORT);
  4561. req.headers.emplace("Host", host_and_port.c_str());
  4562. req.headers.emplace("Accept", "*/*");
  4563. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4564. req.headers.emplace(
  4565. "Header-Name",
  4566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4594. "@@@@@@@@@@@@@@@@@");
  4595. auto res = std::make_shared<Response>();
  4596. auto error = Error::Success;
  4597. auto ret = cli_.send(req, *res, error);
  4598. ASSERT_TRUE(ret);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. }
  4601. TEST_F(ServerTest, HeaderCountAtLimit) {
  4602. // Test with headers just under the 100 limit
  4603. httplib::Headers headers;
  4604. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4605. // This should keep us just under the 100 header limit
  4606. for (int i = 0; i < 95; i++) {
  4607. std::string name = "X-Test-Header-" + std::to_string(i);
  4608. std::string value = "value" + std::to_string(i);
  4609. headers.emplace(name, value);
  4610. }
  4611. // This should work fine as we're under the limit
  4612. auto res = cli_.Get("/hi", headers);
  4613. EXPECT_TRUE(res);
  4614. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4615. }
  4616. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4617. // Test with many headers to exceed the 100 limit
  4618. httplib::Headers headers;
  4619. // Add 150 headers to definitely exceed the 100 limit
  4620. for (int i = 0; i < 150; i++) {
  4621. std::string name = "X-Test-Header-" + std::to_string(i);
  4622. std::string value = "value" + std::to_string(i);
  4623. headers.emplace(name, value);
  4624. }
  4625. // This should fail due to exceeding header count limit
  4626. cli_.set_keep_alive(true);
  4627. auto res = cli_.Get("/hi", headers);
  4628. // The server should respond with 400 Bad Request
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4631. EXPECT_EQ("close", res->get_header_value("Connection"));
  4632. EXPECT_FALSE(cli_.is_socket_open());
  4633. }
  4634. TEST_F(ServerTest, PercentEncoding) {
  4635. auto res = cli_.Get("/e%6edwith%");
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. TEST_F(ServerTest, PercentEncodingUnicode) {
  4640. auto res = cli_.Get("/e%u006edwith%");
  4641. ASSERT_TRUE(res);
  4642. EXPECT_EQ(StatusCode::OK_200, res->status);
  4643. }
  4644. TEST_F(ServerTest, InvalidPercentEncoding) {
  4645. auto res = cli_.Get("/%endwith%");
  4646. ASSERT_TRUE(res);
  4647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4648. }
  4649. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4650. auto res = cli_.Get("/%uendwith%");
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4653. }
  4654. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4655. auto res = cli_.Get("/hello?aaa=bbb%");
  4656. ASSERT_TRUE(res);
  4657. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4658. }
  4659. TEST_F(ServerTest, PlusSignEncoding) {
  4660. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4661. ASSERT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::OK_200, res->status);
  4663. EXPECT_EQ("a +b", res->body);
  4664. }
  4665. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4666. // This test simulates a potential DoS attack using many headers
  4667. // to verify our security fix prevents memory exhaustion
  4668. httplib::Headers attack_headers;
  4669. // Attempt to add many headers like an attacker would (200 headers to far
  4670. // exceed limit)
  4671. for (int i = 0; i < 200; i++) {
  4672. std::string name = "X-Attack-Header-" + std::to_string(i);
  4673. std::string value = "attack_payload_" + std::to_string(i);
  4674. attack_headers.emplace(name, value);
  4675. }
  4676. // Try to POST with excessive headers
  4677. cli_.set_keep_alive(true);
  4678. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4679. // Should either fail or return 400 Bad Request due to security limit
  4680. if (res) {
  4681. // If we get a response, it should be 400 Bad Request
  4682. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4683. EXPECT_EQ("close", res->get_header_value("Connection"));
  4684. }
  4685. EXPECT_FALSE(cli_.is_socket_open());
  4686. }
  4687. TEST_F(ServerTest, MultipartFormData) {
  4688. UploadFormDataItems items = {
  4689. {"text1", "text default", "", ""},
  4690. {"text2", "aωb", "", ""},
  4691. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4692. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4693. {"file3", "", "", "application/octet-stream"},
  4694. {"file4", "", "", " application/json tmp-string "}};
  4695. auto res = cli_.Post("/multipart", items);
  4696. ASSERT_TRUE(res);
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. }
  4699. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4700. UploadFormDataItems items = {
  4701. {"text", "default text", "", ""},
  4702. {"multi_text1", "aaaaa", "", ""},
  4703. {"multi_text1", "bbbbb", "", ""},
  4704. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4705. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4706. "application/json"},
  4707. };
  4708. auto res = cli_.Post("/multipart/multi_file_values", items);
  4709. ASSERT_TRUE(res);
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. }
  4712. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4713. auto res = cli_.Get("/hi");
  4714. ASSERT_TRUE(res);
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4717. EXPECT_EQ("Hello World!", res->body);
  4718. }
  4719. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4720. Request req;
  4721. req.method = "POST";
  4722. req.path = "/chunked";
  4723. std::string host_and_port;
  4724. host_and_port += HOST;
  4725. host_and_port += ":";
  4726. host_and_port += std::to_string(PORT);
  4727. req.headers.emplace("Host", host_and_port.c_str());
  4728. req.headers.emplace("Accept", "*/*");
  4729. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4730. req.headers.emplace("Content-Type", "text/plain");
  4731. req.headers.emplace("Content-Length", "0");
  4732. req.headers.emplace(
  4733. "Transfer-Encoding",
  4734. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4735. // Client does not chunk, so make a chunked body manually.
  4736. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4737. auto res = std::make_shared<Response>();
  4738. auto error = Error::Success;
  4739. auto ret = cli_.send(req, *res, error);
  4740. ASSERT_TRUE(ret);
  4741. EXPECT_EQ(StatusCode::OK_200, res->status);
  4742. }
  4743. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4744. // rather than treat them as valid lengths.
  4745. template <typename ClientT>
  4746. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4747. Request req;
  4748. req.method = "POST";
  4749. req.path = "/chunked";
  4750. std::string host_and_port;
  4751. host_and_port += HOST;
  4752. host_and_port += ":";
  4753. host_and_port += std::to_string(PORT);
  4754. req.headers.emplace("Host", host_and_port.c_str());
  4755. req.headers.emplace("Content-Length", "0");
  4756. req.headers.emplace("Transfer-Encoding", "chunked");
  4757. req.body = body;
  4758. auto res = std::make_shared<Response>();
  4759. auto error = Error::Success;
  4760. ASSERT_TRUE(cli.send(req, *res, error));
  4761. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4762. }
  4763. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4764. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4765. }
  4766. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4767. expect_chunked_body_rejected(
  4768. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4769. }
  4770. TEST_F(ServerTest, GetStreamed2) {
  4771. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4772. ASSERT_TRUE(res);
  4773. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4774. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4775. EXPECT_EQ(true, res->has_header("Content-Range"));
  4776. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4777. EXPECT_EQ(std::string("ab"), res->body);
  4778. }
  4779. TEST_F(ServerTest, GetStreamed) {
  4780. auto res = cli_.Get("/streamed");
  4781. ASSERT_TRUE(res);
  4782. EXPECT_EQ(StatusCode::OK_200, res->status);
  4783. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4784. EXPECT_EQ(std::string("aaabbb"), res->body);
  4785. }
  4786. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4787. auto res = cli_.Get("/streamed-without-length",
  4788. Headers{make_range_header({{0, -1}})});
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ(false, res->has_header("Content-Length"));
  4792. EXPECT_EQ(false, res->has_header("Content-Range"));
  4793. EXPECT_EQ(std::string("abcdefg"), res->body);
  4794. }
  4795. TEST_F(ServerTest, GetStreamedWithRange1) {
  4796. auto res =
  4797. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4798. ASSERT_TRUE(res);
  4799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4800. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4801. EXPECT_EQ(true, res->has_header("Content-Range"));
  4802. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4803. EXPECT_EQ(std::string("def"), res->body);
  4804. }
  4805. TEST_F(ServerTest, GetStreamedWithRange2) {
  4806. auto res =
  4807. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4810. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4811. EXPECT_EQ(true, res->has_header("Content-Range"));
  4812. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4813. EXPECT_EQ(std::string("bcdefg"), res->body);
  4814. }
  4815. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4816. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4817. ASSERT_TRUE(res);
  4818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4819. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4820. EXPECT_EQ(true, res->has_header("Content-Range"));
  4821. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4822. EXPECT_EQ(std::string("efg"), res->body);
  4823. }
  4824. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4825. auto res =
  4826. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4827. ASSERT_TRUE(res);
  4828. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4829. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4830. EXPECT_EQ(false, res->has_header("Content-Range"));
  4831. EXPECT_EQ(0U, res->body.size());
  4832. }
  4833. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4834. auto res =
  4835. cli_.Get("/streamed-with-range",
  4836. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4837. "92233720368547758079223372036854775807"}});
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4840. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4841. EXPECT_EQ(false, res->has_header("Content-Range"));
  4842. EXPECT_EQ(0U, res->body.size());
  4843. }
  4844. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4845. auto res = cli_.Get(
  4846. "/with-range",
  4847. Headers{{"Range",
  4848. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4849. {"Accept-Encoding", ""}});
  4850. ASSERT_TRUE(res);
  4851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4852. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4853. EXPECT_EQ(true, res->has_header("Content-Range"));
  4854. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4855. EXPECT_EQ(std::string("abcdefg"), res->body);
  4856. }
  4857. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4858. auto res = cli_.Get("/with-range", Headers{
  4859. {"Range", "bytes=0-"},
  4860. {"Accept-Encoding", ""},
  4861. });
  4862. ASSERT_TRUE(res);
  4863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4864. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4865. EXPECT_EQ(true, res->has_header("Content-Range"));
  4866. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4867. EXPECT_EQ(std::string("abcdefg"), res->body);
  4868. }
  4869. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4870. auto res = cli_.Get("/streamed-with-range",
  4871. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4872. ASSERT_TRUE(res);
  4873. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4874. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4875. EXPECT_EQ(false, res->has_header("Content-Range"));
  4876. EXPECT_EQ(267U, res->body.size());
  4877. // Check that both range contents are present
  4878. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4879. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4880. // Check that Content-Range headers are present for both ranges
  4881. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4882. std::string::npos);
  4883. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4884. std::string::npos);
  4885. }
  4886. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4887. Ranges ranges;
  4888. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4889. ranges.emplace_back(0, -1);
  4890. }
  4891. auto res = cli_.Get("/streamed-with-range?error",
  4892. Headers{{make_range_header(ranges)}});
  4893. ASSERT_TRUE(res);
  4894. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4895. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4896. EXPECT_EQ(false, res->has_header("Content-Range"));
  4897. EXPECT_EQ(0U, res->body.size());
  4898. }
  4899. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4900. auto res = cli_.Get("/streamed-with-range",
  4901. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4902. ASSERT_TRUE(res);
  4903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4904. EXPECT_EQ(5U, res->body.size());
  4905. // Check that overlapping ranges are coalesced into a single range
  4906. EXPECT_EQ("bcdef", res->body);
  4907. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4908. // Should be single range, not multipart
  4909. EXPECT_TRUE(res->has_header("Content-Range"));
  4910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4911. }
  4912. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4913. auto res = cli_.Get("/streamed-with-range",
  4914. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4915. ASSERT_TRUE(res);
  4916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4917. EXPECT_EQ(268U, res->body.size());
  4918. // Check that both range contents are present
  4919. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4920. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4921. // Check that Content-Range headers are present for both ranges
  4922. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4923. std::string::npos);
  4924. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4925. std::string::npos);
  4926. }
  4927. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4928. auto res = cli_.Get("/streamed-with-range",
  4929. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4930. ASSERT_TRUE(res);
  4931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4932. EXPECT_EQ(269U, res->body.size());
  4933. // Check that both duplicate range contents are present
  4934. size_t first_abc = res->body.find("abc\r\n");
  4935. EXPECT_TRUE(first_abc != std::string::npos);
  4936. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4937. EXPECT_TRUE(second_abc != std::string::npos);
  4938. // Check that Content-Range headers are present for both ranges
  4939. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4940. EXPECT_TRUE(first_range != std::string::npos);
  4941. size_t second_range =
  4942. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4943. EXPECT_TRUE(second_range != std::string::npos);
  4944. }
  4945. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4946. auto res =
  4947. cli_.Get("/streamed-with-range?error",
  4948. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4949. ASSERT_TRUE(res);
  4950. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4951. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4952. EXPECT_EQ(false, res->has_header("Content-Range"));
  4953. EXPECT_EQ(0U, res->body.size());
  4954. }
  4955. TEST_F(ServerTest, GetStreamedEndless) {
  4956. uint64_t offset = 0;
  4957. auto res = cli_.Get("/streamed-cancel",
  4958. [&](const char * /*data*/, uint64_t data_length) {
  4959. if (offset < 100) {
  4960. offset += data_length;
  4961. return true;
  4962. }
  4963. return false;
  4964. });
  4965. ASSERT_TRUE(!res);
  4966. EXPECT_EQ(Error::Canceled, res.error());
  4967. }
  4968. TEST_F(ServerTest, ClientStop) {
  4969. std::atomic_size_t count{4};
  4970. std::vector<std::thread> threads;
  4971. for (auto i = count.load(); i != 0; --i) {
  4972. threads.emplace_back([&]() {
  4973. auto res = cli_.Get("/streamed-cancel",
  4974. [&](const char *, uint64_t) { return true; });
  4975. --count;
  4976. ASSERT_TRUE(!res);
  4977. EXPECT_TRUE(res.error() == Error::Canceled ||
  4978. res.error() == Error::Read || res.error() == Error::Write);
  4979. });
  4980. }
  4981. std::this_thread::sleep_for(std::chrono::seconds(2));
  4982. while (count != 0) {
  4983. cli_.stop();
  4984. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4985. }
  4986. for (auto &t : threads) {
  4987. t.join();
  4988. }
  4989. }
  4990. TEST_F(ServerTest, GetWithRange1) {
  4991. auto res = cli_.Get("/with-range", Headers{
  4992. make_range_header({{3, 5}}),
  4993. {"Accept-Encoding", ""},
  4994. });
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4997. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4998. EXPECT_EQ(true, res->has_header("Content-Range"));
  4999. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5000. EXPECT_EQ(std::string("def"), res->body);
  5001. }
  5002. TEST_F(ServerTest, GetWithRange2) {
  5003. auto res = cli_.Get("/with-range", Headers{
  5004. make_range_header({{1, -1}}),
  5005. {"Accept-Encoding", ""},
  5006. });
  5007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5009. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5010. EXPECT_EQ(true, res->has_header("Content-Range"));
  5011. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5012. EXPECT_EQ(std::string("bcdefg"), res->body);
  5013. }
  5014. TEST_F(ServerTest, GetWithRange3) {
  5015. auto res = cli_.Get("/with-range", Headers{
  5016. make_range_header({{0, 0}}),
  5017. {"Accept-Encoding", ""},
  5018. });
  5019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5020. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5021. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5022. EXPECT_EQ(true, res->has_header("Content-Range"));
  5023. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5024. EXPECT_EQ(std::string("a"), res->body);
  5025. }
  5026. TEST_F(ServerTest, GetWithRange4) {
  5027. auto res = cli_.Get("/with-range", Headers{
  5028. make_range_header({{-1, 2}}),
  5029. {"Accept-Encoding", ""},
  5030. });
  5031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5033. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5034. EXPECT_EQ(true, res->has_header("Content-Range"));
  5035. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5036. EXPECT_EQ(std::string("fg"), res->body);
  5037. }
  5038. TEST_F(ServerTest, GetWithRange5) {
  5039. auto res = cli_.Get("/with-range", Headers{
  5040. make_range_header({{0, 5}}),
  5041. {"Accept-Encoding", ""},
  5042. });
  5043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5045. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5046. EXPECT_EQ(true, res->has_header("Content-Range"));
  5047. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5048. EXPECT_EQ(std::string("abcdef"), res->body);
  5049. }
  5050. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5051. auto res =
  5052. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5053. ASSERT_TRUE(res);
  5054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5055. }
  5056. TEST_F(ServerTest, GetWithRangeMultipart) {
  5057. auto res =
  5058. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5059. ASSERT_TRUE(res);
  5060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5061. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5062. EXPECT_EQ(false, res->has_header("Content-Range"));
  5063. EXPECT_EQ(267U, res->body.size());
  5064. }
  5065. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5066. auto res = cli_.Get("/with-range",
  5067. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5068. ASSERT_TRUE(res);
  5069. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5070. }
  5071. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5072. auto res = cli_.Get("/with-range-customized-response",
  5073. Headers{{make_range_header({{1, 2}})}});
  5074. ASSERT_TRUE(res);
  5075. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5076. EXPECT_EQ(true, res->has_header("Content-Length"));
  5077. EXPECT_EQ(false, res->has_header("Content-Range"));
  5078. EXPECT_EQ(JSON_DATA, res->body);
  5079. }
  5080. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5081. auto res = cli_.Get("/with-range-customized-response",
  5082. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5083. ASSERT_TRUE(res);
  5084. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5085. EXPECT_EQ(true, res->has_header("Content-Length"));
  5086. EXPECT_EQ(false, res->has_header("Content-Range"));
  5087. EXPECT_EQ(JSON_DATA, res->body);
  5088. }
  5089. TEST_F(ServerTest, Issue1772) {
  5090. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5091. ASSERT_TRUE(res);
  5092. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5093. }
  5094. TEST_F(ServerTest, Issue609) {
  5095. auto res = cli_.Delete("/issue609");
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ(std::string("ok"), res->body);
  5099. }
  5100. TEST_F(ServerTest, GetStreamedChunked) {
  5101. auto res = cli_.Get("/streamed-chunked");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ(std::string("123456789"), res->body);
  5105. }
  5106. TEST_F(ServerTest, GetStreamedChunked2) {
  5107. auto res = cli_.Get("/streamed-chunked2");
  5108. ASSERT_TRUE(res);
  5109. EXPECT_EQ(StatusCode::OK_200, res->status);
  5110. EXPECT_EQ(std::string("123456789"), res->body);
  5111. }
  5112. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5113. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5114. ASSERT_TRUE(res);
  5115. EXPECT_EQ(StatusCode::OK_200, res->status);
  5116. EXPECT_EQ(std::string("123456789"), res->body);
  5117. EXPECT_TRUE(res->has_header("Trailer"));
  5118. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5119. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5120. // Trailers are now stored separately from headers (security fix)
  5121. EXPECT_EQ(2U, res->trailers.size());
  5122. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5123. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5124. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5125. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5126. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5127. // Verify trailers are NOT in headers (security verification)
  5128. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5129. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5130. }
  5131. TEST_F(ServerTest, LargeChunkedPost) {
  5132. Request req;
  5133. req.method = "POST";
  5134. req.path = "/large-chunked";
  5135. std::string host_and_port;
  5136. host_and_port += HOST;
  5137. host_and_port += ":";
  5138. host_and_port += std::to_string(PORT);
  5139. req.headers.emplace("Host", host_and_port.c_str());
  5140. req.headers.emplace("Accept", "*/*");
  5141. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5142. req.headers.emplace("Content-Type", "text/plain");
  5143. req.headers.emplace("Content-Length", "0");
  5144. req.headers.emplace("Transfer-Encoding", "chunked");
  5145. std::string long_string(30 * 1024u, 'a');
  5146. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5147. // Attempt to make a large enough post to exceed OS buffers, to test that
  5148. // the server handles short reads if the full chunk data isn't available.
  5149. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5150. auto res = std::make_shared<Response>();
  5151. auto error = Error::Success;
  5152. auto ret = cli_.send(req, *res, error);
  5153. ASSERT_TRUE(ret);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. }
  5156. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5157. auto res = cli_.Get("/remote_addr");
  5158. ASSERT_TRUE(res);
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5161. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5162. }
  5163. TEST_F(ServerTest, GetMethodLocalAddr) {
  5164. auto res = cli_.Get("/local_addr");
  5165. ASSERT_TRUE(res);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5168. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5169. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5170. }
  5171. TEST_F(ServerTest, HTTPResponseSplitting) {
  5172. auto res = cli_.Get("/http_response_splitting");
  5173. ASSERT_TRUE(res);
  5174. EXPECT_EQ(StatusCode::OK_200, res->status);
  5175. }
  5176. TEST_F(ServerTest, SlowRequest) {
  5177. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5178. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5179. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5180. }
  5181. #if 0
  5182. TEST_F(ServerTest, SlowPost) {
  5183. char buffer[64 * 1024];
  5184. memset(buffer, 0x42, sizeof(buffer));
  5185. auto res = cli_.Post(
  5186. "/slowpost", 64 * 1024 * 1024,
  5187. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5188. auto ret = sink.write(buffer, sizeof(buffer));
  5189. EXPECT_TRUE(ret);
  5190. return true;
  5191. },
  5192. "text/plain");
  5193. ASSERT_TRUE(res);
  5194. EXPECT_EQ(StatusCode::OK_200, res->status);
  5195. }
  5196. TEST_F(ServerTest, SlowPostFail) {
  5197. char buffer[64 * 1024];
  5198. memset(buffer, 0x42, sizeof(buffer));
  5199. cli_.set_write_timeout(std::chrono::seconds(0));
  5200. auto res = cli_.Post(
  5201. "/slowpost", 64 * 1024 * 1024,
  5202. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5203. sink.write(buffer, sizeof(buffer));
  5204. return true;
  5205. },
  5206. "text/plain");
  5207. ASSERT_TRUE(!res);
  5208. EXPECT_EQ(Error::Write, res.error());
  5209. }
  5210. #endif
  5211. TEST_F(ServerTest, Put) {
  5212. auto res = cli_.Put("/put", "PUT", "text/plain");
  5213. ASSERT_TRUE(res);
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. EXPECT_EQ("PUT", res->body);
  5216. }
  5217. TEST_F(ServerTest, PutWithContentProvider) {
  5218. auto res = cli_.Put(
  5219. "/put", 3,
  5220. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5221. sink.os << "PUT";
  5222. return true;
  5223. },
  5224. "text/plain");
  5225. ASSERT_TRUE(res);
  5226. EXPECT_EQ(StatusCode::OK_200, res->status);
  5227. EXPECT_EQ("PUT", res->body);
  5228. }
  5229. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5230. auto res = cli_.Post(
  5231. "/post", 42,
  5232. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5233. return false;
  5234. },
  5235. "text/plain");
  5236. ASSERT_TRUE(!res);
  5237. EXPECT_EQ(Error::Canceled, res.error());
  5238. }
  5239. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5240. auto res = cli_.Put(
  5241. "/put",
  5242. [](size_t /*offset*/, DataSink &sink) {
  5243. sink.os << "PUT";
  5244. sink.done();
  5245. return true;
  5246. },
  5247. "text/plain");
  5248. ASSERT_TRUE(res);
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. EXPECT_EQ("PUT", res->body);
  5251. }
  5252. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5253. auto res = cli_.Post(
  5254. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5255. "text/plain");
  5256. ASSERT_TRUE(!res);
  5257. EXPECT_EQ(Error::Canceled, res.error());
  5258. }
  5259. TEST_F(ServerTest, PostLoopBack) {
  5260. std::string body;
  5261. auto res = cli_.Post(
  5262. "/post-loopback", 9,
  5263. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5264. EXPECT_EQ(9u, length);
  5265. sink.write("123", 3);
  5266. sink.write("456", 3);
  5267. sink.write("789", 3);
  5268. return true;
  5269. },
  5270. "text/plain",
  5271. [&body](const char *data, size_t data_length) {
  5272. body.append(data, data_length);
  5273. return true;
  5274. });
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("123456789", body);
  5278. }
  5279. TEST_F(ServerTest, PutLoopBack) {
  5280. std::string body;
  5281. auto res = cli_.Put(
  5282. "/put-loopback", 9,
  5283. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5284. EXPECT_EQ(9u, length);
  5285. sink.write("123", 3);
  5286. sink.write("456", 3);
  5287. sink.write("789", 3);
  5288. return true;
  5289. },
  5290. "text/plain",
  5291. [&body](const char *data, size_t data_length) {
  5292. body.append(data, data_length);
  5293. return true;
  5294. });
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("123456789", body);
  5298. }
  5299. TEST_F(ServerTest, PatchLoopBack) {
  5300. std::string body;
  5301. auto res = cli_.Patch(
  5302. "/patch-loopback", 9,
  5303. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5304. EXPECT_EQ(9u, length);
  5305. sink.write("123", 3);
  5306. sink.write("456", 3);
  5307. sink.write("789", 3);
  5308. return true;
  5309. },
  5310. "text/plain",
  5311. [&body](const char *data, size_t data_length) {
  5312. body.append(data, data_length);
  5313. return true;
  5314. });
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. EXPECT_EQ("123456789", body);
  5318. }
  5319. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5320. std::string body;
  5321. auto res = cli_.Post(
  5322. "/post-loopback",
  5323. [](size_t /*offset*/, DataSink &sink) {
  5324. sink.write("123", 3);
  5325. sink.write("456", 3);
  5326. sink.write("789", 3);
  5327. sink.done();
  5328. return true;
  5329. },
  5330. "text/plain",
  5331. [&body](const char *data, size_t data_length) {
  5332. body.append(data, data_length);
  5333. return true;
  5334. });
  5335. ASSERT_TRUE(res);
  5336. EXPECT_EQ(StatusCode::OK_200, res->status);
  5337. EXPECT_EQ("123456789", body);
  5338. }
  5339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5340. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5341. cli_.set_compress(true);
  5342. auto res = cli_.Put(
  5343. "/put", 3,
  5344. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5345. sink.os << "PUT";
  5346. return true;
  5347. },
  5348. "text/plain");
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. EXPECT_EQ("PUT", res->body);
  5352. }
  5353. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5354. cli_.set_compress(true);
  5355. auto res = cli_.Post(
  5356. "/post", 42,
  5357. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5358. return false;
  5359. },
  5360. "text/plain");
  5361. ASSERT_TRUE(!res);
  5362. EXPECT_EQ(Error::Canceled, res.error());
  5363. }
  5364. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5365. cli_.set_compress(true);
  5366. auto res = cli_.Put(
  5367. "/put",
  5368. [](size_t /*offset*/, DataSink &sink) {
  5369. sink.os << "PUT";
  5370. sink.done();
  5371. return true;
  5372. },
  5373. "text/plain");
  5374. ASSERT_TRUE(res);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. EXPECT_EQ("PUT", res->body);
  5377. }
  5378. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5379. cli_.set_compress(true);
  5380. auto res = cli_.Post(
  5381. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5382. "text/plain");
  5383. ASSERT_TRUE(!res);
  5384. EXPECT_EQ(Error::Canceled, res.error());
  5385. }
  5386. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5387. cli_.set_compress(true);
  5388. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5389. ASSERT_TRUE(res);
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ(LARGE_DATA, res->body);
  5392. }
  5393. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5394. #ifdef CPPHTTPLIB_SSL_ENABLED
  5395. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5396. Client cli(s.c_str());
  5397. cli.enable_server_certificate_verification(false);
  5398. #else
  5399. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5400. Client cli(s.c_str());
  5401. #endif
  5402. cli.set_compress(true);
  5403. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5404. ASSERT_TRUE(res);
  5405. EXPECT_EQ(StatusCode::OK_200, res->status);
  5406. EXPECT_EQ(LARGE_DATA, res->body);
  5407. // The compressed size should be less than a 10th of the original. May vary
  5408. // depending on the zlib library.
  5409. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5410. static_cast<uint64_t>(10 * 1024 * 1024));
  5411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5412. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5413. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5414. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5415. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5416. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5417. #endif
  5418. }
  5419. TEST_F(ServerTest, PutContentWithDeflate) {
  5420. cli_.set_compress(false);
  5421. Headers headers;
  5422. headers.emplace("Content-Encoding", "deflate");
  5423. // PUT in deflate format:
  5424. auto res = cli_.Put("/put", headers,
  5425. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5426. ASSERT_TRUE(res);
  5427. EXPECT_EQ(StatusCode::OK_200, res->status);
  5428. EXPECT_EQ("PUT", res->body);
  5429. }
  5430. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "gzip, deflate");
  5433. auto res = cli_.Get("/streamed-chunked", headers);
  5434. ASSERT_TRUE(res);
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ(std::string("123456789"), res->body);
  5437. }
  5438. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5439. Headers headers;
  5440. headers.emplace("Accept-Encoding", "gzip, deflate");
  5441. auto res = cli_.Get("/streamed-chunked2", headers);
  5442. ASSERT_TRUE(res);
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. EXPECT_EQ(std::string("123456789"), res->body);
  5445. }
  5446. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5447. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5448. ASSERT_TRUE(res);
  5449. EXPECT_EQ(StatusCode::OK_200, res->status);
  5450. }
  5451. TEST(GzipDecompressor, ChunkedDecompression) {
  5452. std::string data;
  5453. for (size_t i = 0; i < 32 * 1024; ++i) {
  5454. data.push_back(static_cast<char>('a' + i % 26));
  5455. }
  5456. std::string compressed_data;
  5457. {
  5458. httplib::detail::gzip_compressor compressor;
  5459. bool result = compressor.compress(
  5460. data.data(), data.size(),
  5461. /*last=*/true,
  5462. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5463. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5464. compressed_data_size);
  5465. return true;
  5466. });
  5467. ASSERT_TRUE(result);
  5468. }
  5469. std::string decompressed_data;
  5470. {
  5471. httplib::detail::gzip_decompressor decompressor;
  5472. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5473. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5474. size_t chunk_size = 130;
  5475. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5476. chunk_begin += chunk_size) {
  5477. size_t current_chunk_size =
  5478. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5479. bool result = decompressor.decompress(
  5480. compressed_data.data() + chunk_begin, current_chunk_size,
  5481. [&](const char *decompressed_data_chunk,
  5482. size_t decompressed_data_chunk_size) {
  5483. decompressed_data.insert(decompressed_data.size(),
  5484. decompressed_data_chunk,
  5485. decompressed_data_chunk_size);
  5486. return true;
  5487. });
  5488. ASSERT_TRUE(result);
  5489. }
  5490. }
  5491. ASSERT_EQ(data, decompressed_data);
  5492. }
  5493. TEST(GzipDecompressor, DeflateDecompression) {
  5494. std::string original_text = "Raw deflate without gzip";
  5495. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5496. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5497. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5498. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5499. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5500. std::string decompressed_data;
  5501. {
  5502. httplib::detail::gzip_decompressor decompressor;
  5503. bool result = decompressor.decompress(
  5504. compressed_data.data(), compressed_data.size(),
  5505. [&](const char *decompressed_data_chunk,
  5506. size_t decompressed_data_chunk_size) {
  5507. decompressed_data.insert(decompressed_data.size(),
  5508. decompressed_data_chunk,
  5509. decompressed_data_chunk_size);
  5510. return true;
  5511. });
  5512. ASSERT_TRUE(result);
  5513. }
  5514. ASSERT_EQ(original_text, decompressed_data);
  5515. }
  5516. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5517. std::string original_text = "Raw deflate without gzip";
  5518. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5519. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5520. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5521. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5522. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5523. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5524. std::string decompressed_data;
  5525. {
  5526. httplib::detail::gzip_decompressor decompressor;
  5527. bool result = decompressor.decompress(
  5528. compressed_data.data(), compressed_data.size(),
  5529. [&](const char *decompressed_data_chunk,
  5530. size_t decompressed_data_chunk_size) {
  5531. decompressed_data.insert(decompressed_data.size(),
  5532. decompressed_data_chunk,
  5533. decompressed_data_chunk_size);
  5534. return true;
  5535. });
  5536. ASSERT_TRUE(result);
  5537. }
  5538. ASSERT_EQ(original_text, decompressed_data);
  5539. }
  5540. #endif
  5541. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5542. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5543. Headers headers;
  5544. headers.emplace("Accept-Encoding", "br");
  5545. auto res = cli_.Get("/streamed-chunked", headers);
  5546. ASSERT_TRUE(res);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ(std::string("123456789"), res->body);
  5549. }
  5550. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5551. Headers headers;
  5552. headers.emplace("Accept-Encoding", "br");
  5553. auto res = cli_.Get("/streamed-chunked2", headers);
  5554. ASSERT_TRUE(res);
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. EXPECT_EQ(std::string("123456789"), res->body);
  5557. }
  5558. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5559. cli_.set_compress(true);
  5560. auto res = cli_.Put(
  5561. "/put", 3,
  5562. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5563. sink.os << "PUT";
  5564. return true;
  5565. },
  5566. "text/plain");
  5567. ASSERT_TRUE(res);
  5568. EXPECT_EQ(StatusCode::OK_200, res->status);
  5569. EXPECT_EQ("PUT", res->body);
  5570. }
  5571. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5572. cli_.set_compress(true);
  5573. auto res = cli_.Put(
  5574. "/put",
  5575. [](size_t /*offset*/, DataSink &sink) {
  5576. sink.os << "PUT";
  5577. sink.done();
  5578. return true;
  5579. },
  5580. "text/plain");
  5581. ASSERT_TRUE(res);
  5582. EXPECT_EQ(StatusCode::OK_200, res->status);
  5583. EXPECT_EQ("PUT", res->body);
  5584. }
  5585. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5586. cli_.set_compress(true);
  5587. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5588. ASSERT_TRUE(res);
  5589. EXPECT_EQ(StatusCode::OK_200, res->status);
  5590. EXPECT_EQ(LARGE_DATA, res->body);
  5591. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5592. }
  5593. #endif
  5594. TEST_F(ServerTest, Patch) {
  5595. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5596. ASSERT_TRUE(res);
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. EXPECT_EQ("PATCH", res->body);
  5599. }
  5600. TEST_F(ServerTest, Delete) {
  5601. auto res = cli_.Delete("/delete");
  5602. ASSERT_TRUE(res);
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. EXPECT_EQ("DELETE", res->body);
  5605. }
  5606. TEST_F(ServerTest, DeleteContentReceiver) {
  5607. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5608. ASSERT_TRUE(res);
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. EXPECT_EQ("content", res->body);
  5611. }
  5612. TEST_F(ServerTest, Options) {
  5613. auto res = cli_.Options("*");
  5614. ASSERT_TRUE(res);
  5615. EXPECT_EQ(StatusCode::OK_200, res->status);
  5616. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5617. EXPECT_TRUE(res->body.empty());
  5618. }
  5619. TEST_F(ServerTest, URL) {
  5620. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5621. ASSERT_TRUE(res);
  5622. EXPECT_EQ(StatusCode::OK_200, res->status);
  5623. }
  5624. TEST_F(ServerTest, ArrayParam) {
  5625. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5626. ASSERT_TRUE(res);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. TEST_F(ServerTest, ArrayParamValues) {
  5630. auto res =
  5631. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5632. ASSERT_TRUE(res);
  5633. EXPECT_EQ(StatusCode::OK_200, res->status);
  5634. }
  5635. TEST_F(ServerTest, NoMultipleHeaders) {
  5636. Headers headers = {{"Content-Length", "5"}};
  5637. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5638. "text/plain");
  5639. ASSERT_TRUE(res);
  5640. EXPECT_EQ(StatusCode::OK_200, res->status);
  5641. }
  5642. TEST_F(ServerTest, PostContentReceiver) {
  5643. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5644. ASSERT_TRUE(res);
  5645. ASSERT_EQ(StatusCode::OK_200, res->status);
  5646. ASSERT_EQ("content", res->body);
  5647. }
  5648. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5649. UploadFormDataItems items = {
  5650. {"text1", "text default", "", ""},
  5651. {"text2", "aωb", "", ""},
  5652. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5653. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5654. {"file3", "", "", "application/octet-stream"},
  5655. };
  5656. auto res = cli_.Post("/content_receiver", items);
  5657. ASSERT_TRUE(res);
  5658. EXPECT_EQ(StatusCode::OK_200, res->status);
  5659. }
  5660. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5661. UploadFormDataItems items = {
  5662. {"text1", "text default", "", ""},
  5663. {"text2", "aωb", "", ""},
  5664. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5665. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5666. {"file3", "", "", "application/octet-stream"},
  5667. };
  5668. auto boundary = std::string("+++++");
  5669. std::string body;
  5670. for (const auto &item : items) {
  5671. body += "--" + boundary + "\r\n";
  5672. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5673. if (!item.filename.empty()) {
  5674. body += "; filename=\"" + item.filename + "\"";
  5675. }
  5676. body += "\r\n";
  5677. if (!item.content_type.empty()) {
  5678. body += "Content-Type: " + item.content_type + "\r\n";
  5679. }
  5680. body += "\r\n";
  5681. body += item.content + "\r\n";
  5682. }
  5683. body += "--" + boundary + "--\r\n";
  5684. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5685. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5686. ASSERT_TRUE(res);
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. }
  5689. TEST(MultipartFormDataTest, FieldEscaping) {
  5690. Server svr;
  5691. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5692. const ContentReader &content_reader) {
  5693. ASSERT_TRUE(req.is_multipart_form_data());
  5694. std::vector<FormData> received;
  5695. content_reader(
  5696. [&](const FormData &file) {
  5697. received.push_back(file);
  5698. return true;
  5699. },
  5700. [&](const char *data, size_t data_length) {
  5701. received.back().content.append(data, data_length);
  5702. return true;
  5703. });
  5704. // '"', CR and LF in names and filenames are escaped following the
  5705. // WHATWG HTML standard, so each part still parses as a single part
  5706. // with no injected headers. Content types get CR/LF escaped too,
  5707. // while '"' (legal there, e.g. quoted charset) is preserved.
  5708. ASSERT_EQ(4U, received.size());
  5709. EXPECT_EQ("na%22me", received[0].name);
  5710. EXPECT_EQ("quoted name", received[0].content);
  5711. EXPECT_EQ("file", received[1].name);
  5712. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5713. received[1].filename);
  5714. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5715. EXPECT_EQ("injected", received[1].content);
  5716. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5717. EXPECT_EQ("my%22file.txt", received[2].filename);
  5718. EXPECT_EQ("cr lf name", received[2].content);
  5719. EXPECT_EQ("typed", received[3].name);
  5720. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5721. received[3].content_type);
  5722. EXPECT_EQ("typed content", received[3].content);
  5723. });
  5724. auto port = svr.bind_to_any_port("localhost");
  5725. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5726. auto se = detail::scope_exit([&] {
  5727. svr.stop();
  5728. t.join();
  5729. ASSERT_FALSE(svr.is_running());
  5730. });
  5731. svr.wait_until_ready();
  5732. Client cli("localhost", port);
  5733. UploadFormDataItems items = {
  5734. {"na\"me", "quoted name", "", ""},
  5735. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5736. "application/octet-stream"},
  5737. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5738. {"typed", "typed content", "",
  5739. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5740. };
  5741. auto res = cli.Post("/post", items);
  5742. ASSERT_TRUE(res);
  5743. EXPECT_EQ(StatusCode::OK_200, res->status);
  5744. }
  5745. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5746. const UploadFormDataItems items = {
  5747. {"name1", "Content 1", "", ""},
  5748. {"name2", "Content 2", "file2.txt", "text/plain"},
  5749. };
  5750. Server svr;
  5751. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5752. const ContentReader &content_reader) {
  5753. ASSERT_TRUE(req.is_multipart_form_data());
  5754. std::vector<FormData> received;
  5755. content_reader(
  5756. [&](const FormData &file) {
  5757. received.push_back(file);
  5758. return true;
  5759. },
  5760. [&](const char *data, size_t data_length) {
  5761. received.back().content.append(data, data_length);
  5762. return true;
  5763. });
  5764. ASSERT_EQ(2U, received.size());
  5765. EXPECT_EQ("name1", received[0].name);
  5766. EXPECT_EQ("Content 1", received[0].content);
  5767. EXPECT_EQ("name2", received[1].name);
  5768. EXPECT_EQ("Content 2", received[1].content);
  5769. EXPECT_EQ("file2.txt", received[1].filename);
  5770. EXPECT_EQ("text/plain", received[1].content_type);
  5771. });
  5772. auto port = svr.bind_to_any_port("localhost");
  5773. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5774. auto se = detail::scope_exit([&] {
  5775. svr.stop();
  5776. t.join();
  5777. ASSERT_FALSE(svr.is_running());
  5778. });
  5779. svr.wait_until_ready();
  5780. Client cli("localhost", port);
  5781. // Whole-body serialization with a generated boundary
  5782. {
  5783. MultipartFormDataWriter writer;
  5784. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5785. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5786. writer.content_type());
  5787. auto body = writer.serialize(items);
  5788. EXPECT_EQ(body.size(), writer.content_length(items));
  5789. auto res = cli.Post("/post", body, writer.content_type());
  5790. ASSERT_TRUE(res);
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. }
  5793. // Per-part framing with a custom boundary via a content provider
  5794. {
  5795. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5796. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5797. MultipartFormDataWriter writer("custom-boundary_123");
  5798. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5799. std::string body;
  5800. for (const auto &item : items) {
  5801. body += writer.item_begin(item);
  5802. body += item.content;
  5803. body += MultipartFormDataWriter::item_end();
  5804. }
  5805. body += writer.finish();
  5806. EXPECT_EQ(body.size(), writer.content_length(items));
  5807. auto res = cli.Post(
  5808. "/post", body.size(),
  5809. [&](size_t offset, size_t length, DataSink &sink) {
  5810. sink.write(body.data() + offset, length);
  5811. return true;
  5812. },
  5813. writer.content_type());
  5814. ASSERT_TRUE(res);
  5815. EXPECT_EQ(StatusCode::OK_200, res->status);
  5816. }
  5817. }
  5818. TEST_F(ServerTest, PostContentReceiverGzip) {
  5819. cli_.set_compress(true);
  5820. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5821. ASSERT_TRUE(res);
  5822. ASSERT_EQ(StatusCode::OK_200, res->status);
  5823. ASSERT_EQ("content", res->body);
  5824. }
  5825. TEST_F(ServerTest, PutContentReceiver) {
  5826. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5827. ASSERT_TRUE(res);
  5828. ASSERT_EQ(StatusCode::OK_200, res->status);
  5829. ASSERT_EQ("content", res->body);
  5830. }
  5831. TEST_F(ServerTest, PatchContentReceiver) {
  5832. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5833. ASSERT_TRUE(res);
  5834. ASSERT_EQ(StatusCode::OK_200, res->status);
  5835. ASSERT_EQ("content", res->body);
  5836. }
  5837. template <typename ClientType>
  5838. void TestWithHeadersAndContentReceiver(
  5839. ClientType &cli,
  5840. std::function<Result(ClientType &, const std::string &, const Headers &,
  5841. const std::string &, const std::string &,
  5842. ContentReceiver, DownloadProgress)>
  5843. request_func) {
  5844. Headers headers;
  5845. headers.emplace("X-Custom-Header", "test-value");
  5846. std::string received_body;
  5847. auto res = request_func(
  5848. cli, "/content_receiver", headers, "content", "application/json",
  5849. [&](const char *data, size_t data_length) {
  5850. received_body.append(data, data_length);
  5851. return true;
  5852. },
  5853. nullptr);
  5854. ASSERT_TRUE(res);
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("content", received_body);
  5857. }
  5858. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5859. #ifdef CPPHTTPLIB_SSL_ENABLED
  5860. using ClientT = SSLClient;
  5861. #else
  5862. using ClientT = Client;
  5863. #endif
  5864. TestWithHeadersAndContentReceiver<ClientT>(
  5865. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5866. const std::string &body, const std::string &content_type,
  5867. ContentReceiver receiver, DownloadProgress progress) {
  5868. return cli.Post(path, headers, body, content_type, receiver, progress);
  5869. });
  5870. }
  5871. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5872. #ifdef CPPHTTPLIB_SSL_ENABLED
  5873. using ClientT = SSLClient;
  5874. #else
  5875. using ClientT = Client;
  5876. #endif
  5877. TestWithHeadersAndContentReceiver<ClientT>(
  5878. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5879. const std::string &body, const std::string &content_type,
  5880. ContentReceiver receiver, DownloadProgress progress) {
  5881. return cli.Put(path, headers, body, content_type, receiver, progress);
  5882. });
  5883. }
  5884. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5885. #ifdef CPPHTTPLIB_SSL_ENABLED
  5886. using ClientT = SSLClient;
  5887. #else
  5888. using ClientT = Client;
  5889. #endif
  5890. TestWithHeadersAndContentReceiver<ClientT>(
  5891. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5892. const std::string &body, const std::string &content_type,
  5893. ContentReceiver receiver, DownloadProgress progress) {
  5894. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5895. });
  5896. }
  5897. template <typename ClientType>
  5898. void TestWithHeadersAndContentReceiverWithProgress(
  5899. ClientType &cli,
  5900. std::function<Result(ClientType &, const std::string &, const Headers &,
  5901. const std::string &, const std::string &,
  5902. ContentReceiver, DownloadProgress)>
  5903. request_func) {
  5904. Headers headers;
  5905. headers.emplace("X-Test-Header", "progress-test");
  5906. std::string received_body;
  5907. auto progress_called = false;
  5908. auto res = request_func(
  5909. cli, "/content_receiver", headers, "content", "text/plain",
  5910. [&](const char *data, size_t data_length) {
  5911. received_body.append(data, data_length);
  5912. return true;
  5913. },
  5914. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5915. progress_called = true;
  5916. return true;
  5917. });
  5918. ASSERT_TRUE(res);
  5919. EXPECT_EQ(StatusCode::OK_200, res->status);
  5920. EXPECT_EQ("content", received_body);
  5921. EXPECT_TRUE(progress_called);
  5922. }
  5923. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5924. #ifdef CPPHTTPLIB_SSL_ENABLED
  5925. using ClientT = SSLClient;
  5926. #else
  5927. using ClientT = Client;
  5928. #endif
  5929. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5931. const std::string &body, const std::string &content_type,
  5932. ContentReceiver receiver, DownloadProgress progress) {
  5933. return cli.Post(path, headers, body, content_type, receiver, progress);
  5934. });
  5935. }
  5936. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5937. #ifdef CPPHTTPLIB_SSL_ENABLED
  5938. using ClientT = SSLClient;
  5939. #else
  5940. using ClientT = Client;
  5941. #endif
  5942. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5944. const std::string &body, const std::string &content_type,
  5945. ContentReceiver receiver, DownloadProgress progress) {
  5946. return cli.Put(path, headers, body, content_type, receiver, progress);
  5947. });
  5948. }
  5949. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5950. #ifdef CPPHTTPLIB_SSL_ENABLED
  5951. using ClientT = SSLClient;
  5952. #else
  5953. using ClientT = Client;
  5954. #endif
  5955. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5956. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5957. const std::string &body, const std::string &content_type,
  5958. ContentReceiver receiver, DownloadProgress progress) {
  5959. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5960. });
  5961. }
  5962. template <typename ClientType>
  5963. void TestWithHeadersAndContentReceiverError(
  5964. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5965. const Headers &, const std::string &,
  5966. const std::string &, ContentReceiver)>
  5967. request_func) {
  5968. Headers headers;
  5969. headers.emplace("X-Error-Test", "true");
  5970. std::string received_body;
  5971. auto receiver_failed = false;
  5972. auto res =
  5973. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5974. [&](const char *data, size_t data_length) {
  5975. received_body.append(data, data_length);
  5976. receiver_failed = true;
  5977. return false;
  5978. });
  5979. ASSERT_FALSE(res);
  5980. EXPECT_TRUE(receiver_failed);
  5981. }
  5982. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5983. #ifdef CPPHTTPLIB_SSL_ENABLED
  5984. using ClientT = SSLClient;
  5985. #else
  5986. using ClientT = Client;
  5987. #endif
  5988. TestWithHeadersAndContentReceiverError<ClientT>(
  5989. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5990. const std::string &body, const std::string &content_type,
  5991. ContentReceiver receiver) {
  5992. return cli.Post(path, headers, body, content_type, receiver);
  5993. });
  5994. }
  5995. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5996. #ifdef CPPHTTPLIB_SSL_ENABLED
  5997. using ClientT = SSLClient;
  5998. #else
  5999. using ClientT = Client;
  6000. #endif
  6001. TestWithHeadersAndContentReceiverError<ClientT>(
  6002. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6003. const std::string &body, const std::string &content_type,
  6004. ContentReceiver receiver) {
  6005. return cli.Put(path, headers, body, content_type, receiver);
  6006. });
  6007. }
  6008. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6009. #ifdef CPPHTTPLIB_SSL_ENABLED
  6010. using ClientT = SSLClient;
  6011. #else
  6012. using ClientT = Client;
  6013. #endif
  6014. TestWithHeadersAndContentReceiverError<ClientT>(
  6015. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6016. const std::string &body, const std::string &content_type,
  6017. ContentReceiver receiver) {
  6018. return cli.Patch(path, headers, body, content_type, receiver);
  6019. });
  6020. }
  6021. TEST_F(ServerTest, PostQueryStringAndBody) {
  6022. auto res =
  6023. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6024. ASSERT_TRUE(res);
  6025. ASSERT_EQ(StatusCode::OK_200, res->status);
  6026. }
  6027. TEST_F(ServerTest, HTTP2Magic) {
  6028. Request req;
  6029. req.method = "PRI";
  6030. req.path = "*";
  6031. req.body = "SM";
  6032. auto res = std::make_shared<Response>();
  6033. auto error = Error::Success;
  6034. auto ret = cli_.send(req, *res, error);
  6035. ASSERT_TRUE(ret);
  6036. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6037. }
  6038. TEST_F(ServerTest, KeepAlive) {
  6039. auto res = cli_.Get("/hi");
  6040. ASSERT_TRUE(res);
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6043. EXPECT_EQ("Hello World!", res->body);
  6044. res = cli_.Get("/hi");
  6045. ASSERT_TRUE(res);
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6048. EXPECT_EQ("Hello World!", res->body);
  6049. res = cli_.Get("/hi");
  6050. ASSERT_TRUE(res);
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6053. EXPECT_EQ("Hello World!", res->body);
  6054. res = cli_.Get("/not-exist");
  6055. ASSERT_TRUE(res);
  6056. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6057. res = cli_.Post("/empty", "", "text/plain");
  6058. ASSERT_TRUE(res);
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6061. EXPECT_EQ("empty", res->body);
  6062. EXPECT_EQ("close", res->get_header_value("Connection"));
  6063. res = cli_.Post(
  6064. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6065. "text/plain");
  6066. ASSERT_TRUE(res);
  6067. EXPECT_EQ(StatusCode::OK_200, res->status);
  6068. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6069. EXPECT_EQ("empty", res->body);
  6070. cli_.set_keep_alive(false);
  6071. res = cli_.Get("/last-request");
  6072. ASSERT_TRUE(res);
  6073. EXPECT_EQ(StatusCode::OK_200, res->status);
  6074. EXPECT_EQ("close", res->get_header_value("Connection"));
  6075. }
  6076. TEST_F(ServerTest, TooManyRedirect) {
  6077. cli_.set_follow_location(true);
  6078. auto res = cli_.Get("/redirect/0");
  6079. ASSERT_TRUE(!res);
  6080. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6081. }
  6082. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6083. Request req;
  6084. req.method = "FOOBAR";
  6085. req.path = "/hi";
  6086. cli_.set_keep_alive(true);
  6087. auto res = cli_.send(req);
  6088. ASSERT_TRUE(res);
  6089. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6090. EXPECT_EQ("close", res->get_header_value("Connection"));
  6091. EXPECT_FALSE(cli_.is_socket_open());
  6092. }
  6093. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6095. TEST_F(ServerTest, Gzip) {
  6096. Headers headers;
  6097. headers.emplace("Accept-Encoding", "gzip, deflate");
  6098. auto res = cli_.Get("/compress", headers);
  6099. ASSERT_TRUE(res);
  6100. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6101. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6102. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6103. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6104. "7890123456789012345678901234567890",
  6105. res->body);
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. }
  6108. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6109. Headers headers;
  6110. headers.emplace("Accept-Encoding", "gzip, deflate");
  6111. auto res = cli_.Get("/compress-with-charset", headers);
  6112. ASSERT_TRUE(res);
  6113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6114. EXPECT_EQ("application/json; charset=utf-8",
  6115. res->get_header_value("Content-Type"));
  6116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6117. "7890123456789012345678901234567890",
  6118. res->body);
  6119. EXPECT_EQ(StatusCode::OK_200, res->status);
  6120. }
  6121. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6122. Headers headers;
  6123. headers.emplace("Accept-Encoding", "");
  6124. auto res = cli_.Get("/compress", headers);
  6125. ASSERT_TRUE(res);
  6126. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6128. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6129. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6130. "7890123456789012345678901234567890",
  6131. res->body);
  6132. EXPECT_EQ(StatusCode::OK_200, res->status);
  6133. }
  6134. TEST_F(ServerTest, GzipWithContentReceiver) {
  6135. Headers headers;
  6136. headers.emplace("Accept-Encoding", "gzip, deflate");
  6137. std::string body;
  6138. auto res = cli_.Get("/compress", headers,
  6139. [&](const char *data, uint64_t data_length) {
  6140. EXPECT_EQ(100U, data_length);
  6141. body.append(data, data_length);
  6142. return true;
  6143. });
  6144. ASSERT_TRUE(res);
  6145. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6146. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6147. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6148. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6149. "7890123456789012345678901234567890",
  6150. body);
  6151. EXPECT_EQ(StatusCode::OK_200, res->status);
  6152. }
  6153. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6154. Headers headers;
  6155. headers.emplace("Accept-Encoding", "gzip, deflate");
  6156. cli_.set_decompress(false);
  6157. auto res = cli_.Get("/compress", headers);
  6158. ASSERT_TRUE(res);
  6159. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6161. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6162. EXPECT_EQ(33U, res->body.size());
  6163. EXPECT_EQ(StatusCode::OK_200, res->status);
  6164. }
  6165. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6166. Headers headers;
  6167. headers.emplace("Accept-Encoding", "");
  6168. std::string body;
  6169. auto res = cli_.Get("/compress", headers,
  6170. [&](const char *data, uint64_t data_length) {
  6171. EXPECT_EQ(100U, data_length);
  6172. body.append(data, data_length);
  6173. return true;
  6174. });
  6175. ASSERT_TRUE(res);
  6176. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6177. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6178. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6179. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6180. "7890123456789012345678901234567890",
  6181. body);
  6182. EXPECT_EQ(StatusCode::OK_200, res->status);
  6183. }
  6184. TEST_F(ServerTest, NoGzip) {
  6185. Headers headers;
  6186. headers.emplace("Accept-Encoding", "gzip, deflate");
  6187. auto res = cli_.Get("/nocompress", headers);
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6190. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6191. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6192. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6193. "7890123456789012345678901234567890",
  6194. res->body);
  6195. EXPECT_EQ(StatusCode::OK_200, res->status);
  6196. }
  6197. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6198. Headers headers;
  6199. headers.emplace("Accept-Encoding", "gzip, deflate");
  6200. std::string body;
  6201. auto res = cli_.Get("/nocompress", headers,
  6202. [&](const char *data, uint64_t data_length) {
  6203. EXPECT_EQ(100U, data_length);
  6204. body.append(data, data_length);
  6205. return true;
  6206. });
  6207. ASSERT_TRUE(res);
  6208. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6209. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6210. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6211. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6212. "7890123456789012345678901234567890",
  6213. body);
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. TEST_F(ServerTest, MultipartFormDataGzip) {
  6217. UploadFormDataItems items = {
  6218. {"key1", "test", "", ""},
  6219. {"key2", "--abcdefg123", "", ""},
  6220. };
  6221. cli_.set_compress(true);
  6222. auto res = cli_.Post("/compress-multipart", items);
  6223. ASSERT_TRUE(res);
  6224. EXPECT_EQ(StatusCode::OK_200, res->status);
  6225. }
  6226. #endif
  6227. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6228. TEST_F(ServerTest, Brotli) {
  6229. Headers headers;
  6230. headers.emplace("Accept-Encoding", "br");
  6231. auto res = cli_.Get("/compress", headers);
  6232. ASSERT_TRUE(res);
  6233. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6235. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6237. "7890123456789012345678901234567890",
  6238. res->body);
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. }
  6241. #endif
  6242. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6243. TEST_F(ServerTest, Zstd) {
  6244. Headers headers;
  6245. headers.emplace("Accept-Encoding", "zstd");
  6246. auto res = cli_.Get("/compress", headers);
  6247. ASSERT_TRUE(res);
  6248. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6249. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6250. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6251. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6252. "7890123456789012345678901234567890",
  6253. res->body);
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. }
  6256. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6257. Headers headers;
  6258. headers.emplace("Accept-Encoding", "");
  6259. auto res = cli_.Get("/compress", headers);
  6260. ASSERT_TRUE(res);
  6261. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6263. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6264. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6265. "7890123456789012345678901234567890",
  6266. res->body);
  6267. EXPECT_EQ(StatusCode::OK_200, res->status);
  6268. }
  6269. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6270. Headers headers;
  6271. headers.emplace("Accept-Encoding", "zstd");
  6272. std::string body;
  6273. auto res = cli_.Get("/compress", headers,
  6274. [&](const char *data, uint64_t data_length) {
  6275. EXPECT_EQ(100U, data_length);
  6276. body.append(data, data_length);
  6277. return true;
  6278. });
  6279. ASSERT_TRUE(res);
  6280. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6282. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6283. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6284. "7890123456789012345678901234567890",
  6285. body);
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. }
  6288. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6289. Headers headers;
  6290. headers.emplace("Accept-Encoding", "zstd");
  6291. cli_.set_decompress(false);
  6292. auto res = cli_.Get("/compress", headers);
  6293. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6294. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6295. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6296. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6297. ASSERT_TRUE(res);
  6298. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6300. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6301. EXPECT_EQ(StatusCode::OK_200, res->status);
  6302. ASSERT_EQ(26U, res->body.size());
  6303. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6304. 0);
  6305. }
  6306. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6307. Headers headers;
  6308. headers.emplace("Accept-Encoding", "");
  6309. std::string body;
  6310. auto res = cli_.Get("/compress", headers,
  6311. [&](const char *data, uint64_t data_length) {
  6312. EXPECT_EQ(100U, data_length);
  6313. body.append(data, data_length);
  6314. return true;
  6315. });
  6316. ASSERT_TRUE(res);
  6317. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6319. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6320. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6321. "7890123456789012345678901234567890",
  6322. body);
  6323. EXPECT_EQ(StatusCode::OK_200, res->status);
  6324. }
  6325. TEST_F(ServerTest, NoZstd) {
  6326. Headers headers;
  6327. headers.emplace("Accept-Encoding", "zstd");
  6328. auto res = cli_.Get("/nocompress", headers);
  6329. ASSERT_TRUE(res);
  6330. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6331. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6332. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6333. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6334. "7890123456789012345678901234567890",
  6335. res->body);
  6336. EXPECT_EQ(StatusCode::OK_200, res->status);
  6337. }
  6338. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6339. Headers headers;
  6340. headers.emplace("Accept-Encoding", "zstd");
  6341. std::string body;
  6342. auto res = cli_.Get("/nocompress", headers,
  6343. [&](const char *data, uint64_t data_length) {
  6344. EXPECT_EQ(100U, data_length);
  6345. body.append(data, data_length);
  6346. return true;
  6347. });
  6348. ASSERT_TRUE(res);
  6349. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6350. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6351. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6352. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6353. "7890123456789012345678901234567890",
  6354. body);
  6355. EXPECT_EQ(StatusCode::OK_200, res->status);
  6356. }
  6357. // TODO: How to enable zstd ??
  6358. TEST_F(ServerTest, MultipartFormDataZstd) {
  6359. UploadFormDataItems items = {
  6360. {"key1", "test", "", ""},
  6361. {"key2", "--abcdefg123", "", ""},
  6362. };
  6363. Headers headers;
  6364. headers.emplace("Accept-Encoding", "zstd");
  6365. cli_.set_compress(true);
  6366. auto res = cli_.Post("/compress-multipart", headers, items);
  6367. ASSERT_TRUE(res);
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. }
  6370. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6371. Headers headers;
  6372. headers.emplace("Accept-Encoding", "zstd");
  6373. cli_.set_compress(true);
  6374. auto res = cli_.Put(
  6375. "/put", headers, 3,
  6376. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6377. sink.os << "PUT";
  6378. return true;
  6379. },
  6380. "text/plain");
  6381. ASSERT_TRUE(res);
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. EXPECT_EQ("PUT", res->body);
  6384. }
  6385. // Pre-compression logging tests
  6386. TEST_F(ServerTest, PreCompressionLogging) {
  6387. // Test data for compression (matches the actual /compress endpoint content)
  6388. const std::string test_content =
  6389. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6390. "3456789012345678901234567890";
  6391. // Variables to capture logging data
  6392. std::string pre_compression_body;
  6393. std::string pre_compression_content_type;
  6394. std::string pre_compression_content_encoding;
  6395. std::string post_compression_body;
  6396. std::string post_compression_content_type;
  6397. std::string post_compression_content_encoding;
  6398. // Set up pre-compression logger
  6399. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6400. const Response &res) {
  6401. pre_compression_body = res.body;
  6402. pre_compression_content_type = res.get_header_value("Content-Type");
  6403. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6404. });
  6405. // Set up post-compression logger
  6406. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6407. post_compression_body = res.body;
  6408. post_compression_content_type = res.get_header_value("Content-Type");
  6409. post_compression_content_encoding =
  6410. res.get_header_value("Content-Encoding");
  6411. });
  6412. // Test with gzip compression
  6413. Headers headers;
  6414. headers.emplace("Accept-Encoding", "gzip");
  6415. auto res = cli_.Get("/compress", headers);
  6416. // Verify response was compressed
  6417. ASSERT_TRUE(res);
  6418. EXPECT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6420. // Verify pre-compression logger captured uncompressed content
  6421. EXPECT_EQ(test_content, pre_compression_body);
  6422. EXPECT_EQ("text/plain", pre_compression_content_type);
  6423. EXPECT_TRUE(pre_compression_content_encoding
  6424. .empty()); // No encoding header before compression
  6425. // Verify post-compression logger captured compressed content
  6426. EXPECT_NE(test_content,
  6427. post_compression_body); // Should be different after compression
  6428. EXPECT_EQ("text/plain", post_compression_content_type);
  6429. EXPECT_EQ("gzip", post_compression_content_encoding);
  6430. // Verify compressed content is smaller
  6431. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6432. }
  6433. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6434. const std::string test_content =
  6435. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6436. "3456789012345678901234567890";
  6437. std::string pre_compression_body;
  6438. std::string post_compression_body;
  6439. svr_.set_pre_compression_logger(
  6440. [&](const Request & /*req*/, const Response &res) {
  6441. pre_compression_body = res.body;
  6442. });
  6443. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6444. post_compression_body = res.body;
  6445. });
  6446. Headers headers;
  6447. headers.emplace("Accept-Encoding", "br");
  6448. auto res = cli_.Get("/compress", headers);
  6449. ASSERT_TRUE(res);
  6450. EXPECT_EQ(StatusCode::OK_200, res->status);
  6451. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6452. // Verify pre-compression content is uncompressed
  6453. EXPECT_EQ(test_content, pre_compression_body);
  6454. // Verify post-compression content is compressed
  6455. EXPECT_NE(test_content, post_compression_body);
  6456. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6457. }
  6458. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6459. const std::string test_content =
  6460. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6461. "3456789012345678901234567890";
  6462. std::string pre_compression_body;
  6463. std::string post_compression_body;
  6464. svr_.set_pre_compression_logger(
  6465. [&](const Request & /*req*/, const Response &res) {
  6466. pre_compression_body = res.body;
  6467. });
  6468. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6469. post_compression_body = res.body;
  6470. });
  6471. // Request without compression (use /nocompress endpoint)
  6472. Headers headers;
  6473. auto res = cli_.Get("/nocompress", headers);
  6474. ASSERT_TRUE(res);
  6475. EXPECT_EQ(StatusCode::OK_200, res->status);
  6476. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6477. // Pre-compression logger should not be called when no compression is applied
  6478. EXPECT_TRUE(
  6479. pre_compression_body.empty()); // Pre-compression logger not called
  6480. EXPECT_EQ(
  6481. test_content,
  6482. post_compression_body); // Post-compression logger captures final content
  6483. }
  6484. TEST_F(ServerTest, LoggerSeesContentLength) {
  6485. size_t logged_content_length = 0;
  6486. std::string logged_content_length_header;
  6487. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6488. logged_content_length = res.content_length_;
  6489. logged_content_length_header = res.get_header_value("Content-Length");
  6490. });
  6491. auto res = cli_.Get("/nocompress");
  6492. ASSERT_TRUE(res);
  6493. EXPECT_EQ(StatusCode::OK_200, res->status);
  6494. EXPECT_EQ(res->body.size(), logged_content_length);
  6495. EXPECT_EQ(std::to_string(logged_content_length),
  6496. logged_content_length_header);
  6497. }
  6498. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6499. const std::string test_content =
  6500. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6501. "3456789012345678901234567890";
  6502. std::string pre_compression_body;
  6503. bool pre_logger_called = false;
  6504. // Set only pre-compression logger
  6505. svr_.set_pre_compression_logger(
  6506. [&](const Request & /*req*/, const Response &res) {
  6507. pre_compression_body = res.body;
  6508. pre_logger_called = true;
  6509. });
  6510. Headers headers;
  6511. headers.emplace("Accept-Encoding", "gzip");
  6512. auto res = cli_.Get("/compress", headers);
  6513. ASSERT_TRUE(res);
  6514. EXPECT_EQ(StatusCode::OK_200, res->status);
  6515. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6516. // Verify pre-compression logger was called
  6517. EXPECT_TRUE(pre_logger_called);
  6518. EXPECT_EQ(test_content, pre_compression_body);
  6519. }
  6520. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6521. {
  6522. // Test with Expect: 100-continue header - success case
  6523. // Server returns 100 Continue, client sends body, server returns 200 OK
  6524. Request req;
  6525. req.method = "POST";
  6526. req.path = "/post-large";
  6527. req.set_header("Expect", "100-continue");
  6528. req.body = LARGE_DATA;
  6529. Response res;
  6530. auto error = Error::Success;
  6531. cli_.set_keep_alive(true);
  6532. auto ret = cli_.send(req, res, error);
  6533. EXPECT_TRUE(ret);
  6534. EXPECT_EQ(StatusCode::OK_200, res.status);
  6535. EXPECT_EQ(LARGE_DATA, res.body);
  6536. }
  6537. {
  6538. // Test with Expect: 100-continue header - error case
  6539. // Client should not send the body when server returns an error
  6540. Request req;
  6541. req.method = "POST";
  6542. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6543. req.set_header("Expect", "100-continue");
  6544. req.body = LARGE_DATA;
  6545. Response res;
  6546. auto error = Error::Success;
  6547. auto start = std::chrono::high_resolution_clock::now();
  6548. cli_.set_keep_alive(true);
  6549. auto ret = cli_.send(req, res, error);
  6550. auto end = std::chrono::high_resolution_clock::now();
  6551. auto elapsed =
  6552. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6553. .count();
  6554. // With Expect: 100-continue, request completes successfully but with error
  6555. EXPECT_TRUE(ret);
  6556. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6557. EXPECT_EQ("close", res.get_header_value("Connection"));
  6558. EXPECT_FALSE(cli_.is_socket_open());
  6559. EXPECT_LE(elapsed, 2000);
  6560. }
  6561. {
  6562. // Send an extra GET request to ensure error recovery without hanging
  6563. Request req;
  6564. req.method = "GET";
  6565. req.path = "/hi";
  6566. auto start = std::chrono::high_resolution_clock::now();
  6567. auto res = cli_.send(req);
  6568. auto end = std::chrono::high_resolution_clock::now();
  6569. auto elapsed =
  6570. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6571. .count();
  6572. ASSERT_TRUE(res);
  6573. EXPECT_EQ(StatusCode::OK_200, res->status);
  6574. EXPECT_EQ("Hello World!", res->body);
  6575. EXPECT_LE(elapsed, 500);
  6576. }
  6577. }
  6578. TEST(ZstdDecompressor, ChunkedDecompression) {
  6579. std::string data;
  6580. for (size_t i = 0; i < 32 * 1024; ++i) {
  6581. data.push_back(static_cast<char>('a' + i % 26));
  6582. }
  6583. std::string compressed_data;
  6584. {
  6585. httplib::detail::zstd_compressor compressor;
  6586. bool result = compressor.compress(
  6587. data.data(), data.size(),
  6588. /*last=*/true,
  6589. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6590. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6591. compressed_data_size);
  6592. return true;
  6593. });
  6594. ASSERT_TRUE(result);
  6595. }
  6596. std::string decompressed_data;
  6597. {
  6598. httplib::detail::zstd_decompressor decompressor;
  6599. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6600. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6601. size_t chunk_size = 130;
  6602. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6603. chunk_begin += chunk_size) {
  6604. size_t current_chunk_size =
  6605. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6606. bool result = decompressor.decompress(
  6607. compressed_data.data() + chunk_begin, current_chunk_size,
  6608. [&](const char *decompressed_data_chunk,
  6609. size_t decompressed_data_chunk_size) {
  6610. decompressed_data.insert(decompressed_data.size(),
  6611. decompressed_data_chunk,
  6612. decompressed_data_chunk_size);
  6613. return true;
  6614. });
  6615. ASSERT_TRUE(result);
  6616. }
  6617. }
  6618. ASSERT_EQ(data, decompressed_data);
  6619. }
  6620. TEST(ZstdDecompressor, Decompress) {
  6621. std::string original_text = "Compressed with ZSTD";
  6622. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6623. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6624. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6625. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6626. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6627. std::string decompressed_data;
  6628. {
  6629. httplib::detail::zstd_decompressor decompressor;
  6630. bool result = decompressor.decompress(
  6631. compressed_data.data(), compressed_data.size(),
  6632. [&](const char *decompressed_data_chunk,
  6633. size_t decompressed_data_chunk_size) {
  6634. decompressed_data.insert(decompressed_data.size(),
  6635. decompressed_data_chunk,
  6636. decompressed_data_chunk_size);
  6637. return true;
  6638. });
  6639. ASSERT_TRUE(result);
  6640. }
  6641. ASSERT_EQ(original_text, decompressed_data);
  6642. }
  6643. #endif
  6644. // Sends a raw request to a server listening at HOST:PORT.
  6645. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6646. std::string *resp = nullptr) {
  6647. auto error = Error::Success;
  6648. auto client_sock = detail::create_client_socket(
  6649. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6650. /*connection_timeout_sec=*/5, 0,
  6651. /*read_timeout_sec=*/5, 0,
  6652. /*write_timeout_sec=*/5, 0, std::string(), error);
  6653. if (client_sock == INVALID_SOCKET) { return false; }
  6654. auto ret = detail::process_client_socket(
  6655. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6656. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6657. if (req.size() !=
  6658. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6659. return false;
  6660. }
  6661. char buf[512];
  6662. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6663. while (line_reader.getline()) {
  6664. if (resp) { *resp += line_reader.ptr(); }
  6665. }
  6666. return true;
  6667. });
  6668. detail::close_socket(client_sock);
  6669. return ret;
  6670. }
  6671. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6672. Server svr;
  6673. std::string header_value;
  6674. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6675. header_value = req.get_header_value("foo");
  6676. res.set_content("ok", "text/plain");
  6677. });
  6678. thread t = thread([&] { svr.listen(HOST, PORT); });
  6679. auto se = detail::scope_exit([&] {
  6680. svr.stop();
  6681. t.join();
  6682. ASSERT_FALSE(svr.is_running());
  6683. });
  6684. svr.wait_until_ready();
  6685. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6686. // like characters are not treated the same - use vertical tab and escape.
  6687. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6688. "foo: \t \v bar \x1B\t \r\n"
  6689. "Connection: close\r\n"
  6690. "\r\n";
  6691. std::string res;
  6692. ASSERT_TRUE(send_request(5, req, &res));
  6693. EXPECT_EQ(header_value, "");
  6694. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6695. }
  6696. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6697. Server svr;
  6698. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6699. auto i = new int(0);
  6700. res.set_header("Trailer", "X-Safe, X-Reflected");
  6701. res.set_chunked_content_provider(
  6702. "text/plain",
  6703. [i](size_t /*offset*/, DataSink &sink) {
  6704. if (*i == 0) {
  6705. sink.os << "body";
  6706. } else {
  6707. Headers trailer;
  6708. // A valid trailer that must survive.
  6709. trailer.emplace("X-Safe", "safe");
  6710. // Attacker-controlled value carrying CR/LF (response splitting).
  6711. trailer.emplace("X-Reflected",
  6712. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6713. // Attacker-controlled name carrying CR/LF.
  6714. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6715. sink.done_with_trailer(trailer);
  6716. }
  6717. (*i)++;
  6718. return true;
  6719. },
  6720. [i](bool /*success*/) { delete i; });
  6721. });
  6722. thread t = thread([&] { svr.listen(HOST, PORT); });
  6723. auto se = detail::scope_exit([&] {
  6724. svr.stop();
  6725. t.join();
  6726. ASSERT_FALSE(svr.is_running());
  6727. });
  6728. svr.wait_until_ready();
  6729. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6730. "Host: " + HOST +
  6731. "\r\n"
  6732. "Connection: close\r\n"
  6733. "\r\n";
  6734. std::string res;
  6735. ASSERT_TRUE(send_request(5, req, &res));
  6736. // The injected fields must not appear anywhere in the raw response.
  6737. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6738. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6739. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6740. // Invalid trailers are dropped entirely, matching set_header().
  6741. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6742. // The valid trailer still passes through.
  6743. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6744. }
  6745. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  6746. Server svr;
  6747. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  6748. // res.headers is a public field an application can populate directly,
  6749. // bypassing set_header()'s validation (e.g. reflecting a request value).
  6750. // A valid header that must survive.
  6751. res.headers.emplace("X-Safe", "safe");
  6752. // Attacker-controlled value carrying CR/LF (response splitting).
  6753. res.headers.emplace("X-Reflected",
  6754. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6755. // Attacker-controlled name carrying CR/LF.
  6756. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6757. res.set_content("body", "text/plain");
  6758. });
  6759. thread t = thread([&] { svr.listen(HOST, PORT); });
  6760. auto se = detail::scope_exit([&] {
  6761. svr.stop();
  6762. t.join();
  6763. ASSERT_FALSE(svr.is_running());
  6764. });
  6765. svr.wait_until_ready();
  6766. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  6767. "Host: " + HOST +
  6768. "\r\n"
  6769. "Connection: close\r\n"
  6770. "\r\n";
  6771. std::string res;
  6772. ASSERT_TRUE(send_request(5, req, &res));
  6773. // The injected fields must not appear anywhere in the raw response.
  6774. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6775. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6776. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6777. // Invalid headers are dropped entirely, matching set_header().
  6778. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6779. // The valid header still passes through.
  6780. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6781. }
  6782. // Forward declaration: in split builds split.py strips `inline` and moves the
  6783. // definition into httplib.cc, so detail::write_request_line is not visible from
  6784. // the public httplib.h. Re-declaring it here lets the tests link against the
  6785. // symbol in both header-only and split builds.
  6786. namespace httplib {
  6787. namespace detail {
  6788. ssize_t write_request_line(Stream &strm, const std::string &method,
  6789. const std::string &path);
  6790. } // namespace detail
  6791. } // namespace httplib
  6792. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  6793. // A well-formed target is written verbatim.
  6794. {
  6795. detail::BufferStream strm;
  6796. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  6797. EXPECT_GT(n, 0);
  6798. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  6799. }
  6800. // A target carrying CR/LF must be rejected before anything reaches the wire,
  6801. // otherwise it splits the request line and injects a header or a whole
  6802. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  6803. // when path encoding is disabled.
  6804. const std::string evil_targets[] = {
  6805. "/a\r\nInjected: pwned",
  6806. "/a\rInjected",
  6807. "/a\nInjected",
  6808. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  6809. };
  6810. for (const auto &evil : evil_targets) {
  6811. detail::BufferStream strm;
  6812. auto n = detail::write_request_line(strm, "GET", evil);
  6813. EXPECT_LT(n, 0);
  6814. EXPECT_TRUE(strm.get_buffer().empty());
  6815. }
  6816. }
  6817. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  6818. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  6819. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  6820. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  6821. // client must fail cleanly with Error::Write instead of putting a
  6822. // request-line-less, header-injecting request on the wire.
  6823. Server svr;
  6824. svr.Get("/a", [](const Request &, Response &res) {
  6825. res.set_content("ok", "text/plain");
  6826. });
  6827. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6828. auto se = detail::scope_exit([&] {
  6829. svr.stop();
  6830. thread.join();
  6831. ASSERT_FALSE(svr.is_running());
  6832. });
  6833. svr.wait_until_ready();
  6834. {
  6835. Client cli(HOST, PORT);
  6836. cli.set_path_encode(false);
  6837. // The request is rejected before anything is written, so the connection
  6838. // stays silent and the subsequent response read would otherwise block for
  6839. // the full default read timeout. Shorten it -- the assertion is on the
  6840. // error, not the timeout.
  6841. cli.set_read_timeout(1, 0);
  6842. auto res = cli.Get("/a\r\nInjected: pwned");
  6843. EXPECT_FALSE(res);
  6844. EXPECT_EQ(Error::Write, res.error());
  6845. }
  6846. }
  6847. // Sends a raw request and verifies that there isn't a crash or exception.
  6848. static void test_raw_request(const std::string &req,
  6849. std::string *out = nullptr) {
  6850. Server svr;
  6851. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6852. res.set_content("ok", "text/plain");
  6853. });
  6854. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6855. res.set_content("ok", "text/plain");
  6856. });
  6857. svr.Get("/header_field_value_check",
  6858. [&](const Request & /*req*/, Response &res) {
  6859. res.set_content("ok", "text/plain");
  6860. });
  6861. // Server read timeout must be longer than the client read timeout for the
  6862. // bug to reproduce, probably to force the server to process a request
  6863. // without a trailing blank line.
  6864. const time_t client_read_timeout_sec = 1;
  6865. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6866. bool listen_thread_ok = false;
  6867. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6868. auto se = detail::scope_exit([&] {
  6869. svr.stop();
  6870. t.join();
  6871. ASSERT_FALSE(svr.is_running());
  6872. EXPECT_TRUE(listen_thread_ok);
  6873. });
  6874. svr.wait_until_ready();
  6875. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6876. }
  6877. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6878. // A certain header line causes an exception if the header property is parsed
  6879. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6880. test_raw_request(
  6881. "GET /hi HTTP/1.1\r\n"
  6882. " : "
  6883. " "
  6884. " ");
  6885. }
  6886. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6887. // A certain header line causes an exception if the header property *name* is
  6888. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6889. // greedy matcher and requires backtracking when there are a lot of ":"
  6890. // characters.
  6891. // This occurs with libc++ but not libstdc++.
  6892. test_raw_request(
  6893. "GET /hi HTTP/1.1\r\n"
  6894. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6895. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6896. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6897. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6898. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6899. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6900. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6901. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6902. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6903. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6904. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6905. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6906. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6907. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6908. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6909. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6910. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6911. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6912. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6913. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6914. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6915. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6916. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6917. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6918. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6919. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6920. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6921. "&&&%%%");
  6922. }
  6923. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6924. // Make sure this doesn't crash the server.
  6925. // In a previous version of the header line regex, the "\r" rendered the line
  6926. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6927. // a new position where the leading white space ended and the field value
  6928. // began.
  6929. // The crash occurs with libc++ but not libstdc++.
  6930. test_raw_request("GET /hi HTTP/1.1\r\n"
  6931. "a:" +
  6932. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6933. "\r\n"
  6934. "\r\n");
  6935. }
  6936. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6937. std::string out;
  6938. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6939. "Content-Type: text/plain\r\n"
  6940. "Transfer-Encoding: chunked\r\n"
  6941. "\r\n"
  6942. "nothex\r\n",
  6943. &out);
  6944. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6945. }
  6946. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6947. std::string out;
  6948. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6949. "Content-Type: text/plain\r\n"
  6950. "Transfer-Encoding: chunked\r\n"
  6951. "\r\n"
  6952. "3\r\n"
  6953. "xyz\r\n"
  6954. "NaN\r\n",
  6955. &out);
  6956. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6957. }
  6958. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6959. std::string out;
  6960. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6961. "Content-Type: text/plain\r\n"
  6962. "Transfer-Encoding: chunked\r\n"
  6963. "\r\n"
  6964. // Length is too large for 64 bits.
  6965. "1ffffffffffffffff\r\n"
  6966. "xyz\r\n",
  6967. &out);
  6968. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6969. }
  6970. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6971. test_raw_request("GET /hi HTTP/1.1\r\n"
  6972. "Content-Type: text/plain\r\n\r");
  6973. }
  6974. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6975. std::string out;
  6976. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6977. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6978. }
  6979. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6980. Server svr;
  6981. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6982. EXPECT_TRUE(!req.remote_addr.empty());
  6983. });
  6984. thread t = thread([&] { svr.listen(HOST, PORT); });
  6985. auto se = detail::scope_exit([&] {
  6986. svr.stop();
  6987. t.join();
  6988. ASSERT_FALSE(svr.is_running());
  6989. });
  6990. svr.wait_until_ready();
  6991. // Send an invalid request line to trigger Bad Request
  6992. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6993. std::string out;
  6994. ASSERT_TRUE(send_request(5, bad_req, &out));
  6995. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6996. }
  6997. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6998. std::string out;
  6999. std::string request(
  7000. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7001. test_raw_request(request, &out);
  7002. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7003. }
  7004. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7005. std::string out;
  7006. std::string request(
  7007. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7008. test_raw_request(request, &out);
  7009. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7010. }
  7011. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7012. std::string out;
  7013. std::string request(
  7014. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7015. test_raw_request(request, &out);
  7016. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7017. }
  7018. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7019. std::string out;
  7020. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7021. "Test: \r\n\r\n",
  7022. &out);
  7023. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7024. }
  7025. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7026. Server svr;
  7027. std::string x_custom;
  7028. std::string cookie;
  7029. std::string xff;
  7030. std::string x_unicode;
  7031. std::string x_iis;
  7032. svr.Get("/check", [&](const Request &req, Response &res) {
  7033. x_custom = req.get_header_value("X-Custom");
  7034. cookie = req.get_header_value("Cookie");
  7035. xff = req.get_header_value("X-Forwarded-For");
  7036. x_unicode = req.get_header_value("X-Unicode");
  7037. x_iis = req.get_header_value("X-IIS");
  7038. res.set_content("ok", "text/plain");
  7039. });
  7040. thread t = thread([&] { svr.listen(HOST, PORT); });
  7041. auto se = detail::scope_exit([&] {
  7042. svr.stop();
  7043. t.join();
  7044. ASSERT_FALSE(svr.is_running());
  7045. });
  7046. svr.wait_until_ready();
  7047. const std::string req = "GET /check HTTP/1.1\r\n"
  7048. "Host: localhost\r\n"
  7049. "X-Custom: a%0D%0AInjected: b\r\n"
  7050. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7051. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7052. "X-Unicode: %E3%81%82\r\n"
  7053. "X-IIS: %u00E9\r\n"
  7054. "Connection: close\r\n"
  7055. "\r\n";
  7056. std::string res;
  7057. ASSERT_TRUE(send_request(5, req, &res));
  7058. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7059. // Every value must be returned verbatim (wire form), with no decoding.
  7060. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7061. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7062. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7063. EXPECT_EQ("%E3%81%82", x_unicode);
  7064. EXPECT_EQ("%u00E9", x_iis);
  7065. }
  7066. // Applications that previously relied on automatic percent-decoding can
  7067. // reproduce the old behavior by explicitly calling decode_path_component()
  7068. // or, for RFC 3986 conformance, decode_uri_component().
  7069. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7070. Server svr;
  7071. std::string decoded;
  7072. svr.Get("/check", [&](const Request &req, Response &res) {
  7073. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7074. res.set_content("ok", "text/plain");
  7075. });
  7076. thread t = thread([&] { svr.listen(HOST, PORT); });
  7077. auto se = detail::scope_exit([&] {
  7078. svr.stop();
  7079. t.join();
  7080. ASSERT_FALSE(svr.is_running());
  7081. });
  7082. svr.wait_until_ready();
  7083. const std::string req = "GET /check HTTP/1.1\r\n"
  7084. "Host: localhost\r\n"
  7085. "X-Custom: hello%20world\r\n"
  7086. "Connection: close\r\n"
  7087. "\r\n";
  7088. std::string res;
  7089. ASSERT_TRUE(send_request(5, req, &res));
  7090. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7091. EXPECT_EQ("hello world", decoded);
  7092. }
  7093. // Regression test for #2033. Browsers send Referer values that include
  7094. // percent-encoded characters such as %0A inside the URL. Decoding the
  7095. // header value would either trip the post-decode CR/LF/NUL guard (the
  7096. // original bug, returning 400) or, after that guard was relaxed, silently
  7097. // store a literal LF — both unacceptable. The wire form must round-trip.
  7098. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7099. Server svr;
  7100. std::string referer;
  7101. svr.Get("/check", [&](const Request &req, Response &res) {
  7102. referer = req.get_header_value("Referer");
  7103. res.set_content("ok", "text/plain");
  7104. });
  7105. thread t = thread([&] { svr.listen(HOST, PORT); });
  7106. auto se = detail::scope_exit([&] {
  7107. svr.stop();
  7108. t.join();
  7109. ASSERT_FALSE(svr.is_running());
  7110. });
  7111. svr.wait_until_ready();
  7112. const std::string req = "GET /check HTTP/1.1\r\n"
  7113. "Host: localhost\r\n"
  7114. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7115. "Connection: close\r\n"
  7116. "\r\n";
  7117. std::string res;
  7118. ASSERT_TRUE(send_request(5, req, &res));
  7119. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7120. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7121. }
  7122. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7123. Server svr;
  7124. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7125. res.set_header("Cache-Control", "no-cache");
  7126. res.set_chunked_content_provider(
  7127. "text/event-stream", [](size_t offset, DataSink &sink) {
  7128. std::string s = "data:";
  7129. s += std::to_string(offset);
  7130. s += "\n\n";
  7131. auto ret = sink.write(s.data(), s.size());
  7132. EXPECT_TRUE(ret);
  7133. std::this_thread::sleep_for(std::chrono::seconds(1));
  7134. return true;
  7135. });
  7136. });
  7137. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7138. svr.wait_until_ready();
  7139. Client client(HOST, PORT);
  7140. const Headers headers = {{"Accept", "text/event-stream"}};
  7141. auto get_thread = std::thread([&client, &headers]() {
  7142. auto res = client.Get(
  7143. "/events", headers,
  7144. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7145. });
  7146. auto se = detail::scope_exit([&] {
  7147. svr.stop();
  7148. get_thread.join();
  7149. listen_thread.join();
  7150. ASSERT_FALSE(svr.is_running());
  7151. });
  7152. // Give GET time to get a few messages.
  7153. std::this_thread::sleep_for(std::chrono::seconds(2));
  7154. }
  7155. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7156. httplib::Server svr;
  7157. svr.Post("/hi",
  7158. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7159. res.status = StatusCode::OK_200;
  7160. });
  7161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7162. svr.wait_until_ready();
  7163. Client cli(HOST, PORT);
  7164. auto res = cli.Post("/hi", "data", "text/plain");
  7165. ASSERT_TRUE(res);
  7166. EXPECT_EQ(StatusCode::OK_200, res->status);
  7167. svr.stop();
  7168. thread.join();
  7169. ASSERT_FALSE(svr.is_running());
  7170. res = cli.Post("/hi", "data", "text/plain");
  7171. ASSERT_FALSE(res);
  7172. }
  7173. TEST(ServerStopTest, ListenFailure) {
  7174. Server svr;
  7175. auto t = thread([&]() {
  7176. auto ret = svr.listen("????", PORT);
  7177. EXPECT_FALSE(ret);
  7178. });
  7179. svr.wait_until_ready();
  7180. svr.stop();
  7181. t.join();
  7182. }
  7183. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7184. TEST(ServerStopTest, Decommision) {
  7185. Server svr;
  7186. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7187. for (int i = 0; i < 4; i++) {
  7188. auto is_even = !(i % 2);
  7189. std::thread t{[&] {
  7190. try {
  7191. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7192. if (is_even) {
  7193. throw std::runtime_error("Some thing that happens to go wrong.");
  7194. }
  7195. svr.listen(HOST, PORT);
  7196. } catch (...) { svr.decommission(); }
  7197. }};
  7198. svr.wait_until_ready();
  7199. // Server is up
  7200. {
  7201. Client cli(HOST, PORT);
  7202. auto res = cli.Get("/hi");
  7203. if (is_even) {
  7204. EXPECT_FALSE(res);
  7205. } else {
  7206. EXPECT_TRUE(res);
  7207. EXPECT_EQ("hi...", res->body);
  7208. }
  7209. }
  7210. svr.stop();
  7211. t.join();
  7212. // Server is down...
  7213. {
  7214. Client cli(HOST, PORT);
  7215. auto res = cli.Get("/hi");
  7216. EXPECT_FALSE(res);
  7217. }
  7218. }
  7219. }
  7220. #endif
  7221. // Helper function for string body upload progress tests
  7222. template <typename SetupHandler, typename ClientCall>
  7223. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7224. ClientCall &&client_call,
  7225. const string &body) {
  7226. Server svr;
  7227. setup_handler(svr);
  7228. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7229. auto se = detail::scope_exit([&] {
  7230. svr.stop();
  7231. t.join();
  7232. });
  7233. svr.wait_until_ready();
  7234. Client cli(HOST, PORT);
  7235. vector<uint64_t> progress_values;
  7236. bool progress_called = false;
  7237. auto res =
  7238. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7239. progress_values.push_back(current);
  7240. progress_called = true;
  7241. return true;
  7242. });
  7243. ASSERT_TRUE(res);
  7244. EXPECT_EQ(200, res->status);
  7245. EXPECT_TRUE(progress_called);
  7246. }
  7247. TEST(UploadProgressTest, PostStringBodyBasic) {
  7248. TestStringBodyUploadProgress(
  7249. [](Server &svr) {
  7250. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7251. res.set_content("received", "text/plain");
  7252. });
  7253. },
  7254. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7255. return cli.Post("/test", body, "text/plain", progress_callback);
  7256. },
  7257. "test data for upload progress");
  7258. }
  7259. TEST(UploadProgressTest, PutStringBodyBasic) {
  7260. TestStringBodyUploadProgress(
  7261. [](Server &svr) {
  7262. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7263. res.set_content("put received", "text/plain");
  7264. });
  7265. },
  7266. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7267. return cli.Put("/test", body, "text/plain", progress_callback);
  7268. },
  7269. "put test data for upload progress");
  7270. }
  7271. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7272. TestStringBodyUploadProgress(
  7273. [](Server &svr) {
  7274. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7275. res.set_content("patch received", "text/plain");
  7276. });
  7277. },
  7278. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7279. return cli.Patch("/test", body, "text/plain", progress_callback);
  7280. },
  7281. "patch test data for upload progress");
  7282. }
  7283. // Helper function for content provider upload progress tests
  7284. template <typename SetupHandler, typename ClientCall>
  7285. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7286. ClientCall &&client_call) {
  7287. Server svr;
  7288. setup_handler(svr);
  7289. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7290. auto se = detail::scope_exit([&] {
  7291. svr.stop();
  7292. t.join();
  7293. });
  7294. svr.wait_until_ready();
  7295. Client cli(HOST, PORT);
  7296. vector<uint64_t> progress_values;
  7297. auto res =
  7298. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7299. progress_values.push_back(current);
  7300. return true;
  7301. });
  7302. ASSERT_TRUE(res);
  7303. EXPECT_EQ(200, res->status);
  7304. EXPECT_FALSE(progress_values.empty());
  7305. }
  7306. TEST(UploadProgressTest, PostContentProviderProgress) {
  7307. TestContentProviderUploadProgress(
  7308. [](Server &svr) {
  7309. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7310. res.set_content("provider received", "text/plain");
  7311. });
  7312. },
  7313. [](Client &cli, UploadProgress progress_callback) {
  7314. return cli.Post(
  7315. "/test", 10,
  7316. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7317. sink.os << "test data";
  7318. return true;
  7319. },
  7320. "text/plain", progress_callback);
  7321. });
  7322. }
  7323. // Helper function for multipart upload progress tests
  7324. template <typename SetupHandler, typename ClientCall>
  7325. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7326. ClientCall &&client_call,
  7327. const string &endpoint) {
  7328. Server svr;
  7329. setup_handler(svr);
  7330. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7331. auto se = detail::scope_exit([&] {
  7332. svr.stop();
  7333. t.join();
  7334. });
  7335. svr.wait_until_ready();
  7336. Client cli(HOST, PORT);
  7337. vector<uint64_t> progress_values;
  7338. UploadFormDataItems items = {
  7339. {"field1", "value1", "", ""},
  7340. {"field2", "longer value for progress tracking test", "", ""},
  7341. {"file1", "file content data for upload progress", "test.txt",
  7342. "text/plain"}};
  7343. auto res = client_call(cli, endpoint, items,
  7344. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7345. progress_values.push_back(current);
  7346. return true;
  7347. });
  7348. ASSERT_TRUE(res);
  7349. EXPECT_EQ(200, res->status);
  7350. EXPECT_FALSE(progress_values.empty());
  7351. }
  7352. TEST(UploadProgressTest, PostMultipartProgress) {
  7353. TestMultipartUploadProgress(
  7354. [](Server &svr) {
  7355. svr.Post("/multipart", [](const Request &req, Response &res) {
  7356. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7357. res.set_content("multipart received", "text/plain");
  7358. });
  7359. },
  7360. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7361. UploadProgress progress_callback) {
  7362. return cli.Post(endpoint, items, progress_callback);
  7363. },
  7364. "/multipart");
  7365. }
  7366. // Helper function for basic download progress tests
  7367. template <typename SetupHandler, typename ClientCall>
  7368. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7369. ClientCall &&client_call, const string &endpoint,
  7370. size_t expected_content_size) {
  7371. Server svr;
  7372. setup_handler(svr);
  7373. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7374. auto se = detail::scope_exit([&] {
  7375. svr.stop();
  7376. t.join();
  7377. });
  7378. svr.wait_until_ready();
  7379. Client cli(HOST, PORT);
  7380. vector<uint64_t> progress_values;
  7381. auto res = client_call(cli, endpoint,
  7382. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7383. progress_values.push_back(current);
  7384. return true;
  7385. });
  7386. ASSERT_TRUE(res);
  7387. EXPECT_EQ(200, res->status);
  7388. EXPECT_FALSE(progress_values.empty());
  7389. EXPECT_EQ(expected_content_size, res->body.size());
  7390. }
  7391. TEST(DownloadProgressTest, GetBasic) {
  7392. TestBasicDownloadProgress(
  7393. [](Server &svr) {
  7394. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7395. string content(1000, 'D');
  7396. res.set_content(content, "text/plain");
  7397. });
  7398. },
  7399. [](Client &cli, const string &endpoint,
  7400. DownloadProgress progress_callback) {
  7401. return cli.Get(endpoint, progress_callback);
  7402. },
  7403. "/download", 1000u);
  7404. }
  7405. // Helper function for content receiver download progress tests
  7406. template <typename SetupHandler, typename ClientCall>
  7407. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7408. ClientCall &&client_call,
  7409. const string &endpoint,
  7410. size_t expected_content_size) {
  7411. Server svr;
  7412. setup_handler(svr);
  7413. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7414. auto se = detail::scope_exit([&] {
  7415. svr.stop();
  7416. t.join();
  7417. });
  7418. svr.wait_until_ready();
  7419. Client cli(HOST, PORT);
  7420. vector<uint64_t> progress_values;
  7421. string received_body;
  7422. auto res = client_call(
  7423. cli, endpoint,
  7424. [&](const char *data, size_t data_length) -> bool {
  7425. received_body.append(data, data_length);
  7426. return true;
  7427. },
  7428. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7429. progress_values.push_back(current);
  7430. return true;
  7431. });
  7432. ASSERT_TRUE(res);
  7433. EXPECT_EQ(200, res->status);
  7434. EXPECT_FALSE(progress_values.empty());
  7435. EXPECT_EQ(expected_content_size, received_body.size());
  7436. EXPECT_TRUE(res->body.empty());
  7437. }
  7438. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7439. TestContentReceiverDownloadProgress(
  7440. [](Server &svr) {
  7441. svr.Get("/download-receiver",
  7442. [](const Request & /*req*/, Response &res) {
  7443. string content(2000, 'R');
  7444. res.set_content(content, "text/plain");
  7445. });
  7446. },
  7447. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7448. DownloadProgress progress_callback) {
  7449. return cli.Get(endpoint, content_receiver, progress_callback);
  7450. },
  7451. "/download-receiver", 2000u);
  7452. }
  7453. TEST(StreamingTest, NoContentLengthStreaming) {
  7454. Server svr;
  7455. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7456. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7457. if (offset < 6) {
  7458. sink.os << (offset < 3 ? "a" : "b");
  7459. } else {
  7460. sink.done();
  7461. }
  7462. return true;
  7463. });
  7464. });
  7465. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7466. auto listen_se = detail::scope_exit([&] {
  7467. svr.stop();
  7468. listen_thread.join();
  7469. ASSERT_FALSE(svr.is_running());
  7470. });
  7471. svr.wait_until_ready();
  7472. Client client(HOST, PORT);
  7473. auto get_thread = std::thread([&client]() {
  7474. std::string s;
  7475. auto res =
  7476. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7477. s += std::string(data, len);
  7478. return true;
  7479. });
  7480. ASSERT_TRUE(res);
  7481. EXPECT_EQ(StatusCode::OK_200, res->status);
  7482. EXPECT_EQ("aaabbb", s);
  7483. });
  7484. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7485. // Give GET time to get a few messages.
  7486. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7487. }
  7488. TEST(MountTest, Unmount) {
  7489. Server svr;
  7490. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7491. auto se = detail::scope_exit([&] {
  7492. svr.stop();
  7493. listen_thread.join();
  7494. ASSERT_FALSE(svr.is_running());
  7495. });
  7496. svr.wait_until_ready();
  7497. Client cli("localhost", PORT);
  7498. svr.set_mount_point("/mount2", "./www2");
  7499. auto res = cli.Get("/");
  7500. ASSERT_TRUE(res);
  7501. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7502. res = cli.Get("/mount2/dir/test.html");
  7503. ASSERT_TRUE(res);
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. svr.set_mount_point("/", "./www");
  7506. res = cli.Get("/dir/");
  7507. ASSERT_TRUE(res);
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. svr.remove_mount_point("/");
  7510. res = cli.Get("/dir/");
  7511. ASSERT_TRUE(res);
  7512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7513. svr.remove_mount_point("/mount2");
  7514. res = cli.Get("/mount2/dir/test.html");
  7515. ASSERT_TRUE(res);
  7516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7517. }
  7518. TEST(MountTest, Redicect) {
  7519. Server svr;
  7520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7521. auto se = detail::scope_exit([&] {
  7522. svr.stop();
  7523. listen_thread.join();
  7524. ASSERT_FALSE(svr.is_running());
  7525. });
  7526. svr.set_mount_point("/", "./www");
  7527. svr.wait_until_ready();
  7528. Client cli("localhost", PORT);
  7529. auto res = cli.Get("/dir/");
  7530. ASSERT_TRUE(res);
  7531. EXPECT_EQ(StatusCode::OK_200, res->status);
  7532. res = cli.Get("/dir");
  7533. ASSERT_TRUE(res);
  7534. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7535. res = cli.Get("/file");
  7536. ASSERT_TRUE(res);
  7537. EXPECT_EQ(StatusCode::OK_200, res->status);
  7538. res = cli.Get("/file/");
  7539. ASSERT_TRUE(res);
  7540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7541. cli.set_follow_location(true);
  7542. res = cli.Get("/dir");
  7543. ASSERT_TRUE(res);
  7544. EXPECT_EQ(StatusCode::OK_200, res->status);
  7545. }
  7546. TEST(MountTest, MultibytesPathName) {
  7547. Server svr;
  7548. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7549. auto se = detail::scope_exit([&] {
  7550. svr.stop();
  7551. listen_thread.join();
  7552. ASSERT_FALSE(svr.is_running());
  7553. });
  7554. svr.set_mount_point("/", "./www");
  7555. svr.wait_until_ready();
  7556. Client cli("localhost", PORT);
  7557. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7558. ASSERT_TRUE(res);
  7559. EXPECT_EQ(StatusCode::OK_200, res->status);
  7560. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7561. }
  7562. #ifdef _WIN32
  7563. // Issue #2435: mmap::open() must succeed even when another handle holds
  7564. // the file open for writing (e.g. an active log file).
  7565. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7566. const char *path = "mmap_concurrent_writer_test.txt";
  7567. const char *content = "hello";
  7568. {
  7569. std::ofstream f(path, std::ios::binary);
  7570. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7571. }
  7572. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7573. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7574. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7575. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7576. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7577. detail::mmap m(path);
  7578. ASSERT_TRUE(m.is_open());
  7579. EXPECT_EQ(strlen(content), m.size());
  7580. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7581. }
  7582. #endif
  7583. TEST(KeepAliveTest, ReadTimeout) {
  7584. Server svr;
  7585. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7586. std::this_thread::sleep_for(std::chrono::seconds(2));
  7587. res.set_content("a", "text/plain");
  7588. });
  7589. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7590. res.set_content("b", "text/plain");
  7591. });
  7592. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7593. auto se = detail::scope_exit([&] {
  7594. svr.stop();
  7595. listen_thread.join();
  7596. ASSERT_FALSE(svr.is_running());
  7597. });
  7598. svr.wait_until_ready();
  7599. Client cli("localhost", PORT);
  7600. cli.set_keep_alive(true);
  7601. cli.set_read_timeout(std::chrono::seconds(1));
  7602. auto resa = cli.Get("/a");
  7603. ASSERT_FALSE(resa);
  7604. EXPECT_EQ(Error::Read, resa.error());
  7605. auto resb = cli.Get("/b");
  7606. ASSERT_TRUE(resb);
  7607. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7608. EXPECT_EQ("b", resb->body);
  7609. }
  7610. TEST(KeepAliveTest, MaxCount) {
  7611. size_t keep_alive_max_count = 3;
  7612. Server svr;
  7613. svr.set_keep_alive_max_count(keep_alive_max_count);
  7614. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7615. res.set_content("Hello World!", "text/plain");
  7616. });
  7617. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7618. auto se = detail::scope_exit([&] {
  7619. svr.stop();
  7620. listen_thread.join();
  7621. ASSERT_FALSE(svr.is_running());
  7622. });
  7623. svr.wait_until_ready();
  7624. Client cli(HOST, PORT);
  7625. cli.set_keep_alive(true);
  7626. for (size_t i = 0; i < 5; i++) {
  7627. auto result = cli.Get("/hi");
  7628. ASSERT_TRUE(result);
  7629. EXPECT_EQ(StatusCode::OK_200, result->status);
  7630. if (i == keep_alive_max_count - 1) {
  7631. EXPECT_EQ("close", result->get_header_value("Connection"));
  7632. } else {
  7633. EXPECT_FALSE(result->has_header("Connection"));
  7634. }
  7635. }
  7636. }
  7637. TEST(KeepAliveTest, Issue1041) {
  7638. Server svr;
  7639. svr.set_keep_alive_timeout(3);
  7640. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7641. res.set_content("Hello World!", "text/plain");
  7642. });
  7643. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7644. auto se = detail::scope_exit([&] {
  7645. svr.stop();
  7646. listen_thread.join();
  7647. ASSERT_FALSE(svr.is_running());
  7648. });
  7649. svr.wait_until_ready();
  7650. Client cli(HOST, PORT);
  7651. cli.set_keep_alive(true);
  7652. auto result = cli.Get("/hi");
  7653. ASSERT_TRUE(result);
  7654. EXPECT_EQ(StatusCode::OK_200, result->status);
  7655. std::this_thread::sleep_for(std::chrono::seconds(5));
  7656. result = cli.Get("/hi");
  7657. ASSERT_TRUE(result);
  7658. EXPECT_EQ(StatusCode::OK_200, result->status);
  7659. }
  7660. TEST(KeepAliveTest, Issue1959) {
  7661. Server svr;
  7662. svr.set_keep_alive_timeout(5);
  7663. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7664. res.set_content("a", "text/plain");
  7665. });
  7666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7667. auto se = detail::scope_exit([&] {
  7668. if (!svr.is_running()) return;
  7669. svr.stop();
  7670. listen_thread.join();
  7671. ASSERT_FALSE(svr.is_running());
  7672. });
  7673. svr.wait_until_ready();
  7674. Client cli("localhost", PORT);
  7675. cli.set_keep_alive(true);
  7676. using namespace std::chrono;
  7677. auto start = steady_clock::now();
  7678. cli.Get("/a");
  7679. svr.stop();
  7680. listen_thread.join();
  7681. auto end = steady_clock::now();
  7682. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7683. EXPECT_LT(elapsed, 5000);
  7684. }
  7685. #ifdef CPPHTTPLIB_SSL_ENABLED
  7686. TEST(KeepAliveTest, SSLClientReconnection) {
  7687. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7688. ASSERT_TRUE(svr.is_valid());
  7689. svr.set_keep_alive_timeout(1);
  7690. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7691. res.set_content("Hello World!", "text/plain");
  7692. });
  7693. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7694. auto se = detail::scope_exit([&] {
  7695. svr.stop();
  7696. listen_thread.join();
  7697. ASSERT_FALSE(svr.is_running());
  7698. });
  7699. svr.wait_until_ready();
  7700. SSLClient cli(HOST, PORT);
  7701. cli.enable_server_certificate_verification(false);
  7702. cli.set_keep_alive(true);
  7703. auto result = cli.Get("/hi");
  7704. ASSERT_TRUE(result);
  7705. EXPECT_EQ(StatusCode::OK_200, result->status);
  7706. result = cli.Get("/hi");
  7707. ASSERT_TRUE(result);
  7708. EXPECT_EQ(StatusCode::OK_200, result->status);
  7709. std::this_thread::sleep_for(std::chrono::seconds(2));
  7710. // Recoonect
  7711. result = cli.Get("/hi");
  7712. ASSERT_TRUE(result);
  7713. EXPECT_EQ(StatusCode::OK_200, result->status);
  7714. result = cli.Get("/hi");
  7715. ASSERT_TRUE(result);
  7716. EXPECT_EQ(StatusCode::OK_200, result->status);
  7717. }
  7718. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7720. ASSERT_TRUE(svr.is_valid());
  7721. svr.set_keep_alive_timeout(1);
  7722. std::string content = "reconnect";
  7723. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7724. res.set_content("Hello World!", "text/plain");
  7725. });
  7726. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7727. auto se = detail::scope_exit([&] {
  7728. svr.stop();
  7729. listen_thread.join();
  7730. ASSERT_FALSE(svr.is_running());
  7731. });
  7732. svr.wait_until_ready();
  7733. SSLClient cli(HOST, PORT);
  7734. cli.enable_server_certificate_verification(false);
  7735. cli.set_keep_alive(true);
  7736. auto result = cli.Post(
  7737. "/hi", content.size(),
  7738. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7739. sink.write(content.c_str(), content.size());
  7740. return true;
  7741. },
  7742. "text/plain");
  7743. ASSERT_TRUE(result);
  7744. EXPECT_EQ(200, result->status);
  7745. std::this_thread::sleep_for(std::chrono::seconds(2));
  7746. // Recoonect
  7747. result = cli.Post(
  7748. "/hi", content.size(),
  7749. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7750. sink.write(content.c_str(), content.size());
  7751. return true;
  7752. },
  7753. "text/plain");
  7754. ASSERT_TRUE(result);
  7755. EXPECT_EQ(200, result->status);
  7756. result = cli.Post(
  7757. "/hi", content.size(),
  7758. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7759. sink.write(content.c_str(), content.size());
  7760. return true;
  7761. },
  7762. "text/plain");
  7763. ASSERT_TRUE(result);
  7764. EXPECT_EQ(200, result->status);
  7765. }
  7766. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7767. using namespace httplib::tls;
  7768. {
  7769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7770. ASSERT_TRUE(svr.is_valid());
  7771. svr.Get("/sni", [&](const Request &req, Response &res) {
  7772. std::string expected = req.sni();
  7773. EXPECT_EQ(expected, req.get_param_value("expected"));
  7774. res.set_content("ok", "text/plain");
  7775. });
  7776. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7777. auto se = detail::scope_exit([&] {
  7778. svr.stop();
  7779. listen_thread.join();
  7780. ASSERT_FALSE(svr.is_running());
  7781. });
  7782. svr.wait_until_ready();
  7783. {
  7784. SSLClient cli("localhost", PORT);
  7785. cli.enable_server_certificate_verification(false);
  7786. auto res = cli.Get("/sni?expected=localhost");
  7787. ASSERT_TRUE(res);
  7788. }
  7789. {
  7790. SSLClient cli("::1", PORT);
  7791. cli.enable_server_certificate_verification(false);
  7792. auto res = cli.Get("/sni?expected=");
  7793. // NOTE: This may fail if the server is listening on IPv4 only
  7794. // (e.g., when localhost resolves to 127.0.0.1 only)
  7795. if (res) {
  7796. EXPECT_EQ(StatusCode::OK_200, res->status);
  7797. } else {
  7798. EXPECT_EQ(Error::Connection, res.error());
  7799. }
  7800. }
  7801. }
  7802. }
  7803. #endif
  7804. TEST(ClientProblemDetectionTest, ContentProvider) {
  7805. Server svr;
  7806. size_t content_length = 1024 * 1024;
  7807. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7808. res.set_content_provider(
  7809. content_length, "text/plain",
  7810. [&](size_t offset, size_t length, DataSink &sink) {
  7811. auto out_len = std::min(length, static_cast<size_t>(1024));
  7812. std::string out(out_len, '@');
  7813. sink.write(out.data(), out_len);
  7814. return offset < 4096;
  7815. },
  7816. [](bool success) { ASSERT_FALSE(success); });
  7817. });
  7818. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7819. res.set_content_provider(
  7820. 0, "text/plain",
  7821. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7822. EXPECT_TRUE(false);
  7823. return true;
  7824. },
  7825. [](bool success) { ASSERT_FALSE(success); });
  7826. });
  7827. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7828. auto se = detail::scope_exit([&] {
  7829. svr.stop();
  7830. listen_thread.join();
  7831. ASSERT_FALSE(svr.is_running());
  7832. });
  7833. svr.wait_until_ready();
  7834. Client cli("localhost", PORT);
  7835. {
  7836. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7837. size_t /*data_length*/) { return false; });
  7838. ASSERT_FALSE(res);
  7839. }
  7840. {
  7841. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7842. size_t /*data_length*/) { return false; });
  7843. ASSERT_TRUE(res);
  7844. }
  7845. }
  7846. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7847. Server svr;
  7848. svr.set_error_handler([](Request const &, Response &res) -> void {
  7849. res.set_chunked_content_provider(
  7850. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7851. sink.os << "hello";
  7852. sink.os << "world";
  7853. sink.done();
  7854. return true;
  7855. });
  7856. });
  7857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7858. auto se = detail::scope_exit([&] {
  7859. svr.stop();
  7860. listen_thread.join();
  7861. ASSERT_FALSE(svr.is_running());
  7862. });
  7863. svr.wait_until_ready();
  7864. Client cli("localhost", PORT);
  7865. auto res = cli.Get("/");
  7866. ASSERT_TRUE(res);
  7867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7868. EXPECT_EQ("helloworld", res->body);
  7869. }
  7870. TEST(LongPollingTest, ClientCloseDetection) {
  7871. Server svr;
  7872. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7873. res.set_chunked_content_provider(
  7874. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7875. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7876. sink.os << "hello";
  7877. auto count = 10;
  7878. while (count > 0 && sink.is_writable()) {
  7879. this_thread::sleep_for(chrono::milliseconds(10));
  7880. count--;
  7881. }
  7882. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7883. return true;
  7884. });
  7885. });
  7886. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7887. auto se = detail::scope_exit([&] {
  7888. svr.stop();
  7889. listen_thread.join();
  7890. ASSERT_FALSE(svr.is_running());
  7891. });
  7892. svr.wait_until_ready();
  7893. Client cli("localhost", PORT);
  7894. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7895. EXPECT_EQ("hello", string(data, data_length));
  7896. return false; // close the socket immediately.
  7897. });
  7898. ASSERT_FALSE(res);
  7899. }
  7900. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7901. Server svr;
  7902. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7903. res.set_chunked_content_provider(
  7904. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7905. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7906. sink.os << "hello";
  7907. EXPECT_TRUE(sink.os.good());
  7908. // Wait for the client to close the connection
  7909. auto count = 10;
  7910. while (count > 0 && sink.is_writable()) {
  7911. this_thread::sleep_for(chrono::milliseconds(10));
  7912. count--;
  7913. }
  7914. // After client disconnect, write repeatedly until the socket
  7915. // write actually fails (small writes may be absorbed by the
  7916. // kernel buffer)
  7917. std::string chunk(1024, 'x');
  7918. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7919. sink.os << chunk;
  7920. }
  7921. EXPECT_TRUE(sink.os.fail());
  7922. return true;
  7923. });
  7924. });
  7925. auto port = svr.bind_to_any_port("localhost");
  7926. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7927. auto se = detail::scope_exit([&] {
  7928. svr.stop();
  7929. listen_thread.join();
  7930. ASSERT_FALSE(svr.is_running());
  7931. });
  7932. svr.wait_until_ready();
  7933. Client cli("localhost", port);
  7934. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7935. EXPECT_EQ("hello", string(data, data_length));
  7936. return false; // close the socket immediately.
  7937. });
  7938. ASSERT_FALSE(res);
  7939. }
  7940. TEST(GetWithParametersTest, GetWithParameters) {
  7941. Server svr;
  7942. svr.Get("/", [&](const Request &req, Response &) {
  7943. EXPECT_EQ("world", req.get_param_value("hello"));
  7944. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7945. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7946. });
  7947. svr.Get("/params", [&](const Request &req, Response &) {
  7948. EXPECT_EQ("world", req.get_param_value("hello"));
  7949. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7950. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7951. });
  7952. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7953. EXPECT_EQ("resource-id", req.matches[1]);
  7954. EXPECT_EQ("foo", req.get_param_value("param1"));
  7955. EXPECT_EQ("bar", req.get_param_value("param2"));
  7956. });
  7957. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7958. EXPECT_EQ("user-id", req.path_params.at("id"));
  7959. EXPECT_EQ("foo", req.get_param_value("param1"));
  7960. EXPECT_EQ("bar", req.get_param_value("param2"));
  7961. });
  7962. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7963. auto se = detail::scope_exit([&] {
  7964. svr.stop();
  7965. listen_thread.join();
  7966. ASSERT_FALSE(svr.is_running());
  7967. });
  7968. svr.wait_until_ready();
  7969. {
  7970. Client cli(HOST, PORT);
  7971. Params params;
  7972. params.emplace("hello", "world");
  7973. params.emplace("hello2", "world2");
  7974. params.emplace("hello3", "world3");
  7975. auto res = cli.Get("/", params, Headers{});
  7976. ASSERT_TRUE(res);
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. }
  7979. {
  7980. Client cli(HOST, PORT);
  7981. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7982. ASSERT_TRUE(res);
  7983. EXPECT_EQ(StatusCode::OK_200, res->status);
  7984. }
  7985. {
  7986. Client cli(HOST, PORT);
  7987. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7988. ASSERT_TRUE(res);
  7989. EXPECT_EQ(StatusCode::OK_200, res->status);
  7990. }
  7991. {
  7992. Client cli(HOST, PORT);
  7993. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7994. ASSERT_TRUE(res);
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. }
  7997. }
  7998. TEST(GetWithParametersTest, GetWithParameters2) {
  7999. Server svr;
  8000. svr.Get("/", [&](const Request &req, Response &res) {
  8001. auto text = req.get_param_value("hello");
  8002. res.set_content(text, "text/plain");
  8003. });
  8004. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8005. auto se = detail::scope_exit([&] {
  8006. svr.stop();
  8007. listen_thread.join();
  8008. ASSERT_FALSE(svr.is_running());
  8009. });
  8010. svr.wait_until_ready();
  8011. Client cli("localhost", PORT);
  8012. Params params;
  8013. params.emplace("hello", "world");
  8014. std::string body;
  8015. auto res = cli.Get("/", params, Headers{},
  8016. [&](const char *data, size_t data_length) {
  8017. body.append(data, data_length);
  8018. return true;
  8019. });
  8020. ASSERT_TRUE(res);
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. EXPECT_EQ("world", body);
  8023. }
  8024. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8025. Server svr;
  8026. svr.Get("/search", [&](const Request &req, Response &res) {
  8027. auto q = req.get_param_value("q");
  8028. res.set_content(q, "text/plain");
  8029. });
  8030. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8031. auto se = detail::scope_exit([&] {
  8032. svr.stop();
  8033. listen_thread.join();
  8034. ASSERT_FALSE(svr.is_running());
  8035. });
  8036. svr.wait_until_ready();
  8037. Client cli("localhost", PORT);
  8038. // Verify that Get(path, params) works without requiring Headers argument
  8039. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8040. ASSERT_TRUE(res);
  8041. EXPECT_EQ(StatusCode::OK_200, res->status);
  8042. EXPECT_EQ("cpp-httplib", res->body);
  8043. }
  8044. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8045. auto host = "httpbingo.org";
  8046. auto path = std::string{"/range/32"};
  8047. #ifdef CPPHTTPLIB_SSL_ENABLED
  8048. SSLClient cli(host);
  8049. #else
  8050. Client cli(host);
  8051. #endif
  8052. cli.set_default_headers({make_range_header({{1, 10}})});
  8053. cli.set_connection_timeout(5);
  8054. {
  8055. auto res = cli.Get(path);
  8056. ASSERT_TRUE(res);
  8057. EXPECT_EQ("bcdefghijk", res->body);
  8058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8059. }
  8060. {
  8061. auto res = cli.Get(path);
  8062. ASSERT_TRUE(res);
  8063. EXPECT_EQ("bcdefghijk", res->body);
  8064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8065. }
  8066. }
  8067. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8068. Server svr;
  8069. svr.set_default_headers({{"Hello", "World"}});
  8070. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8071. res.set_content("ok", "text/plain");
  8072. });
  8073. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8074. auto se = detail::scope_exit([&] {
  8075. svr.stop();
  8076. listen_thread.join();
  8077. ASSERT_FALSE(svr.is_running());
  8078. });
  8079. svr.wait_until_ready();
  8080. Client cli("localhost", PORT);
  8081. auto res = cli.Get("/");
  8082. ASSERT_TRUE(res);
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. EXPECT_EQ("ok", res->body);
  8085. EXPECT_EQ("World", res->get_header_value("Hello"));
  8086. }
  8087. #ifdef CPPHTTPLIB_SSL_ENABLED
  8088. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8090. ASSERT_TRUE(svr.is_valid());
  8091. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8092. std::this_thread::sleep_for(std::chrono::seconds(2));
  8093. res.set_content("a", "text/plain");
  8094. });
  8095. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8096. res.set_content("b", "text/plain");
  8097. });
  8098. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8099. auto se = detail::scope_exit([&] {
  8100. svr.stop();
  8101. listen_thread.join();
  8102. ASSERT_FALSE(svr.is_running());
  8103. });
  8104. svr.wait_until_ready();
  8105. SSLClient cli("localhost", PORT);
  8106. cli.enable_server_certificate_verification(false);
  8107. cli.set_keep_alive(true);
  8108. cli.set_read_timeout(std::chrono::seconds(1));
  8109. auto resa = cli.Get("/a");
  8110. ASSERT_TRUE(!resa);
  8111. EXPECT_EQ(Error::Read, resa.error());
  8112. auto resb = cli.Get("/b");
  8113. ASSERT_TRUE(resb);
  8114. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8115. EXPECT_EQ("b", resb->body);
  8116. }
  8117. #endif
  8118. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8119. protected:
  8120. ServerTestWithAI_PASSIVE()
  8121. : cli_(HOST, PORT)
  8122. #ifdef CPPHTTPLIB_SSL_ENABLED
  8123. ,
  8124. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8125. #endif
  8126. {
  8127. #ifdef CPPHTTPLIB_SSL_ENABLED
  8128. cli_.enable_server_certificate_verification(false);
  8129. #endif
  8130. }
  8131. virtual void SetUp() {
  8132. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8133. res.set_content("Hello World!", "text/plain");
  8134. });
  8135. t_ = thread(
  8136. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8137. svr_.wait_until_ready();
  8138. }
  8139. virtual void TearDown() {
  8140. svr_.stop();
  8141. t_.join();
  8142. }
  8143. #ifdef CPPHTTPLIB_SSL_ENABLED
  8144. SSLClient cli_;
  8145. SSLServer svr_;
  8146. #else
  8147. Client cli_;
  8148. Server svr_;
  8149. #endif
  8150. thread t_;
  8151. };
  8152. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8153. auto res = cli_.Get("/hi");
  8154. ASSERT_TRUE(res);
  8155. EXPECT_EQ(StatusCode::OK_200, res->status);
  8156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8157. EXPECT_EQ("Hello World!", res->body);
  8158. }
  8159. class ServerUpDownTest : public ::testing::Test {
  8160. protected:
  8161. ServerUpDownTest() : cli_(HOST, PORT) {}
  8162. virtual void SetUp() {
  8163. t_ = thread([&]() {
  8164. svr_.bind_to_any_port(HOST);
  8165. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8166. ASSERT_TRUE(svr_.listen_after_bind());
  8167. });
  8168. svr_.wait_until_ready();
  8169. }
  8170. virtual void TearDown() {
  8171. svr_.stop();
  8172. t_.join();
  8173. }
  8174. Client cli_;
  8175. Server svr_;
  8176. thread t_;
  8177. };
  8178. TEST_F(ServerUpDownTest, QuickStartStop) {
  8179. // Should not crash, especially when run with
  8180. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8181. }
  8182. class PayloadMaxLengthTest : public ::testing::Test {
  8183. protected:
  8184. PayloadMaxLengthTest()
  8185. : cli_(HOST, PORT)
  8186. #ifdef CPPHTTPLIB_SSL_ENABLED
  8187. ,
  8188. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8189. #endif
  8190. {
  8191. #ifdef CPPHTTPLIB_SSL_ENABLED
  8192. cli_.enable_server_certificate_verification(false);
  8193. #endif
  8194. }
  8195. virtual void SetUp() {
  8196. svr_.set_payload_max_length(8);
  8197. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8198. res.set_content("test", "text/plain");
  8199. });
  8200. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8201. svr_.wait_until_ready();
  8202. }
  8203. virtual void TearDown() {
  8204. svr_.stop();
  8205. t_.join();
  8206. }
  8207. #ifdef CPPHTTPLIB_SSL_ENABLED
  8208. SSLClient cli_;
  8209. SSLServer svr_;
  8210. #else
  8211. Client cli_;
  8212. Server svr_;
  8213. #endif
  8214. thread t_;
  8215. };
  8216. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8217. auto res = cli_.Post("/test", "123456789", "text/plain");
  8218. ASSERT_TRUE(res);
  8219. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8220. res = cli_.Post("/test", "12345678", "text/plain");
  8221. ASSERT_TRUE(res);
  8222. EXPECT_EQ(StatusCode::OK_200, res->status);
  8223. }
  8224. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8225. // Test chunked encoding with payload exceeding the 8-byte limit
  8226. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8227. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8228. ASSERT_TRUE(res);
  8229. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8230. }
  8231. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8232. // Test chunked encoding with payload within the 8-byte limit
  8233. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8234. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8235. ASSERT_TRUE(res);
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. }
  8238. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8239. // Test using send_request to send chunked data exceeding payload limit
  8240. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8241. "Host: " +
  8242. std::string(HOST) + ":" + std::to_string(PORT) +
  8243. "\r\n"
  8244. "Transfer-Encoding: chunked\r\n"
  8245. "Connection: close\r\n"
  8246. "\r\n"
  8247. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8248. "0123456789\r\n"
  8249. "0\r\n" // End chunk
  8250. "\r\n";
  8251. std::string response;
  8252. bool result = send_request(1, chunked_request, &response);
  8253. if (!result) {
  8254. // If send_request fails, it might be because the server closed the
  8255. // connection due to payload limit enforcement, which is acceptable
  8256. SUCCEED()
  8257. << "Server rejected oversized chunked request (connection closed)";
  8258. } else {
  8259. // If we got a response, check if it's an error response or connection was
  8260. // closed early Short response length indicates connection was closed due to
  8261. // payload limit
  8262. if (response.length() <= 10) {
  8263. SUCCEED() << "Server closed connection for oversized chunked request";
  8264. } else {
  8265. // Check for error status codes
  8266. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8267. response.find("Payload Too Large") != std::string::npos ||
  8268. response.find("400") != std::string::npos);
  8269. }
  8270. }
  8271. }
  8272. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8273. // Test request without Content-Length header exceeding payload limit
  8274. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8275. "Host: " +
  8276. std::string(HOST) + ":" +
  8277. std::to_string(PORT) +
  8278. "\r\n"
  8279. "Connection: close\r\n"
  8280. "\r\n";
  8281. // Add payload exceeding the 8-byte limit
  8282. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8283. request_without_content_length += large_payload;
  8284. std::string response;
  8285. bool result = send_request(1, request_without_content_length, &response);
  8286. if (!result) {
  8287. // If send_request fails, server likely closed connection due to payload
  8288. // limit
  8289. SUCCEED() << "Server rejected oversized request without Content-Length "
  8290. "(connection closed)";
  8291. } else {
  8292. // Check if server responded with error or closed connection early
  8293. if (response.length() <= 10) {
  8294. SUCCEED() << "Server closed connection for oversized request without "
  8295. "Content-Length";
  8296. } else {
  8297. // Check for error status codes
  8298. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8299. response.find("Payload Too Large") != std::string::npos ||
  8300. response.find("400") != std::string::npos);
  8301. }
  8302. }
  8303. }
  8304. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8305. // Test request without Content-Length header within payload limit
  8306. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8307. "Host: " +
  8308. std::string(HOST) + ":" +
  8309. std::to_string(PORT) +
  8310. "\r\n"
  8311. "Connection: close\r\n"
  8312. "\r\n";
  8313. // Add payload within the 8-byte limit
  8314. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8315. request_without_content_length += small_payload;
  8316. std::string response;
  8317. bool result = send_request(1, request_without_content_length, &response);
  8318. // For requests without Content-Length, the server may have different behavior
  8319. // The key is that it should not reject due to payload limit for small
  8320. // payloads
  8321. if (result) {
  8322. // Check for any HTTP response (success or error, but not connection closed)
  8323. if (response.length() > 10) {
  8324. SUCCEED()
  8325. << "Server processed request without Content-Length within limit";
  8326. } else {
  8327. // Short response might indicate connection closed, which is acceptable
  8328. SUCCEED() << "Server closed connection for request without "
  8329. "Content-Length (acceptable behavior)";
  8330. }
  8331. } else {
  8332. // Connection failure might be due to protocol requirements
  8333. SUCCEED() << "Connection issue with request without Content-Length "
  8334. "(environment-specific)";
  8335. }
  8336. }
  8337. class LargePayloadMaxLengthTest : public ::testing::Test {
  8338. protected:
  8339. LargePayloadMaxLengthTest()
  8340. : cli_(HOST, PORT)
  8341. #ifdef CPPHTTPLIB_SSL_ENABLED
  8342. ,
  8343. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8344. #endif
  8345. {
  8346. #ifdef CPPHTTPLIB_SSL_ENABLED
  8347. cli_.enable_server_certificate_verification(false);
  8348. #endif
  8349. }
  8350. virtual void SetUp() {
  8351. // Set 10MB payload limit
  8352. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8353. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8354. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8355. res.set_content("Large payload test", "text/plain");
  8356. });
  8357. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8358. svr_.wait_until_ready();
  8359. }
  8360. virtual void TearDown() {
  8361. svr_.stop();
  8362. t_.join();
  8363. }
  8364. #ifdef CPPHTTPLIB_SSL_ENABLED
  8365. SSLClient cli_;
  8366. SSLServer svr_;
  8367. #else
  8368. Client cli_;
  8369. Server svr_;
  8370. #endif
  8371. thread t_;
  8372. };
  8373. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8374. // Test chunked encoding with payload within 10MB limit
  8375. std::string medium_payload(5 * 1024 * 1024,
  8376. 'A'); // 5MB payload, within 10MB limit
  8377. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8378. ASSERT_TRUE(res);
  8379. EXPECT_EQ(StatusCode::OK_200, res->status);
  8380. }
  8381. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8382. // Test chunked encoding with payload exceeding 10MB limit
  8383. std::string large_payload(12 * 1024 * 1024,
  8384. 'B'); // 12MB payload, exceeds 10MB limit
  8385. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8386. // Server may either return 413 or close the connection
  8387. if (res) {
  8388. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8389. } else {
  8390. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8391. }
  8392. }
  8393. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8394. // Test request without Content-Length header within 10MB limit
  8395. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8396. "Host: " +
  8397. std::string(HOST) + ":" +
  8398. std::to_string(PORT) +
  8399. "\r\n"
  8400. "Connection: close\r\n"
  8401. "\r\n";
  8402. // Add 1MB payload (within 10MB limit)
  8403. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8404. request_without_content_length += medium_payload;
  8405. std::string response;
  8406. bool result = send_request(5, request_without_content_length, &response);
  8407. if (result) {
  8408. // Should get a proper HTTP response for payloads within limit
  8409. if (response.length() > 10) {
  8410. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8411. "10MB limit";
  8412. } else {
  8413. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8414. "Content-Length)";
  8415. }
  8416. } else {
  8417. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8418. }
  8419. }
  8420. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8421. // Test request without Content-Length header exceeding 10MB limit
  8422. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8423. "Host: " +
  8424. std::string(HOST) + ":" +
  8425. std::to_string(PORT) +
  8426. "\r\n"
  8427. "Connection: close\r\n"
  8428. "\r\n";
  8429. // Add 12MB payload (exceeds 10MB limit)
  8430. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8431. request_without_content_length += large_payload;
  8432. std::string response;
  8433. bool result = send_request(10, request_without_content_length, &response);
  8434. if (!result) {
  8435. // Server should close connection due to payload limit
  8436. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8437. "(connection closed)";
  8438. } else {
  8439. // Check for error response
  8440. if (response.length() <= 10) {
  8441. SUCCEED()
  8442. << "Server closed connection for 12MB request exceeding 10MB limit";
  8443. } else {
  8444. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8445. response.find("Payload Too Large") != std::string::npos ||
  8446. response.find("400") != std::string::npos);
  8447. }
  8448. }
  8449. }
  8450. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8451. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8452. // path.
  8453. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8454. Server svr;
  8455. const size_t LIMIT = 64 * 1024; // 64KB
  8456. svr.set_payload_max_length(LIMIT);
  8457. size_t total = 0;
  8458. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8459. const ContentReader &content_reader) {
  8460. content_reader([&](const char * /*data*/, size_t len) {
  8461. total += len;
  8462. return true;
  8463. });
  8464. res.status = 200;
  8465. res.set_content("stream_ok", "text/plain");
  8466. });
  8467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8468. auto se = detail::scope_exit([&] {
  8469. svr.stop();
  8470. thread.join();
  8471. ASSERT_FALSE(svr.is_running());
  8472. });
  8473. svr.wait_until_ready();
  8474. // Prepare 256KB raw data and gzip-compress it
  8475. std::string raw(256 * 1024, 'A');
  8476. std::string gz;
  8477. {
  8478. z_stream zs{};
  8479. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8480. Z_DEFAULT_STRATEGY);
  8481. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8482. zs.avail_in = static_cast<uInt>(raw.size());
  8483. char outbuf[4096];
  8484. int ret;
  8485. do {
  8486. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8487. zs.avail_out = sizeof(outbuf);
  8488. ret = deflate(&zs, Z_FINISH);
  8489. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8490. } while (ret != Z_STREAM_END);
  8491. deflateEnd(&zs);
  8492. }
  8493. Client cli(HOST, PORT);
  8494. cli.set_connection_timeout(std::chrono::seconds(5));
  8495. Headers headers = {{"Content-Encoding", "gzip"}};
  8496. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8497. "application/octet-stream");
  8498. ASSERT_TRUE(res);
  8499. // Server must reject oversized decompressed payloads with 413.
  8500. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8501. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8502. EXPECT_LE(total, LIMIT);
  8503. }
  8504. #endif
  8505. // Regression test for DoS vulnerability: a malicious server sending a response
  8506. // without Content-Length header must not cause unbounded memory consumption on
  8507. // the client side. The client should stop reading after a reasonable limit,
  8508. // similar to the server-side set_payload_max_length protection.
  8509. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8510. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8511. #ifndef _WIN32
  8512. signal(SIGPIPE, SIG_IGN);
  8513. #endif
  8514. auto server_thread = std::thread([] {
  8515. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8516. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8517. default_socket_options(srv);
  8518. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8519. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8520. sockaddr_in addr{};
  8521. addr.sin_family = AF_INET;
  8522. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8523. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8524. int opt = 1;
  8525. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8526. #ifdef _WIN32
  8527. reinterpret_cast<const char *>(&opt),
  8528. #else
  8529. &opt,
  8530. #endif
  8531. sizeof(opt));
  8532. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8533. ::listen(srv, 1);
  8534. sockaddr_in cli_addr{};
  8535. socklen_t cli_len = sizeof(cli_addr);
  8536. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8537. if (cli != INVALID_SOCKET) {
  8538. char buf[4096];
  8539. ::recv(cli, buf, sizeof(buf), 0);
  8540. // Malicious response: no Content-Length, no chunked encoding
  8541. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8542. "Connection: close\r\n"
  8543. "\r\n";
  8544. ::send(cli,
  8545. #ifdef _WIN32
  8546. static_cast<const char *>(response_header.c_str()),
  8547. static_cast<int>(response_header.size()),
  8548. #else
  8549. response_header.c_str(), response_header.size(),
  8550. #endif
  8551. 0);
  8552. // Send 10MB of data
  8553. std::string chunk(64 * 1024, 'A');
  8554. size_t total_sent = 0;
  8555. while (total_sent < MALICIOUS_DATA_SIZE) {
  8556. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8557. auto sent = ::send(cli,
  8558. #ifdef _WIN32
  8559. static_cast<const char *>(chunk.c_str()),
  8560. static_cast<int>(to_send),
  8561. #else
  8562. chunk.c_str(), to_send,
  8563. #endif
  8564. 0);
  8565. if (sent <= 0) break;
  8566. total_sent += static_cast<size_t>(sent);
  8567. }
  8568. detail::close_socket(cli);
  8569. }
  8570. detail::close_socket(srv);
  8571. });
  8572. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8573. size_t total_read = 0;
  8574. {
  8575. Client cli("127.0.0.1", PORT + 2);
  8576. cli.set_read_timeout(5, 0);
  8577. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8578. auto stream = cli.open_stream("GET", "/malicious");
  8579. ASSERT_TRUE(stream.is_valid());
  8580. char buffer[64 * 1024];
  8581. ssize_t n;
  8582. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8583. total_read += static_cast<size_t>(n);
  8584. }
  8585. } // StreamHandle and Client destroyed here, closing the socket
  8586. server_thread.join();
  8587. // With set_payload_max_length, the client must stop reading before consuming
  8588. // all 10MB. The read loop should be cut off at or near the configured limit.
  8589. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8590. << "Client read " << total_read << " bytes, exceeding the configured "
  8591. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8592. }
  8593. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8594. // the entire response body without truncation.
  8595. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8596. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8597. #ifndef _WIN32
  8598. signal(SIGPIPE, SIG_IGN);
  8599. #endif
  8600. auto server_thread = std::thread([] {
  8601. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8602. default_socket_options(srv);
  8603. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8604. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8605. sockaddr_in addr{};
  8606. addr.sin_family = AF_INET;
  8607. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8608. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8609. int opt = 1;
  8610. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8611. #ifdef _WIN32
  8612. reinterpret_cast<const char *>(&opt),
  8613. #else
  8614. &opt,
  8615. #endif
  8616. sizeof(opt));
  8617. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8618. ::listen(srv, 1);
  8619. sockaddr_in cli_addr{};
  8620. socklen_t cli_len = sizeof(cli_addr);
  8621. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8622. if (cli != INVALID_SOCKET) {
  8623. char buf[4096];
  8624. ::recv(cli, buf, sizeof(buf), 0);
  8625. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8626. "Connection: close\r\n"
  8627. "\r\n";
  8628. ::send(cli,
  8629. #ifdef _WIN32
  8630. static_cast<const char *>(response_header.c_str()),
  8631. static_cast<int>(response_header.size()),
  8632. #else
  8633. response_header.c_str(), response_header.size(),
  8634. #endif
  8635. 0);
  8636. std::string chunk(64 * 1024, 'A');
  8637. size_t total_sent = 0;
  8638. while (total_sent < DATA_SIZE) {
  8639. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8640. auto sent = ::send(cli,
  8641. #ifdef _WIN32
  8642. static_cast<const char *>(chunk.c_str()),
  8643. static_cast<int>(to_send),
  8644. #else
  8645. chunk.c_str(), to_send,
  8646. #endif
  8647. 0);
  8648. if (sent <= 0) break;
  8649. total_sent += static_cast<size_t>(sent);
  8650. }
  8651. #ifdef _WIN32
  8652. ::shutdown(cli, SD_SEND);
  8653. #else
  8654. ::shutdown(cli, SHUT_WR);
  8655. #endif
  8656. // Drain until the client closes its end, ensuring all data is delivered
  8657. char drain[1024];
  8658. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8659. detail::close_socket(cli);
  8660. }
  8661. detail::close_socket(srv);
  8662. });
  8663. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8664. size_t total_read = 0;
  8665. {
  8666. Client cli("127.0.0.1", PORT + 2);
  8667. cli.set_read_timeout(5, 0);
  8668. cli.set_payload_max_length(0); // 0 means no limit
  8669. auto stream = cli.open_stream("GET", "/data");
  8670. ASSERT_TRUE(stream.is_valid());
  8671. char buffer[64 * 1024];
  8672. ssize_t n;
  8673. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8674. total_read += static_cast<size_t>(n);
  8675. }
  8676. }
  8677. server_thread.join();
  8678. EXPECT_EQ(total_read, DATA_SIZE)
  8679. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8680. << " bytes without truncation, but only read " << total_read << " bytes.";
  8681. }
  8682. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8683. // enormous Content-Length must not cause the client to pre-allocate a huge
  8684. // response body buffer. The reservation is capped at payload_max_length_, and
  8685. // the read itself fails when the body exceeds the limit.
  8686. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8687. #ifndef _WIN32
  8688. signal(SIGPIPE, SIG_IGN);
  8689. #endif
  8690. auto server_thread = std::thread([] {
  8691. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8692. default_socket_options(srv);
  8693. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8694. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8695. sockaddr_in addr{};
  8696. addr.sin_family = AF_INET;
  8697. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8698. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8699. int opt = 1;
  8700. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8701. #ifdef _WIN32
  8702. reinterpret_cast<const char *>(&opt),
  8703. #else
  8704. &opt,
  8705. #endif
  8706. sizeof(opt));
  8707. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8708. ::listen(srv, 1);
  8709. sockaddr_in cli_addr{};
  8710. socklen_t cli_len = sizeof(cli_addr);
  8711. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8712. if (cli != INVALID_SOCKET) {
  8713. char buf[4096];
  8714. ::recv(cli, buf, sizeof(buf), 0);
  8715. // Malicious response: claim a 20GB body but send only a tiny payload.
  8716. std::string response = "HTTP/1.1 200 OK\r\n"
  8717. "Content-Length: 20000000000\r\n"
  8718. "\r\n"
  8719. "abc";
  8720. ::send(cli,
  8721. #ifdef _WIN32
  8722. static_cast<const char *>(response.c_str()),
  8723. static_cast<int>(response.size()),
  8724. #else
  8725. response.c_str(), response.size(),
  8726. #endif
  8727. 0);
  8728. detail::close_socket(cli);
  8729. }
  8730. detail::close_socket(srv);
  8731. });
  8732. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8733. {
  8734. Client cli("127.0.0.1", PORT + 2);
  8735. cli.set_read_timeout(5, 0);
  8736. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8737. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8738. // (server claims more bytes than payload_max_length permits), but it must
  8739. // not exhaust memory before getting there.
  8740. auto res = cli.Get("/malicious");
  8741. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8742. }
  8743. server_thread.join();
  8744. }
  8745. // Verify that content_receiver bypasses the default payload_max_length,
  8746. // allowing streaming downloads larger than 100MB without requiring an explicit
  8747. // set_payload_max_length call.
  8748. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8749. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8750. #ifndef _WIN32
  8751. signal(SIGPIPE, SIG_IGN);
  8752. #endif
  8753. auto server_thread = std::thread([] {
  8754. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8755. default_socket_options(srv);
  8756. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8757. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8758. sockaddr_in addr{};
  8759. addr.sin_family = AF_INET;
  8760. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8761. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8762. int opt = 1;
  8763. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8764. #ifdef _WIN32
  8765. reinterpret_cast<const char *>(&opt),
  8766. #else
  8767. &opt,
  8768. #endif
  8769. sizeof(opt));
  8770. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8771. ::listen(srv, 1);
  8772. sockaddr_in cli_addr{};
  8773. socklen_t cli_len = sizeof(cli_addr);
  8774. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8775. if (cli != INVALID_SOCKET) {
  8776. char buf[4096];
  8777. ::recv(cli, buf, sizeof(buf), 0);
  8778. // Response with Content-Length larger than default 100MB limit
  8779. auto content_length = std::to_string(DATA_SIZE);
  8780. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8781. "Content-Length: " +
  8782. content_length +
  8783. "\r\n"
  8784. "Connection: close\r\n"
  8785. "\r\n";
  8786. ::send(cli,
  8787. #ifdef _WIN32
  8788. static_cast<const char *>(response_header.c_str()),
  8789. static_cast<int>(response_header.size()),
  8790. #else
  8791. response_header.c_str(), response_header.size(),
  8792. #endif
  8793. 0);
  8794. std::string chunk(64 * 1024, 'A');
  8795. size_t total_sent = 0;
  8796. while (total_sent < DATA_SIZE) {
  8797. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8798. auto sent = ::send(cli,
  8799. #ifdef _WIN32
  8800. static_cast<const char *>(chunk.c_str()),
  8801. static_cast<int>(to_send),
  8802. #else
  8803. chunk.c_str(), to_send,
  8804. #endif
  8805. 0);
  8806. if (sent <= 0) break;
  8807. total_sent += static_cast<size_t>(sent);
  8808. }
  8809. detail::close_socket(cli);
  8810. }
  8811. detail::close_socket(srv);
  8812. });
  8813. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8814. size_t total_received = 0;
  8815. {
  8816. Client cli("127.0.0.1", PORT + 2);
  8817. cli.set_read_timeout(10, 0);
  8818. // Do NOT call set_payload_max_length — use the default 100MB limit
  8819. auto res =
  8820. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8821. total_received += data_length;
  8822. return true;
  8823. });
  8824. ASSERT_TRUE(res);
  8825. EXPECT_EQ(StatusCode::OK_200, res->status);
  8826. }
  8827. server_thread.join();
  8828. EXPECT_EQ(total_received, DATA_SIZE)
  8829. << "With content_receiver, the client should read all " << DATA_SIZE
  8830. << " bytes despite the default 100MB payload_max_length, but only read "
  8831. << total_received << " bytes.";
  8832. }
  8833. // Verify that an explicit set_payload_max_length smaller than the response is
  8834. // enforced even when a content_receiver is used.
  8835. TEST(ClientVulnerabilityTest,
  8836. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8837. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8838. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8839. #ifndef _WIN32
  8840. signal(SIGPIPE, SIG_IGN);
  8841. #endif
  8842. auto server_thread = std::thread([] {
  8843. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8844. default_socket_options(srv);
  8845. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8846. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8847. sockaddr_in addr{};
  8848. addr.sin_family = AF_INET;
  8849. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8850. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8851. int opt = 1;
  8852. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8853. #ifdef _WIN32
  8854. reinterpret_cast<const char *>(&opt),
  8855. #else
  8856. &opt,
  8857. #endif
  8858. sizeof(opt));
  8859. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8860. ::listen(srv, 1);
  8861. sockaddr_in cli_addr{};
  8862. socklen_t cli_len = sizeof(cli_addr);
  8863. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8864. if (cli != INVALID_SOCKET) {
  8865. char buf[4096];
  8866. ::recv(cli, buf, sizeof(buf), 0);
  8867. auto content_length = std::to_string(DATA_SIZE);
  8868. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8869. "Content-Length: " +
  8870. content_length +
  8871. "\r\n"
  8872. "Connection: close\r\n"
  8873. "\r\n";
  8874. ::send(cli,
  8875. #ifdef _WIN32
  8876. static_cast<const char *>(response_header.c_str()),
  8877. static_cast<int>(response_header.size()),
  8878. #else
  8879. response_header.c_str(), response_header.size(),
  8880. #endif
  8881. 0);
  8882. std::string chunk(64 * 1024, 'A');
  8883. size_t total_sent = 0;
  8884. while (total_sent < DATA_SIZE) {
  8885. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8886. auto sent = ::send(cli,
  8887. #ifdef _WIN32
  8888. static_cast<const char *>(chunk.c_str()),
  8889. static_cast<int>(to_send),
  8890. #else
  8891. chunk.c_str(), to_send,
  8892. #endif
  8893. 0);
  8894. if (sent <= 0) break;
  8895. total_sent += static_cast<size_t>(sent);
  8896. }
  8897. detail::close_socket(cli);
  8898. }
  8899. detail::close_socket(srv);
  8900. });
  8901. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8902. size_t total_received = 0;
  8903. {
  8904. Client cli("127.0.0.1", PORT + 2);
  8905. cli.set_read_timeout(10, 0);
  8906. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8907. auto res =
  8908. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8909. total_received += data_length;
  8910. return true;
  8911. });
  8912. // Should fail because 200MB exceeds the explicit 150MB limit
  8913. EXPECT_FALSE(res);
  8914. }
  8915. server_thread.join();
  8916. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8917. << "Client with content_receiver should respect the explicit "
  8918. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8919. << total_received << " bytes.";
  8920. }
  8921. // Verify that an explicit set_payload_max_length larger than the response
  8922. // allows the content_receiver to read all data successfully.
  8923. TEST(ClientVulnerabilityTest,
  8924. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8925. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8926. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8927. #ifndef _WIN32
  8928. signal(SIGPIPE, SIG_IGN);
  8929. #endif
  8930. auto server_thread = std::thread([] {
  8931. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8932. default_socket_options(srv);
  8933. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8934. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8935. sockaddr_in addr{};
  8936. addr.sin_family = AF_INET;
  8937. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8938. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8939. int opt = 1;
  8940. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8941. #ifdef _WIN32
  8942. reinterpret_cast<const char *>(&opt),
  8943. #else
  8944. &opt,
  8945. #endif
  8946. sizeof(opt));
  8947. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8948. ::listen(srv, 1);
  8949. sockaddr_in cli_addr{};
  8950. socklen_t cli_len = sizeof(cli_addr);
  8951. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8952. if (cli != INVALID_SOCKET) {
  8953. char buf[4096];
  8954. ::recv(cli, buf, sizeof(buf), 0);
  8955. auto content_length = std::to_string(DATA_SIZE);
  8956. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8957. "Content-Length: " +
  8958. content_length +
  8959. "\r\n"
  8960. "Connection: close\r\n"
  8961. "\r\n";
  8962. ::send(cli,
  8963. #ifdef _WIN32
  8964. static_cast<const char *>(response_header.c_str()),
  8965. static_cast<int>(response_header.size()),
  8966. #else
  8967. response_header.c_str(), response_header.size(),
  8968. #endif
  8969. 0);
  8970. std::string chunk(64 * 1024, 'A');
  8971. size_t total_sent = 0;
  8972. while (total_sent < DATA_SIZE) {
  8973. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8974. auto sent = ::send(cli,
  8975. #ifdef _WIN32
  8976. static_cast<const char *>(chunk.c_str()),
  8977. static_cast<int>(to_send),
  8978. #else
  8979. chunk.c_str(), to_send,
  8980. #endif
  8981. 0);
  8982. if (sent <= 0) break;
  8983. total_sent += static_cast<size_t>(sent);
  8984. }
  8985. #ifdef _WIN32
  8986. ::shutdown(cli, SD_SEND);
  8987. #else
  8988. ::shutdown(cli, SHUT_WR);
  8989. #endif
  8990. char drain[1024];
  8991. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8992. detail::close_socket(cli);
  8993. }
  8994. detail::close_socket(srv);
  8995. });
  8996. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8997. size_t total_received = 0;
  8998. {
  8999. Client cli("127.0.0.1", PORT + 2);
  9000. cli.set_read_timeout(10, 0);
  9001. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9002. auto res =
  9003. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9004. total_received += data_length;
  9005. return true;
  9006. });
  9007. ASSERT_TRUE(res);
  9008. EXPECT_EQ(StatusCode::OK_200, res->status);
  9009. }
  9010. server_thread.join();
  9011. EXPECT_EQ(total_received, DATA_SIZE)
  9012. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9013. << " bytes (larger than " << DATA_SIZE
  9014. << " bytes response), content_receiver should read all data, but only "
  9015. "read "
  9016. << total_received << " bytes.";
  9017. }
  9018. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9019. // Regression test for "zip bomb" attack on the client side: a malicious server
  9020. // sends a small gzip-compressed response that decompresses to a huge payload.
  9021. // The client must enforce payload_max_length on the decompressed size.
  9022. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9023. constexpr size_t DECOMPRESSED_SIZE =
  9024. 10 * 1024 * 1024; // 10MB after decompression
  9025. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9026. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9027. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9028. std::string compressed;
  9029. {
  9030. httplib::detail::gzip_compressor compressor;
  9031. bool ok =
  9032. compressor.compress(uncompressed.data(), uncompressed.size(),
  9033. /*last=*/true, [&](const char *buf, size_t len) {
  9034. compressed.append(buf, len);
  9035. return true;
  9036. });
  9037. ASSERT_TRUE(ok);
  9038. }
  9039. // Sanity: compressed data should be much smaller than the decompressed size
  9040. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9041. #ifndef _WIN32
  9042. signal(SIGPIPE, SIG_IGN);
  9043. #endif
  9044. // Set up the listening socket in the main thread so the server is guaranteed
  9045. // to be ready before the client connects (eliminates race condition).
  9046. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9047. default_socket_options(srv);
  9048. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9049. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9050. sockaddr_in addr{};
  9051. addr.sin_family = AF_INET;
  9052. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9053. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9054. int opt = 1;
  9055. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9056. #ifdef _WIN32
  9057. reinterpret_cast<const char *>(&opt),
  9058. #else
  9059. &opt,
  9060. #endif
  9061. sizeof(opt));
  9062. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9063. ASSERT_EQ(0, ::listen(srv, 1));
  9064. auto server_thread = std::thread([&compressed, srv] {
  9065. sockaddr_in cli_addr{};
  9066. socklen_t cli_len = sizeof(cli_addr);
  9067. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9068. if (cli != INVALID_SOCKET) {
  9069. // Read the full HTTP request (until \r\n\r\n)
  9070. char buf[4096];
  9071. size_t total = 0;
  9072. while (total < sizeof(buf)) {
  9073. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9074. if (n <= 0) break;
  9075. total += static_cast<size_t>(n);
  9076. // Check for end of headers
  9077. if (total >= 4) {
  9078. std::string req(buf, total);
  9079. if (req.find("\r\n\r\n") != std::string::npos) break;
  9080. }
  9081. }
  9082. // Malicious response: gzip-compressed body, no Content-Length
  9083. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9084. "Content-Encoding: gzip\r\n"
  9085. "Connection: close\r\n"
  9086. "\r\n";
  9087. ::send(cli,
  9088. #ifdef _WIN32
  9089. static_cast<const char *>(response_header.c_str()),
  9090. static_cast<int>(response_header.size()),
  9091. #else
  9092. response_header.c_str(), response_header.size(),
  9093. #endif
  9094. 0);
  9095. // Send the compressed payload (small on the wire, huge when decompressed)
  9096. size_t total_sent = 0;
  9097. while (total_sent < compressed.size()) {
  9098. auto to_send = std::min(compressed.size() - total_sent,
  9099. static_cast<size_t>(64 * 1024));
  9100. auto sent =
  9101. ::send(cli,
  9102. #ifdef _WIN32
  9103. static_cast<const char *>(compressed.c_str() + total_sent),
  9104. static_cast<int>(to_send),
  9105. #else
  9106. compressed.c_str() + total_sent, to_send,
  9107. #endif
  9108. 0);
  9109. if (sent <= 0) break;
  9110. total_sent += static_cast<size_t>(sent);
  9111. }
  9112. detail::close_socket(cli);
  9113. }
  9114. });
  9115. auto se = detail::scope_exit([&] {
  9116. detail::close_socket(srv);
  9117. server_thread.join();
  9118. });
  9119. size_t total_decompressed = 0;
  9120. {
  9121. Client cli("127.0.0.1", PORT + 3);
  9122. cli.set_read_timeout(5, 0);
  9123. cli.set_decompress(true);
  9124. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9125. auto stream = cli.open_stream("GET", "/zipbomb");
  9126. ASSERT_TRUE(stream.is_valid());
  9127. char buffer[64 * 1024];
  9128. ssize_t n;
  9129. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9130. total_decompressed += static_cast<size_t>(n);
  9131. }
  9132. }
  9133. // The decompressed size must be capped by payload_max_length. Without
  9134. // protection, the client would decompress the full 10MB from a tiny
  9135. // compressed payload, enabling a zip bomb DoS attack.
  9136. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9137. << "Client decompressed " << total_decompressed
  9138. << " bytes from a gzip response. The decompressed size should be "
  9139. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9140. }
  9141. #endif
  9142. TEST(HostAndPortPropertiesTest, NoSSL) {
  9143. httplib::Client cli("www.google.com", 1234);
  9144. ASSERT_EQ("www.google.com", cli.host());
  9145. ASSERT_EQ(1234, cli.port());
  9146. }
  9147. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9148. httplib::Client cli("www.google.com:1234");
  9149. ASSERT_EQ("www.google.com", cli.host());
  9150. ASSERT_EQ(1234, cli.port());
  9151. }
  9152. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9153. // Port number that overflows int — should not crash, client becomes invalid
  9154. httplib::Client cli("http://www.google.com:99999999999999999999");
  9155. ASSERT_FALSE(cli.is_valid());
  9156. }
  9157. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9158. // Port 99999 exceeds valid range (1-65535) — should not crash
  9159. httplib::Client cli("http://www.google.com:99999");
  9160. ASSERT_FALSE(cli.is_valid());
  9161. }
  9162. #ifdef CPPHTTPLIB_SSL_ENABLED
  9163. TEST(HostAndPortPropertiesTest, SSL) {
  9164. httplib::SSLClient cli("www.google.com");
  9165. ASSERT_EQ("www.google.com", cli.host());
  9166. ASSERT_EQ(443, cli.port());
  9167. }
  9168. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9169. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9170. std::string cert;
  9171. read_file(CA_CERT_FILE, cert);
  9172. httplib::SSLClient httplib_client("www.google.com");
  9173. // Load CA store first time
  9174. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9175. // Load CA store second time (update)
  9176. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9177. // Verify client is still valid and can make connections
  9178. httplib_client.enable_server_certificate_verification(true);
  9179. auto res = httplib_client.Get("/");
  9180. ASSERT_TRUE(res);
  9181. // Google may return 200 or 301 depending on various factors
  9182. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9183. res->status == StatusCode::MovedPermanently_301);
  9184. }
  9185. TEST(SSLClientTest, ServerNameIndication_Online) {
  9186. auto host = "httpbingo.org";
  9187. auto path = std::string{"/get"};
  9188. SSLClient cli(host, 443);
  9189. auto res = cli.Get(path);
  9190. ASSERT_TRUE(res);
  9191. ASSERT_EQ(StatusCode::OK_200, res->status);
  9192. }
  9193. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9194. // Use a site that will cause SSL verification failure due to self-signed cert
  9195. SSLClient cli("self-signed.badssl.com", 443);
  9196. cli.enable_server_certificate_verification(true);
  9197. auto res = cli.Get("/");
  9198. ASSERT_TRUE(!res);
  9199. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9200. // Verify backend error is captured for SSLServerVerification
  9201. // This occurs when certificate verification fails
  9202. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9203. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9204. EXPECT_NE(0UL, res.ssl_backend_error());
  9205. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9206. // For OpenSSL, ssl_error is 0 for verification errors
  9207. EXPECT_EQ(0, res.ssl_error());
  9208. #if !defined(_WIN32) || \
  9209. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9210. // On non-Windows or when Windows Schannel is disabled, the error comes
  9211. // from OpenSSL's verification
  9212. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9213. res.ssl_backend_error());
  9214. #endif
  9215. #endif
  9216. }
  9217. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9218. // Use a site where hostname doesn't match the certificate
  9219. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9220. SSLClient cli("wrong.host.badssl.com", 443);
  9221. cli.enable_server_certificate_verification(true);
  9222. cli.enable_server_hostname_verification(true);
  9223. auto res = cli.Get("/");
  9224. ASSERT_TRUE(!res);
  9225. // The error type depends on when hostname verification occurs:
  9226. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9227. // - Mbed TLS: SSLServerVerification (during handshake)
  9228. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9229. res.error() == Error::SSLServerVerification);
  9230. // Verify backend error is captured for hostname verification failure
  9231. EXPECT_NE(0UL, res.ssl_backend_error());
  9232. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9233. // For OpenSSL, ssl_error is 0 for verification errors
  9234. EXPECT_EQ(0, res.ssl_error());
  9235. #if !defined(_WIN32) || \
  9236. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9237. // On non-Windows or when Windows Schannel is disabled, the error comes
  9238. // from OpenSSL's hostname verification
  9239. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9240. res.ssl_backend_error());
  9241. #endif
  9242. #endif
  9243. }
  9244. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9245. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9246. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9247. SSLClient cli("www.google.com", 443);
  9248. cli.enable_server_certificate_verification(true);
  9249. auto res = cli.Get("/");
  9250. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9251. }
  9252. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9253. SSLClient cli("www.google.com", 443);
  9254. cli.enable_server_certificate_verification(true);
  9255. cli.enable_windows_certificate_verification(false);
  9256. auto res = cli.Get("/");
  9257. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9258. }
  9259. #endif
  9260. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9261. Client cli("https://google.com");
  9262. auto res = cli.Get("/");
  9263. ASSERT_TRUE(res);
  9264. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9265. }
  9266. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9267. SSLClient cli("google.com");
  9268. cli.set_ca_cert_path(CA_CERT_FILE);
  9269. auto res = cli.Get("/");
  9270. ASSERT_TRUE(res);
  9271. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9272. }
  9273. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9274. SSLClient cli("google.com");
  9275. cli.enable_server_certificate_verification(true);
  9276. cli.set_ca_cert_path("hello");
  9277. auto res = cli.Get("/");
  9278. ASSERT_TRUE(!res);
  9279. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9280. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9281. // should be set
  9282. EXPECT_EQ(0, res.ssl_error());
  9283. // Verify backend error is captured for SSLLoadingCerts
  9284. // This error occurs when loading CA certificates fails
  9285. EXPECT_NE(0UL, res.ssl_backend_error());
  9286. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9287. // OpenSSL specific error codes:
  9288. // > openssl errstr 0x80000002
  9289. // error:80000002:system library::No such file or directory
  9290. // > openssl errstr 0xA000126
  9291. // error:0A000126:SSL routines::unexpected eof while reading
  9292. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9293. res.ssl_backend_error() == 0xA000126);
  9294. #endif
  9295. }
  9296. TEST(SSLClientTest, ServerCertificateVerification4) {
  9297. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9298. ASSERT_TRUE(svr.is_valid());
  9299. svr.Get("/test", [&](const Request &, Response &res) {
  9300. res.set_content("test", "text/plain");
  9301. svr.stop();
  9302. ASSERT_TRUE(true);
  9303. });
  9304. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9305. auto se = detail::scope_exit([&] {
  9306. t.join();
  9307. ASSERT_FALSE(svr.is_running());
  9308. });
  9309. svr.wait_until_ready();
  9310. SSLClient cli("127.0.0.1", PORT);
  9311. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9312. cli.enable_server_certificate_verification(true);
  9313. cli.set_connection_timeout(30);
  9314. auto res = cli.Get("/test");
  9315. ASSERT_TRUE(res);
  9316. ASSERT_EQ(StatusCode::OK_200, res->status);
  9317. }
  9318. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9319. std::string cert;
  9320. read_file(CA_CERT_FILE, cert);
  9321. SSLClient cli("google.com");
  9322. cli.load_ca_cert_store(cert.data(), cert.size());
  9323. const auto res = cli.Get("/");
  9324. ASSERT_TRUE(res);
  9325. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9326. }
  9327. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9328. // clang-format off
  9329. static constexpr char cert[] =
  9330. "GlobalSign Root CA\n"
  9331. "==================\n"
  9332. "-----BEGIN CERTIFICATE-----\n"
  9333. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9334. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9335. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9336. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9337. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9338. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9339. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9340. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9341. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9342. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9343. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9344. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9345. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9346. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9347. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9348. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9349. "-----END CERTIFICATE-----\n";
  9350. // clang-format on
  9351. SSLClient cli("google.com");
  9352. cli.load_ca_cert_store(cert, sizeof(cert));
  9353. const auto res = cli.Get("/");
  9354. ASSERT_TRUE(res);
  9355. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9356. }
  9357. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9358. SSLClient cli("www.youtube.com");
  9359. cli.set_ca_cert_path(CA_CERT_FILE);
  9360. cli.enable_server_certificate_verification(true);
  9361. cli.set_follow_location(true);
  9362. auto res = cli.Get("/");
  9363. ASSERT_TRUE(res);
  9364. ASSERT_EQ(StatusCode::OK_200, res->status);
  9365. }
  9366. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9367. SSLClient cli("wWw.YouTube.Com");
  9368. cli.set_ca_cert_path(CA_CERT_FILE);
  9369. cli.enable_server_certificate_verification(true);
  9370. cli.enable_server_hostname_verification(true);
  9371. cli.set_follow_location(true);
  9372. auto res = cli.Get("/");
  9373. ASSERT_TRUE(res);
  9374. ASSERT_EQ(StatusCode::OK_200, res->status);
  9375. }
  9376. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9377. SSLClient cli("gOoGlE.COm");
  9378. cli.enable_server_certificate_verification(true);
  9379. cli.enable_server_hostname_verification(true);
  9380. cli.set_follow_location(true);
  9381. auto res = cli.Get("/");
  9382. ASSERT_TRUE(res);
  9383. ASSERT_EQ(StatusCode::OK_200, res->status);
  9384. }
  9385. TEST(SSLClientTest, Issue2004_Online) {
  9386. Client client("https://google.com");
  9387. client.set_follow_location(true);
  9388. auto res = client.Get("/");
  9389. ASSERT_TRUE(res);
  9390. ASSERT_EQ(StatusCode::OK_200, res->status);
  9391. auto body = res->body;
  9392. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9393. }
  9394. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9395. // Create SSLClient with invalid cert/key to make is_valid() return false
  9396. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9397. "nonexistent_key.pem");
  9398. // is_valid() should be false due to cert loading failure
  9399. ASSERT_FALSE(cli.is_valid());
  9400. auto res = cli.Get("/");
  9401. ASSERT_FALSE(res);
  9402. EXPECT_EQ(Error::SSLConnection, res.error());
  9403. }
  9404. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9405. // Test for Issue #2251: SSL error not properly reported when client cert
  9406. // and key paths are swapped or mismatched
  9407. // This simulates the scenario where user accidentally swaps the cert and key
  9408. // files
  9409. // Using client cert file as private key and vice versa (completely wrong)
  9410. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9411. // Should fail validation due to cert/key mismatch
  9412. ASSERT_FALSE(cli.is_valid());
  9413. // Attempt to make a request should fail with proper error
  9414. auto res = cli.Get("/");
  9415. ASSERT_FALSE(res);
  9416. EXPECT_EQ(Error::SSLConnection, res.error());
  9417. // SSL error should be recorded in the Result object (this is the key fix for
  9418. // Issue #2251)
  9419. auto backend_error = res.ssl_backend_error();
  9420. EXPECT_NE(0u, backend_error);
  9421. }
  9422. // Tests cert/key mismatch detection at the TLS context level
  9423. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9424. // Test that using mismatched cert/key causes connection failure.
  9425. // We verify this at the SSLClient level rather than through internal
  9426. // TLS API functions.
  9427. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9428. cli.enable_server_certificate_verification(false);
  9429. cli.set_connection_timeout(2);
  9430. // The mismatch should cause a connection or handshake error
  9431. auto res = cli.Get("/test");
  9432. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9433. // Either way, the request should fail
  9434. EXPECT_FALSE(res);
  9435. }
  9436. #endif
  9437. #if 0
  9438. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9439. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9440. ASSERT_TRUE(cli != nullptr);
  9441. cli->set_address_family(AF_INET6);
  9442. cli->set_interface("en0");
  9443. auto res = cli->Get("/get");
  9444. ASSERT_TRUE(res);
  9445. ASSERT_EQ(StatusCode::OK_200, res->status);
  9446. }
  9447. #endif
  9448. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9449. #ifdef CPPHTTPLIB_SSL_ENABLED
  9450. void ClientCertPresent(
  9451. const std::string &client_cert_file,
  9452. const std::string &client_private_key_file,
  9453. const std::string &client_encrypted_private_key_pass = std::string()) {
  9454. using namespace httplib::tls;
  9455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9456. CLIENT_CA_CERT_DIR);
  9457. ASSERT_TRUE(svr.is_valid());
  9458. svr.Get("/test", [&](const Request &req, Response &res) {
  9459. res.set_content("test", "text/plain");
  9460. auto cert = req.peer_cert();
  9461. ASSERT_TRUE(static_cast<bool>(cert));
  9462. std::string common_name = cert.subject_cn();
  9463. EXPECT_EQ("Common Name", common_name);
  9464. });
  9465. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9466. auto se = detail::scope_exit([&] {
  9467. svr.stop();
  9468. t.join();
  9469. ASSERT_FALSE(svr.is_running());
  9470. });
  9471. svr.wait_until_ready();
  9472. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9473. client_encrypted_private_key_pass);
  9474. cli.enable_server_certificate_verification(false);
  9475. cli.set_connection_timeout(30);
  9476. auto res = cli.Get("/test");
  9477. ASSERT_TRUE(res);
  9478. ASSERT_EQ(StatusCode::OK_200, res->status);
  9479. }
  9480. TEST(SSLClientServerTest, ClientCertPresent) {
  9481. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9482. }
  9483. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9484. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9485. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9486. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9487. }
  9488. // PEM memory-based constructor tests (works with all TLS backends)
  9489. void PemMemoryClientCertPresent(
  9490. const std::string &client_cert_file,
  9491. const std::string &client_private_key_file,
  9492. const std::string &client_encrypted_private_key_pass = std::string()) {
  9493. // Read PEM files into memory
  9494. std::string server_cert_pem, server_key_pem;
  9495. std::string client_ca_pem;
  9496. std::string client_cert_pem, client_key_pem;
  9497. read_file(SERVER_CERT_FILE, server_cert_pem);
  9498. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9499. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9500. read_file(client_cert_file, client_cert_pem);
  9501. read_file(client_private_key_file, client_key_pem);
  9502. // Create server with PEM memory
  9503. SSLServer::PemMemory server_pem = {
  9504. server_cert_pem.c_str(),
  9505. server_cert_pem.size(),
  9506. server_key_pem.c_str(),
  9507. server_key_pem.size(),
  9508. client_ca_pem.c_str(),
  9509. client_ca_pem.size(),
  9510. nullptr // no password for server key
  9511. };
  9512. SSLServer svr(server_pem);
  9513. ASSERT_TRUE(svr.is_valid());
  9514. svr.Get("/test", [&](const Request &, Response &res) {
  9515. res.set_content("test", "text/plain");
  9516. });
  9517. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9518. auto se = detail::scope_exit([&] {
  9519. svr.stop();
  9520. t.join();
  9521. ASSERT_FALSE(svr.is_running());
  9522. });
  9523. svr.wait_until_ready();
  9524. // Create client with PEM memory
  9525. const char *password = client_encrypted_private_key_pass.empty()
  9526. ? nullptr
  9527. : client_encrypted_private_key_pass.c_str();
  9528. SSLClient::PemMemory client_pem = {
  9529. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9530. client_key_pem.size(), password};
  9531. SSLClient cli(HOST, PORT, client_pem);
  9532. cli.enable_server_certificate_verification(false);
  9533. cli.set_connection_timeout(30);
  9534. auto res = cli.Get("/test");
  9535. ASSERT_TRUE(res);
  9536. ASSERT_EQ(StatusCode::OK_200, res->status);
  9537. }
  9538. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9539. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9540. }
  9541. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9542. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9543. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9544. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9545. }
  9546. TEST(SSLClientServerTest, ClientCertMissing) {
  9547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9548. CLIENT_CA_CERT_DIR);
  9549. ASSERT_TRUE(svr.is_valid());
  9550. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9551. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9552. auto se = detail::scope_exit([&] {
  9553. svr.stop();
  9554. t.join();
  9555. ASSERT_FALSE(svr.is_running());
  9556. });
  9557. svr.wait_until_ready();
  9558. SSLClient cli(HOST, PORT);
  9559. cli.set_connection_timeout(30);
  9560. auto res = cli.Get("/test");
  9561. ASSERT_TRUE(!res);
  9562. // When client cert is missing and server requires it, connection fails
  9563. // Error type depends on backend implementation
  9564. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9565. res.error() == Error::SSLConnection);
  9566. // Verify backend error is captured
  9567. // Note: This test may have different error codes depending on the exact
  9568. // verification failure
  9569. EXPECT_NE(0UL, res.ssl_backend_error());
  9570. }
  9571. TEST(SSLClientServerTest, TrustDirOptional) {
  9572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9573. ASSERT_TRUE(svr.is_valid());
  9574. svr.Get("/test", [&](const Request &, Response &res) {
  9575. res.set_content("test", "text/plain");
  9576. });
  9577. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9578. auto se = detail::scope_exit([&] {
  9579. svr.stop();
  9580. t.join();
  9581. ASSERT_FALSE(svr.is_running());
  9582. });
  9583. svr.wait_until_ready();
  9584. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9585. cli.enable_server_certificate_verification(false);
  9586. cli.set_connection_timeout(30);
  9587. auto res = cli.Get("/test");
  9588. ASSERT_TRUE(res);
  9589. ASSERT_EQ(StatusCode::OK_200, res->status);
  9590. }
  9591. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9592. class NoListenSSLServer : public SSLServer {
  9593. public:
  9594. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9595. const char *client_ca_cert_file_path,
  9596. const char *client_ca_cert_dir_path = nullptr)
  9597. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9598. client_ca_cert_dir_path),
  9599. stop_(false) {}
  9600. std::atomic_bool stop_;
  9601. private:
  9602. bool process_and_close_socket(socket_t /*sock*/) override {
  9603. // Don't create SSL context
  9604. while (!stop_.load()) {
  9605. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9606. }
  9607. return true;
  9608. }
  9609. };
  9610. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9611. CLIENT_CA_CERT_FILE);
  9612. ASSERT_TRUE(svr.is_valid());
  9613. svr.Get("/test", [&](const Request &, Response &res) {
  9614. res.set_content("test", "text/plain");
  9615. });
  9616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9617. auto se = detail::scope_exit([&] {
  9618. svr.stop_ = true;
  9619. svr.stop();
  9620. t.join();
  9621. ASSERT_FALSE(svr.is_running());
  9622. });
  9623. svr.wait_until_ready();
  9624. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9625. cli.enable_server_certificate_verification(false);
  9626. cli.set_connection_timeout(1);
  9627. auto res = cli.Get("/test");
  9628. ASSERT_TRUE(!res);
  9629. EXPECT_EQ(Error::SSLConnection, res.error());
  9630. // Timeout results in WantRead error code (maps to backend-specific value)
  9631. EXPECT_NE(0, res.ssl_error());
  9632. }
  9633. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9634. // Test SSLServer with client certificate verification using the standard
  9635. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9637. CLIENT_CA_CERT_DIR);
  9638. ASSERT_TRUE(svr.is_valid());
  9639. svr.Get("/test", [&](const Request &req, Response &res) {
  9640. res.set_content("test", "text/plain");
  9641. auto cert = req.peer_cert();
  9642. ASSERT_TRUE(static_cast<bool>(cert));
  9643. auto common_name = cert.subject_cn();
  9644. EXPECT_EQ("Common Name", common_name);
  9645. });
  9646. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9647. auto se = detail::scope_exit([&] {
  9648. svr.stop();
  9649. t.join();
  9650. ASSERT_FALSE(svr.is_running());
  9651. });
  9652. svr.wait_until_ready();
  9653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9654. cli.enable_server_certificate_verification(false);
  9655. cli.set_connection_timeout(30);
  9656. auto res = cli.Get("/test");
  9657. ASSERT_TRUE(res);
  9658. ASSERT_EQ(StatusCode::OK_200, res->status);
  9659. }
  9660. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9661. // Verifies that wildcard matching and exact matching work consistently
  9662. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9663. using namespace httplib::tls;
  9664. // We need a running server to test against
  9665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9666. ASSERT_TRUE(svr.is_valid());
  9667. svr.Get("/test", [](const Request &, Response &res) {
  9668. res.set_content("ok", "text/plain");
  9669. });
  9670. thread t([&]() { svr.listen(HOST, PORT); });
  9671. auto se = detail::scope_exit([&] {
  9672. svr.stop();
  9673. t.join();
  9674. });
  9675. svr.wait_until_ready();
  9676. bool verify_callback_called = false;
  9677. bool verify_result_wrong = false;
  9678. SSLClient cli(HOST, PORT);
  9679. cli.enable_server_certificate_verification(true);
  9680. cli.set_ca_cert_path(CA_CERT_FILE);
  9681. cli.set_connection_timeout(5);
  9682. // Note: Test certificate has CN="Common Name", not "localhost"
  9683. bool verify_result_cn = false;
  9684. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9685. verify_callback_called = true;
  9686. if (!ctx.cert) return false;
  9687. // Test 1: "Common Name" should match (our test server cert CN)
  9688. verify_result_cn = ctx.check_hostname("Common Name");
  9689. // Test 2: wrong hostname should not match
  9690. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9691. return true; // Accept for the purpose of this test
  9692. });
  9693. auto res = cli.Get("/test");
  9694. // The request may succeed or fail depending on cert configuration
  9695. // but the callback should have been called
  9696. ASSERT_TRUE(verify_callback_called)
  9697. << "Verify callback should have been called";
  9698. // CN="Common Name" should match our test certificate
  9699. //
  9700. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9701. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9702. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9703. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9704. // <openssl/base.h>, which is included transitively when
  9705. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9706. #if defined(OPENSSL_IS_BORINGSSL)
  9707. EXPECT_FALSE(verify_result_cn)
  9708. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9709. #else
  9710. EXPECT_TRUE(verify_result_cn)
  9711. << "verify_hostname should match 'Common Name' (certificate CN)";
  9712. #endif
  9713. // Wrong hostname should not match
  9714. EXPECT_FALSE(verify_result_wrong)
  9715. << "verify_hostname should not match 'wronghost.example.com'";
  9716. }
  9717. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9718. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9719. // X509_check_ip behavior and must hold for every backend.
  9720. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9721. using namespace httplib::tls;
  9722. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9723. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9724. ASSERT_TRUE(svr.is_valid());
  9725. svr.Get("/test", [](const Request &, Response &res) {
  9726. res.set_content("ok", "text/plain");
  9727. });
  9728. thread t([&]() { svr.listen(HOST, PORT); });
  9729. auto se = detail::scope_exit([&] {
  9730. svr.stop();
  9731. t.join();
  9732. });
  9733. svr.wait_until_ready();
  9734. bool verify_callback_called = false;
  9735. bool ip_matched_via_cn = true;
  9736. SSLClient cli(HOST, PORT);
  9737. cli.enable_server_certificate_verification(true);
  9738. cli.set_ca_cert_path(CA_CERT_FILE);
  9739. cli.set_connection_timeout(5);
  9740. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9741. verify_callback_called = true;
  9742. if (!ctx.cert) return false;
  9743. // The IP appears only in the CN, so it must NOT be accepted.
  9744. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9745. return true; // Accept for the purpose of this test
  9746. });
  9747. cli.Get("/test");
  9748. ASSERT_TRUE(verify_callback_called)
  9749. << "Verify callback should have been called";
  9750. EXPECT_FALSE(ip_matched_via_cn)
  9751. << "An IP host must not be authenticated via the certificate CN";
  9752. }
  9753. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9754. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9755. using namespace httplib::tls;
  9756. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9757. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9758. ASSERT_TRUE(svr.is_valid());
  9759. svr.Get("/test", [](const Request &, Response &res) {
  9760. res.set_content("ok", "text/plain");
  9761. });
  9762. thread t([&]() { svr.listen(HOST, PORT); });
  9763. auto se = detail::scope_exit([&] {
  9764. svr.stop();
  9765. t.join();
  9766. });
  9767. svr.wait_until_ready();
  9768. bool verify_callback_called = false;
  9769. bool san_matched = false;
  9770. bool wrong_ipv6_matched = true;
  9771. bool cn_ipv6_matched = true;
  9772. SSLClient cli(HOST, PORT);
  9773. cli.enable_server_certificate_verification(true);
  9774. cli.set_ca_cert_path(CA_CERT_FILE);
  9775. cli.set_connection_timeout(5);
  9776. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9777. verify_callback_called = true;
  9778. if (!ctx.cert) return false;
  9779. // Matches the IPv6 iPAddress SAN.
  9780. san_matched = ctx.check_hostname("2001:db8::1");
  9781. // A different IPv6 address must not match.
  9782. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9783. // "::1" lives only in the CN, so it must not be accepted.
  9784. cn_ipv6_matched = ctx.check_hostname("::1");
  9785. return true; // Accept for the purpose of this test
  9786. });
  9787. cli.Get("/test");
  9788. ASSERT_TRUE(verify_callback_called)
  9789. << "Verify callback should have been called";
  9790. EXPECT_TRUE(san_matched)
  9791. << "verify_hostname should match an IPv6 iPAddress SAN";
  9792. EXPECT_FALSE(wrong_ipv6_matched)
  9793. << "verify_hostname should not match a non-matching IPv6 address";
  9794. EXPECT_FALSE(cn_ipv6_matched)
  9795. << "An IPv6 host must not be authenticated via the certificate CN";
  9796. }
  9797. #endif
  9798. // mbedTLS-specific callback constructor test
  9799. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9800. #ifdef CPPHTTPLIB_SSL_ENABLED
  9801. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9802. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9803. ASSERT_TRUE(svr.is_valid());
  9804. // Set up a handler to verify client certificate is present
  9805. bool client_cert_verified = false;
  9806. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9807. // Verify that client certificate was provided
  9808. client_cert_verified = true;
  9809. res.set_content("success", "text/plain");
  9810. });
  9811. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9812. auto se = detail::scope_exit([&] {
  9813. svr.stop();
  9814. t.join();
  9815. ASSERT_FALSE(svr.is_running());
  9816. });
  9817. svr.wait_until_ready();
  9818. // Client with certificate
  9819. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9820. cli.enable_server_certificate_verification(false);
  9821. cli.set_connection_timeout(30);
  9822. auto res = cli.Get("/test");
  9823. ASSERT_TRUE(res);
  9824. ASSERT_EQ(StatusCode::OK_200, res->status);
  9825. ASSERT_TRUE(client_cert_verified);
  9826. EXPECT_EQ("success", res->body);
  9827. }
  9828. #endif
  9829. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9830. // backends
  9831. #ifdef CPPHTTPLIB_SSL_ENABLED
  9832. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9833. using namespace httplib::tls;
  9834. // Test that when client CA cert file is provided,
  9835. // the server properly requests and validates client certificates
  9836. // Create a server with client authentication
  9837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9838. ASSERT_TRUE(svr.is_valid());
  9839. bool handler_called = false;
  9840. svr.Get("/test", [&](const Request &req, Response &res) {
  9841. handler_called = true;
  9842. // Verify that a client certificate was provided
  9843. auto cert = req.peer_cert();
  9844. ASSERT_TRUE(static_cast<bool>(cert));
  9845. // Get the issuer name
  9846. std::string issuer_str = cert.issuer_name();
  9847. ASSERT_FALSE(issuer_str.empty());
  9848. // The client certificate should be issued by our test CA
  9849. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9850. res.set_content("authenticated", "text/plain");
  9851. });
  9852. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9853. auto se = detail::scope_exit([&] {
  9854. svr.stop();
  9855. t.join();
  9856. ASSERT_FALSE(svr.is_running());
  9857. });
  9858. svr.wait_until_ready();
  9859. // Connect with a client certificate issued by the CA
  9860. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9861. cli.enable_server_certificate_verification(false);
  9862. cli.set_connection_timeout(30);
  9863. auto res = cli.Get("/test");
  9864. ASSERT_TRUE(res);
  9865. ASSERT_EQ(StatusCode::OK_200, res->status);
  9866. ASSERT_TRUE(handler_called);
  9867. EXPECT_EQ("authenticated", res->body);
  9868. }
  9869. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9870. using namespace httplib::tls;
  9871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9872. ASSERT_TRUE(svr.is_valid());
  9873. svr.Get("/test", [](const Request &, Response &res) {
  9874. res.set_content("ok", "text/plain");
  9875. });
  9876. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9877. auto se = detail::scope_exit([&] {
  9878. svr.stop();
  9879. t.join();
  9880. });
  9881. svr.wait_until_ready();
  9882. SSLClient cli(HOST, PORT);
  9883. cli.enable_server_certificate_verification(false);
  9884. cli.set_connection_timeout(30);
  9885. bool cert_checked = false;
  9886. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9887. if (ctx.cert) {
  9888. auto sans = ctx.sans();
  9889. // Test certificate may or may not have SANs - just verify the API
  9890. // works If SANs exist, verify the types are valid
  9891. for (const auto &san : sans) {
  9892. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9893. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9894. san.type == SanType::OTHER);
  9895. EXPECT_FALSE(san.value.empty());
  9896. }
  9897. cert_checked = true;
  9898. }
  9899. return true;
  9900. });
  9901. auto res = cli.Get("/test");
  9902. ASSERT_TRUE(res);
  9903. EXPECT_TRUE(cert_checked);
  9904. }
  9905. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9906. using namespace httplib::tls;
  9907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9908. ASSERT_TRUE(svr.is_valid());
  9909. svr.Get("/test", [](const Request &, Response &res) {
  9910. res.set_content("ok", "text/plain");
  9911. });
  9912. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9913. auto se = detail::scope_exit([&] {
  9914. svr.stop();
  9915. t.join();
  9916. });
  9917. svr.wait_until_ready();
  9918. SSLClient cli(HOST, PORT);
  9919. cli.enable_server_certificate_verification(false);
  9920. cli.set_connection_timeout(30);
  9921. bool validity_checked = false;
  9922. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9923. if (ctx.cert) {
  9924. time_t not_before = 0, not_after = 0;
  9925. bool result = ctx.validity(not_before, not_after);
  9926. EXPECT_TRUE(result);
  9927. // Verify that not_before < now < not_after for a valid cert
  9928. time_t now = time(nullptr);
  9929. EXPECT_LT(not_before, now);
  9930. EXPECT_GT(not_after, now);
  9931. validity_checked = true;
  9932. }
  9933. return true;
  9934. });
  9935. auto res = cli.Get("/test");
  9936. ASSERT_TRUE(res);
  9937. EXPECT_TRUE(validity_checked);
  9938. }
  9939. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9940. using namespace httplib::tls;
  9941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9942. ASSERT_TRUE(svr.is_valid());
  9943. svr.Get("/test", [](const Request &, Response &res) {
  9944. res.set_content("ok", "text/plain");
  9945. });
  9946. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9947. auto se = detail::scope_exit([&] {
  9948. svr.stop();
  9949. t.join();
  9950. });
  9951. svr.wait_until_ready();
  9952. SSLClient cli(HOST, PORT);
  9953. cli.enable_server_certificate_verification(false);
  9954. cli.set_connection_timeout(30);
  9955. bool serial_checked = false;
  9956. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9957. if (ctx.cert) {
  9958. std::string serial = ctx.serial();
  9959. EXPECT_FALSE(serial.empty());
  9960. // Serial should be a hex string
  9961. for (char c : serial) {
  9962. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9963. (c >= 'a' && c <= 'f'));
  9964. }
  9965. serial_checked = true;
  9966. }
  9967. return true;
  9968. });
  9969. auto res = cli.Get("/test");
  9970. ASSERT_TRUE(res);
  9971. EXPECT_TRUE(serial_checked);
  9972. }
  9973. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9974. // Test 1: Valid CA file - no error should be recorded
  9975. {
  9976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9977. CLIENT_CA_CERT_FILE);
  9978. ASSERT_TRUE(svr.is_valid());
  9979. // With valid setup, last_ssl_error should be 0
  9980. EXPECT_EQ(0, svr.ssl_last_error());
  9981. }
  9982. // Test 2: Invalid CA file content
  9983. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9984. {
  9985. // Create a temporary file with completely invalid content
  9986. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9987. {
  9988. std::ofstream ofs(temp_invalid_ca);
  9989. ofs << "This is not a certificate file at all\n";
  9990. ofs << "Just plain text content\n";
  9991. }
  9992. // Create server with invalid CA file
  9993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9994. // Clean up temporary file
  9995. std::remove(temp_invalid_ca);
  9996. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9997. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9998. // Note: SSL_CTX_load_verify_locations typically fails first,
  9999. // but our error handling code path is still exercised
  10000. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10001. }
  10002. }
  10003. TEST(VerifyCallbackTest, VerifyContextFields) {
  10004. using namespace httplib::tls;
  10005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10006. ASSERT_TRUE(svr.is_valid());
  10007. svr.Get("/test", [](const Request &, Response &res) {
  10008. res.set_content("ok", "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. });
  10015. svr.wait_until_ready();
  10016. SSLClient cli(HOST, PORT);
  10017. cli.enable_server_certificate_verification(false);
  10018. cli.set_connection_timeout(30);
  10019. int callback_count = 0;
  10020. bool saw_leaf_cert = false;
  10021. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10022. if (ctx.cert) {
  10023. callback_count++;
  10024. // We should see at least one certificate (the leaf)
  10025. std::string cn = ctx.subject_cn();
  10026. if (!cn.empty()) { saw_leaf_cert = true; }
  10027. // Verify context fields are populated
  10028. EXPECT_NE(ctx.session, nullptr);
  10029. EXPECT_GE(ctx.depth, 0);
  10030. }
  10031. return true;
  10032. });
  10033. auto res = cli.Get("/test");
  10034. ASSERT_TRUE(res);
  10035. EXPECT_GT(callback_count, 0);
  10036. EXPECT_TRUE(saw_leaf_cert);
  10037. }
  10038. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10039. using httplib::tls::TlsError;
  10040. // Test that verify_error_to_string returns empty for success
  10041. std::string success_str = TlsError::verify_error_to_string(0);
  10042. EXPECT_TRUE(success_str.empty());
  10043. // Test that verify_error_to_string returns non-empty for error codes
  10044. // Using a common error code (certificate expired)
  10045. std::string error_str =
  10046. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10047. EXPECT_FALSE(error_str.empty());
  10048. }
  10049. TEST(SessionVerifierTest, CertificateAccepted) {
  10050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10051. ASSERT_TRUE(svr.is_valid());
  10052. svr.Get("/test", [](const Request &, Response &res) {
  10053. res.set_content("ok", "text/plain");
  10054. });
  10055. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10056. auto se = detail::scope_exit([&] {
  10057. svr.stop();
  10058. t.join();
  10059. });
  10060. svr.wait_until_ready();
  10061. SSLClient cli(HOST, PORT);
  10062. cli.enable_server_certificate_verification(false);
  10063. cli.set_connection_timeout(30);
  10064. bool callback_called = false;
  10065. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10066. EXPECT_NE(session, nullptr);
  10067. callback_called = true;
  10068. return SSLVerifierResponse::CertificateAccepted;
  10069. });
  10070. auto res = cli.Get("/test");
  10071. ASSERT_TRUE(res);
  10072. EXPECT_EQ(200, res->status);
  10073. EXPECT_TRUE(callback_called);
  10074. }
  10075. TEST(SessionVerifierTest, CertificateRejected) {
  10076. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10077. ASSERT_TRUE(svr.is_valid());
  10078. svr.Get("/test", [](const Request &, Response &res) {
  10079. res.set_content("ok", "text/plain");
  10080. });
  10081. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10082. auto se = detail::scope_exit([&] {
  10083. svr.stop();
  10084. t.join();
  10085. });
  10086. svr.wait_until_ready();
  10087. SSLClient cli(HOST, PORT);
  10088. cli.enable_server_certificate_verification(false);
  10089. cli.set_connection_timeout(30);
  10090. bool callback_called = false;
  10091. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10092. EXPECT_NE(session, nullptr);
  10093. callback_called = true;
  10094. return SSLVerifierResponse::CertificateRejected;
  10095. });
  10096. auto res = cli.Get("/test");
  10097. EXPECT_FALSE(res);
  10098. EXPECT_TRUE(callback_called);
  10099. }
  10100. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10102. ASSERT_TRUE(svr.is_valid());
  10103. svr.Get("/test", [](const Request &, Response &res) {
  10104. res.set_content("ok", "text/plain");
  10105. });
  10106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10107. auto se = detail::scope_exit([&] {
  10108. svr.stop();
  10109. t.join();
  10110. });
  10111. svr.wait_until_ready();
  10112. // NoDecisionMade with verification disabled should succeed (no default check)
  10113. SSLClient cli(HOST, PORT);
  10114. cli.enable_server_certificate_verification(false);
  10115. cli.set_connection_timeout(30);
  10116. bool callback_called = false;
  10117. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10118. EXPECT_NE(session, nullptr);
  10119. callback_called = true;
  10120. return SSLVerifierResponse::NoDecisionMade;
  10121. });
  10122. auto res = cli.Get("/test");
  10123. ASSERT_TRUE(res);
  10124. EXPECT_EQ(200, res->status);
  10125. EXPECT_TRUE(callback_called);
  10126. }
  10127. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10129. ASSERT_TRUE(svr.is_valid());
  10130. svr.Get("/test", [](const Request &, Response &res) {
  10131. res.set_content("ok", "text/plain");
  10132. });
  10133. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10134. auto se = detail::scope_exit([&] {
  10135. svr.stop();
  10136. t.join();
  10137. });
  10138. svr.wait_until_ready();
  10139. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10140. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10141. // so we only check that the request fails, not whether the callback was
  10142. // called.
  10143. SSLClient cli(HOST, PORT);
  10144. cli.enable_server_certificate_verification(true);
  10145. cli.set_connection_timeout(30);
  10146. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10147. EXPECT_NE(session, nullptr);
  10148. return SSLVerifierResponse::NoDecisionMade;
  10149. });
  10150. auto res = cli.Get("/test");
  10151. EXPECT_FALSE(res);
  10152. }
  10153. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10154. // Test SSL server using PemMemory constructor with client CA certificates
  10155. // Read PEM files
  10156. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10157. read_file(SERVER_CERT_FILE, server_cert_pem);
  10158. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10159. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10160. // Create SSLServer with PemMemory constructor including client CA
  10161. SSLServer::PemMemory server_pem = {
  10162. server_cert_pem.c_str(),
  10163. server_cert_pem.size(),
  10164. server_key_pem.c_str(),
  10165. server_key_pem.size(),
  10166. client_ca_pem.c_str(),
  10167. client_ca_pem.size(),
  10168. nullptr // no password for server key
  10169. };
  10170. SSLServer svr(server_pem);
  10171. ASSERT_TRUE(svr.is_valid());
  10172. // No SSL error should be recorded for valid setup
  10173. EXPECT_EQ(0, svr.ssl_last_error());
  10174. // Set up server endpoints
  10175. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10176. res.set_content("ok", "text/plain");
  10177. });
  10178. // Start server in a thread
  10179. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10180. svr.wait_until_ready();
  10181. // Connect with client certificate (using constructor with paths)
  10182. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10183. cli.enable_server_certificate_verification(false);
  10184. auto res = cli.Get("/test-pem-ca");
  10185. ASSERT_TRUE(res);
  10186. EXPECT_EQ(200, res->status);
  10187. EXPECT_EQ("ok", res->body);
  10188. svr.stop();
  10189. server_thread.join();
  10190. }
  10191. #endif
  10192. #ifdef _WIN32
  10193. TEST(CleanupTest, WSACleanup) {
  10194. int ret = WSACleanup();
  10195. ASSERT_EQ(0, ret);
  10196. }
  10197. #endif
  10198. #ifndef CPPHTTPLIB_SSL_ENABLED
  10199. TEST(NoSSLSupport, SimpleInterface) {
  10200. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10201. }
  10202. #endif
  10203. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10204. TEST(InvalidScheme, SimpleInterface) {
  10205. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10206. }
  10207. #endif
  10208. TEST(NoScheme, SimpleInterface) {
  10209. Client cli("yahoo.com:80");
  10210. ASSERT_TRUE(cli.is_valid());
  10211. }
  10212. TEST(SendAPI, SimpleInterface_Online) {
  10213. Client cli("http://yahoo.com");
  10214. Request req;
  10215. req.method = "GET";
  10216. req.path = "/";
  10217. auto res = cli.send(req);
  10218. ASSERT_TRUE(res);
  10219. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10220. }
  10221. TEST(SendAPI, WithParamsInRequest) {
  10222. Server svr;
  10223. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10224. EXPECT_TRUE(req.has_param("test"));
  10225. EXPECT_EQ("test_value", req.get_param_value("test"));
  10226. });
  10227. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. svr.stop();
  10230. t.join();
  10231. ASSERT_FALSE(svr.is_running());
  10232. });
  10233. svr.wait_until_ready();
  10234. Client cli(HOST, PORT);
  10235. {
  10236. Request req;
  10237. req.method = "GET";
  10238. req.path = "/";
  10239. req.params.emplace("test", "test_value");
  10240. auto res = cli.send(req);
  10241. ASSERT_TRUE(res);
  10242. }
  10243. {
  10244. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10245. ASSERT_TRUE(res);
  10246. }
  10247. }
  10248. TEST(ClientImplMethods, GetSocketTest) {
  10249. httplib::Server svr;
  10250. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10251. res.status = StatusCode::OK_200;
  10252. });
  10253. auto port = svr.bind_to_any_port("127.0.0.1");
  10254. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. thread.join();
  10258. ASSERT_FALSE(svr.is_running());
  10259. });
  10260. svr.wait_until_ready();
  10261. {
  10262. httplib::Client cli("127.0.0.1", port);
  10263. cli.set_keep_alive(true);
  10264. // Use the behavior of cpp-httplib of opening the connection
  10265. // only when the first request happens. If that changes,
  10266. // this test would be obsolete.
  10267. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10268. // This also implicitly tests the server. But other tests would fail much
  10269. // earlier than this one to be considered.
  10270. auto res = cli.Get("/");
  10271. ASSERT_TRUE(res);
  10272. EXPECT_EQ(StatusCode::OK_200, res->status);
  10273. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10274. }
  10275. }
  10276. #ifdef CPPHTTPLIB_SSL_ENABLED
  10277. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10278. Client cli("http://yahoo.com");
  10279. auto res = cli.Get("/");
  10280. ASSERT_TRUE(res);
  10281. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10282. cli.set_follow_location(true);
  10283. res = cli.Get("/");
  10284. ASSERT_TRUE(res);
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10287. }
  10288. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10289. Client cli("https://yahoo.com");
  10290. auto res = cli.Get("/");
  10291. ASSERT_TRUE(res);
  10292. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10293. cli.set_follow_location(true);
  10294. res = cli.Get("/");
  10295. ASSERT_TRUE(res);
  10296. EXPECT_EQ(StatusCode::OK_200, res->status);
  10297. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10298. }
  10299. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10300. Client cli("https://yahoo.com");
  10301. auto res = cli.Get("/");
  10302. ASSERT_TRUE(res);
  10303. ASSERT_FALSE(!res);
  10304. ASSERT_TRUE(res);
  10305. ASSERT_FALSE(res == nullptr);
  10306. ASSERT_TRUE(res != nullptr);
  10307. EXPECT_EQ(Error::Success, res.error());
  10308. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10309. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10310. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10311. cli.set_follow_location(true);
  10312. res = cli.Get("/");
  10313. ASSERT_TRUE(res);
  10314. EXPECT_EQ(Error::Success, res.error());
  10315. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10316. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10317. EXPECT_EQ(StatusCode::OK_200, res->status);
  10318. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10319. }
  10320. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10321. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10322. Client cli("https://cdnjs.cloudflare.com");
  10323. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10324. Headers{{"Accept-Encoding", "br"}});
  10325. ASSERT_TRUE(res);
  10326. EXPECT_EQ(StatusCode::OK_200, res->status);
  10327. EXPECT_EQ(287630U, res->body.size());
  10328. EXPECT_EQ("application/javascript; charset=utf-8",
  10329. res->get_header_value("Content-Type"));
  10330. }
  10331. #endif
  10332. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10333. #undef REDIR_HOST // Silence compiler warning
  10334. #define REDIR_HOST "https://httpbingo.org"
  10335. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10336. Client cli(REDIR_HOST);
  10337. cli.set_follow_location(true);
  10338. auto res =
  10339. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10340. ASSERT_TRUE(res);
  10341. EXPECT_EQ(StatusCode::OK_200, res->status);
  10342. }
  10343. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10344. Client cli(REDIR_HOST);
  10345. cli.set_follow_location(true);
  10346. Params params;
  10347. params.emplace("url", "http://example.com");
  10348. params.emplace("status_code", "302");
  10349. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10350. ASSERT_TRUE(res);
  10351. EXPECT_EQ(StatusCode::OK_200, res->status);
  10352. }
  10353. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10354. Client cli(REDIR_HOST);
  10355. cli.set_follow_location(true);
  10356. Params params;
  10357. params.emplace("url", "http://example.com");
  10358. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10359. ASSERT_TRUE(res);
  10360. EXPECT_EQ(StatusCode::OK_200, res->status);
  10361. }
  10362. TEST(HttpToHttpsRedirectTest, CertFile) {
  10363. auto ssl_port = PORT + 1;
  10364. Server svr;
  10365. ASSERT_TRUE(svr.is_valid());
  10366. svr.Get("/index", [&](const Request &, Response &res) {
  10367. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10368. "/index");
  10369. svr.stop();
  10370. });
  10371. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10372. ASSERT_TRUE(ssl_svr.is_valid());
  10373. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10374. res.set_content("test", "text/plain");
  10375. ssl_svr.stop();
  10376. });
  10377. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10378. thread t2 =
  10379. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10380. auto se = detail::scope_exit([&] {
  10381. t2.join();
  10382. t.join();
  10383. ASSERT_FALSE(svr.is_running());
  10384. });
  10385. svr.wait_until_ready();
  10386. ssl_svr.wait_until_ready();
  10387. Client cli("127.0.0.1", PORT);
  10388. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10389. cli.enable_server_certificate_verification(true);
  10390. cli.set_follow_location(true);
  10391. cli.set_connection_timeout(30);
  10392. auto res = cli.Get("/index");
  10393. ASSERT_TRUE(res);
  10394. ASSERT_EQ(StatusCode::OK_200, res->status);
  10395. }
  10396. TEST(SSLClientRedirectTest, CertFile) {
  10397. auto ssl_port = PORT + 1;
  10398. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10399. ASSERT_TRUE(ssl_svr1.is_valid());
  10400. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10401. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10402. "/index");
  10403. ssl_svr1.stop();
  10404. });
  10405. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10406. ASSERT_TRUE(ssl_svr2.is_valid());
  10407. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10408. res.set_content("test", "text/plain");
  10409. ssl_svr2.stop();
  10410. });
  10411. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10412. thread t2 =
  10413. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10414. auto se = detail::scope_exit([&] {
  10415. t2.join();
  10416. t.join();
  10417. ASSERT_FALSE(ssl_svr1.is_running());
  10418. });
  10419. ssl_svr1.wait_until_ready();
  10420. ssl_svr2.wait_until_ready();
  10421. SSLClient cli("127.0.0.1", PORT);
  10422. std::string cert;
  10423. read_file(SERVER_CERT2_FILE, cert);
  10424. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10425. cli.enable_server_certificate_verification(true);
  10426. cli.set_follow_location(true);
  10427. cli.set_connection_timeout(30);
  10428. auto res = cli.Get("/index");
  10429. ASSERT_TRUE(res);
  10430. ASSERT_EQ(StatusCode::OK_200, res->status);
  10431. }
  10432. #endif
  10433. #ifdef CPPHTTPLIB_SSL_ENABLED
  10434. // Test that set_ca_cert_store() skips system certs (consistent with
  10435. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10436. // should be trusted - system certs should NOT be loaded.
  10437. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10438. // Load a specific cert that is NOT a system CA cert
  10439. std::string cert;
  10440. read_file(SERVER_CERT2_FILE, cert);
  10441. SSLClient cli("google.com");
  10442. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10443. cli.enable_server_certificate_verification(true);
  10444. // This should FAIL because:
  10445. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10446. // 2. System certs should NOT be loaded when custom store is set
  10447. // If system certs WERE loaded, this would succeed
  10448. auto res = cli.Get("/");
  10449. ASSERT_FALSE(res);
  10450. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10451. }
  10452. // Same as above, but through the native store handle path. Regression test:
  10453. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10454. // merged system certs into the user-provided store.
  10455. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10456. std::string cert;
  10457. read_file(SERVER_CERT2_FILE, cert);
  10458. SSLClient cli("google.com");
  10459. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10460. cli.enable_server_certificate_verification(true);
  10461. auto res = cli.Get("/");
  10462. ASSERT_FALSE(res);
  10463. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10464. }
  10465. // A custom store set via the native handle must still verify a server whose
  10466. // cert it does contain.
  10467. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10468. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10469. ASSERT_TRUE(svr.is_valid());
  10470. svr.Get("/test", [&](const Request &, Response &res) {
  10471. res.set_content("test", "text/plain");
  10472. });
  10473. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10474. auto se = detail::scope_exit([&] {
  10475. svr.stop();
  10476. t.join();
  10477. ASSERT_FALSE(svr.is_running());
  10478. });
  10479. svr.wait_until_ready();
  10480. SSLClient cli("127.0.0.1", PORT);
  10481. std::string cert;
  10482. read_file(SERVER_CERT2_FILE, cert);
  10483. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10484. cli.enable_server_certificate_verification(true);
  10485. cli.set_connection_timeout(30);
  10486. auto res = cli.Get("/test");
  10487. ASSERT_TRUE(res);
  10488. ASSERT_EQ(StatusCode::OK_200, res->status);
  10489. }
  10490. // CA certs loaded through the universal Client must be transferred to the
  10491. // client created internally for following an HTTPS redirect. Regression test:
  10492. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10493. // the CA data for redirect transfer.
  10494. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10495. auto ssl_port = PORT + 1;
  10496. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10497. ASSERT_TRUE(ssl_svr1.is_valid());
  10498. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10499. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10500. "/index");
  10501. });
  10502. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10503. ASSERT_TRUE(ssl_svr2.is_valid());
  10504. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10505. res.set_content("test", "text/plain");
  10506. });
  10507. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10508. thread t2 =
  10509. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10510. auto se = detail::scope_exit([&] {
  10511. ssl_svr2.stop();
  10512. ssl_svr1.stop();
  10513. t2.join();
  10514. t.join();
  10515. ASSERT_FALSE(ssl_svr1.is_running());
  10516. });
  10517. ssl_svr1.wait_until_ready();
  10518. ssl_svr2.wait_until_ready();
  10519. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10520. std::string cert;
  10521. read_file(SERVER_CERT2_FILE, cert);
  10522. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10523. cli.enable_server_certificate_verification(true);
  10524. cli.set_follow_location(true);
  10525. cli.set_connection_timeout(30);
  10526. auto res = cli.Get("/index");
  10527. ASSERT_TRUE(res);
  10528. ASSERT_EQ(StatusCode::OK_200, res->status);
  10529. }
  10530. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10531. // so a host signed by a system CA verifies even though a custom CA is set
  10532. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10533. std::string cert;
  10534. read_file(SERVER_CERT2_FILE, cert);
  10535. SSLClient cli("google.com");
  10536. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10537. cli.enable_system_ca(true);
  10538. cli.enable_server_certificate_verification(true);
  10539. auto res = cli.Get("/");
  10540. ASSERT_TRUE(res);
  10541. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10542. }
  10543. // The custom CA remains effective when combined with the system CA
  10544. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10545. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10546. ASSERT_TRUE(svr.is_valid());
  10547. svr.Get("/test", [&](const Request &, Response &res) {
  10548. res.set_content("test", "text/plain");
  10549. });
  10550. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10551. auto se = detail::scope_exit([&] {
  10552. svr.stop();
  10553. t.join();
  10554. ASSERT_FALSE(svr.is_running());
  10555. });
  10556. svr.wait_until_ready();
  10557. SSLClient cli("127.0.0.1", PORT);
  10558. std::string cert;
  10559. read_file(SERVER_CERT2_FILE, cert);
  10560. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10561. cli.enable_system_ca(true);
  10562. cli.enable_server_certificate_verification(true);
  10563. cli.set_connection_timeout(30);
  10564. auto res = cli.Get("/test");
  10565. ASSERT_TRUE(res);
  10566. ASSERT_EQ(StatusCode::OK_200, res->status);
  10567. }
  10568. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10569. // skip chain verification entirely (only the certificate identity was
  10570. // checked), so a server presenting an untrusted certificate with a matching
  10571. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10572. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10573. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10574. ASSERT_TRUE(svr.is_valid());
  10575. svr.Get("/test", [&](const Request &, Response &res) {
  10576. res.set_content("test", "text/plain");
  10577. });
  10578. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10579. auto se = detail::scope_exit([&] {
  10580. svr.stop();
  10581. t.join();
  10582. ASSERT_FALSE(svr.is_running());
  10583. });
  10584. svr.wait_until_ready();
  10585. SSLClient cli("127.0.0.1", PORT);
  10586. std::string cert;
  10587. // A trusted CA that did not sign the server certificate. The server cert
  10588. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10589. // this connection.
  10590. read_file(CLIENT_CA_CERT_FILE, cert);
  10591. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10592. cli.enable_server_certificate_verification(true);
  10593. cli.set_connection_timeout(30);
  10594. auto res = cli.Get("/test");
  10595. ASSERT_FALSE(res);
  10596. }
  10597. // enable_system_ca(false) prevents system CA loading entirely
  10598. TEST(SSLClientTest, DisableSystemCa_Online) {
  10599. SSLClient cli("google.com");
  10600. cli.enable_system_ca(false);
  10601. cli.enable_server_certificate_verification(true);
  10602. auto res = cli.Get("/");
  10603. ASSERT_FALSE(res);
  10604. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10605. // itself when the CA chain is empty
  10606. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10607. res.error() == Error::SSLConnection);
  10608. }
  10609. // The universal Client forwards enable_system_ca()
  10610. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10611. std::string cert;
  10612. read_file(SERVER_CERT2_FILE, cert);
  10613. Client cli("https://google.com");
  10614. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10615. cli.enable_system_ca(true);
  10616. cli.enable_server_certificate_verification(true);
  10617. auto res = cli.Get("/");
  10618. ASSERT_TRUE(res);
  10619. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10620. }
  10621. // The system CA policy must carry over to the client created internally for
  10622. // following a cross-host HTTPS redirect
  10623. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10624. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10625. ASSERT_TRUE(svr.is_valid());
  10626. svr.Get("/index", [&](const Request &, Response &res) {
  10627. res.set_redirect("https://www.google.com/");
  10628. });
  10629. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10630. auto se = detail::scope_exit([&] {
  10631. svr.stop();
  10632. t.join();
  10633. ASSERT_FALSE(svr.is_running());
  10634. });
  10635. svr.wait_until_ready();
  10636. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10637. std::string cert;
  10638. read_file(SERVER_CERT2_FILE, cert);
  10639. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10640. cli.enable_system_ca(true);
  10641. cli.enable_server_certificate_verification(true);
  10642. cli.set_follow_location(true);
  10643. cli.set_connection_timeout(30);
  10644. // Receiving any response proves the redirect client completed the TLS
  10645. // handshake with a system-CA-signed host
  10646. auto res = cli.Get("/index");
  10647. ASSERT_TRUE(res);
  10648. }
  10649. TEST(MultipartFormDataTest, LargeData) {
  10650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10651. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10652. const ContentReader &content_reader) {
  10653. if (req.is_multipart_form_data()) {
  10654. std::vector<FormData> items;
  10655. content_reader(
  10656. [&](const FormData &file) {
  10657. items.push_back(file);
  10658. return true;
  10659. },
  10660. [&](const char *data, size_t data_length) {
  10661. items.back().content.append(data, data_length);
  10662. return true;
  10663. });
  10664. EXPECT_TRUE(std::string(items[0].name) == "document");
  10665. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10666. EXPECT_TRUE(items[0].filename == "2MB_data");
  10667. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10668. EXPECT_TRUE(items[1].name == "hello");
  10669. EXPECT_TRUE(items[1].content == "world");
  10670. EXPECT_TRUE(items[1].filename == "");
  10671. EXPECT_TRUE(items[1].content_type == "");
  10672. } else {
  10673. std::string body;
  10674. content_reader([&](const char *data, size_t data_length) {
  10675. body.append(data, data_length);
  10676. return true;
  10677. });
  10678. }
  10679. });
  10680. auto port = svr.bind_to_any_port(HOST);
  10681. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10682. auto se = detail::scope_exit([&] {
  10683. svr.stop();
  10684. t.join();
  10685. ASSERT_FALSE(svr.is_running());
  10686. });
  10687. svr.wait_until_ready();
  10688. {
  10689. std::string data(1024 * 1024 * 2, '.');
  10690. std::stringstream buffer;
  10691. buffer << data;
  10692. SSLClient cli(HOST, port);
  10693. cli.enable_server_certificate_verification(false);
  10694. UploadFormDataItems items{
  10695. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10696. {"hello", "world", "", ""},
  10697. };
  10698. auto res = cli.Post("/post", items);
  10699. ASSERT_TRUE(res);
  10700. ASSERT_EQ(StatusCode::OK_200, res->status);
  10701. }
  10702. }
  10703. TEST(MultipartFormDataTest, DataProviderItems) {
  10704. std::random_device seed_gen;
  10705. std::mt19937 random(seed_gen());
  10706. std::string rand1;
  10707. rand1.resize(1000);
  10708. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10709. std::string rand2;
  10710. rand2.resize(3000);
  10711. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10713. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10714. const ContentReader &content_reader) {
  10715. ASSERT_FALSE(req.is_multipart_form_data());
  10716. std::string body;
  10717. content_reader([&](const char *data, size_t data_length) {
  10718. body.append(data, data_length);
  10719. return true;
  10720. });
  10721. EXPECT_EQ(body, "");
  10722. });
  10723. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10724. const ContentReader &content_reader) {
  10725. ASSERT_TRUE(req.is_multipart_form_data());
  10726. std::vector<FormData> items;
  10727. content_reader(
  10728. [&](const FormData &file) {
  10729. items.push_back(file);
  10730. return true;
  10731. },
  10732. [&](const char *data, size_t data_length) {
  10733. items.back().content.append(data, data_length);
  10734. return true;
  10735. });
  10736. ASSERT_TRUE(items.size() == 2);
  10737. EXPECT_EQ(std::string(items[0].name), "name1");
  10738. EXPECT_EQ(items[0].content, "Testing123");
  10739. EXPECT_EQ(items[0].filename, "filename1");
  10740. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10741. EXPECT_EQ(items[1].name, "name2");
  10742. EXPECT_EQ(items[1].content, "Testing456");
  10743. EXPECT_EQ(items[1].filename, "");
  10744. EXPECT_EQ(items[1].content_type, "");
  10745. });
  10746. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10747. const ContentReader &content_reader) {
  10748. ASSERT_TRUE(req.is_multipart_form_data());
  10749. std::vector<FormData> items;
  10750. content_reader(
  10751. [&](const FormData &file) {
  10752. items.push_back(file);
  10753. return true;
  10754. },
  10755. [&](const char *data, size_t data_length) {
  10756. items.back().content.append(data, data_length);
  10757. return true;
  10758. });
  10759. ASSERT_TRUE(items.size() == 2);
  10760. EXPECT_EQ(items[0].name, "name3");
  10761. EXPECT_EQ(items[0].content, rand1);
  10762. EXPECT_EQ(items[0].filename, "filename3");
  10763. EXPECT_EQ(items[0].content_type, "");
  10764. EXPECT_EQ(items[1].name, "name4");
  10765. EXPECT_EQ(items[1].content, rand2);
  10766. EXPECT_EQ(items[1].filename, "filename4");
  10767. EXPECT_EQ(items[1].content_type, "");
  10768. });
  10769. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10770. const ContentReader &content_reader) {
  10771. ASSERT_TRUE(req.is_multipart_form_data());
  10772. std::vector<FormData> items;
  10773. content_reader(
  10774. [&](const FormData &file) {
  10775. items.push_back(file);
  10776. return true;
  10777. },
  10778. [&](const char *data, size_t data_length) {
  10779. items.back().content.append(data, data_length);
  10780. return true;
  10781. });
  10782. ASSERT_TRUE(items.size() == 4);
  10783. EXPECT_EQ(std::string(items[0].name), "name1");
  10784. EXPECT_EQ(items[0].content, "Testing123");
  10785. EXPECT_EQ(items[0].filename, "filename1");
  10786. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10787. EXPECT_EQ(items[1].name, "name2");
  10788. EXPECT_EQ(items[1].content, "Testing456");
  10789. EXPECT_EQ(items[1].filename, "");
  10790. EXPECT_EQ(items[1].content_type, "");
  10791. EXPECT_EQ(items[2].name, "name3");
  10792. EXPECT_EQ(items[2].content, rand1);
  10793. EXPECT_EQ(items[2].filename, "filename3");
  10794. EXPECT_EQ(items[2].content_type, "");
  10795. EXPECT_EQ(items[3].name, "name4");
  10796. EXPECT_EQ(items[3].content, rand2);
  10797. EXPECT_EQ(items[3].filename, "filename4");
  10798. EXPECT_EQ(items[3].content_type, "");
  10799. });
  10800. auto port = svr.bind_to_any_port("localhost");
  10801. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10802. auto se = detail::scope_exit([&] {
  10803. svr.stop();
  10804. t.join();
  10805. ASSERT_FALSE(svr.is_running());
  10806. });
  10807. svr.wait_until_ready();
  10808. {
  10809. SSLClient cli("localhost", port);
  10810. cli.enable_server_certificate_verification(false);
  10811. UploadFormDataItems items{
  10812. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10813. {"name2", "Testing456", "", ""}, // not a file
  10814. };
  10815. {
  10816. auto res = cli.Post("/post-none", {}, {}, {});
  10817. ASSERT_TRUE(res);
  10818. ASSERT_EQ(StatusCode::OK_200, res->status);
  10819. }
  10820. FormDataProviderItems providers;
  10821. {
  10822. auto res =
  10823. cli.Post("/post-items", {}, items, providers); // empty providers
  10824. ASSERT_TRUE(res);
  10825. ASSERT_EQ(StatusCode::OK_200, res->status);
  10826. }
  10827. providers.push_back({"name3",
  10828. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10829. // test the offset is given correctly at each step
  10830. if (!offset)
  10831. sink.os.write(rand1.data(), 30);
  10832. else if (offset == 30)
  10833. sink.os.write(rand1.data() + 30, 300);
  10834. else if (offset == 330)
  10835. sink.os.write(rand1.data() + 330, 670);
  10836. else if (offset == rand1.size())
  10837. sink.done();
  10838. return true;
  10839. },
  10840. "filename3",
  10841. {}});
  10842. providers.push_back({"name4",
  10843. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10844. // test the offset is given correctly at each step
  10845. if (!offset)
  10846. sink.os.write(rand2.data(), 2000);
  10847. else if (offset == 2000)
  10848. sink.os.write(rand2.data() + 2000, 1);
  10849. else if (offset == 2001)
  10850. sink.os.write(rand2.data() + 2001, 999);
  10851. else if (offset == rand2.size())
  10852. sink.done();
  10853. return true;
  10854. },
  10855. "filename4",
  10856. {}});
  10857. {
  10858. auto res = cli.Post("/post-providers", {}, {}, providers);
  10859. ASSERT_TRUE(res);
  10860. ASSERT_EQ(StatusCode::OK_200, res->status);
  10861. }
  10862. {
  10863. auto res = cli.Post("/post-both", {}, items, providers);
  10864. ASSERT_TRUE(res);
  10865. ASSERT_EQ(StatusCode::OK_200, res->status);
  10866. }
  10867. }
  10868. }
  10869. TEST(MultipartFormDataTest, BadHeader) {
  10870. Server svr;
  10871. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10872. res.set_content("ok", "text/plain");
  10873. });
  10874. thread t = thread([&] { svr.listen(HOST, PORT); });
  10875. auto se = detail::scope_exit([&] {
  10876. svr.stop();
  10877. t.join();
  10878. ASSERT_FALSE(svr.is_running());
  10879. });
  10880. svr.wait_until_ready();
  10881. const std::string body =
  10882. "This is the preamble. It is to be ignored, though it\r\n"
  10883. "is a handy place for composition agents to include an\r\n"
  10884. "explanatory note to non-MIME conformant readers.\r\n"
  10885. "\r\n"
  10886. "\r\n"
  10887. "--simple boundary\r\n"
  10888. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10889. ": BAD...\r\n"
  10890. "\r\n"
  10891. "value1\r\n"
  10892. "--simple boundary\r\n"
  10893. "Content-Disposition: form-data; name=\"field2\"; "
  10894. "filename=\"example.txt\"\r\n"
  10895. "\r\n"
  10896. "value2\r\n"
  10897. "--simple boundary--\r\n"
  10898. "This is the epilogue. It is also to be ignored.\r\n";
  10899. std::string content_type =
  10900. R"(multipart/form-data; boundary="simple boundary")";
  10901. Client cli(HOST, PORT);
  10902. auto res = cli.Post("/post", body, content_type.c_str());
  10903. ASSERT_TRUE(res);
  10904. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10905. }
  10906. TEST(MultipartFormDataTest, WithPreamble) {
  10907. Server svr;
  10908. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10909. res.set_content("ok", "text/plain");
  10910. });
  10911. thread t = thread([&] { svr.listen(HOST, PORT); });
  10912. auto se = detail::scope_exit([&] {
  10913. svr.stop();
  10914. t.join();
  10915. ASSERT_FALSE(svr.is_running());
  10916. });
  10917. svr.wait_until_ready();
  10918. const std::string body =
  10919. "This is the preamble. It is to be ignored, though it\r\n"
  10920. "is a handy place for composition agents to include an\r\n"
  10921. "explanatory note to non-MIME conformant readers.\r\n"
  10922. "\r\n"
  10923. "\r\n"
  10924. "--simple boundary\r\n"
  10925. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10926. "\r\n"
  10927. "value1\r\n"
  10928. "--simple boundary\r\n"
  10929. "Content-Disposition: form-data; name=\"field2\"; "
  10930. "filename=\"example.txt\"\r\n"
  10931. "\r\n"
  10932. "value2\r\n"
  10933. "--simple boundary--\r\n"
  10934. "This is the epilogue. It is also to be ignored.\r\n";
  10935. std::string content_type =
  10936. R"(multipart/form-data; boundary="simple boundary")";
  10937. Client cli(HOST, PORT);
  10938. auto res = cli.Post("/post", body, content_type.c_str());
  10939. ASSERT_TRUE(res);
  10940. EXPECT_EQ(StatusCode::OK_200, res->status);
  10941. }
  10942. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10944. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10945. const ContentReader &content_reader) {
  10946. if (req.is_multipart_form_data()) {
  10947. std::vector<FormData> items;
  10948. content_reader(
  10949. [&](const FormData &file) {
  10950. items.push_back(file);
  10951. return true;
  10952. },
  10953. [&](const char *data, size_t data_length) {
  10954. items.back().content.append(data, data_length);
  10955. return true;
  10956. });
  10957. EXPECT_TRUE(std::string(items[0].name) == "document");
  10958. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10959. EXPECT_TRUE(items[0].filename == "2MB_data");
  10960. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10961. EXPECT_TRUE(items[1].name == "hello");
  10962. EXPECT_TRUE(items[1].content == "world");
  10963. EXPECT_TRUE(items[1].filename == "");
  10964. EXPECT_TRUE(items[1].content_type == "");
  10965. } else {
  10966. std::string body;
  10967. content_reader([&](const char *data, size_t data_length) {
  10968. body.append(data, data_length);
  10969. return true;
  10970. });
  10971. }
  10972. });
  10973. auto port = svr.bind_to_any_port("localhost");
  10974. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10975. auto se = detail::scope_exit([&] {
  10976. svr.stop();
  10977. t.join();
  10978. ASSERT_FALSE(svr.is_running());
  10979. });
  10980. svr.wait_until_ready();
  10981. {
  10982. std::string data(1024 * 1024 * 2, '.');
  10983. std::stringstream buffer;
  10984. buffer << data;
  10985. SSLClient cli("localhost", port);
  10986. cli.enable_server_certificate_verification(false);
  10987. UploadFormDataItems items{
  10988. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10989. {"hello", "world", "", ""},
  10990. };
  10991. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10992. ASSERT_TRUE(res);
  10993. ASSERT_EQ(StatusCode::OK_200, res->status);
  10994. }
  10995. }
  10996. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10997. std::string data(1024 * 1024 * 2, '&');
  10998. std::stringstream buffer;
  10999. buffer << data;
  11000. Client cli("https://localhost:8080");
  11001. UploadFormDataItems items{
  11002. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11003. {"hello", "world", "", ""},
  11004. };
  11005. for (const char &c : " \t\r\n") {
  11006. auto res =
  11007. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11008. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11009. ASSERT_FALSE(res);
  11010. }
  11011. }
  11012. TEST(MultipartFormDataTest, PutFormData) {
  11013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11014. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11015. const ContentReader &content_reader) {
  11016. if (req.is_multipart_form_data()) {
  11017. std::vector<FormData> items;
  11018. content_reader(
  11019. [&](const FormData &file) {
  11020. items.push_back(file);
  11021. return true;
  11022. },
  11023. [&](const char *data, size_t data_length) {
  11024. items.back().content.append(data, data_length);
  11025. return true;
  11026. });
  11027. EXPECT_TRUE(std::string(items[0].name) == "document");
  11028. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11029. EXPECT_TRUE(items[0].filename == "2MB_data");
  11030. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11031. EXPECT_TRUE(items[1].name == "hello");
  11032. EXPECT_TRUE(items[1].content == "world");
  11033. EXPECT_TRUE(items[1].filename == "");
  11034. EXPECT_TRUE(items[1].content_type == "");
  11035. } else {
  11036. std::string body;
  11037. content_reader([&](const char *data, size_t data_length) {
  11038. body.append(data, data_length);
  11039. return true;
  11040. });
  11041. }
  11042. });
  11043. auto port = svr.bind_to_any_port("localhost");
  11044. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11045. auto se = detail::scope_exit([&] {
  11046. svr.stop();
  11047. t.join();
  11048. ASSERT_FALSE(svr.is_running());
  11049. });
  11050. svr.wait_until_ready();
  11051. {
  11052. std::string data(1024 * 1024 * 2, '&');
  11053. std::stringstream buffer;
  11054. buffer << data;
  11055. SSLClient cli("localhost", port);
  11056. cli.enable_server_certificate_verification(false);
  11057. UploadFormDataItems items{
  11058. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11059. {"hello", "world", "", ""},
  11060. };
  11061. auto res = cli.Put("/put", items);
  11062. ASSERT_TRUE(res);
  11063. ASSERT_EQ(StatusCode::OK_200, res->status);
  11064. }
  11065. }
  11066. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11068. svr.Put("/put_customboundary",
  11069. [&](const Request &req, const Response & /*res*/,
  11070. const ContentReader &content_reader) {
  11071. if (req.is_multipart_form_data()) {
  11072. std::vector<FormData> items;
  11073. content_reader(
  11074. [&](const FormData &file) {
  11075. items.push_back(file);
  11076. return true;
  11077. },
  11078. [&](const char *data, size_t data_length) {
  11079. items.back().content.append(data, data_length);
  11080. return true;
  11081. });
  11082. EXPECT_TRUE(std::string(items[0].name) == "document");
  11083. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11084. EXPECT_TRUE(items[0].filename == "2MB_data");
  11085. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11086. EXPECT_TRUE(items[1].name == "hello");
  11087. EXPECT_TRUE(items[1].content == "world");
  11088. EXPECT_TRUE(items[1].filename == "");
  11089. EXPECT_TRUE(items[1].content_type == "");
  11090. } else {
  11091. std::string body;
  11092. content_reader([&](const char *data, size_t data_length) {
  11093. body.append(data, data_length);
  11094. return true;
  11095. });
  11096. }
  11097. });
  11098. auto port = svr.bind_to_any_port("localhost");
  11099. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11100. auto se = detail::scope_exit([&] {
  11101. svr.stop();
  11102. t.join();
  11103. ASSERT_FALSE(svr.is_running());
  11104. });
  11105. svr.wait_until_ready();
  11106. {
  11107. std::string data(1024 * 1024 * 2, '&');
  11108. std::stringstream buffer;
  11109. buffer << data;
  11110. SSLClient cli("localhost", port);
  11111. cli.enable_server_certificate_verification(false);
  11112. UploadFormDataItems items{
  11113. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11114. {"hello", "world", "", ""},
  11115. };
  11116. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11117. ASSERT_TRUE(res);
  11118. ASSERT_EQ(StatusCode::OK_200, res->status);
  11119. }
  11120. }
  11121. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11122. std::string data(1024 * 1024 * 2, '&');
  11123. std::stringstream buffer;
  11124. buffer << data;
  11125. Client cli("https://localhost:8080");
  11126. cli.enable_server_certificate_verification(false);
  11127. UploadFormDataItems items{
  11128. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11129. {"hello", "world", "", ""},
  11130. };
  11131. for (const char &c : " \t\r\n") {
  11132. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11133. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11134. ASSERT_FALSE(res);
  11135. }
  11136. }
  11137. TEST(MultipartFormDataTest, AlternateFilename) {
  11138. auto handled = false;
  11139. Server svr;
  11140. svr.Post("/test", [&](const Request &req, Response &res) {
  11141. ASSERT_EQ(2u, req.form.files.size());
  11142. ASSERT_EQ(1u, req.form.fields.size());
  11143. // Test files
  11144. const auto &file1 = req.form.get_file("file1");
  11145. ASSERT_EQ("file1", file1.name);
  11146. ASSERT_EQ("A.txt", file1.filename);
  11147. ASSERT_EQ("text/plain", file1.content_type);
  11148. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11149. const auto &file2 = req.form.get_file("file2");
  11150. ASSERT_EQ("file2", file2.name);
  11151. ASSERT_EQ("a.html", file2.filename);
  11152. ASSERT_EQ("text/html", file2.content_type);
  11153. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11154. file2.content);
  11155. // Test text field
  11156. const auto &text = req.form.get_field("text");
  11157. ASSERT_EQ("text default", text);
  11158. res.set_content("ok", "text/plain");
  11159. handled = true;
  11160. });
  11161. thread t = thread([&] { svr.listen(HOST, PORT); });
  11162. auto se = detail::scope_exit([&] {
  11163. svr.stop();
  11164. t.join();
  11165. ASSERT_FALSE(svr.is_running());
  11166. ASSERT_TRUE(handled);
  11167. });
  11168. svr.wait_until_ready();
  11169. auto req = "POST /test HTTP/1.1\r\n"
  11170. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11171. "Content-Length: 399\r\n"
  11172. "\r\n"
  11173. "----------\r\n"
  11174. "Content-Disposition: form-data; name=\"text\"\r\n"
  11175. "\r\n"
  11176. "text default\r\n"
  11177. "----------\r\n"
  11178. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11179. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11180. "Content-Type: text/plain\r\n"
  11181. "\r\n"
  11182. "Content of a.txt.\r\n"
  11183. "\r\n"
  11184. "----------\r\n"
  11185. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11186. "\"a.html\"\r\n"
  11187. "Content-Type: text/html\r\n"
  11188. "\r\n"
  11189. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11190. "\r\n"
  11191. "------------\r\n";
  11192. ASSERT_TRUE(send_request(1, req));
  11193. }
  11194. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11195. auto handled = false;
  11196. Server svr;
  11197. svr.Post("/test", [&](const Request &req, Response &res) {
  11198. // Case-insensitive "utf-8''" prefix with a long value
  11199. const auto &file = req.form.get_file("file1");
  11200. ASSERT_EQ("file1", file.name);
  11201. // 8000 chars exercises both the Content-Disposition parser and the
  11202. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11203. // Prior to the fix, std::regex_match on this header would cause O(N)
  11204. // stack recursion in libstdc++, leading to SIGSEGV.
  11205. std::string expected_filename(8000, 'A');
  11206. ASSERT_EQ(expected_filename, file.filename);
  11207. res.set_content("ok", "text/plain");
  11208. handled = true;
  11209. });
  11210. thread t = thread([&] { svr.listen(HOST, PORT); });
  11211. auto se = detail::scope_exit([&] {
  11212. svr.stop();
  11213. t.join();
  11214. ASSERT_FALSE(svr.is_running());
  11215. ASSERT_TRUE(handled);
  11216. });
  11217. svr.wait_until_ready();
  11218. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11219. // Regression test for GHSA-qq6v-r583-3h69
  11220. std::string long_filename(8000, 'A');
  11221. std::string body = "----------\r\n"
  11222. "Content-Disposition: form-data; name=\"file1\"; "
  11223. "filename*=\"Utf-8''" +
  11224. long_filename +
  11225. "\"\r\n"
  11226. "\r\n"
  11227. "hello\r\n"
  11228. "------------\r\n";
  11229. auto req = "POST /test HTTP/1.1\r\n"
  11230. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11231. "Content-Length: " +
  11232. std::to_string(body.size()) + "\r\n\r\n" + body;
  11233. ASSERT_TRUE(send_request(1, req));
  11234. }
  11235. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11236. auto handled = false;
  11237. Server svr;
  11238. svr.Post("/test", [&](const Request &req, Response &) {
  11239. ASSERT_EQ(2u, req.form.fields.size());
  11240. const auto &text1 = req.form.get_field("text1");
  11241. ASSERT_EQ("text1", text1);
  11242. const auto &text2 = req.form.get_field("text2");
  11243. ASSERT_EQ("text2", text2);
  11244. handled = true;
  11245. });
  11246. thread t = thread([&] { svr.listen(HOST, PORT); });
  11247. auto se = detail::scope_exit([&] {
  11248. svr.stop();
  11249. t.join();
  11250. ASSERT_FALSE(svr.is_running());
  11251. ASSERT_TRUE(handled);
  11252. });
  11253. svr.wait_until_ready();
  11254. auto req = "POST /test HTTP/1.1\r\n"
  11255. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11256. "Content-Length: 146\r\n"
  11257. "\r\n----------\r\n"
  11258. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11259. "\r\n"
  11260. "text1"
  11261. "\r\n----------\r\n"
  11262. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11263. "\r\n"
  11264. "text2"
  11265. "\r\n------------";
  11266. std::string response;
  11267. ASSERT_TRUE(send_request(1, req, &response));
  11268. ASSERT_EQ("200", response.substr(9, 3));
  11269. }
  11270. TEST(MultipartFormDataTest, ContentLength) {
  11271. auto handled = false;
  11272. Server svr;
  11273. svr.Post("/test", [&](const Request &req, Response &) {
  11274. ASSERT_EQ(2u, req.form.fields.size());
  11275. const auto &text1 = req.form.get_field("text1");
  11276. ASSERT_EQ("text1", text1);
  11277. const auto &text2 = req.form.get_field("text2");
  11278. ASSERT_EQ("text2", text2);
  11279. handled = true;
  11280. });
  11281. thread t = thread([&] { svr.listen(HOST, PORT); });
  11282. auto se = detail::scope_exit([&] {
  11283. svr.stop();
  11284. t.join();
  11285. ASSERT_FALSE(svr.is_running());
  11286. ASSERT_TRUE(handled);
  11287. });
  11288. svr.wait_until_ready();
  11289. auto req = "POST /test HTTP/1.1\r\n"
  11290. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11291. "Content-Length: 167\r\n"
  11292. "\r\n----------\r\n"
  11293. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11294. "Content-Length: 5\r\n"
  11295. "\r\n"
  11296. "text1"
  11297. "\r\n----------\r\n"
  11298. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11299. "\r\n"
  11300. "text2"
  11301. "\r\n------------\r\n";
  11302. std::string response;
  11303. ASSERT_TRUE(send_request(1, req, &response));
  11304. ASSERT_EQ("200", response.substr(9, 3));
  11305. }
  11306. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11307. auto handled = false;
  11308. Server svr;
  11309. svr.Post("/test", [&](const Request &req, Response &) {
  11310. ASSERT_EQ(2u, req.form.fields.size());
  11311. const auto &text1 = req.form.get_field("text1");
  11312. ASSERT_EQ("text1", text1);
  11313. // TODO: Add header access for text fields if needed
  11314. const auto &text2 = req.form.get_field("text2");
  11315. ASSERT_EQ("text2", text2);
  11316. // TODO: Header access for text fields needs to be implemented
  11317. // auto &headers = it->second.headers;
  11318. // ASSERT_EQ(3U, headers.size());
  11319. // auto custom_header = headers.find("x-whatever");
  11320. // ASSERT_TRUE(custom_header != headers.end());
  11321. // ASSERT_NE("customvalue", custom_header->second);
  11322. // ASSERT_EQ("CustomValue", custom_header->second);
  11323. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11324. handled = true;
  11325. });
  11326. thread t = thread([&] { svr.listen(HOST, PORT); });
  11327. auto se = detail::scope_exit([&] {
  11328. svr.stop();
  11329. t.join();
  11330. ASSERT_FALSE(svr.is_running());
  11331. ASSERT_TRUE(handled);
  11332. });
  11333. svr.wait_until_ready();
  11334. auto req = "POST /test HTTP/1.1\r\n"
  11335. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11336. "Content-Length: 232\r\n"
  11337. "\r\n----------\r\n"
  11338. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11339. "Content-Length: 5\r\n"
  11340. "X-Test: 1\r\n"
  11341. "\r\n"
  11342. "text1"
  11343. "\r\n----------\r\n"
  11344. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11345. "Content-Type: text/plain\r\n"
  11346. "X-Whatever: CustomValue\r\n"
  11347. "\r\n"
  11348. "text2"
  11349. "\r\n------------\r\n"
  11350. "That should be disregarded. Not even read";
  11351. std::string response;
  11352. ASSERT_TRUE(send_request(1, req, &response));
  11353. ASSERT_EQ("200", response.substr(9, 3));
  11354. }
  11355. TEST(MultipartFormDataTest, LargeHeader) {
  11356. auto handled = false;
  11357. Server svr;
  11358. svr.Post("/test", [&](const Request &req, Response &) {
  11359. ASSERT_EQ(1u, req.form.fields.size());
  11360. const auto &text = req.form.get_field("name1");
  11361. ASSERT_EQ("text1", text);
  11362. handled = true;
  11363. });
  11364. thread t = thread([&] { svr.listen(HOST, PORT); });
  11365. auto se = detail::scope_exit([&] {
  11366. svr.stop();
  11367. t.join();
  11368. ASSERT_FALSE(svr.is_running());
  11369. ASSERT_TRUE(handled);
  11370. });
  11371. svr.wait_until_ready();
  11372. auto boundary = std::string("cpp-httplib-multipart-data");
  11373. std::string content = "--" + boundary +
  11374. "\r\n"
  11375. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11376. "\r\n"
  11377. "text1\r\n"
  11378. "--" +
  11379. boundary + "--\r\n";
  11380. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11381. "Content-Type: multipart/form-data;boundary=" +
  11382. boundary +
  11383. "\r\n"
  11384. "Content-Length: " +
  11385. std::to_string(content.size()) +
  11386. "\r\n"
  11387. "Dummy-Header: ";
  11388. std::string header_suffix = "\r\n"
  11389. "\r\n";
  11390. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11391. size_t header_dummy_size =
  11392. read_buff_size -
  11393. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11394. auto header_dummy = std::string(header_dummy_size, '@');
  11395. auto req = header_prefix + header_dummy + header_suffix + content;
  11396. std::string response;
  11397. ASSERT_TRUE(send_request(1, req, &response));
  11398. ASSERT_EQ("200", response.substr(9, 3));
  11399. }
  11400. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11401. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11402. // (not chunked Transfer-Encoding) after the streaming refactor.
  11403. auto handled = false;
  11404. Server svr;
  11405. svr.Post("/upload", [&](const Request &req, Response &res) {
  11406. auto cl_it = req.headers.find("Content-Length");
  11407. EXPECT_TRUE(cl_it != req.headers.end());
  11408. auto te_it = req.headers.find("Transfer-Encoding");
  11409. EXPECT_TRUE(te_it == req.headers.end());
  11410. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11411. res.set_content("ok", "text/plain");
  11412. handled = true;
  11413. });
  11414. auto port = svr.bind_to_any_port(HOST);
  11415. auto t = thread([&] { svr.listen_after_bind(); });
  11416. auto se = detail::scope_exit([&] {
  11417. svr.stop();
  11418. t.join();
  11419. ASSERT_FALSE(svr.is_running());
  11420. ASSERT_TRUE(handled);
  11421. });
  11422. svr.wait_until_ready();
  11423. UploadFormDataItems items = {
  11424. {"field1", "hello", "", "text/plain"},
  11425. {"file1", "world", "test.txt", "application/octet-stream"},
  11426. };
  11427. Client cli(HOST, port);
  11428. auto res = cli.Post("/upload", {}, items);
  11429. ASSERT_TRUE(res);
  11430. EXPECT_EQ(StatusCode::OK_200, res->status);
  11431. }
  11432. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11433. // Verify that make_multipart_content_provider coalesces many small segments
  11434. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11435. constexpr size_t kItemCount = 1000;
  11436. UploadFormDataItems items;
  11437. items.reserve(kItemCount);
  11438. for (size_t i = 0; i < kItemCount; i++) {
  11439. items.push_back(
  11440. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11441. }
  11442. const std::string boundary = "----test-boundary";
  11443. auto content_length = detail::get_multipart_content_length(items, boundary);
  11444. auto provider = detail::make_multipart_content_provider(items, boundary);
  11445. // Drive the provider the same way write_content_with_progress does
  11446. size_t write_count = 0;
  11447. size_t total_bytes = 0;
  11448. DataSink sink;
  11449. size_t offset = 0;
  11450. sink.write = [&](const char *d, size_t l) -> bool {
  11451. (void)d;
  11452. write_count++;
  11453. total_bytes += l;
  11454. offset += l;
  11455. return true;
  11456. };
  11457. sink.is_writable = []() -> bool { return true; };
  11458. while (offset < content_length) {
  11459. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11460. }
  11461. EXPECT_EQ(content_length, total_bytes);
  11462. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11463. // With buffering into 64KB blocks, write_count should be much smaller.
  11464. auto segment_count = 3 * kItemCount + 1;
  11465. EXPECT_LT(write_count, segment_count / 10);
  11466. }
  11467. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11468. // Integration test: send many UploadFormDataItems and verify the server
  11469. // receives all of them correctly (#2410).
  11470. constexpr size_t kItemCount = 500;
  11471. auto handled = false;
  11472. Server svr;
  11473. svr.Post("/upload", [&](const Request &req, Response &res) {
  11474. EXPECT_EQ(kItemCount, req.form.fields.size());
  11475. for (size_t i = 0; i < kItemCount; i++) {
  11476. auto key = "field" + std::to_string(i);
  11477. auto val = "value" + std::to_string(i);
  11478. auto it = req.form.fields.find(key);
  11479. if (it != req.form.fields.end()) {
  11480. EXPECT_EQ(val, it->second.content);
  11481. } else {
  11482. ADD_FAILURE() << "Missing field: " << key;
  11483. }
  11484. }
  11485. res.set_content("ok", "text/plain");
  11486. handled = true;
  11487. });
  11488. auto port = svr.bind_to_any_port(HOST);
  11489. auto t = thread([&] { svr.listen_after_bind(); });
  11490. auto se = detail::scope_exit([&] {
  11491. svr.stop();
  11492. t.join();
  11493. ASSERT_FALSE(svr.is_running());
  11494. ASSERT_TRUE(handled);
  11495. });
  11496. svr.wait_until_ready();
  11497. UploadFormDataItems items;
  11498. items.reserve(kItemCount);
  11499. for (size_t i = 0; i < kItemCount; i++) {
  11500. items.push_back(
  11501. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11502. }
  11503. Client cli(HOST, port);
  11504. auto res = cli.Post("/upload", items);
  11505. ASSERT_TRUE(res);
  11506. EXPECT_EQ(StatusCode::OK_200, res->status);
  11507. }
  11508. TEST(MultipartFormDataTest, MakeFileProvider) {
  11509. // Verify make_file_provider sends a file's contents correctly.
  11510. const std::string file_content(4096, 'Z');
  11511. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11512. {
  11513. std::ofstream ofs(tmp_path, std::ios::binary);
  11514. ofs.write(file_content.data(),
  11515. static_cast<std::streamsize>(file_content.size()));
  11516. }
  11517. auto handled = false;
  11518. Server svr;
  11519. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11520. const ContentReader &content_reader) {
  11521. ASSERT_TRUE(req.is_multipart_form_data());
  11522. std::vector<FormData> items;
  11523. content_reader(
  11524. [&](const FormData &file) {
  11525. items.push_back(file);
  11526. return true;
  11527. },
  11528. [&](const char *data, size_t data_length) {
  11529. items.back().content.append(data, data_length);
  11530. return true;
  11531. });
  11532. ASSERT_EQ(1u, items.size());
  11533. EXPECT_EQ("myfile", items[0].name);
  11534. EXPECT_EQ("data.bin", items[0].filename);
  11535. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11536. EXPECT_EQ(file_content, items[0].content);
  11537. handled = true;
  11538. });
  11539. auto port = svr.bind_to_any_port(HOST);
  11540. auto t = thread([&] { svr.listen_after_bind(); });
  11541. auto se = detail::scope_exit([&] {
  11542. svr.stop();
  11543. t.join();
  11544. ASSERT_FALSE(svr.is_running());
  11545. ASSERT_TRUE(handled);
  11546. std::remove(tmp_path.c_str());
  11547. });
  11548. svr.wait_until_ready();
  11549. FormDataProviderItems providers;
  11550. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11551. "application/octet-stream"));
  11552. Client cli(HOST, port);
  11553. auto res = cli.Post("/upload", {}, {}, providers);
  11554. ASSERT_TRUE(res);
  11555. EXPECT_EQ(StatusCode::OK_200, res->status);
  11556. }
  11557. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11558. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11559. // (100) headers is rejected with a 400 Bad Request response.
  11560. Server svr;
  11561. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11562. res.set_content("ok", "text/plain");
  11563. });
  11564. thread t = thread([&] { svr.listen(HOST, PORT); });
  11565. auto se = detail::scope_exit([&] {
  11566. svr.stop();
  11567. t.join();
  11568. ASSERT_FALSE(svr.is_running());
  11569. });
  11570. svr.wait_until_ready();
  11571. // Build a multipart part with 101 custom headers (exceeding
  11572. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11573. std::stringstream body;
  11574. body << "--simpleboundary\r\n"
  11575. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11576. for (int i = 0; i < 101; i++) {
  11577. body << "X-Custom-Header-" << i << ": value\r\n";
  11578. }
  11579. body << "\r\n"
  11580. << "value1\r\n"
  11581. << "--simpleboundary--\r\n";
  11582. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11583. Client cli(HOST, PORT);
  11584. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11585. ASSERT_TRUE(res);
  11586. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11587. }
  11588. TEST(MakeFileBodyTest, Basic) {
  11589. const std::string file_content(4096, 'Z');
  11590. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11591. {
  11592. std::ofstream ofs(tmp_path, std::ios::binary);
  11593. ofs.write(file_content.data(),
  11594. static_cast<std::streamsize>(file_content.size()));
  11595. }
  11596. auto handled = false;
  11597. Server svr;
  11598. svr.Post("/upload", [&](const Request &req, Response &res) {
  11599. EXPECT_EQ(file_content, req.body);
  11600. handled = true;
  11601. res.status = StatusCode::OK_200;
  11602. });
  11603. auto port = svr.bind_to_any_port(HOST);
  11604. auto t = thread([&] { svr.listen_after_bind(); });
  11605. auto se = detail::scope_exit([&] {
  11606. svr.stop();
  11607. t.join();
  11608. ASSERT_FALSE(svr.is_running());
  11609. ASSERT_TRUE(handled);
  11610. std::remove(tmp_path.c_str());
  11611. });
  11612. svr.wait_until_ready();
  11613. auto fb = make_file_body(tmp_path);
  11614. ASSERT_GT(fb.first, 0u);
  11615. Client cli(HOST, port);
  11616. auto res =
  11617. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11618. ASSERT_TRUE(res);
  11619. EXPECT_EQ(StatusCode::OK_200, res->status);
  11620. }
  11621. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11622. static constexpr unsigned int number_of_tasks{1000000};
  11623. std::atomic_uint count{0};
  11624. std::unique_ptr<TaskQueue> task_queue{
  11625. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11626. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11627. auto queued = task_queue->enqueue(
  11628. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11629. EXPECT_TRUE(queued);
  11630. }
  11631. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11632. task_queue->shutdown();
  11633. #else
  11634. EXPECT_NO_THROW(task_queue->shutdown());
  11635. #endif
  11636. EXPECT_EQ(number_of_tasks, count.load());
  11637. }
  11638. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11639. static constexpr unsigned int number_of_tasks{1000000};
  11640. static constexpr unsigned int qlimit{2};
  11641. unsigned int queued_count{0};
  11642. std::atomic_uint count{0};
  11643. std::unique_ptr<TaskQueue> task_queue{
  11644. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11645. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11646. if (task_queue->enqueue(
  11647. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11648. queued_count++;
  11649. }
  11650. }
  11651. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11652. task_queue->shutdown();
  11653. #else
  11654. EXPECT_NO_THROW(task_queue->shutdown());
  11655. #endif
  11656. EXPECT_EQ(queued_count, count.load());
  11657. EXPECT_TRUE(queued_count <= number_of_tasks);
  11658. EXPECT_TRUE(queued_count >= qlimit);
  11659. }
  11660. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11661. // Use a short idle timeout so a dynamic thread spawns, times out and
  11662. // exits during the test, and the pool keeps working afterwards.
  11663. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11664. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11665. /*idle_timeout_sec=*/1}};
  11666. std::atomic_uint count{0};
  11667. std::condition_variable cv;
  11668. std::mutex mtx;
  11669. bool release = false;
  11670. // Block the base thread so the second task spawns a dynamic thread.
  11671. EXPECT_TRUE(task_queue->enqueue([&] {
  11672. std::unique_lock<std::mutex> lock(mtx);
  11673. while (!release) {
  11674. cv.wait(lock);
  11675. }
  11676. count++;
  11677. }));
  11678. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11679. // Let the dynamic thread finish its task and exceed the idle timeout.
  11680. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11681. {
  11682. std::unique_lock<std::mutex> lock(mtx);
  11683. release = true;
  11684. }
  11685. cv.notify_all();
  11686. // The pool must still accept and run tasks after the dynamic thread exited.
  11687. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11688. task_queue->shutdown();
  11689. EXPECT_EQ(3u, count.load());
  11690. }
  11691. TEST(TaskQueueTest, MaxQueuedRequests) {
  11692. static constexpr unsigned int qlimit{3};
  11693. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11694. std::condition_variable sem_cv;
  11695. std::mutex sem_mtx;
  11696. int credits = 0;
  11697. bool queued;
  11698. /* Fill up the queue with tasks that will block until we give them credits to
  11699. * complete. */
  11700. for (unsigned int n = 0; n <= qlimit;) {
  11701. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11702. std::unique_lock<std::mutex> lock(sem_mtx);
  11703. while (credits <= 0) {
  11704. sem_cv.wait(lock);
  11705. }
  11706. /* Consume the credit and signal the test code if they are all gone. */
  11707. if (--credits == 0) { sem_cv.notify_one(); }
  11708. });
  11709. if (n < qlimit) {
  11710. /* The first qlimit enqueues must succeed. */
  11711. EXPECT_TRUE(queued);
  11712. } else {
  11713. /* The last one will succeed only when the worker thread
  11714. * starts and dequeues the first blocking task. Although
  11715. * not necessary for the correctness of this test, we sleep for
  11716. * a short while to avoid busy waiting. */
  11717. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11718. }
  11719. if (queued) { n++; }
  11720. }
  11721. /* Further enqueues must fail since the queue is full. */
  11722. for (auto i = 0; i < 4; i++) {
  11723. queued = task_queue->enqueue([] {});
  11724. EXPECT_FALSE(queued);
  11725. }
  11726. /* Give the credits to allow the previous tasks to complete. */
  11727. {
  11728. std::unique_lock<std::mutex> lock(sem_mtx);
  11729. credits += qlimit + 1;
  11730. }
  11731. sem_cv.notify_all();
  11732. /* Wait for all the credits to be consumed. */
  11733. {
  11734. std::unique_lock<std::mutex> lock(sem_mtx);
  11735. while (credits > 0) {
  11736. sem_cv.wait(lock);
  11737. }
  11738. }
  11739. /* Check that we are able again to enqueue at least qlimit tasks. */
  11740. for (unsigned int i = 0; i < qlimit; i++) {
  11741. queued = task_queue->enqueue([] {});
  11742. EXPECT_TRUE(queued);
  11743. }
  11744. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11745. task_queue->shutdown();
  11746. #else
  11747. EXPECT_NO_THROW(task_queue->shutdown());
  11748. #endif
  11749. }
  11750. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11751. Server svr;
  11752. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11753. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11754. });
  11755. svr.Get("/hello", [](const Request &req, Response &res) {
  11756. res.set_content(req.get_param_value("key"), "text/plain");
  11757. });
  11758. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11759. auto se = detail::scope_exit([&] {
  11760. svr.stop();
  11761. thread.join();
  11762. ASSERT_FALSE(svr.is_running());
  11763. });
  11764. svr.wait_until_ready();
  11765. {
  11766. Client cli(HOST, PORT);
  11767. cli.set_follow_location(true);
  11768. auto res = cli.Get("/");
  11769. ASSERT_TRUE(res);
  11770. EXPECT_EQ(StatusCode::OK_200, res->status);
  11771. EXPECT_EQ("val&key2=val2", res->body);
  11772. }
  11773. }
  11774. #endif
  11775. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11776. Server svr;
  11777. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11778. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11779. });
  11780. svr.Get("/hello", [](const Request &req, Response &res) {
  11781. res.set_content(req.get_param_value("key"), "text/plain");
  11782. });
  11783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11784. auto se = detail::scope_exit([&] {
  11785. svr.stop();
  11786. thread.join();
  11787. ASSERT_FALSE(svr.is_running());
  11788. });
  11789. svr.wait_until_ready();
  11790. {
  11791. Client cli(HOST, PORT);
  11792. cli.set_follow_location(true);
  11793. auto res = cli.Get("/");
  11794. ASSERT_TRUE(res);
  11795. EXPECT_EQ(StatusCode::OK_200, res->status);
  11796. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11797. }
  11798. }
  11799. TEST(RedirectTest, RedirectWithPlusInPath) {
  11800. Server svr;
  11801. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11802. res.set_redirect("/a+b");
  11803. });
  11804. // Route pattern uses regex; escape + as \\+
  11805. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11806. res.set_content(req.path, "text/plain");
  11807. });
  11808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. thread.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. {
  11816. Client cli(HOST, PORT);
  11817. cli.set_follow_location(true);
  11818. auto res = cli.Get("/");
  11819. ASSERT_TRUE(res);
  11820. EXPECT_EQ(StatusCode::OK_200, res->status);
  11821. EXPECT_EQ("/a+b", res->body);
  11822. }
  11823. }
  11824. #ifdef CPPHTTPLIB_SSL_ENABLED
  11825. TEST(RedirectTest, Issue2185_Online) {
  11826. SSLClient client("github.com");
  11827. client.set_follow_location(true);
  11828. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11829. "Coollab-Windows.zip");
  11830. ASSERT_TRUE(res);
  11831. EXPECT_EQ(StatusCode::OK_200, res->status);
  11832. EXPECT_EQ(9920427U, res->body.size());
  11833. }
  11834. #endif
  11835. TEST(VulnerabilityTest, CRLFInjection) {
  11836. Server svr;
  11837. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11838. res.set_content("Hello 1", "text/plain");
  11839. });
  11840. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11841. res.set_content("Hello 2", "text/plain");
  11842. });
  11843. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11844. res.set_content("Hello 3", "text/plain");
  11845. });
  11846. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11847. res.set_content("Hello 4", "text/plain");
  11848. });
  11849. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11850. for (const auto &x : req.headers) {
  11851. auto key = x.first;
  11852. EXPECT_STRNE("evil", key.c_str());
  11853. }
  11854. });
  11855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11856. auto se = detail::scope_exit([&] {
  11857. svr.stop();
  11858. thread.join();
  11859. ASSERT_FALSE(svr.is_running());
  11860. });
  11861. svr.wait_until_ready();
  11862. {
  11863. Client cli(HOST, PORT);
  11864. cli.Post("/test1", "A=B",
  11865. "application/x-www-form-urlencoded\r\nevil: hello1");
  11866. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11867. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11868. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11869. }
  11870. }
  11871. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11872. auto server_thread = std::thread([] {
  11873. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11874. default_socket_options(srv);
  11875. sockaddr_in addr{};
  11876. addr.sin_family = AF_INET;
  11877. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11878. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11879. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11880. ::listen(srv, 1);
  11881. sockaddr_in cli_addr{};
  11882. socklen_t cli_len = sizeof(cli_addr);
  11883. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11884. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11885. std::string buf_all;
  11886. char buf[2048];
  11887. ssize_t n;
  11888. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11889. buf_all.append(buf, static_cast<size_t>(n));
  11890. size_t pos;
  11891. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11892. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11893. auto e = request_block.find("\r\n");
  11894. if (e != std::string::npos) {
  11895. auto request_line = request_block.substr(0, e);
  11896. std::string msg =
  11897. "CRLF injection detected in request line: '" + request_line + "'";
  11898. EXPECT_FALSE(true) << msg;
  11899. }
  11900. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11901. ::send(cli,
  11902. #ifdef _WIN32
  11903. static_cast<const char *>(resp.c_str()),
  11904. static_cast<int>(resp.size()),
  11905. #else
  11906. resp.c_str(), resp.size(),
  11907. #endif
  11908. 0);
  11909. buf_all.erase(0, pos + 4);
  11910. }
  11911. }
  11912. detail::close_socket(cli);
  11913. detail::close_socket(srv);
  11914. });
  11915. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11916. auto cli = Client("127.0.0.1", PORT + 1);
  11917. auto headers = Headers{
  11918. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11919. {"Connection", "keep-alive"}};
  11920. auto res = cli.Get("/hi", headers);
  11921. EXPECT_FALSE(res);
  11922. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11923. server_thread.join();
  11924. }
  11925. TEST(PathParamsTest, StaticMatch) {
  11926. const auto pattern = "/users/all";
  11927. detail::PathParamsMatcher matcher(pattern);
  11928. Request request;
  11929. request.path = "/users/all";
  11930. ASSERT_TRUE(matcher.match(request));
  11931. std::unordered_map<std::string, std::string> expected_params = {};
  11932. EXPECT_EQ(request.path_params, expected_params);
  11933. }
  11934. TEST(PathParamsTest, StaticMismatch) {
  11935. const auto pattern = "/users/all";
  11936. detail::PathParamsMatcher matcher(pattern);
  11937. Request request;
  11938. request.path = "/users/1";
  11939. ASSERT_FALSE(matcher.match(request));
  11940. }
  11941. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11942. const auto pattern = "/users/:id/subscriptions";
  11943. detail::PathParamsMatcher matcher(pattern);
  11944. Request request;
  11945. request.path = "/users/42/subscriptions";
  11946. ASSERT_TRUE(matcher.match(request));
  11947. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11948. EXPECT_EQ(request.path_params, expected_params);
  11949. }
  11950. TEST(PathParamsTest, SingleParamInTheEnd) {
  11951. const auto pattern = "/users/:id";
  11952. detail::PathParamsMatcher matcher(pattern);
  11953. Request request;
  11954. request.path = "/users/24";
  11955. ASSERT_TRUE(matcher.match(request));
  11956. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11957. EXPECT_EQ(request.path_params, expected_params);
  11958. }
  11959. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11960. const auto pattern = "/users/:id/";
  11961. detail::PathParamsMatcher matcher(pattern);
  11962. Request request;
  11963. request.path = "/users/42/";
  11964. ASSERT_TRUE(matcher.match(request));
  11965. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11966. EXPECT_EQ(request.path_params, expected_params);
  11967. }
  11968. TEST(PathParamsTest, EmptyParam) {
  11969. const auto pattern = "/users/:id/";
  11970. detail::PathParamsMatcher matcher(pattern);
  11971. Request request;
  11972. request.path = "/users//";
  11973. ASSERT_TRUE(matcher.match(request));
  11974. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11975. EXPECT_EQ(request.path_params, expected_params);
  11976. }
  11977. TEST(PathParamsTest, FragmentMismatch) {
  11978. const auto pattern = "/users/:id/";
  11979. detail::PathParamsMatcher matcher(pattern);
  11980. Request request;
  11981. request.path = "/admins/24/";
  11982. ASSERT_FALSE(matcher.match(request));
  11983. }
  11984. TEST(PathParamsTest, ExtraFragments) {
  11985. const auto pattern = "/users/:id";
  11986. detail::PathParamsMatcher matcher(pattern);
  11987. Request request;
  11988. request.path = "/users/42/subscriptions";
  11989. ASSERT_FALSE(matcher.match(request));
  11990. }
  11991. TEST(PathParamsTest, MissingTrailingParam) {
  11992. const auto pattern = "/users/:id";
  11993. detail::PathParamsMatcher matcher(pattern);
  11994. Request request;
  11995. request.path = "/users";
  11996. ASSERT_FALSE(matcher.match(request));
  11997. }
  11998. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11999. const auto pattern = "/users/:id/subscriptions";
  12000. detail::PathParamsMatcher matcher(pattern);
  12001. Request request;
  12002. request.path = "/users/subscriptions";
  12003. ASSERT_FALSE(matcher.match(request));
  12004. }
  12005. TEST(PathParamsTest, MultipleParams) {
  12006. const auto pattern = "/users/:userid/subscriptions/:subid";
  12007. detail::PathParamsMatcher matcher(pattern);
  12008. Request request;
  12009. request.path = "/users/42/subscriptions/2";
  12010. ASSERT_TRUE(matcher.match(request));
  12011. std::unordered_map<std::string, std::string> expected_params = {
  12012. {"userid", "42"}, {"subid", "2"}};
  12013. EXPECT_EQ(request.path_params, expected_params);
  12014. }
  12015. TEST(PathParamsTest, SequenceOfParams) {
  12016. const auto pattern = "/values/:x/:y/:z";
  12017. detail::PathParamsMatcher matcher(pattern);
  12018. Request request;
  12019. request.path = "/values/1/2/3";
  12020. ASSERT_TRUE(matcher.match(request));
  12021. std::unordered_map<std::string, std::string> expected_params = {
  12022. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12023. EXPECT_EQ(request.path_params, expected_params);
  12024. }
  12025. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12026. const auto pattern = "/prefix:suffix";
  12027. detail::PathParamsMatcher matcher(pattern);
  12028. Request request;
  12029. request.path = "/prefix:suffix";
  12030. ASSERT_TRUE(matcher.match(request));
  12031. const std::unordered_map<std::string, std::string> expected_params = {};
  12032. EXPECT_EQ(request.path_params, expected_params);
  12033. }
  12034. TEST(ParseUrlTest, VariousPatterns) {
  12035. {
  12036. detail::UrlComponents uc;
  12037. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12038. EXPECT_EQ("http", uc.scheme);
  12039. EXPECT_EQ("example.com", uc.host);
  12040. EXPECT_EQ("8080", uc.port);
  12041. EXPECT_EQ("/path", uc.path);
  12042. EXPECT_EQ("?q=1", uc.query);
  12043. }
  12044. {
  12045. detail::UrlComponents uc;
  12046. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12047. EXPECT_EQ("https", uc.scheme);
  12048. EXPECT_EQ("example.com", uc.host);
  12049. EXPECT_TRUE(uc.port.empty());
  12050. EXPECT_EQ("/path", uc.path);
  12051. }
  12052. {
  12053. detail::UrlComponents uc;
  12054. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12055. EXPECT_EQ("::1", uc.host);
  12056. EXPECT_EQ("8080", uc.port);
  12057. EXPECT_EQ("/path", uc.path);
  12058. }
  12059. {
  12060. detail::UrlComponents uc;
  12061. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12062. }
  12063. {
  12064. detail::UrlComponents uc;
  12065. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12066. EXPECT_TRUE(uc.scheme.empty());
  12067. EXPECT_EQ("example.com", uc.host);
  12068. EXPECT_EQ("/path", uc.path);
  12069. EXPECT_EQ("?q=1", uc.query);
  12070. }
  12071. {
  12072. detail::UrlComponents uc;
  12073. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12074. EXPECT_TRUE(uc.host.empty());
  12075. EXPECT_EQ("/path", uc.path);
  12076. EXPECT_EQ("?q=1", uc.query);
  12077. }
  12078. {
  12079. detail::UrlComponents uc;
  12080. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12081. EXPECT_EQ("example.com", uc.host);
  12082. EXPECT_EQ("8080", uc.port);
  12083. }
  12084. {
  12085. // Unix socket path — must not be parsed as host
  12086. detail::UrlComponents uc;
  12087. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12088. EXPECT_TRUE(uc.host.empty());
  12089. }
  12090. {
  12091. detail::UrlComponents uc;
  12092. ASSERT_TRUE(detail::parse_url("", uc));
  12093. EXPECT_TRUE(uc.host.empty());
  12094. EXPECT_TRUE(uc.path.empty());
  12095. }
  12096. {
  12097. detail::UrlComponents uc;
  12098. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12099. }
  12100. {
  12101. detail::UrlComponents uc;
  12102. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12103. }
  12104. {
  12105. // Accepted by parse_url; callers restrict to http/https
  12106. detail::UrlComponents uc;
  12107. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12108. EXPECT_EQ("ftp", uc.scheme);
  12109. }
  12110. {
  12111. detail::UrlComponents uc;
  12112. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12113. }
  12114. {
  12115. detail::UrlComponents uc;
  12116. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12117. }
  12118. }
  12119. TEST(ParseUrlTest, FragmentHandling) {
  12120. {
  12121. detail::UrlComponents uc;
  12122. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12123. EXPECT_EQ("/path", uc.path);
  12124. EXPECT_TRUE(uc.query.empty());
  12125. }
  12126. {
  12127. detail::UrlComponents uc;
  12128. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12129. EXPECT_TRUE(uc.path.empty());
  12130. EXPECT_TRUE(uc.query.empty());
  12131. }
  12132. }
  12133. TEST(ParseUrlTest, UserinfoHandling) {
  12134. // Userinfo with @ but no colon — host includes @
  12135. detail::UrlComponents uc;
  12136. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12137. EXPECT_EQ("user@host.com", uc.host);
  12138. EXPECT_EQ("/path", uc.path);
  12139. }
  12140. TEST(ParseUrlTest, IPv6EdgeCases) {
  12141. {
  12142. detail::UrlComponents uc;
  12143. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12144. EXPECT_TRUE(uc.scheme.empty());
  12145. EXPECT_EQ("::1", uc.host);
  12146. EXPECT_EQ("8080", uc.port);
  12147. }
  12148. {
  12149. // Zone ID '%25' is not in [a-fA-F0-9:]
  12150. detail::UrlComponents uc;
  12151. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12152. }
  12153. }
  12154. TEST(ParseUrlTest, SchemeEdgeCases) {
  12155. {
  12156. detail::UrlComponents uc;
  12157. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12158. }
  12159. {
  12160. detail::UrlComponents uc;
  12161. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12162. }
  12163. {
  12164. detail::UrlComponents uc;
  12165. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12166. }
  12167. }
  12168. TEST(ParseUrlTest, PortEdgeCases) {
  12169. {
  12170. detail::UrlComponents uc;
  12171. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12172. EXPECT_TRUE(uc.port.empty());
  12173. EXPECT_EQ("/path", uc.path);
  12174. }
  12175. {
  12176. // parse_url accepts any port string; validation is done by parse_port
  12177. detail::UrlComponents uc;
  12178. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12179. EXPECT_EQ("abc", uc.port);
  12180. }
  12181. }
  12182. TEST(ParseUrlTest, WebSocketPatterns) {
  12183. {
  12184. detail::UrlComponents uc;
  12185. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12186. EXPECT_EQ("ws", uc.scheme);
  12187. EXPECT_EQ("echo.example.com", uc.host);
  12188. EXPECT_EQ("8080", uc.port);
  12189. EXPECT_EQ("/ws", uc.path);
  12190. }
  12191. {
  12192. detail::UrlComponents uc;
  12193. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12194. EXPECT_EQ("wss", uc.scheme);
  12195. EXPECT_EQ("echo.example.com", uc.host);
  12196. EXPECT_TRUE(uc.port.empty());
  12197. EXPECT_EQ("/ws", uc.path);
  12198. }
  12199. }
  12200. TEST(ParseUrlTest, QueryOnly) {
  12201. detail::UrlComponents uc;
  12202. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12203. EXPECT_TRUE(uc.host.empty());
  12204. EXPECT_TRUE(uc.path.empty());
  12205. EXPECT_EQ("?q=1&r=2", uc.query);
  12206. }
  12207. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12208. detail::UrlComponents uc;
  12209. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12210. EXPECT_TRUE(uc.scheme.empty());
  12211. EXPECT_EQ("example.com", uc.host);
  12212. EXPECT_EQ("443", uc.port);
  12213. EXPECT_EQ("/path", uc.path);
  12214. }
  12215. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12216. // If ipv6 regex working, regex match codepath is taken.
  12217. // else port will default to 80 in Client impl
  12218. int clientImplMagicPort = 80;
  12219. int port = 4321;
  12220. // above ports must be different to avoid false negative
  12221. EXPECT_NE(clientImplMagicPort, port);
  12222. std::string ipV6TestURL = "http://[ff06::c3]";
  12223. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12224. CLIENT_PRIVATE_KEY_FILE);
  12225. EXPECT_EQ(cli.port(), port);
  12226. }
  12227. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12228. auto file_path = "./www/dir/index.html";
  12229. auto dir_path = "./www/dir";
  12230. detail::FileStat stat_file(file_path);
  12231. EXPECT_TRUE(stat_file.is_file());
  12232. EXPECT_FALSE(stat_file.is_dir());
  12233. detail::FileStat stat_dir(dir_path);
  12234. EXPECT_FALSE(stat_dir.is_file());
  12235. EXPECT_TRUE(stat_dir.is_dir());
  12236. }
  12237. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12238. // IPv4 with default HTTP port (80)
  12239. EXPECT_EQ("example.com",
  12240. detail::make_host_and_port_string("example.com", 80, false));
  12241. // IPv4 with default HTTPS port (443)
  12242. EXPECT_EQ("example.com",
  12243. detail::make_host_and_port_string("example.com", 443, true));
  12244. // IPv4 with non-default HTTP port
  12245. EXPECT_EQ("example.com:8080",
  12246. detail::make_host_and_port_string("example.com", 8080, false));
  12247. // IPv4 with non-default HTTPS port
  12248. EXPECT_EQ("example.com:8443",
  12249. detail::make_host_and_port_string("example.com", 8443, true));
  12250. // IPv6 with default HTTP port (80)
  12251. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12252. // IPv6 with default HTTPS port (443)
  12253. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12254. // IPv6 with non-default HTTP port
  12255. EXPECT_EQ("[::1]:8080",
  12256. detail::make_host_and_port_string("::1", 8080, false));
  12257. // IPv6 with non-default HTTPS port
  12258. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12259. // IPv6 full address with default port
  12260. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12261. detail::make_host_and_port_string(
  12262. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12263. // IPv6 full address with non-default port
  12264. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12265. detail::make_host_and_port_string(
  12266. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12267. // IPv6 localhost with non-default port
  12268. EXPECT_EQ("[::1]:3000",
  12269. detail::make_host_and_port_string("::1", 3000, false));
  12270. // IPv6 with zone ID (link-local address) with default port
  12271. EXPECT_EQ("[fe80::1%eth0]",
  12272. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12273. // IPv6 with zone ID (link-local address) with non-default port
  12274. EXPECT_EQ("[fe80::1%eth0]:8080",
  12275. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12276. // Edge case: Port 443 with is_ssl=false (should add port)
  12277. EXPECT_EQ("example.com:443",
  12278. detail::make_host_and_port_string("example.com", 443, false));
  12279. // Edge case: Port 80 with is_ssl=true (should add port)
  12280. EXPECT_EQ("example.com:80",
  12281. detail::make_host_and_port_string("example.com", 80, true));
  12282. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12283. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12284. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12285. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12286. // Security fix: Already bracketed IPv6 should not get double brackets
  12287. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12288. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12289. EXPECT_EQ("[::1]:8080",
  12290. detail::make_host_and_port_string("[::1]", 8080, false));
  12291. EXPECT_EQ("[2001:db8::1]:8080",
  12292. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12293. EXPECT_EQ("[fe80::1%eth0]",
  12294. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12295. EXPECT_EQ("[fe80::1%eth0]:8080",
  12296. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12297. // Edge case: Empty host (should return as-is)
  12298. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12299. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12300. // This is a known limitation but shouldn't crash
  12301. EXPECT_EQ("[host:name]",
  12302. detail::make_host_and_port_string("host:name", 80, false));
  12303. // Port number edge cases (no validation, but should not crash)
  12304. EXPECT_EQ("example.com:0",
  12305. detail::make_host_and_port_string("example.com", 0, false));
  12306. EXPECT_EQ("example.com:-1",
  12307. detail::make_host_and_port_string("example.com", -1, false));
  12308. EXPECT_EQ("example.com:65535",
  12309. detail::make_host_and_port_string("example.com", 65535, false));
  12310. EXPECT_EQ("example.com:65536",
  12311. detail::make_host_and_port_string("example.com", 65536, false));
  12312. }
  12313. #ifdef CPPHTTPLIB_SSL_ENABLED
  12314. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12315. httplib::SSLClient cli("roblox.com", 443);
  12316. cli.set_follow_location(true);
  12317. auto res = cli.Get("/");
  12318. ASSERT_TRUE(res);
  12319. EXPECT_EQ(StatusCode::OK_200, res->status);
  12320. }
  12321. #endif
  12322. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12323. Server svr;
  12324. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12325. EXPECT_EQ(res.status, 400);
  12326. });
  12327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12328. auto se = detail::scope_exit([&] {
  12329. svr.stop();
  12330. thread.join();
  12331. ASSERT_FALSE(svr.is_running());
  12332. });
  12333. svr.wait_until_ready();
  12334. Client cli(HOST, PORT);
  12335. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12336. }
  12337. TEST(InvalidHeaderCharsTest, is_field_name) {
  12338. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12339. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12340. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12341. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12342. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12343. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12344. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12345. EXPECT_FALSE(detail::fields::is_field_name(""));
  12346. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12347. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12348. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12349. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12350. }
  12351. TEST(InvalidHeaderCharsTest, is_field_value) {
  12352. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12353. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12354. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12355. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12356. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12357. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12358. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12359. EXPECT_TRUE(detail::fields::is_field_value(""));
  12360. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12361. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12362. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12363. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12364. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12365. }
  12366. TEST(InvalidHeaderCharsTest, OnServer) {
  12367. Server svr;
  12368. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12369. std::string header = "Not Set";
  12370. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12371. res.set_header(header, "value");
  12372. res.set_content("Page Content Page Content", "text/plain");
  12373. });
  12374. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12375. std::string header = "Not Set";
  12376. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12377. res.set_header("X-Test", header);
  12378. res.set_content("Page Content Page Content", "text/plain");
  12379. });
  12380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. thread.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. });
  12386. svr.wait_until_ready();
  12387. Client cli(HOST, PORT);
  12388. {
  12389. auto res = cli.Get(
  12390. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12391. ASSERT_TRUE(res);
  12392. EXPECT_EQ("Page Content Page Content", res->body);
  12393. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12394. }
  12395. {
  12396. auto res = cli.Get(
  12397. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12398. ASSERT_TRUE(res);
  12399. EXPECT_EQ("Page Content Page Content", res->body);
  12400. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12401. }
  12402. }
  12403. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12404. auto handled = false;
  12405. Server svr;
  12406. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12407. thread t = thread([&] { svr.listen(HOST, PORT); });
  12408. auto se = detail::scope_exit([&] {
  12409. svr.stop();
  12410. t.join();
  12411. ASSERT_FALSE(svr.is_running());
  12412. ASSERT_FALSE(handled);
  12413. });
  12414. svr.wait_until_ready();
  12415. auto req = "POST /test HTTP/1.1\r\n"
  12416. "Content-Length: x\r\n"
  12417. "\r\n";
  12418. std::string response;
  12419. ASSERT_TRUE(send_request(1, req, &response));
  12420. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12421. response.substr(0, response.find("\r\n")));
  12422. }
  12423. #ifndef _WIN32
  12424. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12425. static constexpr char reject[] = "Unauthorized";
  12426. static constexpr char accept[] = "Upload accepted";
  12427. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12428. Server svr;
  12429. svr.set_expect_100_continue_handler(
  12430. [](const Request & /*req*/, Response &res) {
  12431. res.status = StatusCode::Unauthorized_401;
  12432. res.set_content(reject, "text/plain");
  12433. return res.status;
  12434. });
  12435. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12436. res.set_content(accept, "text/plain");
  12437. });
  12438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12439. auto se = detail::scope_exit([&] {
  12440. svr.stop();
  12441. thread.join();
  12442. ASSERT_FALSE(svr.is_running());
  12443. });
  12444. svr.wait_until_ready();
  12445. {
  12446. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12447. curl_easy_init(), &curl_easy_cleanup};
  12448. ASSERT_NE(curl, nullptr);
  12449. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12450. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12451. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12452. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12453. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12454. &curl_slist_free_all};
  12455. ASSERT_NE(list, nullptr);
  12456. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12457. struct read_data {
  12458. size_t read_size;
  12459. size_t total_size;
  12460. } data = {0, total_size};
  12461. using read_callback_t =
  12462. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12463. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12464. void *userdata) -> size_t {
  12465. read_data *d = (read_data *)userdata;
  12466. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12467. std::fill_n(ptr, size * nmemb, 'A');
  12468. d->read_size += size * nmemb;
  12469. return size * nmemb;
  12470. };
  12471. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12472. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12473. std::vector<char> buffer;
  12474. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12475. using write_callback_t =
  12476. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12477. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12478. void *userdata) -> size_t {
  12479. std::vector<char> *buf = (std::vector<char> *)userdata;
  12480. buf->reserve(buf->size() + size * nmemb + 1);
  12481. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12482. return size * nmemb;
  12483. };
  12484. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12485. {
  12486. const auto res = curl_easy_perform(curl.get());
  12487. ASSERT_EQ(res, CURLE_OK);
  12488. }
  12489. {
  12490. auto response_code = long{};
  12491. const auto res =
  12492. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12493. ASSERT_EQ(res, CURLE_OK);
  12494. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12495. }
  12496. {
  12497. auto dl = curl_off_t{};
  12498. const auto res =
  12499. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12500. ASSERT_EQ(res, CURLE_OK);
  12501. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12502. }
  12503. {
  12504. buffer.push_back('\0');
  12505. ASSERT_STRCASEEQ(buffer.data(), reject);
  12506. }
  12507. }
  12508. }
  12509. #endif
  12510. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12511. // Regression test for #2458.
  12512. //
  12513. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12514. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12515. // ticket can make the client socket spuriously readable during the
  12516. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12517. // the client withholds the body and then blocks reading a response that never
  12518. // comes, failing with `Failed to read connection`.
  12519. //
  12520. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12521. // within the timeout. This raw OpenSSL server deliberately never sends
  12522. // `100 Continue`; the client must still deliver the body and receive 200.
  12523. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12524. signal(SIGPIPE, SIG_IGN);
  12525. const auto port = PORT + 4;
  12526. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12527. ASSERT_NE(srv, INVALID_SOCKET);
  12528. int opt = 1;
  12529. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12530. sockaddr_in addr{};
  12531. addr.sin_family = AF_INET;
  12532. addr.sin_port = htons(static_cast<uint16_t>(port));
  12533. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12534. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12535. ASSERT_EQ(0, ::listen(srv, 1));
  12536. std::atomic<size_t> server_body_bytes{0};
  12537. auto server_thread = std::thread([&] {
  12538. sockaddr_in cli_addr{};
  12539. socklen_t cli_len = sizeof(cli_addr);
  12540. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12541. if (cli == INVALID_SOCKET) { return; }
  12542. // Bound the lifetime of the server side so a buggy client (which never
  12543. // sends the body) cannot make this thread block forever on join.
  12544. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12545. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12546. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12547. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12548. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12549. SSL *ssl = SSL_new(ctx);
  12550. SSL_set_fd(ssl, static_cast<int>(cli));
  12551. if (SSL_accept(ssl) > 0) {
  12552. // Read the request headers. Reading here also flushes the TLS 1.3
  12553. // session tickets to the client. Deliberately do NOT send
  12554. // `100 Continue`.
  12555. std::string buf;
  12556. char tmp[1024];
  12557. while (buf.find("\r\n\r\n") == std::string::npos) {
  12558. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12559. if (n <= 0) { break; }
  12560. buf.append(tmp, static_cast<size_t>(n));
  12561. }
  12562. // A correct client sends the body now; count what arrives.
  12563. auto pos = buf.find("\r\n\r\n");
  12564. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12565. while (body < 4096) {
  12566. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12567. if (n <= 0) { break; }
  12568. body += static_cast<size_t>(n);
  12569. }
  12570. server_body_bytes = body;
  12571. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12572. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12573. SSL_shutdown(ssl);
  12574. }
  12575. SSL_free(ssl);
  12576. detail::close_socket(cli);
  12577. SSL_CTX_free(ctx);
  12578. });
  12579. auto se = detail::scope_exit([&] {
  12580. server_thread.join();
  12581. detail::close_socket(srv);
  12582. });
  12583. SSLClient cli("127.0.0.1", port);
  12584. cli.enable_server_certificate_verification(false);
  12585. cli.set_connection_timeout(5, 0);
  12586. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12587. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12588. std::string body(4096, 'A');
  12589. auto res = cli.Put("/api/test", body, "application/json");
  12590. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12591. EXPECT_EQ(StatusCode::OK_200, res->status);
  12592. EXPECT_EQ(body.size(), server_body_bytes.load());
  12593. }
  12594. #endif
  12595. template <typename S, typename C>
  12596. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12597. svr.Get("/stream", [&](const Request &, Response &res) {
  12598. auto data = new std::string("01234567890123456789");
  12599. res.set_content_provider(
  12600. data->size(), "text/plain",
  12601. [&, data](size_t offset, size_t length, DataSink &sink) {
  12602. const size_t DATA_CHUNK_SIZE = 4;
  12603. const auto &d = *data;
  12604. std::this_thread::sleep_for(std::chrono::seconds(1));
  12605. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12606. return true;
  12607. },
  12608. [data](bool success) {
  12609. EXPECT_FALSE(success);
  12610. delete data;
  12611. });
  12612. });
  12613. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12614. auto i = new size_t(0);
  12615. res.set_content_provider(
  12616. "text/plain",
  12617. [i](size_t, DataSink &sink) {
  12618. if (*i < 5) {
  12619. std::this_thread::sleep_for(std::chrono::seconds(1));
  12620. sink.write("abcd", 4);
  12621. (*i)++;
  12622. } else {
  12623. sink.done();
  12624. }
  12625. return true;
  12626. },
  12627. [i](bool success) {
  12628. EXPECT_FALSE(success);
  12629. delete i;
  12630. });
  12631. });
  12632. svr.Get("/chunked", [&](const Request &, Response &res) {
  12633. auto i = new size_t(0);
  12634. res.set_chunked_content_provider(
  12635. "text/plain",
  12636. [i](size_t, DataSink &sink) {
  12637. if (*i < 5) {
  12638. std::this_thread::sleep_for(std::chrono::seconds(1));
  12639. sink.os << "abcd";
  12640. (*i)++;
  12641. } else {
  12642. sink.done();
  12643. }
  12644. return true;
  12645. },
  12646. [i](bool success) {
  12647. EXPECT_FALSE(success);
  12648. delete i;
  12649. });
  12650. });
  12651. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12652. auto se = detail::scope_exit([&] {
  12653. svr.stop();
  12654. listen_thread.join();
  12655. ASSERT_FALSE(svr.is_running());
  12656. });
  12657. svr.wait_until_ready();
  12658. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12659. {
  12660. auto start = std::chrono::steady_clock::now();
  12661. auto res = cli.Get("/stream");
  12662. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12663. std::chrono::steady_clock::now() - start)
  12664. .count();
  12665. ASSERT_FALSE(res);
  12666. EXPECT_EQ(Error::Read, res.error());
  12667. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12668. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12669. }
  12670. {
  12671. auto start = std::chrono::steady_clock::now();
  12672. auto res = cli.Get("/stream_without_length");
  12673. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12674. std::chrono::steady_clock::now() - start)
  12675. .count();
  12676. ASSERT_FALSE(res);
  12677. EXPECT_EQ(Error::Read, res.error());
  12678. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12679. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12680. }
  12681. {
  12682. auto start = std::chrono::steady_clock::now();
  12683. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12684. EXPECT_EQ("abcd", string(data, data_length));
  12685. return true;
  12686. });
  12687. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12688. std::chrono::steady_clock::now() - start)
  12689. .count();
  12690. ASSERT_FALSE(res);
  12691. EXPECT_EQ(Error::Read, res.error());
  12692. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12693. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12694. }
  12695. }
  12696. TEST(MaxTimeoutTest, ContentStream) {
  12697. time_t timeout = 2000;
  12698. time_t threshold = 200;
  12699. Server svr;
  12700. Client cli("localhost", PORT);
  12701. max_timeout_test(svr, cli, timeout, threshold);
  12702. }
  12703. #ifdef CPPHTTPLIB_SSL_ENABLED
  12704. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12705. time_t timeout = 2000;
  12706. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12708. SSLClient cli("localhost", PORT);
  12709. cli.enable_server_certificate_verification(false);
  12710. max_timeout_test(svr, cli, timeout, threshold);
  12711. }
  12712. #endif
  12713. class EventDispatcher {
  12714. public:
  12715. EventDispatcher() {}
  12716. bool wait_event(DataSink *sink) {
  12717. unique_lock<mutex> lk(m_);
  12718. int id = id_;
  12719. // Wait with timeout to prevent hanging if client disconnects
  12720. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12721. [&] { return cid_ == id; })) {
  12722. return false; // Timeout occurred
  12723. }
  12724. sink->write(message_.data(), message_.size());
  12725. return true;
  12726. }
  12727. void send_event(const string &message) {
  12728. lock_guard<mutex> lk(m_);
  12729. cid_ = id_++;
  12730. message_ = message;
  12731. cv_.notify_all();
  12732. }
  12733. private:
  12734. mutex m_;
  12735. condition_variable cv_;
  12736. atomic_int id_{0};
  12737. atomic_int cid_{-1};
  12738. string message_;
  12739. };
  12740. TEST(ClientInThreadTest, Issue2068) {
  12741. EventDispatcher ed;
  12742. Server svr;
  12743. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12744. res.set_chunked_content_provider("text/event-stream",
  12745. [&](size_t /*offset*/, DataSink &sink) {
  12746. return ed.wait_event(&sink);
  12747. });
  12748. });
  12749. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12750. svr.wait_until_ready();
  12751. thread event_thread([&] {
  12752. int id = 0;
  12753. while (svr.is_running()) {
  12754. this_thread::sleep_for(chrono::milliseconds(500));
  12755. std::stringstream ss;
  12756. ss << "data: " << id << "\n\n";
  12757. ed.send_event(ss.str());
  12758. id++;
  12759. }
  12760. });
  12761. auto se = detail::scope_exit([&] {
  12762. svr.stop();
  12763. listen_thread.join();
  12764. event_thread.join();
  12765. ASSERT_FALSE(svr.is_running());
  12766. });
  12767. {
  12768. auto client = detail::make_unique<Client>(HOST, PORT);
  12769. client->set_read_timeout(std::chrono::minutes(10));
  12770. std::atomic<bool> stop{false};
  12771. std::thread t([&] {
  12772. client->Get("/event1",
  12773. [&](const char *, size_t) -> bool { return !stop; });
  12774. });
  12775. std::this_thread::sleep_for(std::chrono::seconds(2));
  12776. stop = true;
  12777. client->stop();
  12778. t.join();
  12779. // Reset client after thread has finished
  12780. client.reset();
  12781. }
  12782. }
  12783. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12784. auto handled = false;
  12785. Server svr;
  12786. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12787. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12788. auto se = detail::scope_exit([&] {
  12789. svr.stop();
  12790. t.join();
  12791. ASSERT_FALSE(svr.is_running());
  12792. ASSERT_FALSE(handled);
  12793. });
  12794. svr.wait_until_ready();
  12795. // Two Content-Length headers with different values — must be rejected
  12796. auto req = "POST /test HTTP/1.1\r\n"
  12797. "Content-Length: 5\r\n"
  12798. "Content-Length: 10\r\n"
  12799. "\r\n"
  12800. "hello";
  12801. std::string response;
  12802. ASSERT_TRUE(send_request(1, req, &response));
  12803. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12804. response.substr(0, response.find("\r\n")));
  12805. }
  12806. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12807. auto handled = false;
  12808. Server svr;
  12809. svr.Post("/test", [&](const Request &, Response &res) {
  12810. handled = true;
  12811. res.set_content("ok", "text/plain");
  12812. });
  12813. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop();
  12816. t.join();
  12817. ASSERT_FALSE(svr.is_running());
  12818. ASSERT_TRUE(handled);
  12819. });
  12820. svr.wait_until_ready();
  12821. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12822. auto req = "POST /test HTTP/1.1\r\n"
  12823. "Content-Length: 5\r\n"
  12824. "Content-Length: 5\r\n"
  12825. "\r\n"
  12826. "hello";
  12827. std::string response;
  12828. ASSERT_TRUE(send_request(1, req, &response));
  12829. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12830. }
  12831. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12832. Server svr;
  12833. svr.Get("/", [](const Request &req, Response &res) {
  12834. EXPECT_EQ(2U, req.trailers.size());
  12835. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12836. // Denied
  12837. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12838. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12839. // Accepted
  12840. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12841. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12842. EXPECT_TRUE(req.has_trailer("X-World"));
  12843. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12844. res.set_content("ok", "text/plain");
  12845. });
  12846. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12847. auto se = detail::scope_exit([&] {
  12848. svr.stop();
  12849. t.join();
  12850. ASSERT_FALSE(svr.is_running());
  12851. });
  12852. svr.wait_until_ready();
  12853. const std::string req = "GET / HTTP/1.1\r\n"
  12854. "Transfer-Encoding: chunked\r\n"
  12855. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12856. "\r\n"
  12857. "0\r\n"
  12858. "Content-Length: 10\r\n"
  12859. "Host: internal.local\r\n"
  12860. "Content-Type: malicious/content\r\n"
  12861. "Cookie: any\r\n"
  12862. "Set-Cookie: any\r\n"
  12863. "X-Forwarded-For: attacker.com\r\n"
  12864. "X-Real-Ip: 1.1.1.1\r\n"
  12865. "X-Hello: hello\r\n"
  12866. "X-World: world\r\n"
  12867. "\r\n";
  12868. std::string res;
  12869. ASSERT_TRUE(send_request(1, req, &res));
  12870. }
  12871. // A direct client that is not listed in trusted_proxies must not be able to
  12872. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  12873. // the peer address on the actual TCP connection determines whether the
  12874. // header is honored.
  12875. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  12876. Server svr;
  12877. // Deliberately does NOT include the loopback address the test client
  12878. // actually connects from, so the direct connection is not a trusted proxy.
  12879. svr.set_trusted_proxies({"203.0.113.66"});
  12880. std::string observed_remote_addr;
  12881. svr.Get("/ip", [&](const Request &req, Response &res) {
  12882. observed_remote_addr = req.remote_addr;
  12883. res.set_content("ok", "text/plain");
  12884. });
  12885. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12886. auto se = detail::scope_exit([&] {
  12887. svr.stop();
  12888. t.join();
  12889. ASSERT_FALSE(svr.is_running());
  12890. });
  12891. svr.wait_until_ready();
  12892. Client cli(HOST, PORT);
  12893. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  12894. ASSERT_TRUE(res);
  12895. EXPECT_EQ(StatusCode::OK_200, res->status);
  12896. // The connecting peer is not a trusted proxy, so the spoofed header must be
  12897. // ignored entirely and the real connection-level address retained.
  12898. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12899. observed_remote_addr == "127.0.0.1");
  12900. }
  12901. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12902. Server svr;
  12903. std::string observed_remote_addr;
  12904. std::string observed_xff;
  12905. svr.Get("/ip", [&](const Request &req, Response &res) {
  12906. observed_remote_addr = req.remote_addr;
  12907. observed_xff = req.get_header_value("X-Forwarded-For");
  12908. res.set_content("ok", "text/plain");
  12909. });
  12910. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12911. auto se = detail::scope_exit([&] {
  12912. svr.stop();
  12913. t.join();
  12914. ASSERT_FALSE(svr.is_running());
  12915. });
  12916. svr.wait_until_ready();
  12917. Client cli(HOST, PORT);
  12918. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12919. ASSERT_TRUE(res);
  12920. EXPECT_EQ(StatusCode::OK_200, res->status);
  12921. EXPECT_EQ(observed_xff, "203.0.113.66");
  12922. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12923. observed_remote_addr == "127.0.0.1");
  12924. }
  12925. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12926. Server svr;
  12927. svr.set_trusted_proxies({"203.0.113.66"});
  12928. std::string observed_remote_addr;
  12929. std::string observed_xff;
  12930. svr.Get("/ip", [&](const Request &req, Response &res) {
  12931. observed_remote_addr = req.remote_addr;
  12932. observed_xff = req.get_header_value("X-Forwarded-For");
  12933. res.set_content("ok", "text/plain");
  12934. });
  12935. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12936. auto se = detail::scope_exit([&] {
  12937. svr.stop();
  12938. t.join();
  12939. ASSERT_FALSE(svr.is_running());
  12940. });
  12941. svr.wait_until_ready();
  12942. Client cli(HOST, PORT);
  12943. auto res = cli.Get("/ip");
  12944. ASSERT_TRUE(res);
  12945. EXPECT_EQ(StatusCode::OK_200, res->status);
  12946. EXPECT_EQ(observed_xff, "");
  12947. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12948. observed_remote_addr == "127.0.0.1");
  12949. }
  12950. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12951. Server svr;
  12952. // Include the loopback address the test client actually connects from, so
  12953. // the direct connection itself is recognized as the trusted proxy hop.
  12954. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  12955. std::string observed_remote_addr;
  12956. std::string observed_xff;
  12957. svr.Get("/ip", [&](const Request &req, Response &res) {
  12958. observed_remote_addr = req.remote_addr;
  12959. observed_xff = req.get_header_value("X-Forwarded-For");
  12960. res.set_content("ok", "text/plain");
  12961. });
  12962. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12963. auto se = detail::scope_exit([&] {
  12964. svr.stop();
  12965. t.join();
  12966. ASSERT_FALSE(svr.is_running());
  12967. });
  12968. svr.wait_until_ready();
  12969. Client cli(HOST, PORT);
  12970. auto res = cli.Get(
  12971. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12972. ASSERT_TRUE(res);
  12973. EXPECT_EQ(StatusCode::OK_200, res->status);
  12974. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12975. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12976. }
  12977. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12978. Server svr;
  12979. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  12980. std::string observed_remote_addr;
  12981. std::string observed_xff;
  12982. svr.Get("/ip", [&](const Request &req, Response &res) {
  12983. observed_remote_addr = req.remote_addr;
  12984. observed_xff = req.get_header_value("X-Forwarded-For");
  12985. res.set_content("ok", "text/plain");
  12986. });
  12987. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12988. auto se = detail::scope_exit([&] {
  12989. svr.stop();
  12990. t.join();
  12991. ASSERT_FALSE(svr.is_running());
  12992. });
  12993. svr.wait_until_ready();
  12994. Client cli(HOST, PORT);
  12995. auto res = cli.Get(
  12996. "/ip",
  12997. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12998. ASSERT_TRUE(res);
  12999. EXPECT_EQ(StatusCode::OK_200, res->status);
  13000. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13001. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13002. }
  13003. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13004. Server svr;
  13005. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13006. std::string observed_remote_addr;
  13007. std::string observed_xff;
  13008. svr.Get("/ip", [&](const Request &req, Response &res) {
  13009. observed_remote_addr = req.remote_addr;
  13010. observed_xff = req.get_header_value("X-Forwarded-For");
  13011. res.set_content("ok", "text/plain");
  13012. });
  13013. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13014. auto se = detail::scope_exit([&] {
  13015. svr.stop();
  13016. t.join();
  13017. ASSERT_FALSE(svr.is_running());
  13018. });
  13019. svr.wait_until_ready();
  13020. Client cli(HOST, PORT);
  13021. auto res = cli.Get(
  13022. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13023. ASSERT_TRUE(res);
  13024. EXPECT_EQ(StatusCode::OK_200, res->status);
  13025. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13026. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13027. // and must not be selected.
  13028. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13029. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13030. }
  13031. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13032. Server svr;
  13033. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13034. std::string observed_remote_addr;
  13035. svr.Get("/ip", [&](const Request &req, Response &res) {
  13036. observed_remote_addr = req.remote_addr;
  13037. res.set_content("ok", "text/plain");
  13038. });
  13039. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13040. auto se = detail::scope_exit([&] {
  13041. svr.stop();
  13042. t.join();
  13043. ASSERT_FALSE(svr.is_running());
  13044. });
  13045. svr.wait_until_ready();
  13046. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13047. // a forged address and the trusted proxy's own address; the forged value must
  13048. // not win over the address the trusted proxy actually recorded.
  13049. Client cli(HOST, PORT);
  13050. auto res = cli.Get(
  13051. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13052. ASSERT_TRUE(res);
  13053. EXPECT_EQ(StatusCode::OK_200, res->status);
  13054. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13055. }
  13056. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13057. Server svr;
  13058. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13059. std::string observed_remote_addr;
  13060. std::string observed_xff;
  13061. svr.Get("/ip", [&](const Request &req, Response &res) {
  13062. observed_remote_addr = req.remote_addr;
  13063. observed_xff = req.get_header_value("X-Forwarded-For");
  13064. res.set_content("ok", "text/plain");
  13065. });
  13066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13067. auto se = detail::scope_exit([&] {
  13068. svr.stop();
  13069. t.join();
  13070. ASSERT_FALSE(svr.is_running());
  13071. });
  13072. svr.wait_until_ready();
  13073. Client cli(HOST, PORT);
  13074. auto res = cli.Get(
  13075. "/ip",
  13076. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13077. ASSERT_TRUE(res);
  13078. EXPECT_EQ(StatusCode::OK_200, res->status);
  13079. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13080. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13081. }
  13082. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13083. Server svr;
  13084. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13085. std::string observed_remote_addr;
  13086. std::string observed_xff;
  13087. svr.Get("/ip", [&](const Request &req, Response &res) {
  13088. observed_remote_addr = req.remote_addr;
  13089. observed_xff = req.get_header_value("X-Forwarded-For");
  13090. res.set_content("ok", "text/plain");
  13091. });
  13092. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13093. auto se = detail::scope_exit([&] {
  13094. svr.stop();
  13095. t.join();
  13096. ASSERT_FALSE(svr.is_running());
  13097. });
  13098. svr.wait_until_ready();
  13099. std::string raw_req =
  13100. "GET /ip HTTP/1.1\r\n"
  13101. "Host: localhost\r\n"
  13102. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13103. "Connection: close\r\n"
  13104. "\r\n";
  13105. std::string out;
  13106. ASSERT_TRUE(send_request(5, raw_req, &out));
  13107. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13108. // Header parser trims surrounding whitespace of the header value
  13109. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13110. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13111. }
  13112. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13113. // crash the server (it used to call front() on an empty vector inside
  13114. // get_client_ip). The connection-level remote address must be retained instead.
  13115. static void run_malformed_xff_test(const std::string &xff_value) {
  13116. Server svr;
  13117. svr.set_trusted_proxies({"192.0.2.45"});
  13118. std::string observed_remote_addr;
  13119. svr.Get("/ip", [&](const Request &req, Response &res) {
  13120. observed_remote_addr = req.remote_addr;
  13121. res.set_content("ok", "text/plain");
  13122. });
  13123. int port = 0;
  13124. thread t = thread([&]() {
  13125. port = svr.bind_to_any_port(HOST);
  13126. svr.listen_after_bind();
  13127. });
  13128. auto se = detail::scope_exit([&] {
  13129. svr.stop();
  13130. t.join();
  13131. ASSERT_FALSE(svr.is_running());
  13132. });
  13133. svr.wait_until_ready();
  13134. Client cli(HOST, port);
  13135. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13136. ASSERT_TRUE(res);
  13137. EXPECT_EQ(StatusCode::OK_200, res->status);
  13138. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13139. observed_remote_addr == "127.0.0.1");
  13140. }
  13141. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13142. run_malformed_xff_test("");
  13143. }
  13144. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13145. run_malformed_xff_test(",");
  13146. }
  13147. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13148. run_malformed_xff_test(", , ,");
  13149. }
  13150. #ifndef _WIN32
  13151. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13152. Server svr;
  13153. svr.Post("/post", [&](const Request &req, Response &res) {
  13154. res.set_content(req.body, "text/plain");
  13155. });
  13156. svr.Put("/put", [&](const Request &req, Response &res) {
  13157. res.set_content(req.body, "text/plain");
  13158. });
  13159. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13160. res.set_content(req.body, "text/plain");
  13161. });
  13162. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13163. res.set_content(req.body, "text/plain");
  13164. });
  13165. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13166. auto se = detail::scope_exit([&] {
  13167. svr.stop();
  13168. t.join();
  13169. ASSERT_FALSE(svr.is_running());
  13170. });
  13171. svr.wait_until_ready();
  13172. std::string resp;
  13173. // POST without Content-Length
  13174. ASSERT_TRUE(send_request(5,
  13175. "POST /post HTTP/1.1\r\n"
  13176. "Host: localhost\r\n"
  13177. "Connection: close\r\n"
  13178. "\r\n",
  13179. &resp));
  13180. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13181. // PUT without Content-Length
  13182. resp.clear();
  13183. ASSERT_TRUE(send_request(5,
  13184. "PUT /put HTTP/1.1\r\n"
  13185. "Host: localhost\r\n"
  13186. "Connection: close\r\n"
  13187. "\r\n",
  13188. &resp));
  13189. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13190. // PATCH without Content-Length
  13191. resp.clear();
  13192. ASSERT_TRUE(send_request(5,
  13193. "PATCH /patch HTTP/1.1\r\n"
  13194. "Host: localhost\r\n"
  13195. "Connection: close\r\n"
  13196. "\r\n",
  13197. &resp));
  13198. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13199. // DELETE without Content-Length
  13200. resp.clear();
  13201. ASSERT_TRUE(send_request(5,
  13202. "DELETE /delete HTTP/1.1\r\n"
  13203. "Host: localhost\r\n"
  13204. "Connection: close\r\n"
  13205. "\r\n",
  13206. &resp));
  13207. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13208. }
  13209. #endif
  13210. //==============================================================================
  13211. // open_stream() Tests
  13212. //==============================================================================
  13213. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13214. std::string result;
  13215. char buf[8192];
  13216. ssize_t n;
  13217. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13218. result.append(buf, static_cast<size_t>(n));
  13219. }
  13220. return result;
  13221. }
  13222. // Mock stream for unit tests
  13223. class MockStream : public Stream {
  13224. public:
  13225. std::string data;
  13226. size_t pos = 0;
  13227. ssize_t error_after = -1; // -1 = no error
  13228. explicit MockStream(const std::string &d, ssize_t err = -1)
  13229. : data(d), error_after(err) {}
  13230. bool is_readable() const override { return true; }
  13231. bool wait_readable() const override { return true; }
  13232. bool wait_writable() const override { return true; }
  13233. ssize_t read(char *ptr, size_t size) override {
  13234. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13235. if (pos >= data.size()) return 0;
  13236. size_t limit =
  13237. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13238. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13239. std::memcpy(ptr, data.data() + pos, to_read);
  13240. pos += to_read;
  13241. return static_cast<ssize_t>(to_read);
  13242. }
  13243. ssize_t write(const char *, size_t) override { return -1; }
  13244. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13245. ip = "127.0.0.1";
  13246. port = 0;
  13247. }
  13248. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13249. ip = "127.0.0.1";
  13250. port = 0;
  13251. }
  13252. socket_t socket() const override { return INVALID_SOCKET; }
  13253. time_t duration() const override { return 0; }
  13254. };
  13255. TEST(StreamHandleTest, Basic) {
  13256. ClientImpl::StreamHandle handle;
  13257. EXPECT_FALSE(handle.is_valid());
  13258. handle.response = detail::make_unique<Response>();
  13259. handle.error = Error::Connection;
  13260. EXPECT_FALSE(handle.is_valid());
  13261. handle.error = Error::Success;
  13262. EXPECT_TRUE(handle.is_valid());
  13263. }
  13264. TEST(BodyReaderTest, Basic) {
  13265. MockStream stream("Hello, World!");
  13266. detail::BodyReader reader;
  13267. reader.stream = &stream;
  13268. reader.content_length = 13;
  13269. char buf[32];
  13270. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13271. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13272. EXPECT_TRUE(reader.eof);
  13273. }
  13274. TEST(BodyReaderTest, NoStream) {
  13275. detail::BodyReader reader;
  13276. char buf[32];
  13277. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13278. EXPECT_EQ(Error::Connection, reader.last_error);
  13279. }
  13280. TEST(BodyReaderTest, Error) {
  13281. MockStream stream("Hello, World!", 5);
  13282. detail::BodyReader reader;
  13283. reader.stream = &stream;
  13284. reader.content_length = 13;
  13285. char buf[32];
  13286. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13287. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13288. EXPECT_EQ(Error::Read, reader.last_error);
  13289. }
  13290. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13291. // Mock-based StreamHandle tests relying on private internals are removed.
  13292. class OpenStreamTest : public ::testing::Test {
  13293. protected:
  13294. void SetUp() override {
  13295. svr_.Get("/hello", [](const Request &, Response &res) {
  13296. res.set_content("Hello World!", "text/plain");
  13297. });
  13298. svr_.Get("/large", [](const Request &, Response &res) {
  13299. res.set_content(std::string(10000, 'X'), "text/plain");
  13300. });
  13301. svr_.Get("/chunked", [](const Request &, Response &res) {
  13302. res.set_chunked_content_provider("text/plain",
  13303. [](size_t offset, DataSink &sink) {
  13304. if (offset < 15) {
  13305. sink.write("chunk", 5);
  13306. return true;
  13307. }
  13308. sink.done();
  13309. return true;
  13310. });
  13311. });
  13312. svr_.Get("/compressible", [](const Request &, Response &res) {
  13313. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13314. DataSink &sink) {
  13315. if (offset < 100 * 1024) {
  13316. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13317. sink.write(chunk.data(), chunk.size());
  13318. return true;
  13319. }
  13320. sink.done();
  13321. return true;
  13322. });
  13323. });
  13324. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13325. [](const Request & /*req*/, Response &res) {
  13326. auto i = new int(0);
  13327. res.set_header("Trailer", "Content-Length, X-Allowed");
  13328. res.set_chunked_content_provider(
  13329. "text/plain",
  13330. [i](size_t /*offset*/, DataSink &sink) {
  13331. switch (*i) {
  13332. case 0: sink.os << "123"; break;
  13333. case 1: sink.os << "456"; break;
  13334. case 2: sink.os << "789"; break;
  13335. case 3: {
  13336. sink.done_with_trailer(
  13337. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13338. } break;
  13339. }
  13340. (*i)++;
  13341. return true;
  13342. },
  13343. [i](bool success) {
  13344. EXPECT_TRUE(success);
  13345. delete i;
  13346. });
  13347. });
  13348. // Echo headers endpoint for header-related tests
  13349. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13350. std::string body;
  13351. for (const auto &h : req.headers) {
  13352. body.append(h.first);
  13353. body.push_back(':');
  13354. body.append(h.second);
  13355. body.push_back('\n');
  13356. }
  13357. res.set_content(body, "text/plain");
  13358. });
  13359. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13360. std::string body;
  13361. for (const auto &h : req.headers) {
  13362. body.append(h.first);
  13363. body.push_back(':');
  13364. body.append(h.second);
  13365. body.push_back('\n');
  13366. }
  13367. res.set_content(body, "text/plain");
  13368. });
  13369. port_ = svr_.bind_to_any_port("127.0.0.1");
  13370. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13371. svr_.wait_until_ready();
  13372. }
  13373. void TearDown() override {
  13374. svr_.stop();
  13375. if (thread_.joinable()) thread_.join();
  13376. }
  13377. Server svr_;
  13378. std::thread thread_;
  13379. int port_ = 0;
  13380. };
  13381. TEST_F(OpenStreamTest, Basic) {
  13382. Client cli("127.0.0.1", port_);
  13383. auto handle = cli.open_stream("GET", "/hello");
  13384. EXPECT_TRUE(handle.is_valid());
  13385. EXPECT_EQ("Hello World!", read_all(handle));
  13386. }
  13387. TEST_F(OpenStreamTest, SmallBuffer) {
  13388. Client cli("127.0.0.1", port_);
  13389. auto handle = cli.open_stream("GET", "/hello");
  13390. std::string result;
  13391. char buf[4];
  13392. ssize_t n;
  13393. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13394. result.append(buf, static_cast<size_t>(n));
  13395. EXPECT_EQ("Hello World!", result);
  13396. }
  13397. TEST_F(OpenStreamTest, DefaultHeaders) {
  13398. Client cli("127.0.0.1", port_);
  13399. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13400. {
  13401. auto handle = cli.open_stream("GET", "/echo-headers");
  13402. ASSERT_TRUE(handle.is_valid());
  13403. auto body = read_all(handle);
  13404. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13405. std::string::npos);
  13406. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13407. std::string::npos);
  13408. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13409. }
  13410. // open_stream POST with body and no explicit content_type should NOT add
  13411. // text/plain Content-Type (behavior differs from non-streaming path), but
  13412. // should include Content-Length
  13413. {
  13414. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13415. ASSERT_TRUE(handle.is_valid());
  13416. auto body = read_all(handle);
  13417. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13418. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13419. }
  13420. // open_stream POST with explicit Content-Type should preserve it
  13421. {
  13422. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13423. {{"Content-Type", "application/custom"}},
  13424. "{}", "application/custom");
  13425. ASSERT_TRUE(handle.is_valid());
  13426. auto body = read_all(handle);
  13427. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13428. }
  13429. // User-specified User-Agent must not be overwritten for stream API
  13430. {
  13431. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13432. {{"User-Agent", "MyAgent/1.2"}});
  13433. ASSERT_TRUE(handle.is_valid());
  13434. auto body = read_all(handle);
  13435. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13436. }
  13437. }
  13438. TEST_F(OpenStreamTest, Large) {
  13439. Client cli("127.0.0.1", port_);
  13440. auto handle = cli.open_stream("GET", "/large");
  13441. EXPECT_EQ(10000u, read_all(handle).size());
  13442. }
  13443. TEST_F(OpenStreamTest, ConnectionError) {
  13444. Client cli("127.0.0.1", 9999);
  13445. auto handle = cli.open_stream("GET", "/hello");
  13446. EXPECT_FALSE(handle.is_valid());
  13447. }
  13448. TEST_F(OpenStreamTest, Chunked) {
  13449. Client cli("127.0.0.1", port_);
  13450. auto handle = cli.open_stream("GET", "/chunked");
  13451. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13452. "Transfer-Encoding") == "chunked");
  13453. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13454. }
  13455. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13456. Client cli("127.0.0.1", port_);
  13457. auto handle =
  13458. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13459. ASSERT_TRUE(handle.is_valid());
  13460. // Consume body to allow trailers to be received/parsed
  13461. auto body = read_all(handle);
  13462. // Explicitly parse trailers (ensure trailers are available for assertion)
  13463. handle.parse_trailers_if_needed();
  13464. EXPECT_EQ(std::string("123456789"), body);
  13465. // The response should include a Trailer header declaring both names
  13466. ASSERT_TRUE(handle.response);
  13467. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13468. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13469. handle.response->get_header_value("Trailer"));
  13470. // Prohibited trailer must not be present
  13471. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13472. // Allowed trailer should be present
  13473. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13474. EXPECT_EQ(std::string("yes"),
  13475. handle.response->get_trailer_value("X-Allowed"));
  13476. // Verify trailers are NOT present as regular headers
  13477. EXPECT_EQ(std::string(""),
  13478. handle.response->get_header_value("Content-Length"));
  13479. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13480. }
  13481. static std::thread serve_single_response(std::promise<int> &port_promise,
  13482. const std::string &response) {
  13483. return std::thread([&port_promise, response] {
  13484. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13485. default_socket_options(srv);
  13486. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13487. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13488. sockaddr_in addr{};
  13489. addr.sin_family = AF_INET;
  13490. addr.sin_port = htons(0); // Let OS assign a free port
  13491. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13492. int opt = 1;
  13493. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13494. #ifdef _WIN32
  13495. reinterpret_cast<const char *>(&opt),
  13496. #else
  13497. &opt,
  13498. #endif
  13499. sizeof(opt));
  13500. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13501. ::listen(srv, 1) != 0) {
  13502. port_promise.set_value(-1);
  13503. detail::close_socket(srv);
  13504. return;
  13505. }
  13506. socklen_t addr_len = sizeof(addr);
  13507. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13508. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13509. sockaddr_in cli_addr{};
  13510. socklen_t cli_len = sizeof(cli_addr);
  13511. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13512. if (cli != INVALID_SOCKET) {
  13513. // Read the complete HTTP request (until the blank line that terminates
  13514. // headers) before sending the response. If the server closes the socket
  13515. // while the client's request data is still unread in the kernel receive
  13516. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13517. // connection on both sides: it discards the client's receive buffer
  13518. // (which already holds our response) and causes any in-progress write on
  13519. // the client to fail with ECONNRESET. Reading all request data first
  13520. // ensures close() emits a graceful FIN.
  13521. {
  13522. char rbuf[256];
  13523. std::string req;
  13524. while (req.find("\r\n\r\n") == std::string::npos) {
  13525. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13526. if (n <= 0) { break; }
  13527. req.append(rbuf, static_cast<size_t>(n));
  13528. }
  13529. }
  13530. ::send(cli,
  13531. #ifdef _WIN32
  13532. static_cast<const char *>(response.c_str()),
  13533. static_cast<int>(response.size()),
  13534. #else
  13535. response.c_str(), response.size(),
  13536. #endif
  13537. 0);
  13538. detail::close_socket(cli);
  13539. }
  13540. detail::close_socket(srv);
  13541. });
  13542. }
  13543. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13544. #ifndef _WIN32
  13545. signal(SIGPIPE, SIG_IGN);
  13546. #endif
  13547. std::promise<int> port_promise;
  13548. auto port_future = port_promise.get_future();
  13549. auto server_thread =
  13550. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13551. "Content-Type: text/plain\r\n"
  13552. "Content-Length: not-a-number\r\n"
  13553. "Connection: close\r\n"
  13554. "\r\n"
  13555. "hello");
  13556. auto port = port_future.get();
  13557. ASSERT_GT(port, 0);
  13558. Client cli("127.0.0.1", port);
  13559. auto handle = cli.open_stream("GET", "/");
  13560. EXPECT_FALSE(handle.is_valid());
  13561. server_thread.join();
  13562. }
  13563. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13564. #ifndef _WIN32
  13565. signal(SIGPIPE, SIG_IGN);
  13566. #endif
  13567. std::promise<int> port_promise;
  13568. auto port_future = port_promise.get_future();
  13569. auto server_thread = serve_single_response(
  13570. port_promise, "HTTP/1.1 200 OK\r\n"
  13571. "Content-Type: text/plain\r\n"
  13572. "Content-Length: 99999999999999999999999999\r\n"
  13573. "Connection: close\r\n"
  13574. "\r\n"
  13575. "hello");
  13576. auto port = port_future.get();
  13577. ASSERT_GT(port, 0);
  13578. // Historically std::stoull would throw std::out_of_range here and crash
  13579. // the process, then parsing silently clamped to a bogus framing length and
  13580. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13581. // so the stream fails to open, matching the not-a-number case above. The
  13582. // process still must NOT terminate.
  13583. Client cli("127.0.0.1", port);
  13584. auto handle = cli.open_stream("GET", "/");
  13585. EXPECT_FALSE(handle.is_valid());
  13586. server_thread.join();
  13587. }
  13588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13589. TEST_F(OpenStreamTest, Gzip) {
  13590. Client cli("127.0.0.1", port_);
  13591. auto handle = cli.open_stream("GET", "/compressible", {},
  13592. {{"Accept-Encoding", "gzip"}});
  13593. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13594. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13595. }
  13596. #endif
  13597. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13598. TEST_F(OpenStreamTest, Brotli) {
  13599. Client cli("127.0.0.1", port_);
  13600. auto handle =
  13601. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13602. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13603. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13604. }
  13605. #endif
  13606. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13607. TEST_F(OpenStreamTest, Zstd) {
  13608. Client cli("127.0.0.1", port_);
  13609. auto handle = cli.open_stream("GET", "/compressible", {},
  13610. {{"Accept-Encoding", "zstd"}});
  13611. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13612. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13613. }
  13614. #endif
  13615. #ifdef CPPHTTPLIB_SSL_ENABLED
  13616. class SSLOpenStreamTest : public ::testing::Test {
  13617. protected:
  13618. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13619. void SetUp() override {
  13620. svr_.Get("/hello", [](const Request &, Response &res) {
  13621. res.set_content("Hello SSL World!", "text/plain");
  13622. });
  13623. svr_.Get("/chunked", [](const Request &, Response &res) {
  13624. res.set_chunked_content_provider("text/plain",
  13625. [](size_t offset, DataSink &sink) {
  13626. if (offset < 15) {
  13627. sink.write("chunk", 5);
  13628. return true;
  13629. }
  13630. sink.done();
  13631. return true;
  13632. });
  13633. });
  13634. svr_.Post("/echo", [](const Request &req, Response &res) {
  13635. res.set_content(req.body, req.get_header_value("Content-Type"));
  13636. });
  13637. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13638. std::string body = req.body;
  13639. res.set_chunked_content_provider(
  13640. "text/plain", [body](size_t offset, DataSink &sink) {
  13641. if (offset < body.size()) {
  13642. sink.write(body.data() + offset, body.size() - offset);
  13643. }
  13644. sink.done();
  13645. return true;
  13646. });
  13647. });
  13648. port_ = svr_.bind_to_any_port("127.0.0.1");
  13649. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13650. svr_.wait_until_ready();
  13651. }
  13652. void TearDown() override {
  13653. svr_.stop();
  13654. if (thread_.joinable()) thread_.join();
  13655. }
  13656. SSLServer svr_;
  13657. std::thread thread_;
  13658. int port_ = 0;
  13659. };
  13660. TEST_F(SSLOpenStreamTest, Basic) {
  13661. SSLClient cli("127.0.0.1", port_);
  13662. cli.enable_server_certificate_verification(false);
  13663. auto handle = cli.open_stream("GET", "/hello");
  13664. ASSERT_TRUE(handle.is_valid());
  13665. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13666. }
  13667. TEST_F(SSLOpenStreamTest, Chunked) {
  13668. SSLClient cli("127.0.0.1", port_);
  13669. cli.enable_server_certificate_verification(false);
  13670. auto handle = cli.open_stream("GET", "/chunked");
  13671. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13672. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13673. "Transfer-Encoding") == "chunked");
  13674. auto body = read_all(handle);
  13675. EXPECT_EQ("chunkchunkchunk", body);
  13676. }
  13677. TEST_F(SSLOpenStreamTest, Post) {
  13678. SSLClient cli("127.0.0.1", port_);
  13679. cli.enable_server_certificate_verification(false);
  13680. auto handle =
  13681. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13682. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13683. EXPECT_EQ(200, handle.response->status);
  13684. auto body = read_all(handle);
  13685. EXPECT_EQ("Hello SSL POST", body);
  13686. }
  13687. TEST_F(SSLOpenStreamTest, PostChunked) {
  13688. SSLClient cli("127.0.0.1", port_);
  13689. cli.enable_server_certificate_verification(false);
  13690. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13691. "Chunked SSL Data", "text/plain");
  13692. ASSERT_TRUE(handle.is_valid());
  13693. EXPECT_EQ(200, handle.response->status);
  13694. auto body = read_all(handle);
  13695. EXPECT_EQ("Chunked SSL Data", body);
  13696. }
  13697. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13698. // Content-Length is terminated by the server closing the connection. When the
  13699. // SSL peer sends a close_notify after the body, the client must treat it as a
  13700. // clean EOF and return a successful response rather than an error.
  13701. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13703. ASSERT_TRUE(svr.is_valid());
  13704. svr.set_keep_alive_max_count(1);
  13705. const std::string expected_body = "Hello from connection-close response!";
  13706. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13707. res.set_content_provider("text/plain",
  13708. [&](size_t offset, DataSink &sink) -> bool {
  13709. if (offset < expected_body.size()) {
  13710. sink.write(expected_body.data() + offset,
  13711. expected_body.size() - offset);
  13712. }
  13713. sink.done();
  13714. return true;
  13715. });
  13716. });
  13717. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13718. auto se = detail::scope_exit([&] {
  13719. svr.stop();
  13720. listen_thread.join();
  13721. ASSERT_FALSE(svr.is_running());
  13722. });
  13723. svr.wait_until_ready();
  13724. SSLClient cli(HOST, PORT);
  13725. cli.enable_server_certificate_verification(false);
  13726. auto res = cli.Get("/no-content-length");
  13727. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13728. EXPECT_EQ(StatusCode::OK_200, res->status);
  13729. EXPECT_EQ(expected_body, res->body);
  13730. }
  13731. #endif // CPPHTTPLIB_SSL_ENABLED
  13732. //==============================================================================
  13733. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13734. // results for various scenarios.
  13735. //==============================================================================
  13736. TEST(ParityTest, GetVsOpenStream) {
  13737. Server svr;
  13738. const std::string path = "/parity";
  13739. const std::string content = "Parity test content: hello world";
  13740. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13741. res.set_content(content, "text/plain");
  13742. });
  13743. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13744. auto se = detail::scope_exit([&] {
  13745. svr.stop();
  13746. t.join();
  13747. ASSERT_FALSE(svr.is_running());
  13748. });
  13749. svr.wait_until_ready();
  13750. Client cli(HOST, PORT);
  13751. // Non-stream path
  13752. auto r1 = cli.Get(path);
  13753. ASSERT_TRUE(r1);
  13754. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13755. // Stream path
  13756. auto h = cli.open_stream("GET", path);
  13757. ASSERT_TRUE(h.is_valid());
  13758. EXPECT_EQ(r1->body, read_all(h));
  13759. }
  13760. // Helper to compress data with provided compressor type T
  13761. template <typename Compressor>
  13762. static std::string compress_payload_for_parity(const std::string &in) {
  13763. std::string out;
  13764. Compressor compressor;
  13765. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13766. [&](const char *data, size_t n) {
  13767. out.append(data, n);
  13768. return true;
  13769. });
  13770. EXPECT_TRUE(ok);
  13771. return out;
  13772. }
  13773. // Helper function for compression parity tests
  13774. template <typename Compressor>
  13775. static void test_compression_parity(const std::string &original,
  13776. const std::string &path,
  13777. const std::string &encoding) {
  13778. const std::string compressed =
  13779. compress_payload_for_parity<Compressor>(original);
  13780. Server svr;
  13781. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13782. res.set_content(compressed, "application/octet-stream");
  13783. res.set_header("Content-Encoding", encoding);
  13784. });
  13785. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13786. auto se = detail::scope_exit([&] {
  13787. svr.stop();
  13788. t.join();
  13789. ASSERT_FALSE(svr.is_running());
  13790. });
  13791. svr.wait_until_ready();
  13792. Client cli(HOST, PORT);
  13793. // Non-streaming
  13794. {
  13795. auto res = cli.Get(path);
  13796. ASSERT_TRUE(res);
  13797. EXPECT_EQ(StatusCode::OK_200, res->status);
  13798. EXPECT_EQ(original, res->body);
  13799. }
  13800. // Streaming
  13801. {
  13802. auto h = cli.open_stream("GET", path);
  13803. ASSERT_TRUE(h.is_valid());
  13804. EXPECT_EQ(original, read_all(h));
  13805. }
  13806. }
  13807. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13808. TEST(ParityTest, Gzip) {
  13809. test_compression_parity<detail::gzip_compressor>(
  13810. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13811. }
  13812. #endif
  13813. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13814. TEST(ParityTest, Brotli) {
  13815. test_compression_parity<detail::brotli_compressor>(
  13816. "Hello, brotli parity test payload", "/parity-br", "br");
  13817. }
  13818. #endif
  13819. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13820. TEST(ParityTest, Zstd) {
  13821. test_compression_parity<detail::zstd_compressor>(
  13822. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13823. }
  13824. #endif
  13825. //==============================================================================
  13826. // New Stream API Tests
  13827. //==============================================================================
  13828. inline std::string read_body(httplib::stream::Result &result) {
  13829. std::string body;
  13830. while (result.next()) {
  13831. body.append(result.data(), result.size());
  13832. }
  13833. return body;
  13834. }
  13835. TEST(ClientConnectionTest, Basic) {
  13836. httplib::ClientConnection conn;
  13837. EXPECT_FALSE(conn.is_open());
  13838. conn.sock = 1;
  13839. EXPECT_TRUE(conn.is_open());
  13840. httplib::ClientConnection conn2(std::move(conn));
  13841. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13842. conn2.sock = INVALID_SOCKET;
  13843. }
  13844. // Unified test server for all stream::* tests
  13845. class StreamApiTest : public ::testing::Test {
  13846. protected:
  13847. void SetUp() override {
  13848. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13849. res.set_content("Hello World!", "text/plain");
  13850. });
  13851. svr_.Get("/echo-params",
  13852. [](const httplib::Request &req, httplib::Response &res) {
  13853. std::string r;
  13854. for (const auto &p : req.params) {
  13855. if (!r.empty()) r += "&";
  13856. r += p.first + "=" + p.second;
  13857. }
  13858. res.set_content(r, "text/plain");
  13859. });
  13860. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13861. res.set_content(req.body, req.get_header_value("Content-Type"));
  13862. });
  13863. svr_.Post("/echo-headers",
  13864. [](const httplib::Request &req, httplib::Response &res) {
  13865. std::string r;
  13866. for (const auto &h : req.headers)
  13867. r += h.first + ": " + h.second + "\n";
  13868. res.set_content(r, "text/plain");
  13869. });
  13870. svr_.Post("/echo-params",
  13871. [](const httplib::Request &req, httplib::Response &res) {
  13872. std::string r = "params:";
  13873. for (const auto &p : req.params)
  13874. r += p.first + "=" + p.second + ";";
  13875. res.set_content(r + " body:" + req.body, "text/plain");
  13876. });
  13877. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13878. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13879. });
  13880. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13881. res.set_content("PUT:" + req.body, "text/plain");
  13882. });
  13883. svr_.Patch("/echo",
  13884. [](const httplib::Request &req, httplib::Response &res) {
  13885. res.set_content("PATCH:" + req.body, "text/plain");
  13886. });
  13887. svr_.Delete(
  13888. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13889. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13890. "text/plain");
  13891. });
  13892. svr_.Get("/head-test",
  13893. [](const httplib::Request &, httplib::Response &res) {
  13894. res.set_content("body for HEAD", "text/plain");
  13895. });
  13896. svr_.Options("/options",
  13897. [](const httplib::Request &, httplib::Response &res) {
  13898. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13899. });
  13900. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13901. svr_.wait_until_ready();
  13902. }
  13903. void TearDown() override {
  13904. svr_.stop();
  13905. if (thread_.joinable()) thread_.join();
  13906. }
  13907. httplib::Server svr_;
  13908. std::thread thread_;
  13909. };
  13910. // stream::Get tests
  13911. TEST_F(StreamApiTest, GetBasic) {
  13912. httplib::Client cli(HOST, PORT);
  13913. auto result = httplib::stream::Get(cli, "/hello");
  13914. ASSERT_TRUE(result.is_valid());
  13915. EXPECT_EQ(200, result.status());
  13916. EXPECT_EQ("Hello World!", read_body(result));
  13917. }
  13918. TEST_F(StreamApiTest, GetWithParams) {
  13919. httplib::Client cli(HOST, PORT);
  13920. httplib::Params params{{"foo", "bar"}};
  13921. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13922. ASSERT_TRUE(result.is_valid());
  13923. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13924. }
  13925. TEST_F(StreamApiTest, GetConnectionError) {
  13926. httplib::Client cli(HOST, 9999);
  13927. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13928. }
  13929. TEST_F(StreamApiTest, Get404) {
  13930. httplib::Client cli(HOST, PORT);
  13931. auto result = httplib::stream::Get(cli, "/nonexistent");
  13932. EXPECT_TRUE(result.is_valid());
  13933. EXPECT_EQ(404, result.status());
  13934. }
  13935. // stream::Post tests
  13936. TEST_F(StreamApiTest, PostBasic) {
  13937. httplib::Client cli(HOST, PORT);
  13938. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13939. "application/json");
  13940. ASSERT_TRUE(result.is_valid());
  13941. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13942. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13943. }
  13944. TEST_F(StreamApiTest, PostWithHeaders) {
  13945. httplib::Client cli(HOST, PORT);
  13946. httplib::Headers headers{{"X-Custom", "value"}};
  13947. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13948. "text/plain");
  13949. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13950. }
  13951. TEST_F(StreamApiTest, PostWithParams) {
  13952. httplib::Client cli(HOST, PORT);
  13953. httplib::Params params{{"k", "v"}};
  13954. auto result =
  13955. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13956. auto body = read_body(result);
  13957. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13958. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13959. }
  13960. TEST_F(StreamApiTest, PostLarge) {
  13961. httplib::Client cli(HOST, PORT);
  13962. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13963. size_t total = 0;
  13964. while (result.next()) {
  13965. total += result.size();
  13966. }
  13967. EXPECT_EQ(100u * 1024u, total);
  13968. }
  13969. // stream::Put/Patch tests
  13970. TEST_F(StreamApiTest, PutAndPatch) {
  13971. httplib::Client cli(HOST, PORT);
  13972. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13973. EXPECT_EQ("PUT:test", read_body(put));
  13974. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13975. EXPECT_EQ("PATCH:test", read_body(patch));
  13976. }
  13977. // stream::Delete tests
  13978. TEST_F(StreamApiTest, Delete) {
  13979. httplib::Client cli(HOST, PORT);
  13980. auto del1 = httplib::stream::Delete(cli, "/resource");
  13981. EXPECT_EQ("Deleted", read_body(del1));
  13982. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13983. EXPECT_EQ("Deleted:data", read_body(del2));
  13984. }
  13985. // stream::Head/Options tests
  13986. TEST_F(StreamApiTest, HeadAndOptions) {
  13987. httplib::Client cli(HOST, PORT);
  13988. auto head = httplib::stream::Head(cli, "/head-test");
  13989. EXPECT_TRUE(head.is_valid());
  13990. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13991. auto opts = httplib::stream::Options(cli, "/options");
  13992. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13993. }
  13994. // SSL stream::* tests
  13995. #ifdef CPPHTTPLIB_SSL_ENABLED
  13996. class SSLStreamApiTest : public ::testing::Test {
  13997. protected:
  13998. void SetUp() override {
  13999. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14000. res.set_content("Hello SSL!", "text/plain");
  14001. });
  14002. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14003. res.set_content(req.body, "text/plain");
  14004. });
  14005. port_ = svr_.bind_to_any_port("127.0.0.1");
  14006. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14007. svr_.wait_until_ready();
  14008. }
  14009. void TearDown() override {
  14010. svr_.stop();
  14011. if (thread_.joinable()) thread_.join();
  14012. }
  14013. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14014. std::thread thread_;
  14015. int port_ = 0;
  14016. };
  14017. TEST_F(SSLStreamApiTest, GetAndPost) {
  14018. httplib::SSLClient cli("127.0.0.1", port_);
  14019. cli.enable_server_certificate_verification(false);
  14020. auto get = httplib::stream::Get(cli, "/hello");
  14021. EXPECT_EQ("Hello SSL!", read_body(get));
  14022. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14023. EXPECT_EQ("test", read_body(post));
  14024. }
  14025. #endif
  14026. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14027. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14028. // BodyReader
  14029. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14030. // Test that read timeout during streaming is detected
  14031. // Use a large content-length response where server delays mid-stream
  14032. Server svr;
  14033. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14034. // Send a large response with delay in the middle
  14035. res.set_content_provider(
  14036. 1000, // content_length
  14037. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14038. if (offset < 100) {
  14039. // Send first 100 bytes immediately
  14040. std::string data(100, 'A');
  14041. sink.write(data.c_str(), data.size());
  14042. return true;
  14043. }
  14044. // Then delay longer than client timeout
  14045. std::this_thread::sleep_for(std::chrono::seconds(3));
  14046. std::string data(900, 'B');
  14047. sink.write(data.c_str(), data.size());
  14048. return true;
  14049. });
  14050. });
  14051. auto port = 8091;
  14052. std::thread t([&]() { svr.listen("localhost", port); });
  14053. svr.wait_until_ready();
  14054. Client cli("localhost", port);
  14055. cli.set_read_timeout(1, 0); // 1 second timeout
  14056. auto handle = cli.open_stream("GET", "/slow-stream");
  14057. ASSERT_TRUE(handle.is_valid());
  14058. char buf[256];
  14059. ssize_t total = 0;
  14060. ssize_t n;
  14061. bool got_error = false;
  14062. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14063. total += n;
  14064. }
  14065. if (n < 0) {
  14066. got_error = true;
  14067. // Should be timeout or read error
  14068. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14069. handle.get_read_error() == Error::Read)
  14070. << "Actual error: " << to_string(handle.get_read_error());
  14071. }
  14072. // Either we got an error, or we got less data than expected
  14073. EXPECT_TRUE(got_error || total < 1000)
  14074. << "Expected timeout but got all " << total << " bytes";
  14075. svr.stop();
  14076. t.join();
  14077. }
  14078. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14079. // Test connection closed detection via BodyReader
  14080. Server svr;
  14081. std::atomic<bool> close_now{false};
  14082. svr.Get("/will-close", [&](const Request &, Response &res) {
  14083. res.set_content_provider(
  14084. 10000, // Large content_length that we won't fully send
  14085. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14086. if (offset < 100) {
  14087. std::string data(100, 'X');
  14088. sink.write(data.c_str(), data.size());
  14089. return true;
  14090. }
  14091. // Wait for signal then abort
  14092. while (!close_now) {
  14093. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14094. }
  14095. return false; // Abort - server will close connection
  14096. });
  14097. });
  14098. auto port = 8092;
  14099. std::thread t([&]() { svr.listen("localhost", port); });
  14100. svr.wait_until_ready();
  14101. Client cli("localhost", port);
  14102. auto handle = cli.open_stream("GET", "/will-close");
  14103. ASSERT_TRUE(handle.is_valid());
  14104. char buf[256];
  14105. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14106. EXPECT_GT(n, 0) << "First read should succeed";
  14107. // Signal server to close
  14108. close_now = true;
  14109. // Keep reading until error or EOF
  14110. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14111. // Keep reading
  14112. }
  14113. // Should get an error since content_length wasn't satisfied
  14114. if (n < 0) {
  14115. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14116. handle.get_read_error() == Error::Read)
  14117. << "Actual error: " << to_string(handle.get_read_error());
  14118. }
  14119. svr.stop();
  14120. t.join();
  14121. }
  14122. #ifdef CPPHTTPLIB_SSL_ENABLED
  14123. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14124. // Test that read timeout during SSL streaming is detected
  14125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14126. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14127. res.set_content_provider(
  14128. 1000, "text/plain",
  14129. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14130. if (offset < 100) {
  14131. std::string data(100, 'A');
  14132. sink.write(data.c_str(), data.size());
  14133. return true;
  14134. }
  14135. std::this_thread::sleep_for(std::chrono::seconds(3));
  14136. std::string data(900, 'B');
  14137. sink.write(data.c_str(), data.size());
  14138. return true;
  14139. });
  14140. });
  14141. auto port = 8093;
  14142. std::thread t([&]() { svr.listen("localhost", port); });
  14143. svr.wait_until_ready();
  14144. SSLClient cli("localhost", port);
  14145. cli.enable_server_certificate_verification(false);
  14146. cli.set_read_timeout(1, 0); // 1 second timeout
  14147. auto handle = cli.open_stream("GET", "/slow-stream");
  14148. ASSERT_TRUE(handle.is_valid());
  14149. char buf[256];
  14150. ssize_t total = 0;
  14151. ssize_t n;
  14152. bool got_error = false;
  14153. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14154. total += n;
  14155. }
  14156. if (n < 0) {
  14157. got_error = true;
  14158. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14159. handle.get_read_error() == Error::Read)
  14160. << "Actual error: " << to_string(handle.get_read_error());
  14161. }
  14162. EXPECT_TRUE(got_error || total < 1000)
  14163. << "Expected timeout but got all " << total << " bytes";
  14164. svr.stop();
  14165. t.join();
  14166. }
  14167. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14168. // Test SSL connection closed detection
  14169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14170. std::atomic<bool> close_now{false};
  14171. svr.Get("/will-close", [&](const Request &, Response &res) {
  14172. res.set_content_provider(
  14173. 10000, "text/plain",
  14174. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14175. if (offset < 100) {
  14176. std::string data(100, 'X');
  14177. sink.write(data.c_str(), data.size());
  14178. return true;
  14179. }
  14180. while (!close_now) {
  14181. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14182. }
  14183. return false;
  14184. });
  14185. });
  14186. auto port = 8094;
  14187. std::thread t([&]() { svr.listen("localhost", port); });
  14188. svr.wait_until_ready();
  14189. SSLClient cli("localhost", port);
  14190. cli.enable_server_certificate_verification(false);
  14191. auto handle = cli.open_stream("GET", "/will-close");
  14192. ASSERT_TRUE(handle.is_valid());
  14193. char buf[256];
  14194. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14195. EXPECT_GT(n, 0);
  14196. // Signal server to close
  14197. close_now = true;
  14198. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14199. // Keep reading
  14200. }
  14201. if (n < 0) {
  14202. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14203. handle.get_read_error() == Error::Read)
  14204. << "Actual error: " << to_string(handle.get_read_error());
  14205. }
  14206. svr.stop();
  14207. t.join();
  14208. }
  14209. #endif
  14210. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14211. using namespace httplib;
  14212. // Create a test file
  14213. const char *fname = "etag_testfile.txt";
  14214. const char *content = "etag-content";
  14215. {
  14216. std::ofstream ofs(fname);
  14217. ofs << content;
  14218. ASSERT_TRUE(ofs.good());
  14219. }
  14220. Server svr;
  14221. svr.set_mount_point("/static", ".");
  14222. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14223. svr.wait_until_ready();
  14224. Client cli(HOST, PORT);
  14225. // First request: should get 200 with ETag header
  14226. auto res1 = cli.Get("/static/etag_testfile.txt");
  14227. ASSERT_TRUE(res1);
  14228. ASSERT_EQ(200, res1->status);
  14229. ASSERT_TRUE(res1->has_header("ETag"));
  14230. std::string etag = res1->get_header_value("ETag");
  14231. EXPECT_FALSE(etag.empty());
  14232. // Verify ETag format: W/"hex-hex"
  14233. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14234. EXPECT_EQ('W', etag[0]);
  14235. EXPECT_EQ('/', etag[1]);
  14236. EXPECT_EQ('"', etag[2]);
  14237. EXPECT_EQ('"', etag.back());
  14238. // Exact match: expect 304 Not Modified
  14239. Headers h2 = {{"If-None-Match", etag}};
  14240. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14241. ASSERT_TRUE(res2);
  14242. EXPECT_EQ(304, res2->status);
  14243. // Wildcard match: expect 304 Not Modified
  14244. Headers h3 = {{"If-None-Match", "*"}};
  14245. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14246. ASSERT_TRUE(res3);
  14247. EXPECT_EQ(304, res3->status);
  14248. // Non-matching ETag: expect 200
  14249. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14250. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14251. ASSERT_TRUE(res4);
  14252. EXPECT_EQ(200, res4->status);
  14253. // Multiple ETags with one matching: expect 304
  14254. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14255. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14256. ASSERT_TRUE(res5);
  14257. EXPECT_EQ(304, res5->status);
  14258. svr.stop();
  14259. t.join();
  14260. std::remove(fname);
  14261. }
  14262. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14263. using namespace httplib;
  14264. Server svr;
  14265. svr.set_mount_point("/static", ".");
  14266. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14267. svr.wait_until_ready();
  14268. Client cli(HOST, PORT);
  14269. // Send If-None-Match: * to a non-existent file
  14270. Headers h = {{"If-None-Match", "*"}};
  14271. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14272. ASSERT_TRUE(res);
  14273. EXPECT_EQ(404, res->status);
  14274. svr.stop();
  14275. t.join();
  14276. }
  14277. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14278. using namespace httplib;
  14279. // Create a test file
  14280. const char *fname = "etag_boundary_testfile.txt";
  14281. const char *content = "boundary-test";
  14282. {
  14283. std::ofstream ofs(fname);
  14284. ofs << content;
  14285. ASSERT_TRUE(ofs.good());
  14286. }
  14287. Server svr;
  14288. svr.set_mount_point("/static", ".");
  14289. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14290. svr.wait_until_ready();
  14291. Client cli(HOST, PORT);
  14292. // Get the actual ETag
  14293. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14294. ASSERT_TRUE(res1);
  14295. ASSERT_EQ(200, res1->status);
  14296. ASSERT_TRUE(res1->has_header("ETag"));
  14297. std::string etag = res1->get_header_value("ETag");
  14298. // Test 1: Very long ETag value (longer than actual ETag)
  14299. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14300. Headers h1 = {{"If-None-Match", "W/"
  14301. "\"very-long-etag-value-that-is-much-longer-"
  14302. "than-the-actual-etag-value\""}};
  14303. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14304. ASSERT_TRUE(res2);
  14305. EXPECT_EQ(200, res2->status); // Should not match
  14306. // Test 2: Long string followed by wildcard
  14307. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14308. // string)
  14309. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14310. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14311. ASSERT_TRUE(res3);
  14312. EXPECT_EQ(304, res3->status); // Should match on "*"
  14313. // Test 3: Wildcard followed by long string
  14314. // Should match on "*" immediately and return 304
  14315. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14316. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14317. ASSERT_TRUE(res4);
  14318. EXPECT_EQ(304, res4->status); // Should match on "*"
  14319. // Test 4: Multiple long non-matching values
  14320. // Should NOT match and return 200 (test that all comparisons are safe)
  14321. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14322. "W/\"second-long-non-matching-value\", "
  14323. "W/\"third-long-non-matching-value\""}};
  14324. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14325. ASSERT_TRUE(res5);
  14326. EXPECT_EQ(200, res5->status); // Should not match
  14327. // Test 5: Single character that is not "*" (edge case)
  14328. Headers h5 = {{"If-None-Match", "X"}};
  14329. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14330. ASSERT_TRUE(res6);
  14331. EXPECT_EQ(200, res6->status); // Should not match
  14332. svr.stop();
  14333. t.join();
  14334. std::remove(fname);
  14335. }
  14336. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14337. using namespace httplib;
  14338. // Create a test file
  14339. const char *fname = "ims_testfile.txt";
  14340. const char *content = "if-modified-since-test";
  14341. {
  14342. std::ofstream ofs(fname);
  14343. ofs << content;
  14344. ASSERT_TRUE(ofs.good());
  14345. }
  14346. Server svr;
  14347. svr.set_mount_point("/static", ".");
  14348. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14349. svr.wait_until_ready();
  14350. Client cli(HOST, PORT);
  14351. // First request: should get 200 with Last-Modified header
  14352. auto res1 = cli.Get("/static/ims_testfile.txt");
  14353. ASSERT_TRUE(res1);
  14354. ASSERT_EQ(200, res1->status);
  14355. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14356. std::string last_modified = res1->get_header_value("Last-Modified");
  14357. EXPECT_FALSE(last_modified.empty());
  14358. // If-Modified-Since with same time: expect 304
  14359. Headers h2 = {{"If-Modified-Since", last_modified}};
  14360. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14361. ASSERT_TRUE(res2);
  14362. EXPECT_EQ(304, res2->status);
  14363. // If-Modified-Since with future time: expect 304
  14364. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14365. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14366. ASSERT_TRUE(res3);
  14367. EXPECT_EQ(304, res3->status);
  14368. // If-Modified-Since with past time: expect 200
  14369. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14370. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14371. ASSERT_TRUE(res4);
  14372. EXPECT_EQ(200, res4->status);
  14373. // If-None-Match takes precedence over If-Modified-Since
  14374. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14375. ASSERT_TRUE(res1->has_header("ETag"));
  14376. std::string etag = res1->get_header_value("ETag");
  14377. Headers h5 = {{"If-None-Match", etag},
  14378. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14379. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14380. ASSERT_TRUE(res5);
  14381. EXPECT_EQ(304, res5->status);
  14382. svr.stop();
  14383. t.join();
  14384. std::remove(fname);
  14385. }
  14386. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14387. using namespace httplib;
  14388. Server svr;
  14389. // Endpoint that returns compressible content
  14390. svr.Get("/compressible", [](const Request &, Response &res) {
  14391. // Return a large enough body to trigger compression
  14392. std::string body(1000, 'a');
  14393. res.set_content(body, "text/plain");
  14394. });
  14395. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14396. svr.wait_until_ready();
  14397. Client cli(HOST, PORT);
  14398. // Request with gzip support: should get Vary header when compressed
  14399. cli.set_compress(true);
  14400. auto res1 = cli.Get("/compressible");
  14401. ASSERT_TRUE(res1);
  14402. EXPECT_EQ(200, res1->status);
  14403. // If Content-Encoding is set, Vary should also be set
  14404. if (res1->has_header("Content-Encoding")) {
  14405. EXPECT_TRUE(res1->has_header("Vary"));
  14406. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14407. }
  14408. // Request without Accept-Encoding header: should not have compression
  14409. Headers h_no_compress;
  14410. auto res2 = cli.Get("/compressible", h_no_compress);
  14411. ASSERT_TRUE(res2);
  14412. EXPECT_EQ(200, res2->status);
  14413. // Verify Vary header is present when compression is applied
  14414. // (the exact behavior depends on server configuration)
  14415. svr.stop();
  14416. t.join();
  14417. }
  14418. TEST(ETagTest, IfRangeWithETag) {
  14419. using namespace httplib;
  14420. // Create a test file with known content
  14421. const char *fname = "if_range_testfile.txt";
  14422. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14423. {
  14424. std::ofstream ofs(fname);
  14425. ofs << content;
  14426. ASSERT_TRUE(ofs.good());
  14427. }
  14428. Server svr;
  14429. svr.set_mount_point("/static", ".");
  14430. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14431. svr.wait_until_ready();
  14432. Client cli(HOST, PORT);
  14433. // First request: get ETag
  14434. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14435. ASSERT_TRUE(res1);
  14436. ASSERT_EQ(200, res1->status);
  14437. ASSERT_TRUE(res1->has_header("ETag"));
  14438. std::string etag = res1->get_header_value("ETag");
  14439. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14440. // Since our server generates weak ETags (W/"..."), If-Range with our
  14441. // ETag should NOT result in partial content - it should return full content.
  14442. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14443. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14444. ASSERT_TRUE(res2);
  14445. // Weak ETag in If-Range -> full content (200), not partial (206)
  14446. EXPECT_EQ(200, res2->status);
  14447. EXPECT_EQ(content, res2->body);
  14448. EXPECT_FALSE(res2->has_header("Content-Range"));
  14449. // Range request with non-matching If-Range (ETag): should get 200 (full
  14450. // content)
  14451. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14452. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14453. ASSERT_TRUE(res3);
  14454. EXPECT_EQ(200, res3->status);
  14455. EXPECT_EQ(content, res3->body);
  14456. EXPECT_FALSE(res3->has_header("Content-Range"));
  14457. // Range request with strong ETag (hypothetical - our server doesn't generate
  14458. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14459. // should return full content)
  14460. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14461. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14462. ASSERT_TRUE(res4);
  14463. EXPECT_EQ(200, res4->status);
  14464. EXPECT_EQ(content, res4->body);
  14465. EXPECT_FALSE(res4->has_header("Content-Range"));
  14466. svr.stop();
  14467. t.join();
  14468. std::remove(fname);
  14469. }
  14470. TEST(ETagTest, IfRangeWithDate) {
  14471. using namespace httplib;
  14472. // Create a test file
  14473. const char *fname = "if_range_date_testfile.txt";
  14474. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14475. {
  14476. std::ofstream ofs(fname);
  14477. ofs << content;
  14478. ASSERT_TRUE(ofs.good());
  14479. }
  14480. Server svr;
  14481. svr.set_mount_point("/static", ".");
  14482. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14483. svr.wait_until_ready();
  14484. Client cli(HOST, PORT);
  14485. // First request: get Last-Modified
  14486. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14487. ASSERT_TRUE(res1);
  14488. ASSERT_EQ(200, res1->status);
  14489. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14490. std::string last_modified = res1->get_header_value("Last-Modified");
  14491. // Range request with matching If-Range (date): should get 206
  14492. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14493. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14494. ASSERT_TRUE(res2);
  14495. EXPECT_EQ(206, res2->status);
  14496. EXPECT_EQ("FGHIJ", res2->body);
  14497. // Range request with old If-Range date: should get 200 (full content)
  14498. Headers h3 = {{"Range", "bytes=5-9"},
  14499. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14500. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14501. ASSERT_TRUE(res3);
  14502. EXPECT_EQ(200, res3->status);
  14503. EXPECT_EQ(content, res3->body);
  14504. // Range request with future If-Range date: should get 206
  14505. Headers h4 = {{"Range", "bytes=0-4"},
  14506. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14507. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14508. ASSERT_TRUE(res4);
  14509. EXPECT_EQ(206, res4->status);
  14510. EXPECT_EQ("ABCDE", res4->body);
  14511. svr.stop();
  14512. t.join();
  14513. std::remove(fname);
  14514. }
  14515. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14516. using namespace httplib;
  14517. const char *fname = "etag_malformed.txt";
  14518. const char *content = "malformed-etag";
  14519. {
  14520. std::ofstream ofs(fname);
  14521. ofs << content;
  14522. ASSERT_TRUE(ofs.good());
  14523. }
  14524. Server svr;
  14525. svr.set_mount_point("/static", ".");
  14526. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14527. svr.wait_until_ready();
  14528. Client cli(HOST, PORT);
  14529. // baseline: should get 200 and an ETag
  14530. auto res1 = cli.Get("/static/etag_malformed.txt");
  14531. ASSERT_TRUE(res1);
  14532. ASSERT_EQ(200, res1->status);
  14533. ASSERT_TRUE(res1->has_header("ETag"));
  14534. // Malformed ETag value (missing quotes) should be treated as non-matching
  14535. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14536. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14537. ASSERT_TRUE(res_bad);
  14538. EXPECT_EQ(200, res_bad->status);
  14539. // Whitespace-only header value should be considered invalid / non-matching
  14540. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14541. "Host: localhost\r\n"
  14542. "If-None-Match: \r\n"
  14543. "Connection: close\r\n"
  14544. "\r\n";
  14545. std::string out;
  14546. ASSERT_TRUE(send_request(5, raw_req, &out));
  14547. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14548. svr.stop();
  14549. t.join();
  14550. std::remove(fname);
  14551. }
  14552. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14553. using namespace httplib;
  14554. const char *fname = "ims_invalid_format.txt";
  14555. const char *content = "ims-bad-format";
  14556. {
  14557. std::ofstream ofs(fname);
  14558. ofs << content;
  14559. ASSERT_TRUE(ofs.good());
  14560. }
  14561. Server svr;
  14562. svr.set_mount_point("/static", ".");
  14563. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14564. svr.wait_until_ready();
  14565. Client cli(HOST, PORT);
  14566. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14567. ASSERT_TRUE(res1);
  14568. ASSERT_EQ(200, res1->status);
  14569. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14570. // If-Modified-Since with invalid format should not result in 304
  14571. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14572. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14573. ASSERT_TRUE(res_bad);
  14574. EXPECT_EQ(200, res_bad->status);
  14575. // If-Range with invalid date format should be treated as mismatch -> full
  14576. // content (200)
  14577. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14578. {"If-Range", "invalid-date"}};
  14579. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14580. ASSERT_TRUE(res_ifrange);
  14581. EXPECT_EQ(200, res_ifrange->status);
  14582. svr.stop();
  14583. t.join();
  14584. std::remove(fname);
  14585. }
  14586. TEST(ETagTest, IfRangeWithMalformedETag) {
  14587. using namespace httplib;
  14588. const char *fname = "ifrange_malformed.txt";
  14589. const std::string content = "0123456789";
  14590. {
  14591. std::ofstream ofs(fname);
  14592. ofs << content;
  14593. ASSERT_TRUE(ofs.good());
  14594. }
  14595. Server svr;
  14596. svr.set_mount_point("/static", ".");
  14597. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14598. svr.wait_until_ready();
  14599. Client cli(HOST, PORT);
  14600. // First request: get ETag
  14601. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14602. ASSERT_TRUE(res1);
  14603. ASSERT_EQ(200, res1->status);
  14604. ASSERT_TRUE(res1->has_header("ETag"));
  14605. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14606. // full content (200)
  14607. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14608. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14609. ASSERT_TRUE(res2);
  14610. EXPECT_EQ(200, res2->status);
  14611. EXPECT_EQ(content, res2->body);
  14612. svr.stop();
  14613. t.join();
  14614. std::remove(fname);
  14615. }
  14616. TEST(ETagTest, ExtremeLargeDateValues) {
  14617. using namespace httplib;
  14618. const char *fname = "ims_extreme_date.txt";
  14619. const char *content = "ims-extreme-date";
  14620. {
  14621. std::ofstream ofs(fname);
  14622. ofs << content;
  14623. ASSERT_TRUE(ofs.good());
  14624. }
  14625. Server svr;
  14626. svr.set_mount_point("/static", ".");
  14627. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14628. svr.wait_until_ready();
  14629. Client cli(HOST, PORT);
  14630. auto res1 = cli.Get(std::string("/static/") + fname);
  14631. ASSERT_TRUE(res1);
  14632. ASSERT_EQ(200, res1->status);
  14633. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14634. // Extremely large year that may overflow date parsing routines.
  14635. Headers h_large_date = {
  14636. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14637. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14638. ASSERT_TRUE(res_bad);
  14639. // Expect server to treat this as invalid/mismatch and return full content
  14640. EXPECT_EQ(200, res_bad->status);
  14641. // If-Range with extremely large date should be treated as mismatch -> full
  14642. // content (200)
  14643. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14644. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14645. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14646. ASSERT_TRUE(res_ifrange);
  14647. EXPECT_EQ(200, res_ifrange->status);
  14648. svr.stop();
  14649. t.join();
  14650. std::remove(fname);
  14651. }
  14652. TEST(ETagTest, NegativeFileModificationTime) {
  14653. using namespace httplib;
  14654. const char *fname = "ims_negative_mtime.txt";
  14655. const std::string content = "negative-mtime";
  14656. {
  14657. std::ofstream ofs(fname);
  14658. ofs << content;
  14659. ASSERT_TRUE(ofs.good());
  14660. }
  14661. // Try to set file mtime to a negative value. This may fail on some
  14662. // platforms/filesystems; if it fails, the test will still verify server
  14663. // behaves safely by performing a regular conditional request.
  14664. #if defined(__APPLE__) || defined(__linux__)
  14665. bool set_negative = false;
  14666. do {
  14667. struct timeval times[2];
  14668. // access time: now
  14669. times[0].tv_sec = time(nullptr);
  14670. times[0].tv_usec = 0;
  14671. // modification time: negative (e.g., -1)
  14672. times[1].tv_sec = -1;
  14673. times[1].tv_usec = 0;
  14674. if (utimes(fname, times) == 0) { set_negative = true; }
  14675. } while (0);
  14676. #else
  14677. bool set_negative = false;
  14678. #endif
  14679. Server svr;
  14680. svr.set_mount_point("/static", ".");
  14681. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14682. svr.wait_until_ready();
  14683. Client cli(HOST, PORT);
  14684. auto res1 = cli.Get(std::string("/static/") + fname);
  14685. ASSERT_TRUE(res1);
  14686. ASSERT_EQ(200, res1->status);
  14687. bool has_last_modified = res1->has_header("Last-Modified");
  14688. std::string last_modified;
  14689. if (has_last_modified) {
  14690. last_modified = res1->get_header_value("Last-Modified");
  14691. }
  14692. if (set_negative) {
  14693. // If we successfully set a negative mtime, ensure server returns a
  14694. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14695. // with an old date and ensure server handles it without crash.
  14696. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14697. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14698. ASSERT_TRUE(res2);
  14699. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14700. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14701. } else {
  14702. // Could not set negative mtime on this platform; fall back to verifying
  14703. // that normal invalid/malformed dates are treated safely (non-304).
  14704. Headers h_bad_date = {
  14705. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14706. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14707. ASSERT_TRUE(res_bad);
  14708. EXPECT_EQ(200, res_bad->status);
  14709. }
  14710. svr.stop();
  14711. t.join();
  14712. std::remove(fname);
  14713. }
  14714. //==============================================================================
  14715. // SSE Parsing Tests
  14716. //==============================================================================
  14717. class SSEParsingTest : public ::testing::Test {
  14718. protected:
  14719. // Test helper that mimics SSE parsing behavior
  14720. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14721. int &retry_ms) {
  14722. // Blank line signals end of event
  14723. if (line.empty() || line == "\r") { return true; }
  14724. // Lines starting with ':' are comments (ignored)
  14725. if (!line.empty() && line[0] == ':') { return false; }
  14726. // Find the colon separator
  14727. auto colon_pos = line.find(':');
  14728. if (colon_pos == std::string::npos) {
  14729. // Line with no colon is treated as field name with empty value
  14730. return false;
  14731. }
  14732. std::string field = line.substr(0, colon_pos);
  14733. std::string value;
  14734. // Value starts after colon, skip optional single space
  14735. if (colon_pos + 1 < line.size()) {
  14736. size_t value_start = colon_pos + 1;
  14737. if (line[value_start] == ' ') { value_start++; }
  14738. value = line.substr(value_start);
  14739. // Remove trailing \r if present
  14740. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14741. }
  14742. // Handle known fields
  14743. if (field == "event") {
  14744. msg.event = value;
  14745. } else if (field == "data") {
  14746. // Multiple data lines are concatenated with newlines
  14747. if (!msg.data.empty()) { msg.data += "\n"; }
  14748. msg.data += value;
  14749. } else if (field == "id") {
  14750. // Empty id is valid (clears the last event ID)
  14751. msg.id = value;
  14752. } else if (field == "retry") {
  14753. // Parse retry interval in milliseconds
  14754. {
  14755. int v = 0;
  14756. auto res =
  14757. detail::from_chars(value.data(), value.data() + value.size(), v);
  14758. if (res.ec == std::errc{}) { retry_ms = v; }
  14759. }
  14760. }
  14761. // Unknown fields are ignored per SSE spec
  14762. return false;
  14763. }
  14764. };
  14765. // Test: Single-line data
  14766. TEST_F(SSEParsingTest, SingleLineData) {
  14767. sse::SSEMessage msg;
  14768. int retry_ms = 3000;
  14769. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14770. EXPECT_EQ(msg.data, "hello");
  14771. EXPECT_EQ(msg.event, "message");
  14772. // Blank line ends event
  14773. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14774. }
  14775. // Test: Multi-line data
  14776. TEST_F(SSEParsingTest, MultiLineData) {
  14777. sse::SSEMessage msg;
  14778. int retry_ms = 3000;
  14779. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14780. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14781. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14782. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14783. }
  14784. // Test: Custom event types
  14785. TEST_F(SSEParsingTest, CustomEventType) {
  14786. sse::SSEMessage msg;
  14787. int retry_ms = 3000;
  14788. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14789. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14790. EXPECT_EQ(msg.event, "update");
  14791. EXPECT_EQ(msg.data, "payload");
  14792. }
  14793. // Test: Event ID handling
  14794. TEST_F(SSEParsingTest, EventIdHandling) {
  14795. sse::SSEMessage msg;
  14796. int retry_ms = 3000;
  14797. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14798. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14799. EXPECT_EQ(msg.id, "12345");
  14800. }
  14801. // Test: Empty event ID (clears last event ID)
  14802. TEST_F(SSEParsingTest, EmptyEventId) {
  14803. sse::SSEMessage msg;
  14804. msg.id = "previous";
  14805. int retry_ms = 3000;
  14806. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14807. EXPECT_EQ(msg.id, "");
  14808. }
  14809. // Test: Retry field parsing
  14810. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14811. sse::SSEMessage msg;
  14812. int retry_ms = 3000;
  14813. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14814. EXPECT_EQ(retry_ms, 5000);
  14815. }
  14816. // Test: Invalid retry value
  14817. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14818. sse::SSEMessage msg;
  14819. int retry_ms = 3000;
  14820. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14821. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14822. }
  14823. // Test: Comments (lines starting with :)
  14824. TEST_F(SSEParsingTest, CommentsIgnored) {
  14825. sse::SSEMessage msg;
  14826. int retry_ms = 3000;
  14827. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14828. EXPECT_EQ(msg.data, "");
  14829. EXPECT_EQ(msg.event, "message");
  14830. }
  14831. // Test: Colon in value
  14832. TEST_F(SSEParsingTest, ColonInValue) {
  14833. sse::SSEMessage msg;
  14834. int retry_ms = 3000;
  14835. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14836. EXPECT_EQ(msg.data, "hello:world:test");
  14837. }
  14838. // Test: Line with no colon (field name only)
  14839. TEST_F(SSEParsingTest, FieldNameOnly) {
  14840. sse::SSEMessage msg;
  14841. int retry_ms = 3000;
  14842. // According to SSE spec, this is treated as field name with empty value
  14843. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14844. // Since we don't recognize "data" without colon, data should be empty
  14845. EXPECT_EQ(msg.data, "");
  14846. }
  14847. // Test: Trailing \r handling
  14848. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14849. sse::SSEMessage msg;
  14850. int retry_ms = 3000;
  14851. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14852. EXPECT_EQ(msg.data, "hello");
  14853. }
  14854. // Test: Unknown fields ignored
  14855. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14856. sse::SSEMessage msg;
  14857. int retry_ms = 3000;
  14858. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14859. EXPECT_EQ(msg.data, "");
  14860. EXPECT_EQ(msg.event, "message");
  14861. }
  14862. // Test: Space after colon is optional
  14863. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14864. sse::SSEMessage msg1, msg2;
  14865. int retry_ms = 3000;
  14866. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14867. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14868. EXPECT_EQ(msg1.data, "hello");
  14869. EXPECT_EQ(msg2.data, "hello");
  14870. }
  14871. // Test: SSEMessage clear
  14872. TEST_F(SSEParsingTest, MessageClear) {
  14873. sse::SSEMessage msg;
  14874. msg.event = "custom";
  14875. msg.data = "some data";
  14876. msg.id = "123";
  14877. msg.clear();
  14878. EXPECT_EQ(msg.event, "message");
  14879. EXPECT_EQ(msg.data, "");
  14880. EXPECT_EQ(msg.id, "");
  14881. }
  14882. // Test: Complete event parsing
  14883. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14884. sse::SSEMessage msg;
  14885. int retry_ms = 3000;
  14886. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14887. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14888. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14889. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14890. // Blank line ends event
  14891. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14892. EXPECT_EQ(msg.event, "notification");
  14893. EXPECT_EQ(msg.id, "evt-42");
  14894. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14895. EXPECT_EQ(retry_ms, 1000);
  14896. }
  14897. //==============================================================================
  14898. // Integration Tests with Server
  14899. //==============================================================================
  14900. class SSEIntegrationTest : public ::testing::Test {
  14901. protected:
  14902. void SetUp() override {
  14903. stop_server_.store(false);
  14904. events_.clear();
  14905. server_ = httplib::detail::make_unique<Server>();
  14906. setup_server();
  14907. start_server();
  14908. }
  14909. void TearDown() override {
  14910. stop_server_.store(true);
  14911. event_cv_.notify_all();
  14912. server_->stop();
  14913. if (server_thread_.joinable()) { server_thread_.join(); }
  14914. }
  14915. void setup_server() {
  14916. // Simple SSE endpoint
  14917. server_->Get("/events", [this](const Request &req, Response &res) {
  14918. auto last_id = req.get_header_value("Last-Event-ID");
  14919. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14920. res.set_chunked_content_provider(
  14921. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14922. std::unique_lock<std::mutex> lock(event_mutex_);
  14923. if (event_cv_.wait_for(
  14924. lock, std::chrono::milliseconds(200), [this] {
  14925. return !events_.empty() || stop_server_.load();
  14926. })) {
  14927. if (stop_server_.load()) { return false; }
  14928. if (!events_.empty()) {
  14929. std::string event = events_.front();
  14930. events_.erase(events_.begin());
  14931. sink.write(event.data(), event.size());
  14932. return true;
  14933. }
  14934. }
  14935. return !stop_server_.load();
  14936. });
  14937. });
  14938. // Endpoint that returns error
  14939. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14940. res.status = 500;
  14941. res.set_content("Internal Server Error", "text/plain");
  14942. });
  14943. // Endpoint for custom event types
  14944. server_->Get("/custom-events", [](const Request &, Response &res) {
  14945. res.set_chunked_content_provider(
  14946. "text/event-stream", [](size_t offset, DataSink &sink) {
  14947. if (offset == 0) {
  14948. std::string event = "event: update\ndata: updated\n\n"
  14949. "event: delete\ndata: deleted\n\n";
  14950. sink.write(event.data(), event.size());
  14951. }
  14952. return false; // End stream after sending
  14953. });
  14954. });
  14955. }
  14956. void start_server() {
  14957. port_ = server_->bind_to_any_port(HOST);
  14958. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14959. // Wait for server to start
  14960. while (!server_->is_running()) {
  14961. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14962. }
  14963. }
  14964. int get_port() const { return port_; }
  14965. void send_event(const std::string &event) {
  14966. std::lock_guard<std::mutex> lock(event_mutex_);
  14967. events_.push_back(event);
  14968. event_cv_.notify_all();
  14969. }
  14970. std::unique_ptr<Server> server_;
  14971. std::thread server_thread_;
  14972. std::mutex event_mutex_;
  14973. std::condition_variable event_cv_;
  14974. std::vector<std::string> events_;
  14975. std::atomic<bool> stop_server_{false};
  14976. std::string last_received_event_id_;
  14977. int port_ = 0;
  14978. };
  14979. // Test: Successful connection and on_open callback
  14980. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14981. // Add a simple endpoint that sends one event and closes
  14982. server_->Get("/simple-event", [](const Request &, Response &res) {
  14983. res.set_chunked_content_provider(
  14984. "text/event-stream", [](size_t offset, DataSink &sink) {
  14985. if (offset == 0) {
  14986. std::string event = "data: hello\n\n";
  14987. sink.write(event.data(), event.size());
  14988. }
  14989. return false; // Close stream after sending
  14990. });
  14991. });
  14992. Client client("localhost", get_port());
  14993. sse::SSEClient sse(client, "/simple-event");
  14994. std::atomic<bool> open_called{false};
  14995. std::atomic<bool> message_received{false};
  14996. sse.on_open([&open_called]() { open_called.store(true); });
  14997. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14998. if (msg.data == "hello") { message_received.store(true); }
  14999. });
  15000. sse.set_reconnect_interval(100);
  15001. sse.set_max_reconnect_attempts(1);
  15002. // Start async
  15003. sse.start_async();
  15004. // Wait for message to be processed
  15005. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15006. sse.stop();
  15007. EXPECT_TRUE(open_called.load());
  15008. EXPECT_TRUE(message_received.load());
  15009. }
  15010. // Test: on_message callback
  15011. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15012. // Endpoint that sends multiple events then closes
  15013. server_->Get("/multi-event", [](const Request &, Response &res) {
  15014. res.set_chunked_content_provider(
  15015. "text/event-stream", [](size_t offset, DataSink &sink) {
  15016. if (offset == 0) {
  15017. std::string events = "data: message1\n\ndata: message2\n\n";
  15018. sink.write(events.data(), events.size());
  15019. }
  15020. return false;
  15021. });
  15022. });
  15023. Client client("localhost", get_port());
  15024. sse::SSEClient sse(client, "/multi-event");
  15025. std::vector<std::string> received_messages;
  15026. std::mutex messages_mutex;
  15027. sse.on_message([&](const sse::SSEMessage &msg) {
  15028. std::lock_guard<std::mutex> lock(messages_mutex);
  15029. received_messages.push_back(msg.data);
  15030. });
  15031. sse.set_reconnect_interval(100);
  15032. sse.set_max_reconnect_attempts(1);
  15033. sse.start_async();
  15034. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15035. sse.stop();
  15036. std::lock_guard<std::mutex> lock(messages_mutex);
  15037. EXPECT_GE(received_messages.size(), 2u);
  15038. if (received_messages.size() >= 2) {
  15039. EXPECT_EQ(received_messages[0], "message1");
  15040. EXPECT_EQ(received_messages[1], "message2");
  15041. }
  15042. }
  15043. // Test: on_event for specific types
  15044. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15045. Client client("localhost", get_port());
  15046. sse::SSEClient sse(client, "/custom-events");
  15047. std::atomic<bool> update_received{false};
  15048. std::atomic<bool> delete_received{false};
  15049. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15050. if (msg.data == "updated") { update_received.store(true); }
  15051. });
  15052. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15053. if (msg.data == "deleted") { delete_received.store(true); }
  15054. });
  15055. sse.set_max_reconnect_attempts(1);
  15056. sse.start_async();
  15057. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15058. sse.stop();
  15059. EXPECT_TRUE(update_received.load());
  15060. EXPECT_TRUE(delete_received.load());
  15061. }
  15062. // Test: on_error callback on connection failure
  15063. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15064. // Connect to a non-existent port
  15065. Client client("localhost", 59999);
  15066. sse::SSEClient sse(client, "/events");
  15067. std::atomic<bool> error_called{false};
  15068. Error received_error = Error::Success;
  15069. sse.on_error([&](Error err) {
  15070. error_called.store(true);
  15071. received_error = err;
  15072. });
  15073. sse.set_reconnect_interval(50);
  15074. sse.set_max_reconnect_attempts(1);
  15075. sse.start_async();
  15076. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15077. sse.stop();
  15078. EXPECT_TRUE(error_called.load());
  15079. EXPECT_NE(received_error, Error::Success);
  15080. }
  15081. // Test: Last-Event-ID header sent on reconnect
  15082. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15083. // Endpoint that sends event with ID
  15084. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15085. res.set_chunked_content_provider(
  15086. "text/event-stream", [](size_t offset, DataSink &sink) {
  15087. if (offset == 0) {
  15088. std::string event = "id: evt-123\ndata: test\n\n";
  15089. sink.write(event.data(), event.size());
  15090. }
  15091. return false;
  15092. });
  15093. });
  15094. Client client("localhost", get_port());
  15095. sse::SSEClient sse(client, "/event-with-id");
  15096. std::atomic<bool> id_received{false};
  15097. sse.on_message([&](const sse::SSEMessage &msg) {
  15098. if (!msg.id.empty()) { id_received.store(true); }
  15099. });
  15100. sse.set_reconnect_interval(100);
  15101. sse.set_max_reconnect_attempts(1);
  15102. sse.start_async();
  15103. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15104. sse.stop();
  15105. EXPECT_TRUE(id_received.load());
  15106. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15107. }
  15108. // Test: Manual stop
  15109. TEST_F(SSEIntegrationTest, ManualStop) {
  15110. // Endpoint that sends one event and stays open briefly
  15111. std::atomic<bool> handler_running{true};
  15112. server_->Get("/stay-open", [&handler_running](const Request &,
  15113. Response &res) {
  15114. res.set_chunked_content_provider(
  15115. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15116. if (offset == 0) {
  15117. std::string event = "data: connected\n\n";
  15118. sink.write(event.data(), event.size());
  15119. }
  15120. // Keep connection open while handler_running is true
  15121. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15122. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15123. }
  15124. return false;
  15125. });
  15126. });
  15127. Client client("localhost", get_port());
  15128. sse::SSEClient sse(client, "/stay-open");
  15129. std::atomic<bool> connected{false};
  15130. sse.on_open([&connected]() { connected.store(true); });
  15131. sse.set_reconnect_interval(100);
  15132. sse.set_max_reconnect_attempts(1);
  15133. sse.start_async();
  15134. // Wait for connection to establish
  15135. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15136. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15137. }
  15138. EXPECT_TRUE(connected.load());
  15139. EXPECT_TRUE(sse.is_connected());
  15140. // Signal handler to stop
  15141. handler_running.store(false);
  15142. // Stop SSE client
  15143. sse.stop();
  15144. EXPECT_FALSE(sse.is_connected());
  15145. }
  15146. // Test: SSEClient with custom headers
  15147. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15148. // Setup a server endpoint that checks for custom header
  15149. std::atomic<bool> header_received{false};
  15150. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15151. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15152. header_received.store(true);
  15153. }
  15154. res.set_chunked_content_provider("text/event-stream",
  15155. [](size_t, DataSink &) { return false; });
  15156. });
  15157. Client client("localhost", get_port());
  15158. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15159. sse::SSEClient sse(client, "/header-check", headers);
  15160. sse.set_max_reconnect_attempts(1);
  15161. sse.start_async();
  15162. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15163. sse.stop();
  15164. EXPECT_TRUE(header_received.load());
  15165. }
  15166. // Test: Reconnect interval configuration
  15167. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15168. Client client("localhost", get_port());
  15169. sse::SSEClient sse(client, "/events");
  15170. auto &result = sse.set_reconnect_interval(500);
  15171. // Builder pattern should return reference to self
  15172. EXPECT_EQ(&result, &sse);
  15173. }
  15174. // Test: Max reconnect attempts
  15175. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15176. // Connect to non-existent port to force reconnects
  15177. Client client("localhost", 59998);
  15178. sse::SSEClient sse(client, "/events");
  15179. std::atomic<int> error_count{0};
  15180. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15181. sse.set_reconnect_interval(50);
  15182. sse.set_max_reconnect_attempts(2);
  15183. auto start = std::chrono::steady_clock::now();
  15184. sse.start(); // Blocking call
  15185. auto end = std::chrono::steady_clock::now();
  15186. // Should have stopped after 2 failed attempts
  15187. EXPECT_GE(error_count.load(), 2);
  15188. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15189. auto duration =
  15190. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15191. #ifdef _WIN32
  15192. // Windows is much slower for socket connection failures
  15193. EXPECT_LT(duration.count(), 7000);
  15194. #else
  15195. EXPECT_LT(duration.count(), 1000);
  15196. #endif
  15197. }
  15198. // Test: Multi-line data in integration
  15199. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15200. // Endpoint with multi-line data
  15201. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15202. res.set_chunked_content_provider(
  15203. "text/event-stream", [](size_t offset, DataSink &sink) {
  15204. if (offset == 0) {
  15205. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15206. sink.write(event.data(), event.size());
  15207. }
  15208. return false;
  15209. });
  15210. });
  15211. Client client("localhost", get_port());
  15212. sse::SSEClient sse(client, "/multiline-data");
  15213. std::string received_data;
  15214. std::mutex data_mutex;
  15215. sse.on_message([&](const sse::SSEMessage &msg) {
  15216. std::lock_guard<std::mutex> lock(data_mutex);
  15217. received_data = msg.data;
  15218. });
  15219. sse.set_reconnect_interval(100);
  15220. sse.set_max_reconnect_attempts(1);
  15221. sse.start_async();
  15222. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15223. sse.stop();
  15224. std::lock_guard<std::mutex> lock(data_mutex);
  15225. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15226. }
  15227. // Test: Auto-reconnect after server disconnection
  15228. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15229. std::atomic<int> connection_count{0};
  15230. std::atomic<int> message_count{0};
  15231. // Endpoint that sends one event and closes, forcing reconnect
  15232. server_->Get("/reconnect-test",
  15233. [&connection_count](const Request &, Response &res) {
  15234. connection_count.fetch_add(1);
  15235. res.set_chunked_content_provider(
  15236. "text/event-stream", [](size_t offset, DataSink &sink) {
  15237. if (offset == 0) {
  15238. std::string event = "data: hello\n\n";
  15239. sink.write(event.data(), event.size());
  15240. }
  15241. return false; // Close connection after sending
  15242. });
  15243. });
  15244. Client client("localhost", get_port());
  15245. sse::SSEClient sse(client, "/reconnect-test");
  15246. sse.on_message([&message_count](const sse::SSEMessage &) {
  15247. message_count.fetch_add(1);
  15248. });
  15249. sse.set_reconnect_interval(100);
  15250. sse.set_max_reconnect_attempts(3);
  15251. sse.start_async();
  15252. // Wait long enough for multiple reconnects
  15253. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15254. sse.stop();
  15255. // Should have connected multiple times (initial + reconnects)
  15256. EXPECT_GE(connection_count.load(), 2);
  15257. // Should have received messages from multiple connections
  15258. EXPECT_GE(message_count.load(), 2);
  15259. }
  15260. // Test: Last-Event-ID sent on reconnect
  15261. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15262. std::atomic<int> connection_count{0};
  15263. std::vector<std::string> received_last_event_ids;
  15264. std::mutex id_mutex;
  15265. // Endpoint that checks Last-Event-ID header and sends event with ID
  15266. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15267. int conn = connection_count.fetch_add(1);
  15268. // Capture the Last-Event-ID header from each connection
  15269. {
  15270. std::lock_guard<std::mutex> lock(id_mutex);
  15271. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15272. }
  15273. res.set_chunked_content_provider(
  15274. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15275. if (offset == 0) {
  15276. std::string event =
  15277. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15278. sink.write(event.data(), event.size());
  15279. }
  15280. return false;
  15281. });
  15282. });
  15283. Client client("localhost", get_port());
  15284. sse::SSEClient sse(client, "/reconnect-with-id");
  15285. sse.set_reconnect_interval(100);
  15286. sse.set_max_reconnect_attempts(3);
  15287. sse.start_async();
  15288. // Wait for at least 2 connections
  15289. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15290. sse.stop();
  15291. // Verify behavior
  15292. std::lock_guard<std::mutex> lock(id_mutex);
  15293. EXPECT_GE(received_last_event_ids.size(), 2u);
  15294. // First connection should have no Last-Event-ID
  15295. if (!received_last_event_ids.empty()) {
  15296. EXPECT_EQ(received_last_event_ids[0], "");
  15297. }
  15298. // Second connection should have Last-Event-ID from first connection
  15299. if (received_last_event_ids.size() >= 2) {
  15300. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15301. }
  15302. }
  15303. // Test: set_headers updates headers used on reconnect
  15304. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15305. std::vector<std::string> received_tokens;
  15306. std::mutex token_mutex;
  15307. // Endpoint that captures Authorization header
  15308. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15309. {
  15310. std::lock_guard<std::mutex> lock(token_mutex);
  15311. received_tokens.push_back(req.get_header_value("Authorization"));
  15312. }
  15313. res.set_chunked_content_provider(
  15314. "text/event-stream", [](size_t offset, DataSink &sink) {
  15315. if (offset == 0) {
  15316. std::string event = "data: hello\n\n";
  15317. sink.write(event.data(), event.size());
  15318. }
  15319. return false; // Close connection to trigger reconnect
  15320. });
  15321. });
  15322. Client client("localhost", get_port());
  15323. Headers headers = {{"Authorization", "Bearer old-token"}};
  15324. sse::SSEClient sse(client, "/auth-check", headers);
  15325. // Update headers on each successful connection
  15326. sse.on_open(
  15327. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15328. sse.set_reconnect_interval(100);
  15329. sse.set_max_reconnect_attempts(3);
  15330. sse.start_async();
  15331. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15332. sse.stop();
  15333. std::lock_guard<std::mutex> lock(token_mutex);
  15334. ASSERT_GE(received_tokens.size(), 2u);
  15335. // First connection uses original header
  15336. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15337. // Second connection uses updated header from set_headers
  15338. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15339. }
  15340. // Test: 401 allows reconnection (so on_error can refresh headers)
  15341. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15342. std::atomic<int> connection_count{0};
  15343. // Endpoint: returns 401 on first attempt, 200 on second
  15344. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15345. int conn = connection_count.fetch_add(1);
  15346. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15347. res.status = StatusCode::Unauthorized_401;
  15348. res.set_content("Unauthorized", "text/plain");
  15349. return;
  15350. }
  15351. res.set_chunked_content_provider(
  15352. "text/event-stream", [](size_t offset, DataSink &sink) {
  15353. if (offset == 0) {
  15354. std::string event = "data: authenticated\n\n";
  15355. sink.write(event.data(), event.size());
  15356. }
  15357. return false;
  15358. });
  15359. });
  15360. Client client("localhost", get_port());
  15361. Headers headers = {{"Authorization", "Bearer expired"}};
  15362. sse::SSEClient sse(client, "/auth-retry", headers);
  15363. std::atomic<bool> message_received{false};
  15364. // Refresh token on error
  15365. sse.on_error(
  15366. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15367. sse.on_message([&](const sse::SSEMessage &msg) {
  15368. if (msg.data == "authenticated") { message_received.store(true); }
  15369. });
  15370. sse.set_reconnect_interval(100);
  15371. sse.set_max_reconnect_attempts(3);
  15372. sse.start_async();
  15373. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15374. sse.stop();
  15375. // Should have reconnected after 401 and succeeded with new token
  15376. EXPECT_GE(connection_count.load(), 2);
  15377. EXPECT_TRUE(message_received.load());
  15378. }
  15379. TEST(Issue2318Test, EmptyHostString) {
  15380. {
  15381. httplib::Client cli_empty("", PORT);
  15382. auto res = cli_empty.Get("/");
  15383. ASSERT_FALSE(res);
  15384. EXPECT_EQ(httplib::Error::Connection, res.error());
  15385. }
  15386. {
  15387. httplib::Client cli(" ", PORT);
  15388. auto res = cli.Get("/");
  15389. ASSERT_FALSE(res);
  15390. EXPECT_EQ(httplib::Error::Connection, res.error());
  15391. }
  15392. }
  15393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15394. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15395. Server svr;
  15396. // Set a small payload limit (1KB)
  15397. svr.set_payload_max_length(1024);
  15398. svr.Post("/test", [&](const Request &req, Response &res) {
  15399. res.set_content("Body size: " + std::to_string(req.body.size()),
  15400. "text/plain");
  15401. });
  15402. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15403. auto se = detail::scope_exit([&] {
  15404. svr.stop();
  15405. listen_thread.join();
  15406. });
  15407. svr.wait_until_ready();
  15408. // Create data that compresses well but exceeds limit when decompressed
  15409. // 8KB of repeated null bytes compresses to a very small size
  15410. std::string original_data(8 * 1024, '\0');
  15411. // Compress the data using gzip
  15412. std::string compressed_data;
  15413. detail::gzip_compressor compressor;
  15414. compressor.compress(original_data.data(), original_data.size(), true,
  15415. [&](const char *data, size_t size) {
  15416. compressed_data.append(data, size);
  15417. return true;
  15418. });
  15419. // Verify compression worked (compressed should be much smaller)
  15420. ASSERT_LT(compressed_data.size(), original_data.size());
  15421. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15422. // Send compressed data with Content-Encoding: gzip
  15423. Client cli(HOST, PORT);
  15424. Headers headers = {{"Content-Encoding", "gzip"}};
  15425. auto res =
  15426. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15427. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15428. ASSERT_TRUE(res);
  15429. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15430. }
  15431. #endif
  15432. // ============================================================================
  15433. // OpenSSL-Specific Tests
  15434. // ============================================================================
  15435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15436. X509 *readCertificate(const std::string &strFileName) {
  15437. std::ifstream inStream(strFileName);
  15438. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15439. std::istreambuf_iterator<char>());
  15440. if (strCertPEM.empty()) return (nullptr);
  15441. BIO *pbCert = BIO_new(BIO_s_mem());
  15442. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15443. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15444. BIO_free(pbCert);
  15445. return (pCert);
  15446. }
  15447. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15448. std::ifstream inStream(strFileName);
  15449. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15450. std::istreambuf_iterator<char>());
  15451. if (strPrivateKeyPEM.empty()) return (nullptr);
  15452. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15453. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15454. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15455. BIO_free(pbPrivKey);
  15456. return (pPrivateKey);
  15457. }
  15458. TEST(BindServerTest, UpdateCerts) {
  15459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15460. int port = svr.bind_to_any_port("0.0.0.0");
  15461. ASSERT_TRUE(svr.is_valid());
  15462. ASSERT_TRUE(port > 0);
  15463. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15464. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15465. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15466. ASSERT_TRUE(cert != nullptr);
  15467. ASSERT_TRUE(ca_cert != nullptr);
  15468. ASSERT_TRUE(key != nullptr);
  15469. X509_STORE *cert_store = X509_STORE_new();
  15470. X509_STORE_add_cert(cert_store, ca_cert);
  15471. // svr.update_certs(cert, key, cert_store); // deprecated
  15472. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15473. CLIENT_CA_CERT_FILE);
  15474. ASSERT_TRUE(svr.is_valid());
  15475. svr.stop();
  15476. X509_STORE_free(cert_store);
  15477. X509_free(cert);
  15478. X509_free(ca_cert);
  15479. EVP_PKEY_free(key);
  15480. }
  15481. // Test that update_certs() updates client CA list correctly
  15482. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15483. // Start with file-based constructor
  15484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15485. ASSERT_TRUE(svr.is_valid());
  15486. // Initially no client CA list should be set
  15487. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15488. ASSERT_TRUE(ssl_ctx != nullptr);
  15489. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15490. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15491. EXPECT_EQ(0, count_before);
  15492. // Now update with client CA (PEM string)
  15493. std::string cert_pem, key_pem, ca_pem;
  15494. read_file(SERVER_CERT_FILE, cert_pem);
  15495. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15496. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15497. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15498. ASSERT_TRUE(svr.is_valid());
  15499. // Now client CA list should be set
  15500. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15501. ASSERT_TRUE(ca_list_after != nullptr);
  15502. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15503. }
  15504. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15505. // Test that the file-path SSLServer constructor properly sets the client CA
  15506. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15508. ASSERT_TRUE(svr.is_valid());
  15509. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15510. ASSERT_TRUE(ssl_ctx != nullptr);
  15511. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15512. ASSERT_TRUE(ca_list != nullptr);
  15513. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15514. }
  15515. #endif
  15516. // ============================================================================
  15517. // MbedTLS-Specific Tests
  15518. // ============================================================================
  15519. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15520. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15521. using namespace httplib::tls;
  15522. // Track if callback was invoked
  15523. bool callback_invoked = false;
  15524. // The callback receives void* ctx which is actually MbedTlsContext*
  15525. // We can access the mbedtls_ssl_config via the context
  15526. auto setup_callback = [&callback_invoked](void *ctx) {
  15527. callback_invoked = true;
  15528. // Cast to MbedTlsContext* to access the ssl config
  15529. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15530. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15531. // Use static variables to hold certificate data (simplified for test)
  15532. static mbedtls_x509_crt own_cert;
  15533. static mbedtls_pk_context own_key;
  15534. static mbedtls_x509_crt ca_chain;
  15535. static bool initialized = false;
  15536. if (!initialized) {
  15537. mbedtls_x509_crt_init(&own_cert);
  15538. mbedtls_pk_init(&own_key);
  15539. mbedtls_x509_crt_init(&ca_chain);
  15540. // Load server certificate
  15541. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15542. return false;
  15543. }
  15544. // Load server private key.
  15545. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15546. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15547. #if MBEDTLS_VERSION_MAJOR == 3
  15548. ,
  15549. mbedtls_ctr_drbg_random, nullptr
  15550. #endif
  15551. ) != 0) {
  15552. return false;
  15553. }
  15554. // Load CA chain for client verification
  15555. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15556. return false;
  15557. }
  15558. initialized = true;
  15559. }
  15560. // Configure the SSL config
  15561. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15562. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15563. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15564. // Set minimum TLS version using mbedTLS native API
  15565. #if MBEDTLS_VERSION_MAJOR >= 3
  15566. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15567. #else
  15568. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15569. MBEDTLS_SSL_MINOR_VERSION_3);
  15570. #endif
  15571. return true;
  15572. };
  15573. SSLServer svr(setup_callback);
  15574. ASSERT_TRUE(svr.is_valid());
  15575. ASSERT_TRUE(callback_invoked);
  15576. svr.Get("/test", [&](const Request &req, Response &res) {
  15577. res.set_content("test", "text/plain");
  15578. auto cert = req.peer_cert();
  15579. ASSERT_TRUE(static_cast<bool>(cert));
  15580. auto common_name = cert.subject_cn();
  15581. EXPECT_EQ("Common Name", common_name);
  15582. });
  15583. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15584. auto se = detail::scope_exit([&] {
  15585. svr.stop();
  15586. t.join();
  15587. ASSERT_FALSE(svr.is_running());
  15588. });
  15589. svr.wait_until_ready();
  15590. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15591. cli.enable_server_certificate_verification(false);
  15592. cli.set_connection_timeout(30);
  15593. auto res = cli.Get("/test");
  15594. ASSERT_TRUE(res);
  15595. ASSERT_EQ(StatusCode::OK_200, res->status);
  15596. }
  15597. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15598. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15599. // keep-alive SSL session, which reads through that config in
  15600. // mbedtls_ssl_close_notify.
  15601. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15603. ASSERT_TRUE(svr.is_valid());
  15604. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15605. res.set_content("test", "text/plain");
  15606. });
  15607. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15608. auto se = detail::scope_exit([&] {
  15609. svr.stop();
  15610. t.join();
  15611. ASSERT_FALSE(svr.is_running());
  15612. });
  15613. svr.wait_until_ready();
  15614. {
  15615. SSLClient cli(HOST, PORT);
  15616. cli.enable_server_certificate_verification(false);
  15617. cli.set_keep_alive(true);
  15618. auto res = cli.Get("/test");
  15619. ASSERT_TRUE(res);
  15620. ASSERT_EQ(StatusCode::OK_200, res->status);
  15621. // cli is destructed here with the keep-alive SSL session still open.
  15622. }
  15623. }
  15624. #endif
  15625. // WebSocket Tests
  15626. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15627. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15628. // defining the meaning of these bits has been negotiated.
  15629. auto make_frame = [](uint8_t first_byte) {
  15630. std::string frame;
  15631. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15632. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15633. frame += "Hello";
  15634. return frame;
  15635. };
  15636. // RSV1 set (0x40)
  15637. {
  15638. detail::BufferStream strm;
  15639. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15640. ws::Opcode opcode;
  15641. std::string payload;
  15642. bool fin;
  15643. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15644. false, 1024));
  15645. }
  15646. // RSV2 set (0x20)
  15647. {
  15648. detail::BufferStream strm;
  15649. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15650. ws::Opcode opcode;
  15651. std::string payload;
  15652. bool fin;
  15653. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15654. false, 1024));
  15655. }
  15656. // RSV3 set (0x10)
  15657. {
  15658. detail::BufferStream strm;
  15659. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15660. ws::Opcode opcode;
  15661. std::string payload;
  15662. bool fin;
  15663. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15664. false, 1024));
  15665. }
  15666. // No RSV bits set - should succeed
  15667. {
  15668. detail::BufferStream strm;
  15669. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15670. ws::Opcode opcode;
  15671. std::string payload;
  15672. bool fin;
  15673. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15674. false, 1024));
  15675. EXPECT_EQ(ws::Opcode::Text, opcode);
  15676. EXPECT_EQ("Hello", payload);
  15677. EXPECT_TRUE(fin);
  15678. }
  15679. }
  15680. TEST(WebSocketTest, ControlFrameValidation) {
  15681. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15682. // payload length <= 125.
  15683. // Ping with FIN=0 - must be rejected
  15684. {
  15685. detail::BufferStream strm;
  15686. std::string frame;
  15687. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15688. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15689. strm.write(frame.data(), frame.size());
  15690. ws::Opcode opcode;
  15691. std::string payload;
  15692. bool fin;
  15693. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15694. false, 1024));
  15695. }
  15696. // Close with FIN=0 - must be rejected
  15697. {
  15698. detail::BufferStream strm;
  15699. std::string frame;
  15700. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15701. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15702. strm.write(frame.data(), frame.size());
  15703. ws::Opcode opcode;
  15704. std::string payload;
  15705. bool fin;
  15706. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15707. false, 1024));
  15708. }
  15709. // Ping with payload_len=126 (extended length) - must be rejected
  15710. {
  15711. detail::BufferStream strm;
  15712. std::string frame;
  15713. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15714. frame += static_cast<char>(126); // payload_len=126 (>125)
  15715. frame += static_cast<char>(0x00); // extended length high byte
  15716. frame += static_cast<char>(126); // extended length low byte
  15717. frame += std::string(126, 'x');
  15718. strm.write(frame.data(), frame.size());
  15719. ws::Opcode opcode;
  15720. std::string payload;
  15721. bool fin;
  15722. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15723. false, 1024));
  15724. }
  15725. // Ping with FIN=1 and payload_len=125 - should succeed
  15726. {
  15727. detail::BufferStream strm;
  15728. std::string frame;
  15729. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15730. frame += static_cast<char>(125); // payload_len=125
  15731. frame += std::string(125, 'x');
  15732. strm.write(frame.data(), frame.size());
  15733. ws::Opcode opcode;
  15734. std::string payload;
  15735. bool fin;
  15736. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15737. false, 1024));
  15738. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15739. EXPECT_EQ(125u, payload.size());
  15740. EXPECT_TRUE(fin);
  15741. }
  15742. }
  15743. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15744. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15745. // length MUST be 0.
  15746. // MSB set - must be rejected
  15747. {
  15748. detail::BufferStream strm;
  15749. std::string frame;
  15750. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15751. frame += static_cast<char>(127); // 64-bit extended length
  15752. frame += static_cast<char>(0x80); // MSB set (invalid)
  15753. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15754. strm.write(frame.data(), frame.size());
  15755. ws::Opcode opcode;
  15756. std::string payload;
  15757. bool fin;
  15758. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15759. false, 1024));
  15760. }
  15761. // MSB clear - should pass length parsing (will be rejected by max_len,
  15762. // but that's a different check; use a small length to verify)
  15763. {
  15764. detail::BufferStream strm;
  15765. std::string frame;
  15766. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15767. frame += static_cast<char>(127); // 64-bit extended length
  15768. frame += std::string(7, '\0'); // high bytes = 0
  15769. frame += static_cast<char>(0x03); // length = 3
  15770. frame += "abc";
  15771. strm.write(frame.data(), frame.size());
  15772. ws::Opcode opcode;
  15773. std::string payload;
  15774. bool fin;
  15775. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15776. false, 1024));
  15777. EXPECT_EQ(ws::Opcode::Text, opcode);
  15778. EXPECT_EQ("abc", payload);
  15779. }
  15780. }
  15781. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15782. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15783. // Valid UTF-8
  15784. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15785. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15786. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15787. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15788. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15789. // Invalid UTF-8
  15790. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15791. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15792. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15793. EXPECT_FALSE(
  15794. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15795. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15796. }
  15797. TEST(WebSocketTest, ConnectAndDisconnect) {
  15798. Server svr;
  15799. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15800. std::string msg;
  15801. while (ws.read(msg)) {}
  15802. });
  15803. auto port = svr.bind_to_any_port(HOST);
  15804. std::thread t([&]() { svr.listen_after_bind(); });
  15805. svr.wait_until_ready();
  15806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15807. ASSERT_TRUE(client.connect());
  15808. EXPECT_TRUE(client.is_open());
  15809. client.close();
  15810. EXPECT_FALSE(client.is_open());
  15811. svr.stop();
  15812. t.join();
  15813. }
  15814. TEST(WebSocketTest, ValidURL) {
  15815. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15816. EXPECT_TRUE(ws1.is_valid());
  15817. ws::WebSocketClient ws2("ws://example.com/path");
  15818. EXPECT_TRUE(ws2.is_valid());
  15819. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15820. EXPECT_TRUE(ws3.is_valid());
  15821. #ifdef CPPHTTPLIB_SSL_ENABLED
  15822. ws::WebSocketClient wss1("wss://example.com/path");
  15823. EXPECT_TRUE(wss1.is_valid());
  15824. ws::WebSocketClient wss2("wss://example.com:443/path");
  15825. EXPECT_TRUE(wss2.is_valid());
  15826. #endif
  15827. }
  15828. TEST(WebSocketTest, InvalidURL) {
  15829. // No scheme
  15830. ws::WebSocketClient ws1("localhost:8080/path");
  15831. EXPECT_FALSE(ws1.is_valid());
  15832. // No path
  15833. ws::WebSocketClient ws2("ws://localhost:8080");
  15834. EXPECT_FALSE(ws2.is_valid());
  15835. // Empty string
  15836. ws::WebSocketClient ws3("");
  15837. EXPECT_FALSE(ws3.is_valid());
  15838. // Missing host
  15839. ws::WebSocketClient ws4("ws://:8080/path");
  15840. EXPECT_FALSE(ws4.is_valid());
  15841. // Port number overflow — should not crash
  15842. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15843. EXPECT_FALSE(ws5.is_valid());
  15844. // Port out of range
  15845. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15846. EXPECT_FALSE(ws6.is_valid());
  15847. }
  15848. TEST(WebSocketTest, UnsupportedScheme) {
  15849. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15850. ws::WebSocketClient ws1("http://localhost:8080/path");
  15851. EXPECT_FALSE(ws1.is_valid());
  15852. ws::WebSocketClient ws2("https://localhost:8080/path");
  15853. EXPECT_FALSE(ws2.is_valid());
  15854. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15855. EXPECT_FALSE(ws3.is_valid());
  15856. #else
  15857. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15858. std::invalid_argument);
  15859. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15860. std::invalid_argument);
  15861. #endif
  15862. }
  15863. TEST(WebSocketTest, ConnectWhenInvalid) {
  15864. ws::WebSocketClient ws("not a valid url");
  15865. EXPECT_FALSE(ws.is_valid());
  15866. EXPECT_FALSE(ws.connect());
  15867. }
  15868. TEST(WebSocketTest, DefaultPort) {
  15869. ws::WebSocketClient ws1("ws://example.com/path");
  15870. EXPECT_TRUE(ws1.is_valid());
  15871. // ws:// defaults to port 80 (verified by successful parse)
  15872. #ifdef CPPHTTPLIB_SSL_ENABLED
  15873. ws::WebSocketClient ws2("wss://example.com/path");
  15874. EXPECT_TRUE(ws2.is_valid());
  15875. // wss:// defaults to port 443 (verified by successful parse)
  15876. #endif
  15877. }
  15878. TEST(WebSocketTest, IPv6LiteralAddress) {
  15879. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15880. EXPECT_TRUE(ws1.is_valid());
  15881. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15882. EXPECT_TRUE(ws2.is_valid());
  15883. }
  15884. TEST(WebSocketTest, ComplexPath) {
  15885. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15886. EXPECT_TRUE(ws1.is_valid());
  15887. ws::WebSocketClient ws2("ws://localhost:8080/");
  15888. EXPECT_TRUE(ws2.is_valid());
  15889. }
  15890. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15891. Server svr;
  15892. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15893. std::string msg;
  15894. while (ws.read(msg)) {}
  15895. });
  15896. auto port = svr.bind_to_any_port(HOST);
  15897. std::thread t([&]() { svr.listen_after_bind(); });
  15898. svr.wait_until_ready();
  15899. auto another_host = "example.com";
  15900. auto wrong_ip = "192.0.2.1";
  15901. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15902. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15903. ASSERT_TRUE(client.connect());
  15904. EXPECT_TRUE(client.is_open());
  15905. client.close();
  15906. svr.stop();
  15907. t.join();
  15908. }
  15909. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15910. Server svr;
  15911. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15912. std::string msg;
  15913. while (ws.read(msg)) {}
  15914. });
  15915. auto port = svr.bind_to_any_port(HOST);
  15916. std::thread t([&]() { svr.listen_after_bind(); });
  15917. svr.wait_until_ready();
  15918. auto wrong_ip = "192.0.2.1";
  15919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15920. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15921. client.set_connection_timeout(1);
  15922. client.set_read_timeout(1);
  15923. client.set_write_timeout(1);
  15924. EXPECT_FALSE(client.connect());
  15925. EXPECT_FALSE(client.is_open());
  15926. svr.stop();
  15927. t.join();
  15928. }
  15929. class WebSocketIntegrationTest : public ::testing::Test {
  15930. protected:
  15931. void SetUp() override {
  15932. server_ = httplib::detail::make_unique<Server>();
  15933. setup_server();
  15934. start_server();
  15935. }
  15936. void TearDown() override {
  15937. server_->stop();
  15938. if (server_thread_.joinable()) { server_thread_.join(); }
  15939. }
  15940. void setup_server() {
  15941. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15942. std::string msg;
  15943. ws::ReadResult ret;
  15944. while ((ret = ws.read(msg))) {
  15945. if (ret == ws::Binary) {
  15946. ws.send(msg.data(), msg.size());
  15947. } else {
  15948. ws.send(msg);
  15949. }
  15950. }
  15951. });
  15952. server_->WebSocket("/ws-echo-string",
  15953. [](const Request &, ws::WebSocket &ws) {
  15954. std::string msg;
  15955. while (ws.read(msg)) {
  15956. ws.send("echo: " + msg);
  15957. }
  15958. });
  15959. server_->WebSocket(
  15960. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15961. // Echo back request metadata
  15962. ws.send("path:" + req.path);
  15963. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15964. std::string msg;
  15965. while (ws.read(msg)) {}
  15966. });
  15967. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15968. std::string msg;
  15969. ws.read(msg); // wait for a message
  15970. ws.close();
  15971. });
  15972. server_->WebSocket("/ws-close-status",
  15973. [](const Request &, ws::WebSocket &ws) {
  15974. std::string msg;
  15975. ws.read(msg); // wait for a message
  15976. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15977. });
  15978. server_->WebSocket(
  15979. "/ws-subprotocol",
  15980. [](const Request &, ws::WebSocket &ws) {
  15981. std::string msg;
  15982. while (ws.read(msg)) {
  15983. ws.send(msg);
  15984. }
  15985. },
  15986. [](const std::vector<std::string> &protocols) -> std::string {
  15987. for (const auto &p : protocols) {
  15988. if (p == "graphql-ws") { return p; }
  15989. }
  15990. return "";
  15991. });
  15992. }
  15993. void start_server() {
  15994. port_ = server_->bind_to_any_port(HOST);
  15995. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15996. server_->wait_until_ready();
  15997. }
  15998. std::unique_ptr<Server> server_;
  15999. std::thread server_thread_;
  16000. int port_ = 0;
  16001. };
  16002. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16004. "/ws-echo");
  16005. ASSERT_TRUE(client.connect());
  16006. ASSERT_TRUE(client.is_open());
  16007. ASSERT_TRUE(client.send("Hello WebSocket"));
  16008. std::string msg;
  16009. EXPECT_EQ(ws::Text, client.read(msg));
  16010. EXPECT_EQ("Hello WebSocket", msg);
  16011. client.close();
  16012. }
  16013. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16014. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16015. "/ws-echo");
  16016. ASSERT_TRUE(client.connect());
  16017. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16018. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16019. std::string msg;
  16020. EXPECT_EQ(ws::Binary, client.read(msg));
  16021. EXPECT_EQ(binary_data, msg);
  16022. client.close();
  16023. }
  16024. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16026. "/ws-echo");
  16027. ASSERT_TRUE(client.connect());
  16028. for (int i = 0; i < 10; i++) {
  16029. auto text = "message " + std::to_string(i);
  16030. ASSERT_TRUE(client.send(text));
  16031. std::string msg;
  16032. ASSERT_TRUE(client.read(msg));
  16033. EXPECT_EQ(text, msg);
  16034. }
  16035. client.close();
  16036. }
  16037. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16039. "/ws-close");
  16040. ASSERT_TRUE(client.connect());
  16041. // Send a message to trigger the server to close
  16042. ASSERT_TRUE(client.send("trigger close"));
  16043. // The server will close, so read should return false
  16044. std::string msg;
  16045. EXPECT_FALSE(client.read(msg));
  16046. EXPECT_FALSE(client.is_open());
  16047. }
  16048. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16050. "/ws-echo");
  16051. ASSERT_TRUE(client.connect());
  16052. // 128KB message
  16053. std::string large_data(128 * 1024, 'X');
  16054. ASSERT_TRUE(client.send(large_data));
  16055. std::string msg;
  16056. ASSERT_TRUE(client.read(msg));
  16057. EXPECT_EQ(large_data, msg);
  16058. client.close();
  16059. }
  16060. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16062. "/ws-echo");
  16063. ASSERT_TRUE(client.connect());
  16064. const int num_threads = 4;
  16065. std::vector<std::thread> threads;
  16066. std::atomic<int> send_count{0};
  16067. for (int t = 0; t < num_threads; t++) {
  16068. threads.emplace_back([&client, &send_count, t]() {
  16069. for (int i = 0; i < 5; i++) {
  16070. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16071. if (client.send(text)) { send_count++; }
  16072. }
  16073. });
  16074. }
  16075. for (auto &th : threads) {
  16076. th.join();
  16077. }
  16078. int received = 0;
  16079. std::string msg;
  16080. while (received < send_count.load()) {
  16081. if (!client.read(msg)) { break; }
  16082. received++;
  16083. }
  16084. EXPECT_EQ(send_count.load(), received);
  16085. client.close();
  16086. }
  16087. TEST_F(WebSocketIntegrationTest, ReadString) {
  16088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16089. "/ws-echo-string");
  16090. ASSERT_TRUE(client.connect());
  16091. ASSERT_TRUE(client.send("hello"));
  16092. std::string msg;
  16093. ASSERT_TRUE(client.read(msg));
  16094. EXPECT_EQ("echo: hello", msg);
  16095. ASSERT_TRUE(client.send("world"));
  16096. ASSERT_TRUE(client.read(msg));
  16097. EXPECT_EQ("echo: world", msg);
  16098. client.close();
  16099. }
  16100. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16101. Headers headers = {{"X-Test-Header", "test-value"}};
  16102. ws::WebSocketClient client(
  16103. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16104. ASSERT_TRUE(client.connect());
  16105. std::string msg;
  16106. ASSERT_TRUE(client.read(msg));
  16107. EXPECT_EQ("path:/ws-request-info", msg);
  16108. ASSERT_TRUE(client.read(msg));
  16109. EXPECT_EQ("header:test-value", msg);
  16110. client.close();
  16111. }
  16112. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16113. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16114. "/ws-echo");
  16115. client.set_read_timeout(1, 0); // 1 second
  16116. ASSERT_TRUE(client.connect());
  16117. // Don't send anything — server echo handler waits for a message,
  16118. // so read() should time out and return false.
  16119. std::string msg;
  16120. EXPECT_FALSE(client.read(msg));
  16121. }
  16122. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16123. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16124. "/ws-echo");
  16125. client.set_read_timeout(5, 0);
  16126. ASSERT_TRUE(client.connect());
  16127. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16128. // The server should reject it and close the connection.
  16129. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16130. client.send(oversized);
  16131. // The server's read() should have failed due to payload limit,
  16132. // so our read() should return false (connection closed).
  16133. std::string msg;
  16134. EXPECT_FALSE(client.read(msg));
  16135. }
  16136. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16137. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16138. "/ws-echo");
  16139. client.set_read_timeout(10, 0);
  16140. ASSERT_TRUE(client.connect());
  16141. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16142. // This should succeed.
  16143. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16144. ASSERT_TRUE(client.send(at_limit));
  16145. std::string msg;
  16146. ASSERT_TRUE(client.read(msg));
  16147. EXPECT_EQ(at_limit.size(), msg.size());
  16148. client.close();
  16149. }
  16150. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16151. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16152. "/nonexistent");
  16153. EXPECT_FALSE(client.connect());
  16154. EXPECT_FALSE(client.is_open());
  16155. }
  16156. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16158. "/ws-echo");
  16159. ASSERT_TRUE(client.connect());
  16160. ASSERT_TRUE(client.send(""));
  16161. std::string msg;
  16162. EXPECT_EQ(ws::Text, client.read(msg));
  16163. EXPECT_EQ("", msg);
  16164. client.close();
  16165. }
  16166. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16168. "/ws-echo");
  16169. // First connection
  16170. ASSERT_TRUE(client.connect());
  16171. ASSERT_TRUE(client.send("first"));
  16172. std::string msg;
  16173. ASSERT_TRUE(client.read(msg));
  16174. EXPECT_EQ("first", msg);
  16175. client.close();
  16176. EXPECT_FALSE(client.is_open());
  16177. // Reconnect using the same client object
  16178. ASSERT_TRUE(client.connect());
  16179. ASSERT_TRUE(client.is_open());
  16180. ASSERT_TRUE(client.send("second"));
  16181. ASSERT_TRUE(client.read(msg));
  16182. EXPECT_EQ("second", msg);
  16183. client.close();
  16184. }
  16185. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16187. "/ws-close-status");
  16188. ASSERT_TRUE(client.connect());
  16189. // Trigger the server to close with GoingAway status
  16190. ASSERT_TRUE(client.send("trigger"));
  16191. // read() should return false after receiving the close frame
  16192. std::string msg;
  16193. EXPECT_FALSE(client.read(msg));
  16194. EXPECT_FALSE(client.is_open());
  16195. }
  16196. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16198. "/ws-echo");
  16199. ASSERT_TRUE(client.connect());
  16200. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16201. EXPECT_FALSE(client.is_open());
  16202. }
  16203. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16204. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16205. ws::WebSocketClient client(
  16206. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16207. ASSERT_TRUE(client.connect());
  16208. // Server should have selected graphql-ws
  16209. EXPECT_EQ("graphql-ws", client.subprotocol());
  16210. client.close();
  16211. }
  16212. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16213. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16214. ws::WebSocketClient client(
  16215. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16216. ASSERT_TRUE(client.connect());
  16217. // Server should not have selected any subprotocol
  16218. EXPECT_TRUE(client.subprotocol().empty());
  16219. client.close();
  16220. }
  16221. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16222. // Connect without requesting any subprotocol
  16223. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16224. "/ws-subprotocol");
  16225. ASSERT_TRUE(client.connect());
  16226. EXPECT_TRUE(client.subprotocol().empty());
  16227. client.close();
  16228. }
  16229. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16231. "/ws-echo");
  16232. client.set_tcp_nodelay(true);
  16233. client.set_connection_timeout(3, 0);
  16234. bool socket_options_called = false;
  16235. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16236. ASSERT_TRUE(client.connect());
  16237. ASSERT_TRUE(client.is_open());
  16238. EXPECT_TRUE(socket_options_called);
  16239. ASSERT_TRUE(client.send("hello"));
  16240. std::string msg;
  16241. auto result = client.read(msg);
  16242. EXPECT_EQ(result, ws::ReadResult::Text);
  16243. EXPECT_EQ(msg, "hello");
  16244. client.close();
  16245. }
  16246. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16247. Server svr;
  16248. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16249. if (!req.has_header("Authorization")) {
  16250. res.status = StatusCode::Unauthorized_401;
  16251. res.set_content("Unauthorized", "text/plain");
  16252. return Server::HandlerResponse::Handled;
  16253. }
  16254. return Server::HandlerResponse::Unhandled;
  16255. });
  16256. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16257. std::string msg;
  16258. while (ws.read(msg)) {
  16259. ws.send(msg);
  16260. }
  16261. });
  16262. auto port = svr.bind_to_any_port("localhost");
  16263. std::thread t([&]() { svr.listen_after_bind(); });
  16264. svr.wait_until_ready();
  16265. // Without Authorization header - should be rejected before upgrade
  16266. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16267. EXPECT_FALSE(client1.connect());
  16268. // With Authorization header - should succeed
  16269. Headers headers = {{"Authorization", "Bearer token123"}};
  16270. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16271. headers);
  16272. ASSERT_TRUE(client2.connect());
  16273. ASSERT_TRUE(client2.send("hello"));
  16274. std::string msg;
  16275. ASSERT_TRUE(client2.read(msg));
  16276. EXPECT_EQ("hello", msg);
  16277. client2.close();
  16278. svr.stop();
  16279. t.join();
  16280. }
  16281. TEST(WebSocketTest, QueryStringInHandshake) {
  16282. Server svr;
  16283. std::mutex mtx;
  16284. std::string received_target;
  16285. std::string received_token;
  16286. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16287. {
  16288. std::lock_guard<std::mutex> lock(mtx);
  16289. received_target = req.target;
  16290. if (req.has_param("token")) {
  16291. received_token = req.get_param_value("token");
  16292. }
  16293. }
  16294. std::string msg;
  16295. while (ws.read(msg)) {
  16296. ws.send(msg);
  16297. }
  16298. });
  16299. auto port = svr.bind_to_any_port("localhost");
  16300. std::thread t([&]() { svr.listen_after_bind(); });
  16301. svr.wait_until_ready();
  16302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16303. "/ws?token=ABC&session=123");
  16304. ASSERT_TRUE(client.connect());
  16305. // Round-trip ensures the handler has run and captured the request.
  16306. ASSERT_TRUE(client.send("hello"));
  16307. std::string msg;
  16308. ASSERT_TRUE(client.read(msg));
  16309. EXPECT_EQ("hello", msg);
  16310. client.close();
  16311. {
  16312. std::lock_guard<std::mutex> lock(mtx);
  16313. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16314. EXPECT_EQ("ABC", received_token);
  16315. }
  16316. svr.stop();
  16317. t.join();
  16318. }
  16319. TEST(WebSocketTest, HostHeaderInHandshake) {
  16320. Server svr;
  16321. std::mutex mtx;
  16322. std::string received_host;
  16323. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16324. {
  16325. std::lock_guard<std::mutex> lock(mtx);
  16326. received_host = req.get_header_value("Host");
  16327. }
  16328. std::string msg;
  16329. while (ws.read(msg)) {
  16330. ws.send(msg);
  16331. }
  16332. });
  16333. auto port = svr.bind_to_any_port("localhost");
  16334. std::thread t([&]() { svr.listen_after_bind(); });
  16335. svr.wait_until_ready();
  16336. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16337. ASSERT_TRUE(client.connect());
  16338. // Round-trip ensures the handler has run and captured the request.
  16339. ASSERT_TRUE(client.send("hello"));
  16340. std::string msg;
  16341. ASSERT_TRUE(client.read(msg));
  16342. client.close();
  16343. {
  16344. std::lock_guard<std::mutex> lock(mtx);
  16345. // Non-default port must be present in the Host header. Default ports
  16346. // (80/443) are omitted; that logic is covered by
  16347. // MakeHostAndPortStringTest.
  16348. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16349. }
  16350. svr.stop();
  16351. t.join();
  16352. }
  16353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16354. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16355. protected:
  16356. void SetUp() override {
  16357. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16358. SERVER_PRIVATE_KEY_FILE);
  16359. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16360. std::string msg;
  16361. ws::ReadResult ret;
  16362. while ((ret = ws.read(msg))) {
  16363. if (ret == ws::Binary) {
  16364. ws.send(msg.data(), msg.size());
  16365. } else {
  16366. ws.send(msg);
  16367. }
  16368. }
  16369. });
  16370. port_ = server_->bind_to_any_port(HOST);
  16371. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16372. server_->wait_until_ready();
  16373. }
  16374. void TearDown() override {
  16375. server_->stop();
  16376. if (server_thread_.joinable()) { server_thread_.join(); }
  16377. }
  16378. std::unique_ptr<SSLServer> server_;
  16379. std::thread server_thread_;
  16380. int port_ = 0;
  16381. };
  16382. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16383. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16384. "/ws-echo");
  16385. client.enable_server_certificate_verification(false);
  16386. ASSERT_TRUE(client.connect());
  16387. ASSERT_TRUE(client.is_open());
  16388. ASSERT_TRUE(client.send("Hello WSS"));
  16389. std::string msg;
  16390. EXPECT_EQ(ws::Text, client.read(msg));
  16391. EXPECT_EQ("Hello WSS", msg);
  16392. client.close();
  16393. }
  16394. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16395. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16396. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16397. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16398. // client (without calling close() first) is the only path that runs
  16399. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16400. // bug exactly.
  16401. //
  16402. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16403. // when linked against an instrumented libssl; run under Valgrind to catch it
  16404. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16405. // suite (the freed session otherwise stalls on the close handshake) — this test
  16406. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16407. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16408. {
  16409. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16410. "/ws-echo");
  16411. client.enable_server_certificate_verification(false);
  16412. client.set_read_timeout(2, 0);
  16413. client.set_write_timeout(2, 0);
  16414. ASSERT_TRUE(client.connect());
  16415. ASSERT_TRUE(client.is_open());
  16416. ASSERT_TRUE(client.send("still open"));
  16417. // Intentionally do NOT call client.close(): leaving scope runs
  16418. // shutdown_and_close() with the WebSocket still open, which must send the
  16419. // close frame while the TLS session is still alive.
  16420. }
  16421. }
  16422. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16423. // shutdown_and_close() at the start of connect(), reproducing the same
  16424. // use-after-free within the test body rather than at scope exit. The second
  16425. // connect must succeed and echo, proving the close handshake ran over a live
  16426. // session. See the note above about memory-tool requirements.
  16427. TEST_F(WebSocketSSLIntegrationTest,
  16428. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16429. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16430. "/ws-echo");
  16431. client.enable_server_certificate_verification(false);
  16432. client.set_read_timeout(2, 0);
  16433. client.set_write_timeout(2, 0);
  16434. ASSERT_TRUE(client.connect());
  16435. ASSERT_TRUE(client.is_open());
  16436. ASSERT_TRUE(client.send("still open"));
  16437. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16438. // the still-open connection, which must not touch a freed TLS session.
  16439. ASSERT_TRUE(client.connect());
  16440. ASSERT_TRUE(client.is_open());
  16441. ASSERT_TRUE(client.send("after reconnect"));
  16442. std::string msg;
  16443. EXPECT_EQ(ws::Text, client.read(msg));
  16444. EXPECT_EQ("after reconnect", msg);
  16445. client.close();
  16446. }
  16447. #endif
  16448. #ifdef CPPHTTPLIB_SSL_ENABLED
  16449. class WebSocketSSLCATest : public ::testing::Test {
  16450. protected:
  16451. void SetUp() override {
  16452. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16453. SERVER_PRIVATE_KEY_FILE);
  16454. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16455. std::string msg;
  16456. while (ws.read(msg)) {
  16457. ws.send(msg);
  16458. }
  16459. });
  16460. port_ = server_->bind_to_any_port("127.0.0.1");
  16461. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16462. server_->wait_until_ready();
  16463. }
  16464. void TearDown() override {
  16465. server_->stop();
  16466. if (server_thread_.joinable()) { server_thread_.join(); }
  16467. }
  16468. std::string url() const {
  16469. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16470. }
  16471. std::unique_ptr<SSLServer> server_;
  16472. std::thread server_thread_;
  16473. int port_ = 0;
  16474. };
  16475. // A custom CA loaded as PEM verifies the server with full certificate
  16476. // verification enabled
  16477. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16478. ws::WebSocketClient client(url());
  16479. std::string cert;
  16480. read_file(SERVER_CERT2_FILE, cert);
  16481. client.load_ca_cert_store(cert.c_str(), cert.size());
  16482. ASSERT_TRUE(client.connect());
  16483. ASSERT_TRUE(client.send("hello"));
  16484. std::string msg;
  16485. EXPECT_EQ(ws::Text, client.read(msg));
  16486. EXPECT_EQ("hello", msg);
  16487. client.close();
  16488. }
  16489. // A custom CA that does not cover the server must fail verification (the
  16490. // custom CA is exclusive; system certs are not loaded alongside it)
  16491. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16492. ws::WebSocketClient client(url());
  16493. std::string cert;
  16494. read_file(CLIENT_CA_CERT_FILE, cert);
  16495. client.load_ca_cert_store(cert.c_str(), cert.size());
  16496. ASSERT_FALSE(client.connect());
  16497. }
  16498. // Regression test: reconnecting with a native custom CA store used to reuse
  16499. // a store handle the previous TLS context had already freed (use-after-free
  16500. // under the OpenSSL backend). The context now lives as long as the client.
  16501. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16502. ws::WebSocketClient client(url());
  16503. std::string cert;
  16504. read_file(SERVER_CERT2_FILE, cert);
  16505. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16506. ASSERT_TRUE(client.connect());
  16507. client.close();
  16508. ASSERT_TRUE(client.connect());
  16509. ASSERT_TRUE(client.send("again"));
  16510. std::string msg;
  16511. EXPECT_EQ(ws::Text, client.read(msg));
  16512. EXPECT_EQ("again", msg);
  16513. client.close();
  16514. }
  16515. // Regression test: a certificate with a trusted chain but no identity match
  16516. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16517. // verification entirely for IP hosts, so this connection succeeded there.
  16518. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16519. // chain verification while the identity check must still fail.
  16520. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16522. ASSERT_TRUE(svr.is_valid());
  16523. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16524. std::string msg;
  16525. while (ws.read(msg)) {
  16526. ws.send(msg);
  16527. }
  16528. });
  16529. auto port = svr.bind_to_any_port("127.0.0.1");
  16530. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16531. auto se = detail::scope_exit([&] {
  16532. svr.stop();
  16533. t.join();
  16534. });
  16535. svr.wait_until_ready();
  16536. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16537. "/echo");
  16538. std::string cert;
  16539. read_file(SERVER_CERT_FILE, cert);
  16540. client.load_ca_cert_store(cert.c_str(), cert.size());
  16541. ASSERT_FALSE(client.connect());
  16542. }
  16543. #endif
  16544. #if !defined(_WIN32)
  16545. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16546. auto secret_dir = std::string("./symlink_test_secret");
  16547. auto served_dir = std::string("./symlink_test_served");
  16548. auto secret_file = secret_dir + "/secret.txt";
  16549. auto symlink_path = served_dir + "/escape";
  16550. // Setup: create directories and files
  16551. mkdir(secret_dir.c_str(), 0755);
  16552. mkdir(served_dir.c_str(), 0755);
  16553. {
  16554. std::ofstream ofs(secret_file);
  16555. ofs << "SECRET_DATA";
  16556. }
  16557. // Create symlink using absolute path so it resolves correctly
  16558. #ifdef PATH_MAX
  16559. char abs_secret[PATH_MAX];
  16560. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16561. #else
  16562. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16563. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16564. ASSERT_NE(nullptr, abs_secret);
  16565. #endif
  16566. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16567. auto se = detail::scope_exit([&] {
  16568. unlink(symlink_path.c_str());
  16569. unlink(secret_file.c_str());
  16570. rmdir(served_dir.c_str());
  16571. rmdir(secret_dir.c_str());
  16572. });
  16573. Server svr;
  16574. svr.set_mount_point("/", served_dir);
  16575. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16576. auto se2 = detail::scope_exit([&] {
  16577. svr.stop();
  16578. listen_thread.join();
  16579. });
  16580. svr.wait_until_ready();
  16581. Client cli("localhost", PORT);
  16582. // Symlink pointing outside base dir should be blocked
  16583. auto res = cli.Get("/escape/secret.txt");
  16584. ASSERT_TRUE(res);
  16585. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16586. }
  16587. #endif
  16588. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16589. // A GET request with Content-Length to a static file handler must have its
  16590. // body drained before the keep-alive connection is reused. Otherwise the
  16591. // unread body bytes are interpreted as the next HTTP request.
  16592. //
  16593. // The body is sent AFTER receiving the first response (as in the original
  16594. // PoC) so that the stream_line_reader cannot buffer it together with the
  16595. // headers of the first request.
  16596. Server svr;
  16597. svr.set_mount_point("/", "./www");
  16598. std::atomic<int> smuggled_count(0);
  16599. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16600. smuggled_count++;
  16601. res.set_content("oops", "text/plain");
  16602. });
  16603. auto port = svr.bind_to_any_port("localhost");
  16604. thread t = thread([&] { svr.listen_after_bind(); });
  16605. auto se = detail::scope_exit([&] {
  16606. svr.stop();
  16607. t.join();
  16608. });
  16609. svr.wait_until_ready();
  16610. auto error = Error::Success;
  16611. auto sock = detail::create_client_socket(
  16612. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16613. /*connection_timeout_sec=*/2, 0,
  16614. /*read_timeout_sec=*/2, 0,
  16615. /*write_timeout_sec=*/2, 0, std::string(), error);
  16616. ASSERT_NE(INVALID_SOCKET, sock);
  16617. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16618. // The "smuggled" request will be sent as the body of the outer GET
  16619. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16620. "Host: localhost\r\n"
  16621. "Connection: close\r\n"
  16622. "\r\n";
  16623. // Step 1: Send only the outer request headers (no body yet)
  16624. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16625. "Host: localhost\r\n"
  16626. "Content-Length: " +
  16627. std::to_string(smuggled.size()) +
  16628. "\r\n"
  16629. "\r\n";
  16630. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16631. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16632. // Step 2: Read the first response (server serves file without reading body)
  16633. std::string first_response;
  16634. char buf[4096];
  16635. for (;;) {
  16636. auto n = recv(sock, buf, sizeof(buf), 0);
  16637. if (n <= 0) break;
  16638. first_response.append(buf, static_cast<size_t>(n));
  16639. // Stop once we have a complete response (headers + body)
  16640. auto hdr_end = first_response.find("\r\n\r\n");
  16641. if (hdr_end != std::string::npos) {
  16642. // Check for Content-Length to know when the body is complete
  16643. auto cl_pos = first_response.find("Content-Length:");
  16644. if (cl_pos != std::string::npos) {
  16645. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16646. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16647. auto cl = std::stoul(
  16648. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16649. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16650. } else {
  16651. break; // No Content-Length, assume headers-only response
  16652. }
  16653. }
  16654. }
  16655. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16656. // Step 3: Now send the body, which looks like a new HTTP request.
  16657. // On a vulnerable server the keep-alive loop reads this as a second request.
  16658. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16659. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16660. // Step 4: Try to read a second response (should NOT exist after fix)
  16661. std::string second_response;
  16662. for (;;) {
  16663. auto n = recv(sock, buf, sizeof(buf), 0);
  16664. if (n <= 0) break;
  16665. second_response.append(buf, static_cast<size_t>(n));
  16666. }
  16667. // The smuggled request must NOT have been processed
  16668. EXPECT_EQ(0, smuggled_count.load());
  16669. }
  16670. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16671. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16672. // must be rejected with 400 Bad Request.
  16673. Server svr;
  16674. svr.Post("/test", [&](const Request &, Response &res) {
  16675. res.set_content("ok", "text/plain");
  16676. });
  16677. thread t = thread([&] { svr.listen(HOST, PORT); });
  16678. auto se = detail::scope_exit([&] {
  16679. svr.stop();
  16680. t.join();
  16681. ASSERT_FALSE(svr.is_running());
  16682. });
  16683. svr.wait_until_ready();
  16684. // Exact "chunked"
  16685. {
  16686. auto req = "POST /test HTTP/1.1\r\n"
  16687. "Host: localhost\r\n"
  16688. "Content-Length: 5\r\n"
  16689. "Transfer-Encoding: chunked\r\n"
  16690. "Connection: close\r\n"
  16691. "\r\n"
  16692. "hello";
  16693. std::string response;
  16694. ASSERT_TRUE(send_request(1, req, &response));
  16695. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16696. response.substr(0, response.find("\r\n")));
  16697. }
  16698. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16699. {
  16700. auto req = "POST /test HTTP/1.1\r\n"
  16701. "Host: localhost\r\n"
  16702. "Content-Length: 5\r\n"
  16703. "Transfer-Encoding: gzip, chunked\r\n"
  16704. "Connection: close\r\n"
  16705. "\r\n"
  16706. "hello";
  16707. std::string response;
  16708. ASSERT_TRUE(send_request(1, req, &response));
  16709. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16710. response.substr(0, response.find("\r\n")));
  16711. }
  16712. }
  16713. // Regression for issue #2450: a DELETE without Content-Length on a
  16714. // keep-alive connection must not let the post-response drain consume the
  16715. // next request's bytes.
  16716. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16717. Server svr;
  16718. std::atomic<int> delete_count(0);
  16719. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16720. delete_count++;
  16721. res.status = StatusCode::NoContent_204;
  16722. });
  16723. auto port = svr.bind_to_any_port(HOST);
  16724. thread t = thread([&] { svr.listen_after_bind(); });
  16725. auto se = detail::scope_exit([&] {
  16726. svr.stop();
  16727. t.join();
  16728. });
  16729. svr.wait_until_ready();
  16730. auto error = Error::Success;
  16731. auto sock = detail::create_client_socket(
  16732. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16733. /*connection_timeout_sec=*/2, 0,
  16734. /*read_timeout_sec=*/2, 0,
  16735. /*write_timeout_sec=*/2, 0, std::string(), error);
  16736. ASSERT_NE(INVALID_SOCKET, sock);
  16737. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16738. auto send_request_and_read_response = [&](const std::string &req,
  16739. std::string &out) -> bool {
  16740. auto sent = send(sock, req.data(), req.size(), 0);
  16741. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16742. char buf[4096];
  16743. for (;;) {
  16744. auto n = recv(sock, buf, sizeof(buf), 0);
  16745. if (n <= 0) { return !out.empty(); }
  16746. out.append(buf, static_cast<size_t>(n));
  16747. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16748. }
  16749. };
  16750. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16751. "Host: localhost\r\n"
  16752. "\r\n";
  16753. std::string resp1;
  16754. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16755. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16756. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16757. "Host: localhost\r\n"
  16758. "Connection: close\r\n"
  16759. "\r\n";
  16760. std::string resp2;
  16761. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16762. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16763. EXPECT_EQ(2, delete_count.load());
  16764. }
  16765. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  16766. Server svr;
  16767. svr.Post("/ingest", [&](const Request &, Response &res,
  16768. const ContentReader &content_reader) {
  16769. auto consumed = content_reader([](const char *, size_t) { return false; });
  16770. EXPECT_FALSE(consumed);
  16771. res.status = StatusCode::Conflict_409;
  16772. res.set_header("Connection", "close");
  16773. });
  16774. auto port = svr.bind_to_any_port(HOST);
  16775. thread t = thread([&] { svr.listen_after_bind(); });
  16776. auto se = detail::scope_exit([&] {
  16777. svr.stop();
  16778. t.join();
  16779. });
  16780. svr.wait_until_ready();
  16781. auto error = Error::Success;
  16782. auto sock = detail::create_client_socket(
  16783. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16784. /*connection_timeout_sec=*/2, 0,
  16785. /*read_timeout_sec=*/1, 0,
  16786. /*write_timeout_sec=*/2, 0, std::string(), error);
  16787. ASSERT_NE(INVALID_SOCKET, sock);
  16788. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16789. std::string request = "POST /ingest HTTP/1.1\r\n"
  16790. "Host: localhost\r\n"
  16791. "Transfer-Encoding: chunked\r\n"
  16792. "\r\n"
  16793. "4\r\n"
  16794. "data\r\n";
  16795. auto sent = send(sock, request.data(), request.size(), 0);
  16796. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  16797. std::string response;
  16798. ssize_t received = 0;
  16799. do {
  16800. char buf[4096];
  16801. received = recv(sock, buf, sizeof(buf), 0);
  16802. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  16803. } while (received > 0);
  16804. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  16805. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  16806. EXPECT_EQ(0, received);
  16807. }
  16808. namespace no_proxy_test {
  16809. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16810. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16811. // calling listen().
  16812. class ScopedServer {
  16813. public:
  16814. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16815. ~ScopedServer() {
  16816. svr_.stop();
  16817. if (th_.joinable()) { th_.join(); }
  16818. }
  16819. Server &svr() { return svr_; }
  16820. int port() const { return port_; }
  16821. void listen() {
  16822. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16823. svr_.wait_until_ready();
  16824. }
  16825. private:
  16826. Server svr_;
  16827. std::thread th_;
  16828. int port_ = 0;
  16829. };
  16830. class ProxyAndTargetServers {
  16831. public:
  16832. ProxyAndTargetServers() {
  16833. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16834. proxy_hits_++;
  16835. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16836. res.set_content("via-proxy", "text/plain");
  16837. });
  16838. target_.Get(".*", [this](const Request &req, Response &res) {
  16839. target_hits_++;
  16840. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16841. res.set_content("direct", "text/plain");
  16842. });
  16843. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16844. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16845. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16846. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16847. proxy_mock_.wait_until_ready();
  16848. target_.wait_until_ready();
  16849. }
  16850. ~ProxyAndTargetServers() {
  16851. proxy_mock_.stop();
  16852. target_.stop();
  16853. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16854. if (target_thread_.joinable()) { target_thread_.join(); }
  16855. }
  16856. Server &proxy_mock() { return proxy_mock_; }
  16857. Server &target() { return target_; }
  16858. int proxy_port() const { return proxy_port_; }
  16859. int target_port() const { return target_port_; }
  16860. int proxy_hits() const { return proxy_hits_.load(); }
  16861. int target_hits() const { return target_hits_.load(); }
  16862. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16863. void reset_counters() {
  16864. proxy_hits_ = 0;
  16865. target_hits_ = 0;
  16866. last_had_proxy_authz_ = false;
  16867. }
  16868. private:
  16869. Server proxy_mock_;
  16870. Server target_;
  16871. std::thread proxy_thread_;
  16872. std::thread target_thread_;
  16873. int proxy_port_ = 0;
  16874. int target_port_ = 0;
  16875. std::atomic<int> proxy_hits_{0};
  16876. std::atomic<int> target_hits_{0};
  16877. std::atomic<bool> last_had_proxy_authz_{false};
  16878. };
  16879. inline std::unique_ptr<Client> make_client(const std::string &host,
  16880. ProxyAndTargetServers &s) {
  16881. auto cli = detail::make_unique<Client>(host, s.target_port());
  16882. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16883. cli->set_proxy("127.0.0.1", s.proxy_port());
  16884. return cli;
  16885. }
  16886. } // namespace no_proxy_test
  16887. using no_proxy_test::make_client;
  16888. using no_proxy_test::ProxyAndTargetServers;
  16889. TEST(NoProxyTest, ExactHostnameBypasses) {
  16890. ProxyAndTargetServers s;
  16891. auto cli = make_client("example.com", s);
  16892. cli->set_no_proxy({"example.com"});
  16893. auto res = cli->Get("/");
  16894. ASSERT_TRUE(res);
  16895. EXPECT_EQ(0, s.proxy_hits());
  16896. EXPECT_EQ(1, s.target_hits());
  16897. }
  16898. TEST(NoProxyTest, SubdomainBypasses) {
  16899. ProxyAndTargetServers s;
  16900. auto cli = make_client("foo.example.com", s);
  16901. cli->set_no_proxy({"example.com"});
  16902. auto res = cli->Get("/");
  16903. ASSERT_TRUE(res);
  16904. EXPECT_EQ(0, s.proxy_hits());
  16905. EXPECT_EQ(1, s.target_hits());
  16906. }
  16907. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16908. // Regression guard: "evilexample.com" must not be considered a subdomain
  16909. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16910. // check would let traffic bypass the proxy and leak credentials direct
  16911. // to the attacker host.
  16912. ProxyAndTargetServers s;
  16913. auto cli = make_client("evilexample.com", s);
  16914. cli->set_no_proxy({"example.com"});
  16915. auto res = cli->Get("/");
  16916. ASSERT_TRUE(res);
  16917. EXPECT_GE(s.proxy_hits(), 1);
  16918. EXPECT_EQ(0, s.target_hits());
  16919. }
  16920. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16921. ProxyAndTargetServers s;
  16922. auto cli = make_client("example.com.evil.com", s);
  16923. cli->set_no_proxy({"example.com"});
  16924. auto res = cli->Get("/");
  16925. ASSERT_TRUE(res);
  16926. EXPECT_GE(s.proxy_hits(), 1);
  16927. EXPECT_EQ(0, s.target_hits());
  16928. }
  16929. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16930. ProxyAndTargetServers s;
  16931. auto cli = make_client("example.com", s);
  16932. cli->set_no_proxy({".example.com"});
  16933. auto res = cli->Get("/");
  16934. ASSERT_TRUE(res);
  16935. EXPECT_EQ(0, s.proxy_hits());
  16936. EXPECT_EQ(1, s.target_hits());
  16937. }
  16938. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16939. ProxyAndTargetServers s;
  16940. auto cli = make_client("Example.COM", s);
  16941. cli->set_no_proxy({"EXAMPLE.com"});
  16942. auto res = cli->Get("/");
  16943. ASSERT_TRUE(res);
  16944. EXPECT_EQ(0, s.proxy_hits());
  16945. EXPECT_EQ(1, s.target_hits());
  16946. }
  16947. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16948. ProxyAndTargetServers s;
  16949. auto cli = make_client("example.com.", s);
  16950. cli->set_no_proxy({"example.com"});
  16951. auto res = cli->Get("/");
  16952. ASSERT_TRUE(res);
  16953. EXPECT_EQ(0, s.proxy_hits());
  16954. EXPECT_EQ(1, s.target_hits());
  16955. }
  16956. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16957. // Trailing dots must be normalized on BOTH sides — host and entry.
  16958. // An implementation that only strips the host-side trailing dot would
  16959. // fail to match host "example.com" against entry "example.com." because
  16960. // a literal substring search would compare 11 chars against 12.
  16961. ProxyAndTargetServers s;
  16962. auto cli = make_client("example.com", s);
  16963. cli->set_no_proxy({"example.com."});
  16964. auto res = cli->Get("/");
  16965. ASSERT_TRUE(res);
  16966. EXPECT_EQ(0, s.proxy_hits());
  16967. EXPECT_EQ(1, s.target_hits());
  16968. }
  16969. TEST(NoProxyTest, WildcardBypassesEverything) {
  16970. ProxyAndTargetServers s;
  16971. auto cli = make_client("anything.invalid.test", s);
  16972. cli->set_no_proxy({"*"});
  16973. auto res = cli->Get("/");
  16974. ASSERT_TRUE(res);
  16975. EXPECT_EQ(0, s.proxy_hits());
  16976. EXPECT_EQ(1, s.target_hits());
  16977. }
  16978. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16979. ProxyAndTargetServers s;
  16980. Client cli("127.0.0.1", s.target_port());
  16981. cli.set_proxy("127.0.0.1", s.proxy_port());
  16982. cli.set_no_proxy({"127.0.0.1"});
  16983. auto res = cli.Get("/");
  16984. ASSERT_TRUE(res);
  16985. EXPECT_EQ(0, s.proxy_hits());
  16986. EXPECT_EQ(1, s.target_hits());
  16987. }
  16988. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16989. ProxyAndTargetServers s;
  16990. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16991. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16992. cli.set_proxy("127.0.0.1", s.proxy_port());
  16993. cli.set_no_proxy({"::1"});
  16994. auto res = cli.Get("/");
  16995. ASSERT_TRUE(res);
  16996. EXPECT_EQ(0, s.proxy_hits());
  16997. EXPECT_EQ(1, s.target_hits());
  16998. }
  16999. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17000. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17001. // must still be recognized as IPv6 for CIDR matching. Implementations
  17002. // that detect IPv6 only when the host begins with '[' would parse the
  17003. // host as a hostname and miss the match.
  17004. ProxyAndTargetServers s;
  17005. Client cli("fe80::1", s.target_port());
  17006. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17007. cli.set_proxy("127.0.0.1", s.proxy_port());
  17008. cli.set_no_proxy({"fe80::/10"});
  17009. auto res = cli.Get("/");
  17010. ASSERT_TRUE(res);
  17011. EXPECT_EQ(0, s.proxy_hits());
  17012. EXPECT_EQ(1, s.target_hits());
  17013. }
  17014. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17015. ProxyAndTargetServers s;
  17016. Client cli("::1", s.target_port());
  17017. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17018. cli.set_proxy("127.0.0.1", s.proxy_port());
  17019. cli.set_no_proxy({"[::1]"});
  17020. auto res = cli.Get("/");
  17021. ASSERT_TRUE(res);
  17022. EXPECT_EQ(0, s.proxy_hits());
  17023. EXPECT_EQ(1, s.target_hits());
  17024. }
  17025. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17026. ProxyAndTargetServers s;
  17027. Client cli("fe80::1", s.target_port());
  17028. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17029. cli.set_proxy("127.0.0.1", s.proxy_port());
  17030. cli.set_no_proxy({"[fe80::]/10"});
  17031. auto res = cli.Get("/");
  17032. ASSERT_TRUE(res);
  17033. EXPECT_EQ(0, s.proxy_hits());
  17034. EXPECT_EQ(1, s.target_hits());
  17035. }
  17036. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17037. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17038. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17039. // tricks via address-family conversion.
  17040. ProxyAndTargetServers s;
  17041. Client cli("::ffff:127.0.0.1", s.target_port());
  17042. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17043. cli.set_proxy("127.0.0.1", s.proxy_port());
  17044. cli.set_no_proxy({"127.0.0.1"});
  17045. auto res = cli.Get("/");
  17046. ASSERT_TRUE(res);
  17047. EXPECT_GE(s.proxy_hits(), 1);
  17048. EXPECT_EQ(0, s.target_hits());
  17049. }
  17050. TEST(NoProxyTest, IPv4CidrMatch) {
  17051. ProxyAndTargetServers s;
  17052. Client cli("127.0.0.1", s.target_port());
  17053. cli.set_proxy("127.0.0.1", s.proxy_port());
  17054. cli.set_no_proxy({"127.0.0.0/8"});
  17055. auto res = cli.Get("/");
  17056. ASSERT_TRUE(res);
  17057. EXPECT_EQ(0, s.proxy_hits());
  17058. EXPECT_EQ(1, s.target_hits());
  17059. }
  17060. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17061. ProxyAndTargetServers s;
  17062. Client cli("127.0.0.1", s.target_port());
  17063. cli.set_proxy("127.0.0.1", s.proxy_port());
  17064. cli.set_no_proxy({"10.0.0.0/8"});
  17065. auto res = cli.Get("/");
  17066. ASSERT_TRUE(res);
  17067. EXPECT_GE(s.proxy_hits(), 1);
  17068. EXPECT_EQ(0, s.target_hits());
  17069. }
  17070. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17071. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17072. // IPv4 target matches.
  17073. ProxyAndTargetServers s;
  17074. Client cli("127.0.0.1", s.target_port());
  17075. cli.set_proxy("127.0.0.1", s.proxy_port());
  17076. cli.set_no_proxy({"0.0.0.0/0"});
  17077. auto res = cli.Get("/");
  17078. ASSERT_TRUE(res);
  17079. EXPECT_EQ(0, s.proxy_hits());
  17080. EXPECT_EQ(1, s.target_hits());
  17081. }
  17082. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17083. ProxyAndTargetServers s;
  17084. Client cli("127.0.0.1", s.target_port());
  17085. cli.set_proxy("127.0.0.1", s.proxy_port());
  17086. cli.set_no_proxy({"127.0.0.1"});
  17087. auto res = cli.Get("/");
  17088. ASSERT_TRUE(res);
  17089. EXPECT_EQ(0, s.proxy_hits());
  17090. EXPECT_EQ(1, s.target_hits());
  17091. }
  17092. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17093. ProxyAndTargetServers s;
  17094. Client cli("127.0.0.1", s.target_port());
  17095. cli.set_proxy("127.0.0.1", s.proxy_port());
  17096. cli.set_no_proxy({"127.0.0.0/33"});
  17097. auto res = cli.Get("/");
  17098. ASSERT_TRUE(res);
  17099. EXPECT_GE(s.proxy_hits(), 1);
  17100. EXPECT_EQ(0, s.target_hits());
  17101. }
  17102. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17103. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17104. ProxyAndTargetServers s;
  17105. Client cli("127.0.0.1", s.target_port());
  17106. cli.set_proxy("127.0.0.1", s.proxy_port());
  17107. cli.set_no_proxy({"127.0.0.1/"});
  17108. auto res = cli.Get("/");
  17109. ASSERT_TRUE(res);
  17110. EXPECT_GE(s.proxy_hits(), 1);
  17111. EXPECT_EQ(0, s.target_hits());
  17112. }
  17113. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17114. ProxyAndTargetServers s;
  17115. auto cli = make_client("internal.corp", s);
  17116. cli->set_proxy_basic_auth("u", "p");
  17117. cli->set_no_proxy({"internal.corp"});
  17118. auto res = cli->Get("/");
  17119. ASSERT_TRUE(res);
  17120. EXPECT_EQ(1, s.target_hits());
  17121. EXPECT_EQ(0, s.proxy_hits());
  17122. EXPECT_FALSE(s.last_had_proxy_authz())
  17123. << "Proxy-Authorization must not be sent direct to the target";
  17124. }
  17125. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17126. ProxyAndTargetServers s;
  17127. auto cli = make_client("public.example", s);
  17128. cli->set_proxy_basic_auth("u", "p");
  17129. cli->set_no_proxy({"internal.corp"}); // does not match
  17130. auto res = cli->Get("/");
  17131. ASSERT_TRUE(res);
  17132. EXPECT_GE(s.proxy_hits(), 1);
  17133. EXPECT_TRUE(s.last_had_proxy_authz());
  17134. }
  17135. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17136. ProxyAndTargetServers s;
  17137. auto cli = make_client("anything.test", s);
  17138. auto res = cli->Get("/");
  17139. ASSERT_TRUE(res);
  17140. EXPECT_GE(s.proxy_hits(), 1);
  17141. EXPECT_EQ(0, s.target_hits());
  17142. }
  17143. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17144. ProxyAndTargetServers s;
  17145. auto cli = make_client("example.com", s);
  17146. cli->set_no_proxy({"example.com:8080"});
  17147. auto res = cli->Get("/");
  17148. ASSERT_TRUE(res);
  17149. EXPECT_GE(s.proxy_hits(), 1);
  17150. EXPECT_EQ(0, s.target_hits());
  17151. }
  17152. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17153. ProxyAndTargetServers s;
  17154. auto cli = make_client("anything.test", s);
  17155. cli->set_no_proxy({"", " ", "\t"});
  17156. auto res = cli->Get("/");
  17157. ASSERT_TRUE(res);
  17158. EXPECT_GE(s.proxy_hits(), 1);
  17159. EXPECT_EQ(0, s.target_hits());
  17160. }
  17161. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17162. // An entry with leading/trailing whitespace must still match — env-style
  17163. // values are commonly pasted with stray spaces and an implementation
  17164. // that feeds the raw token directly to inet_pton would fail to match
  17165. // valid CIDRs because of the spaces.
  17166. ProxyAndTargetServers s;
  17167. Client cli("127.0.0.1", s.target_port());
  17168. cli.set_proxy("127.0.0.1", s.proxy_port());
  17169. cli.set_no_proxy({" 127.0.0.0/8 "});
  17170. auto res = cli.Get("/");
  17171. ASSERT_TRUE(res);
  17172. EXPECT_EQ(0, s.proxy_hits());
  17173. EXPECT_EQ(1, s.target_hits());
  17174. }
  17175. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17176. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17177. // go direct and must NOT carry Proxy-Authorization.
  17178. std::atomic<int> proxy_hits{0};
  17179. std::atomic<int> target_hits{0};
  17180. std::atomic<bool> target_saw_authz{false};
  17181. no_proxy_test::ScopedServer proxy_mock, target;
  17182. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17183. proxy_hits++;
  17184. res.status = 302;
  17185. res.set_header("Location", "http://127.0.0.1:" +
  17186. std::to_string(target.port()) + "/landed");
  17187. });
  17188. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17189. target_hits++;
  17190. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17191. res.set_content("direct", "text/plain");
  17192. });
  17193. proxy_mock.listen();
  17194. target.listen();
  17195. Client cli("public.example", target.port());
  17196. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17197. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17198. cli.set_proxy_basic_auth("u", "p");
  17199. cli.set_no_proxy({"127.0.0.1"});
  17200. cli.set_follow_location(true);
  17201. auto res = cli.Get("/redir");
  17202. ASSERT_TRUE(res);
  17203. EXPECT_GE(proxy_hits.load(), 1);
  17204. EXPECT_GE(target_hits.load(), 1);
  17205. EXPECT_FALSE(target_saw_authz.load());
  17206. }
  17207. #ifdef CPPHTTPLIB_SSL_ENABLED
  17208. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17209. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17210. // proxy creds would be sent to the (possibly hostile) origin.
  17211. std::atomic<int> target_hits{0};
  17212. std::atomic<bool> target_saw_proxy_authz{false};
  17213. no_proxy_test::ScopedServer target;
  17214. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17215. target_hits++;
  17216. if (req.has_header("Proxy-Authorization")) {
  17217. target_saw_proxy_authz = true;
  17218. }
  17219. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17220. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17221. "nonce=\"abc\", algorithm=MD5");
  17222. });
  17223. target.listen();
  17224. // The proxy address is set to the target's port: the bypass MUST kick in;
  17225. // if it doesn't, the test still routes "via proxy" to the same server and
  17226. // the Proxy-Authorization assertion below catches the leak.
  17227. Client cli("evil.example", target.port());
  17228. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17229. cli.set_proxy("127.0.0.1", target.port());
  17230. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17231. cli.set_no_proxy({"evil.example"});
  17232. auto res = cli.Get("/x");
  17233. ASSERT_TRUE(res);
  17234. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17235. EXPECT_EQ(1, target_hits.load());
  17236. EXPECT_FALSE(target_saw_proxy_authz.load());
  17237. }
  17238. #endif
  17239. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17240. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17241. std::atomic<int> proxy_hits{0};
  17242. std::atomic<int> bypass_hits{0};
  17243. std::atomic<bool> proxy_saw_c_url{false};
  17244. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17245. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17246. proxy_hits++;
  17247. if (req.path.find("/start") != std::string::npos) {
  17248. res.status = 302;
  17249. res.set_header("Location", "http://127.0.0.1:" +
  17250. std::to_string(bypass_server.port()) +
  17251. "/middle");
  17252. return;
  17253. }
  17254. if (req.path.find("/end") != std::string::npos) {
  17255. proxy_saw_c_url = true;
  17256. res.set_content("c-via-proxy", "text/plain");
  17257. return;
  17258. }
  17259. res.set_content("unexpected", "text/plain");
  17260. });
  17261. // public.example's "advertised" port is arbitrary (the request never lands
  17262. // there — it goes through the proxy), but use a dynamic value to stay
  17263. // friendly with sharded parallel runs.
  17264. int public_port = bypass_server.port();
  17265. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17266. bypass_hits++;
  17267. res.status = 302;
  17268. res.set_header("Location", "http://public.example:" +
  17269. std::to_string(public_port) + "/end");
  17270. });
  17271. proxy_mock.listen();
  17272. bypass_server.listen();
  17273. Client cli("public.example", public_port);
  17274. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17275. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17276. cli.set_no_proxy({"127.0.0.1"});
  17277. cli.set_follow_location(true);
  17278. auto res = cli.Get("/start");
  17279. ASSERT_TRUE(res);
  17280. EXPECT_EQ(StatusCode::OK_200, res->status);
  17281. EXPECT_EQ("c-via-proxy", res->body);
  17282. EXPECT_GE(proxy_hits.load(), 2);
  17283. EXPECT_GE(bypass_hits.load(), 1);
  17284. EXPECT_TRUE(proxy_saw_c_url.load());
  17285. }
  17286. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17287. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17288. // request reconnects to the correct endpoint.
  17289. std::atomic<int> proxy_hits{0};
  17290. std::atomic<int> target_hits{0};
  17291. no_proxy_test::ScopedServer proxy_mock, target;
  17292. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17293. proxy_hits++;
  17294. res.set_content("via-proxy", "text/plain");
  17295. });
  17296. target.svr().Get(".*", [&](const Request &, Response &res) {
  17297. target_hits++;
  17298. res.set_content("direct", "text/plain");
  17299. });
  17300. proxy_mock.listen();
  17301. target.listen();
  17302. Client cli("public.example", target.port());
  17303. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17304. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17305. cli.set_keep_alive(true);
  17306. auto res1 = cli.Get("/a");
  17307. ASSERT_TRUE(res1);
  17308. EXPECT_EQ("via-proxy", res1->body);
  17309. EXPECT_EQ(1, proxy_hits.load());
  17310. EXPECT_EQ(0, target_hits.load());
  17311. cli.set_no_proxy({"public.example"});
  17312. auto res2 = cli.Get("/b");
  17313. ASSERT_TRUE(res2);
  17314. EXPECT_EQ("direct", res2->body);
  17315. EXPECT_EQ(1, proxy_hits.load());
  17316. EXPECT_EQ(1, target_hits.load());
  17317. }
  17318. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17319. namespace proxy_tunnel_test {
  17320. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17321. class ScopedSSLServer {
  17322. public:
  17323. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17324. port_ = svr_.bind_to_any_port("127.0.0.1");
  17325. }
  17326. ~ScopedSSLServer() {
  17327. svr_.stop();
  17328. if (th_.joinable()) { th_.join(); }
  17329. }
  17330. SSLServer &svr() { return svr_; }
  17331. int port() const { return port_; }
  17332. void listen() {
  17333. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17334. svr_.wait_until_ready();
  17335. }
  17336. private:
  17337. SSLServer svr_;
  17338. std::thread th_;
  17339. int port_ = 0;
  17340. };
  17341. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17342. class ScopedConnectProxy {
  17343. public:
  17344. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17345. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17346. if (listen_fd_ < 0) { return; }
  17347. int yes = 1;
  17348. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17349. sockaddr_in a{};
  17350. a.sin_family = AF_INET;
  17351. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17352. a.sin_port = 0;
  17353. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17354. return;
  17355. }
  17356. socklen_t alen = sizeof(a);
  17357. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17358. 0) {
  17359. return;
  17360. }
  17361. port_ = ntohs(a.sin_port);
  17362. if (::listen(listen_fd_, 1) != 0) { return; }
  17363. th_ = std::thread([this] { run(); });
  17364. }
  17365. ~ScopedConnectProxy() {
  17366. stop_ = true;
  17367. if (listen_fd_ >= 0) {
  17368. ::shutdown(listen_fd_, SHUT_RDWR);
  17369. ::close(listen_fd_);
  17370. }
  17371. if (th_.joinable()) { th_.join(); }
  17372. }
  17373. int port() const { return port_; }
  17374. int connect_hits() const { return connect_hits_.load(); }
  17375. private:
  17376. void run() {
  17377. while (!stop_.load()) {
  17378. fd_set rfds;
  17379. FD_ZERO(&rfds);
  17380. FD_SET(listen_fd_, &rfds);
  17381. timeval tv{0, 100 * 1000};
  17382. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17383. if (sel <= 0) { continue; }
  17384. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17385. if (client_fd < 0) { continue; }
  17386. std::string req;
  17387. char buf[2048];
  17388. while (req.find("\r\n\r\n") == std::string::npos) {
  17389. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17390. if (n <= 0) { break; }
  17391. req.append(buf, static_cast<size_t>(n));
  17392. }
  17393. if (req.compare(0, 7, "CONNECT") != 0) {
  17394. ::close(client_fd);
  17395. continue;
  17396. }
  17397. connect_hits_++;
  17398. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17399. ::send(client_fd, ok, std::strlen(ok), 0);
  17400. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17401. sockaddr_in o{};
  17402. o.sin_family = AF_INET;
  17403. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17404. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17405. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17406. 0) {
  17407. ::close(client_fd);
  17408. ::close(origin_fd);
  17409. continue;
  17410. }
  17411. auto forward = [](int from, int to) {
  17412. char b[8192];
  17413. for (;;) {
  17414. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17415. if (n <= 0) { break; }
  17416. ssize_t off = 0;
  17417. while (off < n) {
  17418. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17419. if (s <= 0) {
  17420. off = n;
  17421. break;
  17422. }
  17423. off += s;
  17424. }
  17425. }
  17426. ::shutdown(to, SHUT_WR);
  17427. };
  17428. std::thread t1([&] { forward(client_fd, origin_fd); });
  17429. std::thread t2([&] { forward(origin_fd, client_fd); });
  17430. t1.join();
  17431. t2.join();
  17432. ::close(client_fd);
  17433. ::close(origin_fd);
  17434. }
  17435. }
  17436. int forward_port_ = -1;
  17437. int listen_fd_ = -1;
  17438. int port_ = 0;
  17439. std::thread th_;
  17440. std::atomic<bool> stop_{false};
  17441. std::atomic<int> connect_hits_{0};
  17442. };
  17443. } // namespace proxy_tunnel_test
  17444. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17445. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17446. // retry; otherwise proxy creds would be sent to the origin.
  17447. std::atomic<int> origin_hits{0};
  17448. std::atomic<bool> origin_saw_proxy_authz{false};
  17449. proxy_tunnel_test::ScopedSSLServer origin;
  17450. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17451. origin_hits++;
  17452. if (req.has_header("Proxy-Authorization")) {
  17453. origin_saw_proxy_authz = true;
  17454. }
  17455. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17456. res.set_header("Proxy-Authenticate",
  17457. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17458. "algorithm=MD5");
  17459. });
  17460. origin.listen();
  17461. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17462. ASSERT_NE(0, proxy.port());
  17463. SSLClient cli(HOST, origin.port());
  17464. cli.enable_server_certificate_verification(false);
  17465. cli.set_proxy(HOST, proxy.port());
  17466. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17467. auto res = cli.Get("/x");
  17468. ASSERT_TRUE(res);
  17469. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17470. EXPECT_EQ(1, origin_hits.load());
  17471. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17472. EXPECT_EQ(1, proxy.connect_hits());
  17473. }
  17474. #endif