test.cc 671 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  2183. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2184. cli.set_follow_location(true);
  2185. res = cli.Get("/");
  2186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  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) << "Error: " << to_string(res.error());
  2590. EXPECT_EQ(StatusCode::OK_200, res->status);
  2591. }
  2592. }
  2593. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2594. // `open_stream()` used to skip the path encoding that the buffered send
  2595. // path applies, so the same `path` produced different bytes in the request
  2596. // line depending on which API was used. Assert the two agree.
  2597. Server svr;
  2598. std::string target;
  2599. svr.Get(".*", [&](const Request &req, Response &res) {
  2600. target = req.target;
  2601. res.status = StatusCode::OK_200;
  2602. });
  2603. auto port = svr.bind_to_any_port(HOST);
  2604. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2605. auto se = detail::scope_exit([&] {
  2606. svr.stop();
  2607. thread.join();
  2608. ASSERT_FALSE(svr.is_running());
  2609. });
  2610. svr.wait_until_ready();
  2611. struct {
  2612. const char *path;
  2613. const char *expected;
  2614. } cases[] = {
  2615. {"/a b?x=1", "/a%20b?x=1"},
  2616. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2617. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2618. };
  2619. for (const auto &c : cases) {
  2620. Client cli(HOST, port);
  2621. target.clear();
  2622. auto res = cli.Get(c.path);
  2623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2624. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2625. auto buffered_target = target;
  2626. target.clear();
  2627. auto handle = cli.open_stream("GET", c.path);
  2628. EXPECT_TRUE(handle.is_valid())
  2629. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2630. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2631. }
  2632. }
  2633. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2634. // The `set_path_encode(false)` contract — transmit the supplied target
  2635. // verbatim — must hold for the streaming API too.
  2636. Server svr;
  2637. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2638. std::string target;
  2639. svr.Get("/foo", [&](const Request &req, Response &res) {
  2640. target = req.target;
  2641. res.status = StatusCode::OK_200;
  2642. });
  2643. auto port = svr.bind_to_any_port(HOST);
  2644. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. {
  2652. Client cli(HOST, port);
  2653. cli.set_path_encode(false);
  2654. auto handle = cli.open_stream("GET", expected_target);
  2655. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2656. EXPECT_EQ(expected_target, target);
  2657. }
  2658. }
  2659. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  2660. // With path encoding enabled a CR/LF in the target is percent-encoded
  2661. // rather than rejected, matching the buffered send path. The CR/LF guard in
  2662. // write_request_line still backstops `set_path_encode(false)`, which is
  2663. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  2664. Server svr;
  2665. // Captured before routing: the decoded path contains a newline, which a
  2666. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  2667. std::string target;
  2668. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  2669. target = req.target;
  2670. res.status = StatusCode::OK_200;
  2671. return Server::HandlerResponse::Handled;
  2672. });
  2673. auto port = svr.bind_to_any_port(HOST);
  2674. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2675. auto se = detail::scope_exit([&] {
  2676. svr.stop();
  2677. thread.join();
  2678. ASSERT_FALSE(svr.is_running());
  2679. });
  2680. svr.wait_until_ready();
  2681. {
  2682. Client cli(HOST, port);
  2683. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2684. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2685. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  2686. }
  2687. }
  2688. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  2689. // Nothing may reach the wire: a raw CR/LF target would split the request
  2690. // line and inject headers.
  2691. Server svr;
  2692. // Pre-routing so that "not called" means nothing reached the server at all,
  2693. // rather than merely failing to match a handler pattern.
  2694. auto handler_called = false;
  2695. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  2696. handler_called = true;
  2697. res.status = StatusCode::OK_200;
  2698. return Server::HandlerResponse::Handled;
  2699. });
  2700. auto port = svr.bind_to_any_port(HOST);
  2701. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2702. auto se = detail::scope_exit([&] {
  2703. svr.stop();
  2704. thread.join();
  2705. ASSERT_FALSE(svr.is_running());
  2706. });
  2707. svr.wait_until_ready();
  2708. {
  2709. Client cli(HOST, port);
  2710. cli.set_path_encode(false);
  2711. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2712. EXPECT_FALSE(handle.is_valid());
  2713. EXPECT_EQ(Error::Write, handle.error);
  2714. EXPECT_FALSE(handler_called);
  2715. }
  2716. }
  2717. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  2718. // Which of the two branches runs is decided by whether the query component
  2719. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  2720. // an empty query and must still fall back to building one from
  2721. // `req.params`, while a non-empty query must win over `req.params`.
  2722. Server svr;
  2723. std::string target;
  2724. svr.Get("/foo", [&](const Request &req, Response &res) {
  2725. target = req.target;
  2726. res.status = StatusCode::OK_200;
  2727. });
  2728. auto port = svr.bind_to_any_port(HOST);
  2729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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. // Trailing `?` -> empty query component -> `req.params` is used.
  2738. Client cli(HOST, port);
  2739. Request req;
  2740. req.method = "GET";
  2741. req.path = "/foo?";
  2742. req.params.emplace("a", "1");
  2743. target.clear();
  2744. auto res = cli.send(req);
  2745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2746. EXPECT_EQ("/foo?a=1", target);
  2747. }
  2748. {
  2749. // Non-empty query in `req.path` -> `req.params` is not appended.
  2750. Client cli(HOST, port);
  2751. Request req;
  2752. req.method = "GET";
  2753. req.path = "/foo?b=2";
  2754. req.params.emplace("a", "1");
  2755. target.clear();
  2756. auto res = cli.send(req);
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. EXPECT_EQ("/foo?b=2", target);
  2759. }
  2760. }
  2761. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2762. Server svr;
  2763. svr.Get("/", [](const Request &req, Response &) {
  2764. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2765. });
  2766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2767. auto se = detail::scope_exit([&] {
  2768. svr.stop();
  2769. thread.join();
  2770. ASSERT_FALSE(svr.is_running());
  2771. });
  2772. svr.wait_until_ready();
  2773. {
  2774. Client cli(HOST, PORT);
  2775. cli.set_path_encode(false);
  2776. auto res = cli.Get("/?something=%0A");
  2777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2778. EXPECT_EQ(StatusCode::OK_200, res->status);
  2779. }
  2780. }
  2781. TEST(BindServerTest, BindDualStack) {
  2782. Server svr;
  2783. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2784. res.set_content("Hello World!", "text/plain");
  2785. });
  2786. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. {
  2794. Client cli("127.0.0.1", PORT);
  2795. auto res = cli.Get("/1");
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ(StatusCode::OK_200, res->status);
  2798. EXPECT_EQ("Hello World!", res->body);
  2799. }
  2800. {
  2801. Client cli("::1", PORT);
  2802. auto res = cli.Get("/1");
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ(StatusCode::OK_200, res->status);
  2805. EXPECT_EQ("Hello World!", res->body);
  2806. }
  2807. }
  2808. TEST(BindServerTest, BindAndListenSeparately) {
  2809. Server svr;
  2810. int port = svr.bind_to_any_port("0.0.0.0");
  2811. ASSERT_TRUE(svr.is_valid());
  2812. ASSERT_TRUE(port > 0);
  2813. svr.stop();
  2814. }
  2815. #ifdef CPPHTTPLIB_SSL_ENABLED
  2816. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2818. CLIENT_CA_CERT_DIR);
  2819. int port = svr.bind_to_any_port("0.0.0.0");
  2820. ASSERT_TRUE(svr.is_valid());
  2821. ASSERT_TRUE(port > 0);
  2822. svr.stop();
  2823. }
  2824. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2825. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2826. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2827. int port = svr.bind_to_any_port("0.0.0.0");
  2828. ASSERT_TRUE(svr.is_valid());
  2829. ASSERT_TRUE(port > 0);
  2830. svr.stop();
  2831. }
  2832. TEST(BindServerTest, UpdateCertsPem) {
  2833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2834. int port = svr.bind_to_any_port("0.0.0.0");
  2835. ASSERT_TRUE(svr.is_valid());
  2836. ASSERT_TRUE(port > 0);
  2837. // Read PEM files
  2838. std::string cert_pem, key_pem, ca_pem;
  2839. read_file(SERVER_CERT_FILE, cert_pem);
  2840. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2841. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2842. // Update server certificates using PEM API
  2843. ASSERT_TRUE(
  2844. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2845. ASSERT_TRUE(svr.is_valid());
  2846. svr.stop();
  2847. }
  2848. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2849. // Start server with client CA (enables client auth)
  2850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2851. ASSERT_TRUE(svr.is_valid());
  2852. bool handler_called = false;
  2853. svr.Get("/test", [&](const Request &req, Response &res) {
  2854. handler_called = true;
  2855. // Verify client certificate is present
  2856. auto cert = req.peer_cert();
  2857. EXPECT_TRUE(static_cast<bool>(cert));
  2858. res.set_content("ok", "text/plain");
  2859. });
  2860. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2861. auto se = detail::scope_exit([&] {
  2862. svr.stop();
  2863. t.join();
  2864. ASSERT_FALSE(svr.is_running());
  2865. });
  2866. svr.wait_until_ready();
  2867. // Read PEM files
  2868. std::string cert_pem, key_pem, ca_pem;
  2869. read_file(SERVER_CERT_FILE, cert_pem);
  2870. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2871. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2872. // Update server certificates and client CA using PEM API while server running
  2873. ASSERT_TRUE(
  2874. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2875. // Connect with client certificate
  2876. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2877. cli.enable_server_certificate_verification(false);
  2878. cli.set_connection_timeout(30);
  2879. auto res = cli.Get("/test");
  2880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2881. ASSERT_EQ(StatusCode::OK_200, res->status);
  2882. ASSERT_TRUE(handler_called);
  2883. EXPECT_EQ("ok", res->body);
  2884. }
  2885. #endif
  2886. TEST(ErrorHandlerTest, ContentLength) {
  2887. Server svr;
  2888. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2889. res.status = StatusCode::OK_200;
  2890. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2891. "text/html"); // <= Content-Length still 13
  2892. });
  2893. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2894. res.set_content("Hello World!\n", "text/plain");
  2895. res.status = 524;
  2896. });
  2897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2898. auto se = detail::scope_exit([&] {
  2899. svr.stop();
  2900. thread.join();
  2901. ASSERT_FALSE(svr.is_running());
  2902. });
  2903. svr.wait_until_ready();
  2904. {
  2905. Client cli(HOST, PORT);
  2906. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2910. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2911. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2912. }
  2913. }
  2914. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2915. TEST(ExceptionTest, WithoutExceptionHandler) {
  2916. Server svr;
  2917. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2918. throw std::runtime_error("exception...");
  2919. });
  2920. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2921. throw std::runtime_error("exception\r\n...");
  2922. });
  2923. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2924. auto se = detail::scope_exit([&] {
  2925. svr.stop();
  2926. listen_thread.join();
  2927. ASSERT_FALSE(svr.is_running());
  2928. });
  2929. svr.wait_until_ready();
  2930. Client cli("localhost", PORT);
  2931. {
  2932. auto res = cli.Get("/exception");
  2933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2934. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2935. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2936. }
  2937. {
  2938. auto res = cli.Get("/unknown");
  2939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2940. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2941. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2942. }
  2943. }
  2944. TEST(ExceptionTest, WithExceptionHandler) {
  2945. Server svr;
  2946. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2947. std::exception_ptr ep) {
  2948. EXPECT_FALSE(ep == nullptr);
  2949. try {
  2950. std::rethrow_exception(ep);
  2951. } catch (std::exception &e) {
  2952. EXPECT_EQ("abc", std::string(e.what()));
  2953. } catch (...) {}
  2954. res.status = StatusCode::InternalServerError_500;
  2955. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2956. "text/html"); // <= Content-Length still 13 at this point
  2957. });
  2958. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2959. res.set_content("Hello World!\n", "text/plain");
  2960. throw std::runtime_error("abc");
  2961. });
  2962. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2963. auto se = detail::scope_exit([&] {
  2964. svr.stop();
  2965. thread.join();
  2966. ASSERT_FALSE(svr.is_running());
  2967. });
  2968. svr.wait_until_ready();
  2969. for (size_t i = 0; i < 10; i++) {
  2970. Client cli(HOST, PORT);
  2971. for (size_t j = 0; j < 100; j++) {
  2972. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2974. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2975. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2976. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2977. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2978. }
  2979. cli.set_keep_alive(true);
  2980. for (size_t j = 0; j < 100; j++) {
  2981. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2984. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2985. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2986. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2987. }
  2988. }
  2989. }
  2990. TEST(ExceptionTest, AndErrorHandler) {
  2991. Server svr;
  2992. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2993. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2994. });
  2995. svr.set_exception_handler(
  2996. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2997. EXPECT_FALSE(ep == nullptr);
  2998. try {
  2999. std::rethrow_exception(ep);
  3000. } catch (std::exception &e) {
  3001. res.set_content(e.what(), "text/html");
  3002. } catch (...) {}
  3003. res.status = StatusCode::InternalServerError_500;
  3004. });
  3005. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3006. throw std::runtime_error("EXCEPTION");
  3007. });
  3008. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3009. res.set_content("ERROR", "text/html");
  3010. res.status = StatusCode::InternalServerError_500;
  3011. });
  3012. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3013. auto se = detail::scope_exit([&] {
  3014. svr.stop();
  3015. thread.join();
  3016. ASSERT_FALSE(svr.is_running());
  3017. });
  3018. svr.wait_until_ready();
  3019. Client cli(HOST, PORT);
  3020. {
  3021. auto res = cli.Get("/exception");
  3022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3023. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3024. EXPECT_EQ("EXCEPTION", res->body);
  3025. }
  3026. {
  3027. auto res = cli.Get("/error");
  3028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3029. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3030. EXPECT_EQ("ERROR", res->body);
  3031. }
  3032. {
  3033. auto res = cli.Get("/invalid");
  3034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3035. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3036. EXPECT_EQ("NOT_FOUND", res->body);
  3037. }
  3038. }
  3039. #endif
  3040. TEST(NoContentTest, ContentLength) {
  3041. Server svr;
  3042. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3043. res.status = StatusCode::NoContent_204;
  3044. });
  3045. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3046. auto se = detail::scope_exit([&] {
  3047. svr.stop();
  3048. thread.join();
  3049. ASSERT_FALSE(svr.is_running());
  3050. });
  3051. svr.wait_until_ready();
  3052. {
  3053. Client cli(HOST, PORT);
  3054. auto res = cli.Get("/hi");
  3055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3056. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3057. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3058. }
  3059. }
  3060. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3061. #ifdef CPPHTTPLIB_SSL_ENABLED
  3062. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3063. ASSERT_TRUE(svr.is_valid());
  3064. #else
  3065. Server svr;
  3066. #endif
  3067. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3068. if (req.path == "/routing_handler") {
  3069. res.set_header("PRE_ROUTING", "on");
  3070. res.set_content("Routing Handler", "text/plain");
  3071. return httplib::Server::HandlerResponse::Handled;
  3072. }
  3073. return httplib::Server::HandlerResponse::Unhandled;
  3074. });
  3075. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3076. res.set_content("Error", "text/html");
  3077. });
  3078. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3079. if (req.path == "/routing_handler") {
  3080. res.set_header("POST_ROUTING", "on");
  3081. }
  3082. });
  3083. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3084. res.set_content("Hello World!\n", "text/plain");
  3085. });
  3086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3087. auto se = detail::scope_exit([&] {
  3088. svr.stop();
  3089. thread.join();
  3090. ASSERT_FALSE(svr.is_running());
  3091. });
  3092. svr.wait_until_ready();
  3093. {
  3094. #ifdef CPPHTTPLIB_SSL_ENABLED
  3095. SSLClient cli(HOST, PORT);
  3096. cli.enable_server_certificate_verification(false);
  3097. #else
  3098. Client cli(HOST, PORT);
  3099. #endif
  3100. auto res = cli.Get("/routing_handler");
  3101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3102. EXPECT_EQ(StatusCode::OK_200, res->status);
  3103. EXPECT_EQ("Routing Handler", res->body);
  3104. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3105. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3106. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3107. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3108. }
  3109. {
  3110. #ifdef CPPHTTPLIB_SSL_ENABLED
  3111. SSLClient cli(HOST, PORT);
  3112. cli.enable_server_certificate_verification(false);
  3113. #else
  3114. Client cli(HOST, PORT);
  3115. #endif
  3116. auto res = cli.Get("/hi");
  3117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3118. EXPECT_EQ(StatusCode::OK_200, res->status);
  3119. EXPECT_EQ("Hello World!\n", res->body);
  3120. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3121. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3122. }
  3123. {
  3124. #ifdef CPPHTTPLIB_SSL_ENABLED
  3125. SSLClient cli(HOST, PORT);
  3126. cli.enable_server_certificate_verification(false);
  3127. #else
  3128. Client cli(HOST, PORT);
  3129. #endif
  3130. auto res = cli.Get("/aaa");
  3131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3132. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3133. EXPECT_EQ("Error", res->body);
  3134. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3135. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3136. }
  3137. }
  3138. TEST(RequestHandlerTest, PreRequestHandler) {
  3139. auto route_path = "/user/:user";
  3140. Server svr;
  3141. svr.Get("/hi", [](const Request &, Response &res) {
  3142. res.set_content("hi", "text/plain");
  3143. });
  3144. svr.Get(route_path, [](const Request &req, Response &res) {
  3145. res.set_content(req.path_params.at("user"), "text/plain");
  3146. });
  3147. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3148. if (req.matched_route == route_path) {
  3149. auto user = req.path_params.at("user");
  3150. if (user != "john") {
  3151. res.status = StatusCode::Forbidden_403;
  3152. res.set_content("error", "text/html");
  3153. return Server::HandlerResponse::Handled;
  3154. }
  3155. }
  3156. return Server::HandlerResponse::Unhandled;
  3157. });
  3158. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3159. auto se = detail::scope_exit([&] {
  3160. svr.stop();
  3161. thread.join();
  3162. ASSERT_FALSE(svr.is_running());
  3163. });
  3164. svr.wait_until_ready();
  3165. Client cli(HOST, PORT);
  3166. {
  3167. auto res = cli.Get("/hi");
  3168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. EXPECT_EQ("hi", res->body);
  3171. }
  3172. {
  3173. auto res = cli.Get("/user/john");
  3174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. EXPECT_EQ("john", res->body);
  3177. }
  3178. {
  3179. auto res = cli.Get("/user/invalid-user");
  3180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3181. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3182. EXPECT_EQ("error", res->body);
  3183. }
  3184. }
  3185. // The pre-request handler must run before the request body is read, so a
  3186. // rejected request never forces the server to buffer a (potentially large)
  3187. // body. Here the posted body is larger than the payload limit: if the body
  3188. // were read first the server would answer 413, but because the pre-request
  3189. // handler runs first it answers 403 and the body is never read.
  3190. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3191. Server svr;
  3192. svr.set_payload_max_length(8);
  3193. auto handler_ran = false;
  3194. svr.Post("/reject", [&](const Request &req, Response &res) {
  3195. handler_ran = true;
  3196. res.set_content(req.body, "text/plain");
  3197. });
  3198. svr.Post("/accept", [](const Request &req, Response &res) {
  3199. res.set_content(req.body, "text/plain");
  3200. });
  3201. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3202. if (req.matched_route == "/reject") {
  3203. res.status = StatusCode::Forbidden_403;
  3204. res.set_content("denied", "text/plain");
  3205. return Server::HandlerResponse::Handled;
  3206. }
  3207. return Server::HandlerResponse::Unhandled;
  3208. });
  3209. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3210. auto se = detail::scope_exit([&] {
  3211. svr.stop();
  3212. thread.join();
  3213. ASSERT_FALSE(svr.is_running());
  3214. });
  3215. svr.wait_until_ready();
  3216. Client cli(HOST, PORT);
  3217. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3218. // rejects with 403 before the body is read, so 413 is never reached.
  3219. {
  3220. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3223. EXPECT_EQ("denied", res->body);
  3224. EXPECT_FALSE(handler_ran);
  3225. }
  3226. // An approved route still reads the body and enforces the payload limit.
  3227. {
  3228. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3230. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3231. }
  3232. }
  3233. TEST(UserDataTest, BasicOperations) {
  3234. httplib::UserData ud;
  3235. // Initially empty
  3236. EXPECT_FALSE(ud.has("key"));
  3237. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3238. // set and get
  3239. ud.set("key", 42);
  3240. EXPECT_TRUE(ud.has("key"));
  3241. auto *p = ud.get<int>("key");
  3242. ASSERT_NE(nullptr, p);
  3243. EXPECT_EQ(42, *p);
  3244. // Type mismatch → nullptr
  3245. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3246. // Overwrite with different type
  3247. ud.set("key", std::string("hello"));
  3248. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3249. auto *s = ud.get<std::string>("key");
  3250. ASSERT_NE(nullptr, s);
  3251. EXPECT_EQ("hello", *s);
  3252. // erase
  3253. ud.erase("key");
  3254. EXPECT_FALSE(ud.has("key"));
  3255. // clear
  3256. ud.set("a", 1);
  3257. ud.set("b", 2);
  3258. ud.clear();
  3259. EXPECT_FALSE(ud.has("a"));
  3260. EXPECT_FALSE(ud.has("b"));
  3261. }
  3262. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3263. struct AuthCtx {
  3264. std::string user_id;
  3265. };
  3266. Server svr;
  3267. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3268. res.user_data.set("auth", AuthCtx{"alice"});
  3269. return Server::HandlerResponse::Unhandled;
  3270. });
  3271. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3272. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3273. ASSERT_NE(nullptr, ctx);
  3274. res.set_content("Hello " + ctx->user_id, "text/plain");
  3275. });
  3276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3277. auto se = detail::scope_exit([&] {
  3278. svr.stop();
  3279. thread.join();
  3280. ASSERT_FALSE(svr.is_running());
  3281. });
  3282. svr.wait_until_ready();
  3283. Client cli(HOST, PORT);
  3284. auto res = cli.Get("/me");
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("Hello alice", res->body);
  3288. }
  3289. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3290. struct RoleCtx {
  3291. std::string role;
  3292. };
  3293. Server svr;
  3294. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3295. res.user_data.set("role", RoleCtx{"admin"});
  3296. return Server::HandlerResponse::Unhandled;
  3297. });
  3298. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3299. auto *ctx = res.user_data.get<RoleCtx>("role");
  3300. ASSERT_NE(nullptr, ctx);
  3301. res.set_content(ctx->role, "text/plain");
  3302. });
  3303. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3304. auto se = detail::scope_exit([&] {
  3305. svr.stop();
  3306. thread.join();
  3307. ASSERT_FALSE(svr.is_running());
  3308. });
  3309. svr.wait_until_ready();
  3310. Client cli(HOST, PORT);
  3311. auto res = cli.Get("/role");
  3312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3313. EXPECT_EQ(StatusCode::OK_200, res->status);
  3314. EXPECT_EQ("admin", res->body);
  3315. }
  3316. TEST(InvalidFormatTest, StatusCode) {
  3317. Server svr;
  3318. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3319. res.set_content("Hello World!\n", "text/plain");
  3320. res.status = 9999; // Status should be a three-digit code...
  3321. });
  3322. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3323. auto se = detail::scope_exit([&] {
  3324. svr.stop();
  3325. thread.join();
  3326. ASSERT_FALSE(svr.is_running());
  3327. });
  3328. svr.wait_until_ready();
  3329. {
  3330. Client cli(HOST, PORT);
  3331. auto res = cli.Get("/hi");
  3332. ASSERT_FALSE(res);
  3333. }
  3334. }
  3335. TEST(URLFragmentTest, WithFragment) {
  3336. Server svr;
  3337. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3338. EXPECT_TRUE(req.target == "/hi");
  3339. });
  3340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. {
  3348. Client cli(HOST, PORT);
  3349. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3350. EXPECT_TRUE(res);
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. res = cli.Get("/hi%23key1=val1=key2=val2");
  3353. EXPECT_TRUE(res);
  3354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3355. }
  3356. }
  3357. TEST(HeaderWriter, SetHeaderWriter) {
  3358. Server svr;
  3359. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3360. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3361. return detail::write_headers(strm, hdrs);
  3362. });
  3363. svr.Get("/hi", [](const Request &req, Response &res) {
  3364. auto it = req.headers.find("CustomClientHeader");
  3365. EXPECT_TRUE(it != req.headers.end());
  3366. EXPECT_EQ(it->second, "CustomClientValue");
  3367. res.set_content("Hello World!\n", "text/plain");
  3368. });
  3369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3370. auto se = detail::scope_exit([&] {
  3371. svr.stop();
  3372. thread.join();
  3373. ASSERT_FALSE(svr.is_running());
  3374. });
  3375. svr.wait_until_ready();
  3376. {
  3377. Client cli(HOST, PORT);
  3378. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3379. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3380. return detail::write_headers(strm, hdrs);
  3381. });
  3382. auto res = cli.Get("/hi");
  3383. EXPECT_TRUE(res);
  3384. EXPECT_EQ(StatusCode::OK_200, res->status);
  3385. auto it = res->headers.find("CustomServerHeader");
  3386. EXPECT_TRUE(it != res->headers.end());
  3387. EXPECT_EQ(it->second, "CustomServerValue");
  3388. }
  3389. }
  3390. class ServerTest : public ::testing::Test {
  3391. protected:
  3392. ServerTest()
  3393. : cli_(HOST, PORT)
  3394. #ifdef CPPHTTPLIB_SSL_ENABLED
  3395. ,
  3396. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3397. #endif
  3398. {
  3399. #ifdef CPPHTTPLIB_SSL_ENABLED
  3400. cli_.enable_server_certificate_verification(false);
  3401. #endif
  3402. // Allow LARGE_DATA (100MB) responses
  3403. cli_.set_payload_max_length(200 * 1024 * 1024);
  3404. }
  3405. virtual void SetUp() {
  3406. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3407. svr_.set_payload_max_length(200 * 1024 * 1024);
  3408. svr_.set_mount_point("/", "./www");
  3409. svr_.set_mount_point("/mount", "./www2");
  3410. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3411. svr_.Get("/hi",
  3412. [&](const Request & /*req*/, Response &res) {
  3413. res.set_content("Hello World!", "text/plain");
  3414. })
  3415. .Get("/file_content",
  3416. [&](const Request & /*req*/, Response &res) {
  3417. res.set_file_content("./www/dir/test.html");
  3418. })
  3419. .Get("/file_content_with_content_type",
  3420. [&](const Request & /*req*/, Response &res) {
  3421. res.set_file_content("./www/file", "text/plain");
  3422. })
  3423. .Get("/invalid_file_content",
  3424. [&](const Request & /*req*/, Response &res) {
  3425. res.set_file_content("./www/dir/invalid_file_path");
  3426. })
  3427. .Get("/http_response_splitting",
  3428. [&](const Request & /*req*/, Response &res) {
  3429. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3430. EXPECT_EQ(0U, res.headers.size());
  3431. EXPECT_FALSE(res.has_header("a"));
  3432. res.set_header("a", "1\nSet-Cookie: a=1");
  3433. EXPECT_EQ(0U, res.headers.size());
  3434. EXPECT_FALSE(res.has_header("a"));
  3435. res.set_header("a", "1\rSet-Cookie: a=1");
  3436. EXPECT_EQ(0U, res.headers.size());
  3437. EXPECT_FALSE(res.has_header("a"));
  3438. res.set_header("a\r\nb", "0");
  3439. EXPECT_EQ(0U, res.headers.size());
  3440. EXPECT_FALSE(res.has_header("a"));
  3441. res.set_header("a\rb", "0");
  3442. EXPECT_EQ(0U, res.headers.size());
  3443. EXPECT_FALSE(res.has_header("a"));
  3444. res.set_header("a\nb", "0");
  3445. EXPECT_EQ(0U, res.headers.size());
  3446. EXPECT_FALSE(res.has_header("a"));
  3447. res.set_redirect("1\r\nSet-Cookie: a=1");
  3448. EXPECT_EQ(0U, res.headers.size());
  3449. EXPECT_FALSE(res.has_header("Location"));
  3450. })
  3451. .Get("/slow",
  3452. [&](const Request & /*req*/, Response &res) {
  3453. std::this_thread::sleep_for(std::chrono::seconds(4));
  3454. res.set_content("slow", "text/plain");
  3455. })
  3456. #if 0
  3457. .Post("/slowpost",
  3458. [&](const Request & /*req*/, Response &res) {
  3459. std::this_thread::sleep_for(std::chrono::seconds(2));
  3460. res.set_content("slow", "text/plain");
  3461. })
  3462. #endif
  3463. .Get("/remote_addr",
  3464. [&](const Request &req, Response &res) {
  3465. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3466. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3467. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3468. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3469. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3470. #endif
  3471. res.set_content(req.remote_addr, "text/plain");
  3472. })
  3473. .Get("/local_addr",
  3474. [&](const Request &req, Response &res) {
  3475. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3476. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3477. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3478. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3479. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3480. #endif
  3481. auto local_addr = req.local_addr;
  3482. auto local_port = std::to_string(req.local_port);
  3483. res.set_content(local_addr.append(":").append(local_port),
  3484. "text/plain");
  3485. })
  3486. .Get("/endwith%",
  3487. [&](const Request & /*req*/, Response &res) {
  3488. res.set_content("Hello World!", "text/plain");
  3489. })
  3490. .Get("/a\\+\\+b",
  3491. [&](const Request &req, Response &res) {
  3492. ASSERT_TRUE(req.has_param("a +b"));
  3493. auto val = req.get_param_value("a +b");
  3494. res.set_content(val, "text/plain");
  3495. })
  3496. .Get("/", [&](const Request & /*req*/,
  3497. Response &res) { res.set_redirect("/hi"); })
  3498. .Post("/1",
  3499. [](const Request & /*req*/, Response &res) {
  3500. res.set_redirect("/2", StatusCode::SeeOther_303);
  3501. })
  3502. .Get("/2",
  3503. [](const Request & /*req*/, Response &res) {
  3504. res.set_content("redirected.", "text/plain");
  3505. res.status = StatusCode::OK_200;
  3506. })
  3507. .Post("/person",
  3508. [&](const Request &req, Response &res) {
  3509. if (req.has_param("name") && req.has_param("note")) {
  3510. persons_[req.get_param_value("name")] =
  3511. req.get_param_value("note");
  3512. } else {
  3513. res.status = StatusCode::BadRequest_400;
  3514. }
  3515. })
  3516. .Put("/person",
  3517. [&](const Request &req, Response &res) {
  3518. if (req.has_param("name") && req.has_param("note")) {
  3519. persons_[req.get_param_value("name")] =
  3520. req.get_param_value("note");
  3521. } else {
  3522. res.status = StatusCode::BadRequest_400;
  3523. }
  3524. })
  3525. .Get("/person/(.*)",
  3526. [&](const Request &req, Response &res) {
  3527. string name = req.matches[1];
  3528. if (persons_.find(name) != persons_.end()) {
  3529. auto note = persons_[name];
  3530. res.set_content(note, "text/plain");
  3531. } else {
  3532. res.status = StatusCode::NotFound_404;
  3533. }
  3534. })
  3535. .Delete("/person",
  3536. [&](const Request &req, Response &res) {
  3537. if (req.has_param("name")) {
  3538. string name = req.get_param_value("name");
  3539. if (persons_.find(name) != persons_.end()) {
  3540. persons_.erase(name);
  3541. res.set_content("DELETED", "text/plain");
  3542. } else {
  3543. res.status = StatusCode::NotFound_404;
  3544. }
  3545. } else {
  3546. res.status = StatusCode::BadRequest_400;
  3547. }
  3548. })
  3549. .Post("/x-www-form-urlencoded-json",
  3550. [&](const Request &req, Response &res) {
  3551. auto json = req.get_param_value("json");
  3552. ASSERT_EQ(JSON_DATA, json);
  3553. res.set_content(json, "appliation/json");
  3554. res.status = StatusCode::OK_200;
  3555. })
  3556. .Get("/streamed-chunked",
  3557. [&](const Request & /*req*/, Response &res) {
  3558. res.set_chunked_content_provider(
  3559. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3560. sink.os << "123";
  3561. sink.os << "456";
  3562. sink.os << "789";
  3563. sink.done();
  3564. return true;
  3565. });
  3566. })
  3567. .Get("/streamed-chunked-with-prohibited-trailer",
  3568. [&](const Request & /*req*/, Response &res) {
  3569. auto i = new int(0);
  3570. // Declare both a prohibited trailer (Content-Length) and an
  3571. // allowed one
  3572. res.set_header("Trailer", "Content-Length, X-Allowed");
  3573. res.set_chunked_content_provider(
  3574. "text/plain",
  3575. [i](size_t /*offset*/, DataSink &sink) {
  3576. switch (*i) {
  3577. case 0: sink.os << "123"; break;
  3578. case 1: sink.os << "456"; break;
  3579. case 2: sink.os << "789"; break;
  3580. case 3: {
  3581. sink.done_with_trailer(
  3582. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3583. } break;
  3584. }
  3585. (*i)++;
  3586. return true;
  3587. },
  3588. [i](bool success) {
  3589. EXPECT_TRUE(success);
  3590. delete i;
  3591. });
  3592. })
  3593. .Get("/streamed-chunked2",
  3594. [&](const Request & /*req*/, Response &res) {
  3595. auto i = new int(0);
  3596. res.set_chunked_content_provider(
  3597. "text/plain",
  3598. [i](size_t /*offset*/, DataSink &sink) {
  3599. switch (*i) {
  3600. case 0: sink.os << "123"; break;
  3601. case 1: sink.os << "456"; break;
  3602. case 2: sink.os << "789"; break;
  3603. case 3: sink.done(); break;
  3604. }
  3605. (*i)++;
  3606. return true;
  3607. },
  3608. [i](bool success) {
  3609. EXPECT_TRUE(success);
  3610. delete i;
  3611. });
  3612. })
  3613. .Get("/streamed-chunked-with-trailer",
  3614. [&](const Request & /*req*/, Response &res) {
  3615. auto i = new int(0);
  3616. res.set_header("Trailer", "Dummy1, Dummy2");
  3617. res.set_chunked_content_provider(
  3618. "text/plain",
  3619. [i](size_t /*offset*/, DataSink &sink) {
  3620. switch (*i) {
  3621. case 0: sink.os << "123"; break;
  3622. case 1: sink.os << "456"; break;
  3623. case 2: sink.os << "789"; break;
  3624. case 3: {
  3625. sink.done_with_trailer(
  3626. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3627. } break;
  3628. }
  3629. (*i)++;
  3630. return true;
  3631. },
  3632. [i](bool success) {
  3633. EXPECT_TRUE(success);
  3634. delete i;
  3635. });
  3636. })
  3637. .Get("/streamed",
  3638. [&](const Request & /*req*/, Response &res) {
  3639. res.set_content_provider(
  3640. 6, "text/plain",
  3641. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3642. sink.os << (offset < 3 ? "a" : "b");
  3643. return true;
  3644. });
  3645. })
  3646. .Get("/streamed-without-length",
  3647. [&](const Request & /*req*/, Response &res) {
  3648. auto data = new std::string("abcdefg");
  3649. res.set_content_provider(
  3650. "text/plain",
  3651. [data](size_t offset, DataSink &sink) {
  3652. if (offset < data->size()) {
  3653. sink.os << data->substr(offset);
  3654. }
  3655. sink.done();
  3656. return true;
  3657. },
  3658. [data](bool success) {
  3659. EXPECT_TRUE(success);
  3660. delete data;
  3661. });
  3662. })
  3663. .Get("/streamed-with-range",
  3664. [&](const Request &req, Response &res) {
  3665. auto data = new std::string("abcdefg");
  3666. res.set_content_provider(
  3667. data->size(), "text/plain",
  3668. [data](size_t offset, size_t length, DataSink &sink) {
  3669. size_t DATA_CHUNK_SIZE = 4;
  3670. const auto &d = *data;
  3671. auto out_len =
  3672. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3673. auto ret =
  3674. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3675. EXPECT_TRUE(ret);
  3676. return true;
  3677. },
  3678. [data, &req](bool success) {
  3679. EXPECT_EQ(success, !req.has_param("error"));
  3680. delete data;
  3681. });
  3682. })
  3683. .Get("/streamed-cancel",
  3684. [&](const Request & /*req*/, Response &res) {
  3685. res.set_content_provider(
  3686. size_t(-1), "text/plain",
  3687. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3688. sink.os << "data_chunk";
  3689. return true;
  3690. });
  3691. })
  3692. .Get("/regex-with-delimiter",
  3693. [&](const Request &req, Response & /*res*/) {
  3694. ASSERT_TRUE(req.has_param("key"));
  3695. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3696. })
  3697. .Get("/with-range",
  3698. [&](const Request & /*req*/, Response &res) {
  3699. res.set_content("abcdefg", "text/plain");
  3700. })
  3701. .Get("/test-start-time",
  3702. [&](const Request &req, Response & /*res*/) {
  3703. EXPECT_NE(req.start_time_,
  3704. std::chrono::steady_clock::time_point::min());
  3705. })
  3706. .Get("/with-range-customized-response",
  3707. [&](const Request & /*req*/, Response &res) {
  3708. res.status = StatusCode::BadRequest_400;
  3709. res.set_content(JSON_DATA, "application/json");
  3710. })
  3711. .Post("/chunked",
  3712. [&](const Request &req, Response & /*res*/) {
  3713. EXPECT_EQ(req.body, "dechunked post body");
  3714. })
  3715. .Post("/large-chunked",
  3716. [&](const Request &req, Response & /*res*/) {
  3717. std::string expected(6 * 30 * 1024u, 'a');
  3718. EXPECT_EQ(req.body, expected);
  3719. })
  3720. .Post("/multipart",
  3721. [&](const Request &req, Response & /*res*/) {
  3722. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3723. req.form.get_field_count("text2") +
  3724. req.form.get_field_count("file3") +
  3725. req.form.get_field_count("file4"));
  3726. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3727. req.form.get_file_count("file2"));
  3728. ASSERT_TRUE(!req.form.has_file("???"));
  3729. ASSERT_TRUE(!req.form.has_field("???"));
  3730. ASSERT_TRUE(req.body.empty());
  3731. {
  3732. const auto &text = req.form.get_field("text1");
  3733. EXPECT_EQ("text default", text);
  3734. }
  3735. {
  3736. const auto &text = req.form.get_field("text2");
  3737. EXPECT_EQ("aωb", text);
  3738. }
  3739. {
  3740. const auto &file = req.form.get_file("file1");
  3741. EXPECT_EQ("hello.txt", file.filename);
  3742. EXPECT_EQ("text/plain", file.content_type);
  3743. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3744. }
  3745. {
  3746. const auto &file = req.form.get_file("file2");
  3747. EXPECT_EQ("world.json", file.filename);
  3748. EXPECT_EQ("application/json", file.content_type);
  3749. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3750. }
  3751. {
  3752. const auto &text = req.form.get_field("file3");
  3753. EXPECT_EQ(0u, text.size());
  3754. }
  3755. {
  3756. const auto &text = req.form.get_field("file4");
  3757. EXPECT_EQ(0u, text.size());
  3758. }
  3759. })
  3760. .Post("/multipart/multi_file_values",
  3761. [&](const Request &req, Response & /*res*/) {
  3762. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3763. req.form.get_field_count("multi_text1"));
  3764. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3765. ASSERT_TRUE(!req.form.has_file("???"));
  3766. ASSERT_TRUE(!req.form.has_field("???"));
  3767. ASSERT_TRUE(req.body.empty());
  3768. {
  3769. const auto &text = req.form.get_field("text");
  3770. EXPECT_EQ("default text", text);
  3771. }
  3772. {
  3773. const auto &text1_values = req.form.get_fields("multi_text1");
  3774. EXPECT_EQ(2u, text1_values.size());
  3775. EXPECT_EQ("aaaaa", text1_values[0]);
  3776. EXPECT_EQ("bbbbb", text1_values[1]);
  3777. }
  3778. {
  3779. const auto &file1_values = req.form.get_files("multi_file1");
  3780. EXPECT_EQ(2u, file1_values.size());
  3781. auto file1 = file1_values[0];
  3782. EXPECT_EQ(file1.filename, "hello.txt");
  3783. EXPECT_EQ(file1.content_type, "text/plain");
  3784. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3785. auto file2 = file1_values[1];
  3786. EXPECT_EQ(file2.filename, "world.json");
  3787. EXPECT_EQ(file2.content_type, "application/json");
  3788. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3789. }
  3790. })
  3791. .Post("/empty",
  3792. [&](const Request &req, Response &res) {
  3793. EXPECT_EQ(req.body, "");
  3794. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3795. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3796. res.set_content("empty", "text/plain");
  3797. })
  3798. .Post("/empty-no-content-type",
  3799. [&](const Request &req, Response &res) {
  3800. EXPECT_EQ(req.body, "");
  3801. EXPECT_FALSE(req.has_header("Content-Type"));
  3802. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3803. res.set_content("empty-no-content-type", "text/plain");
  3804. })
  3805. .Post("/path-only",
  3806. [&](const Request &req, Response &res) {
  3807. EXPECT_EQ(req.body, "");
  3808. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3809. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3810. res.set_content("path-only", "text/plain");
  3811. })
  3812. .Post("/path-headers-only",
  3813. [&](const Request &req, Response &res) {
  3814. EXPECT_EQ(req.body, "");
  3815. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3816. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3817. EXPECT_EQ("world", req.get_header_value("hello"));
  3818. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3819. res.set_content("path-headers-only", "text/plain");
  3820. })
  3821. .Post("/post-large",
  3822. [&](const Request &req, Response &res) {
  3823. EXPECT_EQ(req.body, LARGE_DATA);
  3824. res.set_content(req.body, "text/plain");
  3825. })
  3826. .Post("/post-loopback",
  3827. [&](const Request &, Response &res,
  3828. ContentReader const &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. res.set_content(body, "text/plain");
  3835. })
  3836. .Put("/put-loopback",
  3837. [&](const Request &, Response &res,
  3838. ContentReader const &content_reader) {
  3839. std::string body;
  3840. content_reader([&](const char *data, size_t data_length) {
  3841. body.append(data, data_length);
  3842. return true;
  3843. });
  3844. res.set_content(body, "text/plain");
  3845. })
  3846. .Patch("/patch-loopback",
  3847. [&](const Request &, Response &res,
  3848. ContentReader const &content_reader) {
  3849. std::string body;
  3850. content_reader([&](const char *data, size_t data_length) {
  3851. body.append(data, data_length);
  3852. return true;
  3853. });
  3854. res.set_content(body, "text/plain");
  3855. })
  3856. .Put("/empty-no-content-type",
  3857. [&](const Request &req, Response &res) {
  3858. EXPECT_EQ(req.body, "");
  3859. EXPECT_FALSE(req.has_header("Content-Type"));
  3860. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3861. res.set_content("empty-no-content-type", "text/plain");
  3862. })
  3863. .Put("/put",
  3864. [&](const Request &req, Response &res) {
  3865. EXPECT_EQ(req.body, "PUT");
  3866. res.set_content(req.body, "text/plain");
  3867. })
  3868. .Put("/put-large",
  3869. [&](const Request &req, Response &res) {
  3870. EXPECT_EQ(req.body, LARGE_DATA);
  3871. res.set_content(req.body, "text/plain");
  3872. })
  3873. .Patch("/patch",
  3874. [&](const Request &req, Response &res) {
  3875. EXPECT_EQ(req.body, "PATCH");
  3876. res.set_content(req.body, "text/plain");
  3877. })
  3878. .Delete("/delete",
  3879. [&](const Request & /*req*/, Response &res) {
  3880. res.set_content("DELETE", "text/plain");
  3881. })
  3882. .Delete("/delete-body",
  3883. [&](const Request &req, Response &res) {
  3884. EXPECT_EQ(req.body, "content");
  3885. res.set_content(req.body, "text/plain");
  3886. })
  3887. .Options(R"(\*)",
  3888. [&](const Request & /*req*/, Response &res) {
  3889. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3890. })
  3891. .Get("/request-target",
  3892. [&](const Request &req, Response & /*res*/) {
  3893. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3894. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3895. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3896. })
  3897. .Get("/long-query-value",
  3898. [&](const Request &req, Response & /*res*/) {
  3899. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3900. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3901. })
  3902. .Get("/too-long-query-value",
  3903. [&](const Request &req, Response & /*res*/) {
  3904. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3905. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3906. })
  3907. .Get("/array-param",
  3908. [&](const Request &req, Response & /*res*/) {
  3909. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3910. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3911. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3912. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3913. })
  3914. .Get("/array-param-values",
  3915. [&](const Request &req, Response & /*res*/) {
  3916. auto values = req.get_param_values("array");
  3917. EXPECT_EQ(3u, values.size());
  3918. EXPECT_EQ("value1", values[0]);
  3919. EXPECT_EQ("value2", values[1]);
  3920. EXPECT_EQ("value3", values[2]);
  3921. auto empty = req.get_param_values("nonexistent");
  3922. EXPECT_TRUE(empty.empty());
  3923. })
  3924. .Post("/validate-no-multiple-headers",
  3925. [&](const Request &req, Response & /*res*/) {
  3926. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3927. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3928. })
  3929. .Post("/content_receiver",
  3930. [&](const Request &req, Response &res,
  3931. const ContentReader &content_reader) {
  3932. if (req.is_multipart_form_data()) {
  3933. std::vector<FormData> items;
  3934. content_reader(
  3935. [&](const FormData &file) {
  3936. items.push_back(file);
  3937. return true;
  3938. },
  3939. [&](const char *data, size_t data_length) {
  3940. items.back().content.append(data, data_length);
  3941. return true;
  3942. });
  3943. EXPECT_EQ(5u, items.size());
  3944. {
  3945. const auto &file = get_file_value(items, "text1");
  3946. EXPECT_TRUE(file.filename.empty());
  3947. EXPECT_EQ("text default", file.content);
  3948. }
  3949. {
  3950. const auto &file = get_file_value(items, "text2");
  3951. EXPECT_TRUE(file.filename.empty());
  3952. EXPECT_EQ("aωb", file.content);
  3953. }
  3954. {
  3955. const auto &file = get_file_value(items, "file1");
  3956. EXPECT_EQ("hello.txt", file.filename);
  3957. EXPECT_EQ("text/plain", file.content_type);
  3958. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3959. }
  3960. {
  3961. const auto &file = get_file_value(items, "file2");
  3962. EXPECT_EQ("world.json", file.filename);
  3963. EXPECT_EQ("application/json", file.content_type);
  3964. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3965. }
  3966. {
  3967. const auto &file = get_file_value(items, "file3");
  3968. EXPECT_TRUE(file.filename.empty());
  3969. EXPECT_EQ("application/octet-stream", file.content_type);
  3970. EXPECT_EQ(0u, file.content.size());
  3971. }
  3972. } else {
  3973. std::string body;
  3974. content_reader([&](const char *data, size_t data_length) {
  3975. EXPECT_EQ(7U, data_length);
  3976. body.append(data, data_length);
  3977. return true;
  3978. });
  3979. EXPECT_EQ(body, "content");
  3980. res.set_content(body, "text/plain");
  3981. }
  3982. })
  3983. .Put("/content_receiver",
  3984. [&](const Request & /*req*/, Response &res,
  3985. const ContentReader &content_reader) {
  3986. std::string body;
  3987. content_reader([&](const char *data, size_t data_length) {
  3988. body.append(data, data_length);
  3989. return true;
  3990. });
  3991. EXPECT_EQ(body, "content");
  3992. res.set_content(body, "text/plain");
  3993. })
  3994. .Patch("/content_receiver",
  3995. [&](const Request & /*req*/, Response &res,
  3996. const ContentReader &content_reader) {
  3997. std::string body;
  3998. content_reader([&](const char *data, size_t data_length) {
  3999. body.append(data, data_length);
  4000. return true;
  4001. });
  4002. EXPECT_EQ(body, "content");
  4003. res.set_content(body, "text/plain");
  4004. })
  4005. .Post("/query-string-and-body",
  4006. [&](const Request &req, Response & /*res*/) {
  4007. ASSERT_TRUE(req.has_param("key"));
  4008. EXPECT_EQ(req.get_param_value("key"), "value");
  4009. EXPECT_EQ(req.body, "content");
  4010. })
  4011. .Get("/last-request",
  4012. [&](const Request &req, Response & /*res*/) {
  4013. EXPECT_EQ("close", req.get_header_value("Connection"));
  4014. })
  4015. .Get(R"(/redirect/(\d+))",
  4016. [&](const Request &req, Response &res) {
  4017. auto num = std::stoi(req.matches[1]) + 1;
  4018. std::string url = "/redirect/" + std::to_string(num);
  4019. res.set_redirect(url);
  4020. })
  4021. .Post("/binary",
  4022. [&](const Request &req, Response &res) {
  4023. EXPECT_EQ(4U, req.body.size());
  4024. EXPECT_EQ("application/octet-stream",
  4025. req.get_header_value("Content-Type"));
  4026. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4027. res.set_content(req.body, "application/octet-stream");
  4028. })
  4029. .Put("/binary",
  4030. [&](const Request &req, Response &res) {
  4031. EXPECT_EQ(4U, req.body.size());
  4032. EXPECT_EQ("application/octet-stream",
  4033. req.get_header_value("Content-Type"));
  4034. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4035. res.set_content(req.body, "application/octet-stream");
  4036. })
  4037. .Patch("/binary",
  4038. [&](const Request &req, Response &res) {
  4039. EXPECT_EQ(4U, req.body.size());
  4040. EXPECT_EQ("application/octet-stream",
  4041. req.get_header_value("Content-Type"));
  4042. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4043. res.set_content(req.body, "application/octet-stream");
  4044. })
  4045. .Delete("/binary",
  4046. [&](const Request &req, Response &res) {
  4047. EXPECT_EQ(4U, req.body.size());
  4048. EXPECT_EQ("application/octet-stream",
  4049. req.get_header_value("Content-Type"));
  4050. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4051. res.set_content(req.body, "application/octet-stream");
  4052. })
  4053. .Get("/issue1772",
  4054. [&](const Request & /*req*/, Response &res) {
  4055. res.status = 401;
  4056. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4057. })
  4058. .Delete("/issue609",
  4059. [](const httplib::Request &, httplib::Response &res,
  4060. const httplib::ContentReader &) {
  4061. res.set_content("ok", "text/plain");
  4062. })
  4063. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4064. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4065. .Get("/compress",
  4066. [&](const Request & /*req*/, Response &res) {
  4067. res.set_content(
  4068. "12345678901234567890123456789012345678901234567890123456789"
  4069. "01234567890123456789012345678901234567890",
  4070. "text/plain");
  4071. })
  4072. .Get("/compress-with-charset",
  4073. [&](const Request & /*req*/, Response &res) {
  4074. res.set_content(
  4075. "12345678901234567890123456789012345678901234567890123456789"
  4076. "01234567890123456789012345678901234567890",
  4077. "application/json; charset=utf-8");
  4078. })
  4079. .Get("/nocompress",
  4080. [&](const Request & /*req*/, Response &res) {
  4081. res.set_content(
  4082. "12345678901234567890123456789012345678901234567890123456789"
  4083. "01234567890123456789012345678901234567890",
  4084. "application/octet-stream");
  4085. })
  4086. .Post("/compress-multipart",
  4087. [&](const Request &req, Response & /*res*/) {
  4088. EXPECT_EQ(2u, req.form.fields.size());
  4089. ASSERT_TRUE(!req.form.has_field("???"));
  4090. {
  4091. const auto &text = req.form.get_field("key1");
  4092. EXPECT_EQ("test", text);
  4093. }
  4094. {
  4095. const auto &text = req.form.get_field("key2");
  4096. EXPECT_EQ("--abcdefg123", text);
  4097. }
  4098. })
  4099. #endif
  4100. ;
  4101. persons_["john"] = "programmer";
  4102. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4103. svr_.wait_until_ready();
  4104. }
  4105. virtual void TearDown() {
  4106. svr_.stop();
  4107. if (!request_threads_.empty()) {
  4108. std::this_thread::sleep_for(std::chrono::seconds(1));
  4109. for (auto &t : request_threads_) {
  4110. t.join();
  4111. }
  4112. }
  4113. t_.join();
  4114. }
  4115. map<string, string> persons_;
  4116. #ifdef CPPHTTPLIB_SSL_ENABLED
  4117. SSLClient cli_;
  4118. SSLServer svr_;
  4119. #else
  4120. Client cli_;
  4121. Server svr_;
  4122. #endif
  4123. thread t_;
  4124. std::vector<thread> request_threads_;
  4125. };
  4126. TEST_F(ServerTest, GetMethod200) {
  4127. auto res = cli_.Get("/hi");
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ("HTTP/1.1", res->version);
  4130. EXPECT_EQ(StatusCode::OK_200, res->status);
  4131. EXPECT_EQ("OK", res->reason);
  4132. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4133. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4134. EXPECT_EQ("Hello World!", res->body);
  4135. }
  4136. TEST_F(ServerTest, GetEmptyFile) {
  4137. auto res = cli_.Get("/empty_file");
  4138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4139. EXPECT_EQ(StatusCode::OK_200, res->status);
  4140. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4141. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4142. EXPECT_EQ("", res->body);
  4143. }
  4144. TEST_F(ServerTest, GetFileContent) {
  4145. auto res = cli_.Get("/file_content");
  4146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4147. EXPECT_EQ(StatusCode::OK_200, res->status);
  4148. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4149. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4150. EXPECT_EQ("test.html", res->body);
  4151. }
  4152. TEST_F(ServerTest, GetFileContentWithRange) {
  4153. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4157. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4158. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4159. EXPECT_EQ("est", res->body);
  4160. }
  4161. TEST_F(ServerTest, GetFileContentWithContentType) {
  4162. auto res = cli_.Get("/file_content_with_content_type");
  4163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4164. EXPECT_EQ(StatusCode::OK_200, res->status);
  4165. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4166. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4167. EXPECT_EQ("file\n", res->body);
  4168. }
  4169. TEST_F(ServerTest, GetInvalidFileContent) {
  4170. auto res = cli_.Get("/invalid_file_content");
  4171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4173. }
  4174. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4175. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4177. EXPECT_EQ("HTTP/1.1", res->version);
  4178. EXPECT_EQ(StatusCode::OK_200, res->status);
  4179. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4180. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4181. EXPECT_EQ("Hello World!", res->body);
  4182. }
  4183. TEST_F(ServerTest, GetMethod302) {
  4184. auto res = cli_.Get("/");
  4185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4186. EXPECT_EQ(StatusCode::Found_302, res->status);
  4187. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4188. }
  4189. TEST_F(ServerTest, GetMethod302Redirect) {
  4190. cli_.set_follow_location(true);
  4191. auto res = cli_.Get("/");
  4192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4193. EXPECT_EQ(StatusCode::OK_200, res->status);
  4194. EXPECT_EQ("Hello World!", res->body);
  4195. EXPECT_EQ("/hi", res->location);
  4196. }
  4197. TEST_F(ServerTest, GetMethod404) {
  4198. auto res = cli_.Get("/invalid");
  4199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4201. }
  4202. TEST_F(ServerTest, HeadMethod200) {
  4203. auto res = cli_.Head("/hi");
  4204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4205. EXPECT_EQ(StatusCode::OK_200, res->status);
  4206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4207. EXPECT_TRUE(res->body.empty());
  4208. }
  4209. TEST_F(ServerTest, HeadMethod200Static) {
  4210. auto res = cli_.Head("/mount/dir/index.html");
  4211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4212. EXPECT_EQ(StatusCode::OK_200, res->status);
  4213. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4214. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4215. EXPECT_TRUE(res->body.empty());
  4216. }
  4217. TEST_F(ServerTest, HeadMethod404) {
  4218. auto res = cli_.Head("/invalid");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4221. EXPECT_TRUE(res->body.empty());
  4222. }
  4223. TEST_F(ServerTest, GetMethodPersonJohn) {
  4224. auto res = cli_.Get("/person/john");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::OK_200, res->status);
  4227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4228. EXPECT_EQ("programmer", res->body);
  4229. }
  4230. TEST_F(ServerTest, PostMethod1) {
  4231. auto res = cli_.Get("/person/john1");
  4232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4233. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4234. res = cli_.Post("/person", "name=john1&note=coder",
  4235. "application/x-www-form-urlencoded");
  4236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4237. ASSERT_EQ(StatusCode::OK_200, res->status);
  4238. res = cli_.Get("/person/john1");
  4239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4240. ASSERT_EQ(StatusCode::OK_200, res->status);
  4241. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4242. ASSERT_EQ("coder", res->body);
  4243. }
  4244. TEST_F(ServerTest, PostMethod2) {
  4245. auto res = cli_.Get("/person/john2");
  4246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4247. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4248. Params params;
  4249. params.emplace("name", "john2");
  4250. params.emplace("note", "coder");
  4251. res = cli_.Post("/person", params);
  4252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4253. ASSERT_EQ(StatusCode::OK_200, res->status);
  4254. res = cli_.Get("/person/john2");
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. ASSERT_EQ(StatusCode::OK_200, res->status);
  4257. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4258. ASSERT_EQ("coder", res->body);
  4259. }
  4260. TEST_F(ServerTest, PutMethod3) {
  4261. auto res = cli_.Get("/person/john3");
  4262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4263. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4264. Params params;
  4265. params.emplace("name", "john3");
  4266. params.emplace("note", "coder");
  4267. res = cli_.Put("/person", params);
  4268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4269. ASSERT_EQ(StatusCode::OK_200, res->status);
  4270. res = cli_.Get("/person/john3");
  4271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4272. ASSERT_EQ(StatusCode::OK_200, res->status);
  4273. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4274. ASSERT_EQ("coder", res->body);
  4275. }
  4276. TEST_F(ServerTest, DeleteMethod1) {
  4277. auto res = cli_.Get("/person/john4");
  4278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4279. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4280. Params params;
  4281. params.emplace("name", "john4");
  4282. params.emplace("note", "coder");
  4283. res = cli_.Post("/person", params);
  4284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4285. ASSERT_EQ(StatusCode::OK_200, res->status);
  4286. res = cli_.Get("/person/john4");
  4287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4288. ASSERT_EQ(StatusCode::OK_200, res->status);
  4289. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4290. ASSERT_EQ("coder", res->body);
  4291. Params delete_params;
  4292. delete_params.emplace("name", "john4");
  4293. res = cli_.Delete("/person", delete_params);
  4294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4295. ASSERT_EQ(StatusCode::OK_200, res->status);
  4296. ASSERT_EQ("DELETED", res->body);
  4297. res = cli_.Get("/person/john4");
  4298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4299. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4300. }
  4301. TEST_F(ServerTest, DeleteMethod2) {
  4302. auto res = cli_.Get("/person/john5");
  4303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4304. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4305. Params params;
  4306. params.emplace("name", "john5");
  4307. params.emplace("note", "developer");
  4308. res = cli_.Post("/person", params);
  4309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4310. ASSERT_EQ(StatusCode::OK_200, res->status);
  4311. res = cli_.Get("/person/john5");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. ASSERT_EQ(StatusCode::OK_200, res->status);
  4314. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4315. ASSERT_EQ("developer", res->body);
  4316. Params delete_params;
  4317. delete_params.emplace("name", "john5");
  4318. Headers headers;
  4319. headers.emplace("Custom-Header", "test-value");
  4320. res = cli_.Delete("/person", headers, delete_params);
  4321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4322. ASSERT_EQ(StatusCode::OK_200, res->status);
  4323. ASSERT_EQ("DELETED", res->body);
  4324. res = cli_.Get("/person/john5");
  4325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4326. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4327. }
  4328. TEST_F(ServerTest, DeleteMethod3) {
  4329. auto res = cli_.Get("/person/john6");
  4330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4331. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4332. Params params;
  4333. params.emplace("name", "john6");
  4334. params.emplace("note", "tester");
  4335. res = cli_.Post("/person", params);
  4336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4337. ASSERT_EQ(StatusCode::OK_200, res->status);
  4338. res = cli_.Get("/person/john6");
  4339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4340. ASSERT_EQ(StatusCode::OK_200, res->status);
  4341. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4342. ASSERT_EQ("tester", res->body);
  4343. Params delete_params;
  4344. delete_params.emplace("name", "john6");
  4345. Headers headers;
  4346. headers.emplace("Custom-Header", "test-value");
  4347. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4349. ASSERT_EQ(StatusCode::OK_200, res->status);
  4350. ASSERT_EQ("DELETED", res->body);
  4351. res = cli_.Get("/person/john6");
  4352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4353. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4354. }
  4355. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4356. Params params;
  4357. params.emplace("json", JSON_DATA);
  4358. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. ASSERT_EQ(StatusCode::OK_200, res->status);
  4361. ASSERT_EQ(JSON_DATA, res->body);
  4362. }
  4363. TEST_F(ServerTest, PostEmptyContent) {
  4364. auto res = cli_.Post("/empty", "", "text/plain");
  4365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4366. ASSERT_EQ(StatusCode::OK_200, res->status);
  4367. ASSERT_EQ("empty", res->body);
  4368. }
  4369. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4370. auto res = cli_.Post("/empty-no-content-type");
  4371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4372. ASSERT_EQ(StatusCode::OK_200, res->status);
  4373. ASSERT_EQ("empty-no-content-type", res->body);
  4374. }
  4375. TEST_F(ServerTest, PostPathOnly) {
  4376. auto res = cli_.Post("/path-only");
  4377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4378. ASSERT_EQ(StatusCode::OK_200, res->status);
  4379. ASSERT_EQ("path-only", res->body);
  4380. }
  4381. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4382. auto res = cli_.Post("/path-headers-only",
  4383. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4385. ASSERT_EQ(StatusCode::OK_200, res->status);
  4386. ASSERT_EQ("path-headers-only", res->body);
  4387. }
  4388. TEST_F(ServerTest, PostLarge) {
  4389. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4391. ASSERT_EQ(StatusCode::OK_200, res->status);
  4392. EXPECT_EQ(LARGE_DATA, res->body);
  4393. }
  4394. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4395. auto res = cli_.Put("/empty-no-content-type");
  4396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4397. ASSERT_EQ(StatusCode::OK_200, res->status);
  4398. ASSERT_EQ("empty-no-content-type", res->body);
  4399. }
  4400. TEST_F(ServerTest, GetMethodDir) {
  4401. auto res = cli_.Get("/dir/");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::OK_200, res->status);
  4404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4405. auto body = R"(<html>
  4406. <head>
  4407. </head>
  4408. <body>
  4409. <a href="/dir/test.html">Test</a>
  4410. <a href="/hi">hi</a>
  4411. </body>
  4412. </html>
  4413. )";
  4414. EXPECT_EQ(body, res->body);
  4415. }
  4416. TEST_F(ServerTest, GetMethodDirTest) {
  4417. auto res = cli_.Get("/dir/test.html");
  4418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4419. EXPECT_EQ(StatusCode::OK_200, res->status);
  4420. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4421. EXPECT_EQ("test.html", res->body);
  4422. }
  4423. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4424. auto res = cli_.Get("/dir/../dir/test.html");
  4425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4426. EXPECT_EQ(StatusCode::OK_200, res->status);
  4427. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4428. EXPECT_EQ("test.html", res->body);
  4429. }
  4430. TEST_F(ServerTest, GetMethodInvalidPath) {
  4431. auto res = cli_.Get("/dir/../test.html");
  4432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4433. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4434. }
  4435. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4436. auto res = cli_.Get("/../www/dir/test.html");
  4437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4438. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4439. }
  4440. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4441. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4443. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4444. }
  4445. TEST_F(ServerTest, GetMethodDirMountTest) {
  4446. auto res = cli_.Get("/mount/dir/test.html");
  4447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4448. EXPECT_EQ(StatusCode::OK_200, res->status);
  4449. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4450. EXPECT_EQ("test.html", res->body);
  4451. }
  4452. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4453. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4455. EXPECT_EQ(StatusCode::OK_200, res->status);
  4456. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4457. EXPECT_EQ("test.html", res->body);
  4458. }
  4459. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4460. auto res = cli_.Get("/mount/dir/../test.html");
  4461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4463. }
  4464. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4465. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4467. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4468. }
  4469. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4470. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4472. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4473. }
  4474. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4475. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4477. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4478. }
  4479. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4480. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4483. }
  4484. TEST_F(ServerTest, PostMethod303) {
  4485. auto res = cli_.Post("/1", "body", "text/plain");
  4486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4487. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4488. EXPECT_EQ("/2", res->get_header_value("Location"));
  4489. }
  4490. TEST_F(ServerTest, PostMethod303Redirect) {
  4491. cli_.set_follow_location(true);
  4492. auto res = cli_.Post("/1", "body", "text/plain");
  4493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4494. EXPECT_EQ(StatusCode::OK_200, res->status);
  4495. EXPECT_EQ("redirected.", res->body);
  4496. EXPECT_EQ("/2", res->location);
  4497. }
  4498. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4499. auto res = cli_.Get("/dir/test.abcde");
  4500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4501. EXPECT_EQ(StatusCode::OK_200, res->status);
  4502. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4503. EXPECT_EQ("abcde", res->body);
  4504. }
  4505. TEST_F(ServerTest, StaticFileRange) {
  4506. auto res =
  4507. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4509. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4510. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4511. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4512. EXPECT_EQ(true, res->has_header("Content-Range"));
  4513. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4514. EXPECT_EQ(std::string("cd"), res->body);
  4515. }
  4516. TEST_F(ServerTest, StaticFileRanges) {
  4517. auto res = cli_.Get("/dir/test.abcde",
  4518. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4520. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4521. EXPECT_TRUE(
  4522. res->get_header_value("Content-Type")
  4523. .find(
  4524. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4525. 0);
  4526. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4527. }
  4528. TEST_F(ServerTest, StaticFileRangeHead) {
  4529. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4532. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4533. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4534. EXPECT_EQ(true, res->has_header("Content-Range"));
  4535. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4536. }
  4537. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4538. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4540. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4542. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4543. EXPECT_EQ(true, res->has_header("Content-Range"));
  4544. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4545. res->get_header_value("Content-Range"));
  4546. EXPECT_EQ("LAST\n", res->body);
  4547. }
  4548. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4549. auto res =
  4550. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4552. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4554. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4555. EXPECT_EQ(true, res->has_header("Content-Range"));
  4556. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4557. }
  4558. TEST_F(ServerTest, StaticFileBigFile) {
  4559. auto res = cli_.Get("/dir/1MB.txt");
  4560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4563. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4564. }
  4565. TEST_F(ServerTest, InvalidBaseDirMount) {
  4566. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4567. }
  4568. TEST_F(ServerTest, Binary) {
  4569. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4570. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4571. "application/octet-stream");
  4572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4573. ASSERT_EQ(StatusCode::OK_200, res->status);
  4574. ASSERT_EQ(4U, res->body.size());
  4575. res = cli_.Put("/binary", binary.data(), binary.size(),
  4576. "application/octet-stream");
  4577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4578. ASSERT_EQ(StatusCode::OK_200, res->status);
  4579. ASSERT_EQ(4U, res->body.size());
  4580. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4581. "application/octet-stream");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. ASSERT_EQ(StatusCode::OK_200, res->status);
  4584. ASSERT_EQ(4U, res->body.size());
  4585. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4586. "application/octet-stream");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. ASSERT_EQ(StatusCode::OK_200, res->status);
  4589. ASSERT_EQ(4U, res->body.size());
  4590. }
  4591. TEST_F(ServerTest, BinaryString) {
  4592. auto binary = std::string("\x00\x01\x02\x03", 4);
  4593. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4595. ASSERT_EQ(StatusCode::OK_200, res->status);
  4596. ASSERT_EQ(4U, res->body.size());
  4597. res = cli_.Put("/binary", binary, "application/octet-stream");
  4598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4599. ASSERT_EQ(StatusCode::OK_200, res->status);
  4600. ASSERT_EQ(4U, res->body.size());
  4601. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4603. ASSERT_EQ(StatusCode::OK_200, res->status);
  4604. ASSERT_EQ(4U, res->body.size());
  4605. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. ASSERT_EQ(StatusCode::OK_200, res->status);
  4608. ASSERT_EQ(4U, res->body.size());
  4609. }
  4610. TEST_F(ServerTest, EmptyRequest) {
  4611. auto res = cli_.Get("");
  4612. ASSERT_TRUE(!res);
  4613. EXPECT_EQ(Error::Connection, res.error());
  4614. }
  4615. TEST_F(ServerTest, LongRequest) {
  4616. std::string request;
  4617. for (size_t i = 0; i < 545; i++) {
  4618. request += "/TooLongRequest";
  4619. }
  4620. request += "OK";
  4621. auto res = cli_.Get(request.c_str());
  4622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4624. }
  4625. TEST_F(ServerTest, TooLongRequest) {
  4626. std::string request;
  4627. for (size_t i = 0; i < 546; i++) {
  4628. request += "/TooLongRequest";
  4629. }
  4630. request += "_NG";
  4631. auto start = std::chrono::high_resolution_clock::now();
  4632. cli_.set_keep_alive(true);
  4633. auto res = cli_.Get(request.c_str());
  4634. auto end = std::chrono::high_resolution_clock::now();
  4635. auto elapsed =
  4636. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4637. .count();
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4640. EXPECT_LE(elapsed, 1000);
  4641. EXPECT_EQ("close", res->get_header_value("Connection"));
  4642. EXPECT_FALSE(cli_.is_socket_open());
  4643. }
  4644. TEST_F(ServerTest, AlmostTooLongRequest) {
  4645. // test for #2046 - URI length check shouldn't include other content on req
  4646. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4647. // leading /, space, HTTP/1.1)
  4648. std::string request =
  4649. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4650. auto res = cli_.Get(request.c_str());
  4651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4653. }
  4654. TEST_F(ServerTest, LongHeader) {
  4655. Request req;
  4656. req.method = "GET";
  4657. req.path = "/hi";
  4658. std::string host_and_port;
  4659. host_and_port += HOST;
  4660. host_and_port += ":";
  4661. host_and_port += std::to_string(PORT);
  4662. req.headers.emplace("Host", host_and_port.c_str());
  4663. req.headers.emplace("Accept", "*/*");
  4664. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4665. req.headers.emplace(
  4666. "Header-Name",
  4667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4695. "@@@@@@@@@@@@@@@@");
  4696. auto res = std::make_shared<Response>();
  4697. auto error = Error::Success;
  4698. auto ret = cli_.send(req, *res, error);
  4699. ASSERT_TRUE(ret);
  4700. EXPECT_EQ(StatusCode::OK_200, res->status);
  4701. }
  4702. TEST_F(ServerTest, LongQueryValue) {
  4703. auto start = std::chrono::high_resolution_clock::now();
  4704. cli_.set_keep_alive(true);
  4705. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4706. auto end = std::chrono::high_resolution_clock::now();
  4707. auto elapsed =
  4708. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4709. .count();
  4710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4711. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4712. EXPECT_LE(elapsed, 1000);
  4713. EXPECT_EQ("close", res->get_header_value("Connection"));
  4714. EXPECT_FALSE(cli_.is_socket_open());
  4715. }
  4716. TEST_F(ServerTest, TooLongQueryValue) {
  4717. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4718. ASSERT_FALSE(res);
  4719. EXPECT_EQ(Error::Read, res.error());
  4720. }
  4721. TEST_F(ServerTest, TooLongHeader) {
  4722. Request req;
  4723. req.method = "GET";
  4724. req.path = "/hi";
  4725. std::string host_and_port;
  4726. host_and_port += HOST;
  4727. host_and_port += ":";
  4728. host_and_port += std::to_string(PORT);
  4729. req.headers.emplace("Host", host_and_port.c_str());
  4730. req.headers.emplace("Accept", "*/*");
  4731. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4732. req.headers.emplace(
  4733. "Header-Name",
  4734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4762. "@@@@@@@@@@@@@@@@@");
  4763. auto res = std::make_shared<Response>();
  4764. auto error = Error::Success;
  4765. auto ret = cli_.send(req, *res, error);
  4766. ASSERT_TRUE(ret);
  4767. EXPECT_EQ(StatusCode::OK_200, res->status);
  4768. }
  4769. TEST_F(ServerTest, HeaderCountAtLimit) {
  4770. // Test with headers just under the 100 limit
  4771. httplib::Headers headers;
  4772. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4773. // This should keep us just under the 100 header limit
  4774. for (int i = 0; i < 95; i++) {
  4775. std::string name = "X-Test-Header-" + std::to_string(i);
  4776. std::string value = "value" + std::to_string(i);
  4777. headers.emplace(name, value);
  4778. }
  4779. // This should work fine as we're under the limit
  4780. auto res = cli_.Get("/hi", headers);
  4781. EXPECT_TRUE(res);
  4782. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4783. }
  4784. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4785. // Test with many headers to exceed the 100 limit
  4786. httplib::Headers headers;
  4787. // Add 150 headers to definitely exceed the 100 limit
  4788. for (int i = 0; i < 150; i++) {
  4789. std::string name = "X-Test-Header-" + std::to_string(i);
  4790. std::string value = "value" + std::to_string(i);
  4791. headers.emplace(name, value);
  4792. }
  4793. // This should fail due to exceeding header count limit
  4794. cli_.set_keep_alive(true);
  4795. auto res = cli_.Get("/hi", headers);
  4796. // The server should respond with 400 Bad Request
  4797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4798. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4799. EXPECT_EQ("close", res->get_header_value("Connection"));
  4800. EXPECT_FALSE(cli_.is_socket_open());
  4801. }
  4802. TEST_F(ServerTest, PercentEncoding) {
  4803. auto res = cli_.Get("/e%6edwith%");
  4804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. }
  4807. TEST_F(ServerTest, PercentEncodingUnicode) {
  4808. auto res = cli_.Get("/e%u006edwith%");
  4809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4810. EXPECT_EQ(StatusCode::OK_200, res->status);
  4811. }
  4812. TEST_F(ServerTest, InvalidPercentEncoding) {
  4813. auto res = cli_.Get("/%endwith%");
  4814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4815. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4816. }
  4817. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4818. auto res = cli_.Get("/%uendwith%");
  4819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4821. }
  4822. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4823. auto res = cli_.Get("/hello?aaa=bbb%");
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4826. }
  4827. TEST_F(ServerTest, PlusSignEncoding) {
  4828. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4830. EXPECT_EQ(StatusCode::OK_200, res->status);
  4831. EXPECT_EQ("a +b", res->body);
  4832. }
  4833. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4834. // This test simulates a potential DoS attack using many headers
  4835. // to verify our security fix prevents memory exhaustion
  4836. httplib::Headers attack_headers;
  4837. // Attempt to add many headers like an attacker would (200 headers to far
  4838. // exceed limit)
  4839. for (int i = 0; i < 200; i++) {
  4840. std::string name = "X-Attack-Header-" + std::to_string(i);
  4841. std::string value = "attack_payload_" + std::to_string(i);
  4842. attack_headers.emplace(name, value);
  4843. }
  4844. // Try to POST with excessive headers
  4845. cli_.set_keep_alive(true);
  4846. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4847. // Should either fail or return 400 Bad Request due to security limit
  4848. if (res) {
  4849. // If we get a response, it should be 400 Bad Request
  4850. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4851. EXPECT_EQ("close", res->get_header_value("Connection"));
  4852. }
  4853. EXPECT_FALSE(cli_.is_socket_open());
  4854. }
  4855. TEST_F(ServerTest, MultipartFormData) {
  4856. UploadFormDataItems items = {
  4857. {"text1", "text default", "", ""},
  4858. {"text2", "aωb", "", ""},
  4859. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4860. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4861. {"file3", "", "", "application/octet-stream"},
  4862. {"file4", "", "", " application/json tmp-string "}};
  4863. auto res = cli_.Post("/multipart", items);
  4864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4865. EXPECT_EQ(StatusCode::OK_200, res->status);
  4866. }
  4867. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4868. UploadFormDataItems items = {
  4869. {"text", "default text", "", ""},
  4870. {"multi_text1", "aaaaa", "", ""},
  4871. {"multi_text1", "bbbbb", "", ""},
  4872. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4873. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4874. "application/json"},
  4875. };
  4876. auto res = cli_.Post("/multipart/multi_file_values", items);
  4877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4878. EXPECT_EQ(StatusCode::OK_200, res->status);
  4879. }
  4880. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4881. auto res = cli_.Get("/hi");
  4882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4883. EXPECT_EQ(StatusCode::OK_200, res->status);
  4884. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4885. EXPECT_EQ("Hello World!", res->body);
  4886. }
  4887. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4888. Request req;
  4889. req.method = "POST";
  4890. req.path = "/chunked";
  4891. std::string host_and_port;
  4892. host_and_port += HOST;
  4893. host_and_port += ":";
  4894. host_and_port += std::to_string(PORT);
  4895. req.headers.emplace("Host", host_and_port.c_str());
  4896. req.headers.emplace("Accept", "*/*");
  4897. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4898. req.headers.emplace("Content-Type", "text/plain");
  4899. req.headers.emplace("Content-Length", "0");
  4900. req.headers.emplace(
  4901. "Transfer-Encoding",
  4902. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4903. // Client does not chunk, so make a chunked body manually.
  4904. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4905. auto res = std::make_shared<Response>();
  4906. auto error = Error::Success;
  4907. auto ret = cli_.send(req, *res, error);
  4908. ASSERT_TRUE(ret);
  4909. EXPECT_EQ(StatusCode::OK_200, res->status);
  4910. }
  4911. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4912. // rather than treat them as valid lengths.
  4913. template <typename ClientT>
  4914. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4915. Request req;
  4916. req.method = "POST";
  4917. req.path = "/chunked";
  4918. std::string host_and_port;
  4919. host_and_port += HOST;
  4920. host_and_port += ":";
  4921. host_and_port += std::to_string(PORT);
  4922. req.headers.emplace("Host", host_and_port.c_str());
  4923. req.headers.emplace("Content-Length", "0");
  4924. req.headers.emplace("Transfer-Encoding", "chunked");
  4925. req.body = body;
  4926. auto res = std::make_shared<Response>();
  4927. auto error = Error::Success;
  4928. ASSERT_TRUE(cli.send(req, *res, error));
  4929. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4930. }
  4931. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4932. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4933. }
  4934. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4935. expect_chunked_body_rejected(
  4936. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4937. }
  4938. TEST_F(ServerTest, GetStreamed2) {
  4939. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4941. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4942. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4943. EXPECT_EQ(true, res->has_header("Content-Range"));
  4944. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4945. EXPECT_EQ(std::string("ab"), res->body);
  4946. }
  4947. TEST_F(ServerTest, GetStreamed) {
  4948. auto res = cli_.Get("/streamed");
  4949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4952. EXPECT_EQ(std::string("aaabbb"), res->body);
  4953. }
  4954. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4955. auto res = cli_.Get("/streamed-without-length",
  4956. Headers{make_range_header({{0, -1}})});
  4957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4958. EXPECT_EQ(StatusCode::OK_200, res->status);
  4959. EXPECT_EQ(false, res->has_header("Content-Length"));
  4960. EXPECT_EQ(false, res->has_header("Content-Range"));
  4961. EXPECT_EQ(std::string("abcdefg"), res->body);
  4962. }
  4963. TEST_F(ServerTest, GetStreamedWithRange1) {
  4964. auto res =
  4965. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4967. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4968. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4969. EXPECT_EQ(true, res->has_header("Content-Range"));
  4970. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4971. EXPECT_EQ(std::string("def"), res->body);
  4972. }
  4973. TEST_F(ServerTest, GetStreamedWithRange2) {
  4974. auto res =
  4975. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4978. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4979. EXPECT_EQ(true, res->has_header("Content-Range"));
  4980. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4981. EXPECT_EQ(std::string("bcdefg"), res->body);
  4982. }
  4983. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4984. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4987. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4988. EXPECT_EQ(true, res->has_header("Content-Range"));
  4989. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4990. EXPECT_EQ(std::string("efg"), res->body);
  4991. }
  4992. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4993. auto res =
  4994. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4997. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4998. EXPECT_EQ(false, res->has_header("Content-Range"));
  4999. EXPECT_EQ(0U, res->body.size());
  5000. }
  5001. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5002. auto res =
  5003. cli_.Get("/streamed-with-range",
  5004. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5005. "92233720368547758079223372036854775807"}});
  5006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5007. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5008. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5009. EXPECT_EQ(false, res->has_header("Content-Range"));
  5010. EXPECT_EQ(0U, res->body.size());
  5011. }
  5012. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5013. auto res = cli_.Get(
  5014. "/with-range",
  5015. Headers{{"Range",
  5016. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5017. {"Accept-Encoding", ""}});
  5018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5020. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5021. EXPECT_EQ(true, res->has_header("Content-Range"));
  5022. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5023. EXPECT_EQ(std::string("abcdefg"), res->body);
  5024. }
  5025. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5026. auto res = cli_.Get("/with-range", Headers{
  5027. {"Range", "bytes=0-"},
  5028. {"Accept-Encoding", ""},
  5029. });
  5030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5031. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5032. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5033. EXPECT_EQ(true, res->has_header("Content-Range"));
  5034. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5035. EXPECT_EQ(std::string("abcdefg"), res->body);
  5036. }
  5037. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5038. auto res = cli_.Get("/streamed-with-range",
  5039. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5042. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5043. EXPECT_EQ(false, res->has_header("Content-Range"));
  5044. EXPECT_EQ(267U, res->body.size());
  5045. // Check that both range contents are present
  5046. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5047. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5048. // Check that Content-Range headers are present for both ranges
  5049. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5050. std::string::npos);
  5051. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5052. std::string::npos);
  5053. }
  5054. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5055. Ranges ranges;
  5056. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5057. ranges.emplace_back(0, -1);
  5058. }
  5059. auto res = cli_.Get("/streamed-with-range?error",
  5060. Headers{{make_range_header(ranges)}});
  5061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5062. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5063. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5064. EXPECT_EQ(false, res->has_header("Content-Range"));
  5065. EXPECT_EQ(0U, res->body.size());
  5066. }
  5067. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5068. auto res = cli_.Get("/streamed-with-range",
  5069. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5071. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5072. EXPECT_EQ(5U, res->body.size());
  5073. // Check that overlapping ranges are coalesced into a single range
  5074. EXPECT_EQ("bcdef", res->body);
  5075. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5076. // Should be single range, not multipart
  5077. EXPECT_TRUE(res->has_header("Content-Range"));
  5078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5079. }
  5080. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5081. auto res = cli_.Get("/streamed-with-range",
  5082. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5084. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5085. EXPECT_EQ(268U, res->body.size());
  5086. // Check that both range contents are present
  5087. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5088. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5089. // Check that Content-Range headers are present for both ranges
  5090. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5091. std::string::npos);
  5092. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5093. std::string::npos);
  5094. }
  5095. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5096. auto res = cli_.Get("/streamed-with-range",
  5097. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5099. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5100. EXPECT_EQ(269U, res->body.size());
  5101. // Check that both duplicate range contents are present
  5102. size_t first_abc = res->body.find("abc\r\n");
  5103. EXPECT_TRUE(first_abc != std::string::npos);
  5104. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5105. EXPECT_TRUE(second_abc != std::string::npos);
  5106. // Check that Content-Range headers are present for both ranges
  5107. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5108. EXPECT_TRUE(first_range != std::string::npos);
  5109. size_t second_range =
  5110. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5111. EXPECT_TRUE(second_range != std::string::npos);
  5112. }
  5113. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5114. auto res =
  5115. cli_.Get("/streamed-with-range?error",
  5116. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5118. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5119. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5120. EXPECT_EQ(false, res->has_header("Content-Range"));
  5121. EXPECT_EQ(0U, res->body.size());
  5122. }
  5123. TEST_F(ServerTest, GetStreamedEndless) {
  5124. uint64_t offset = 0;
  5125. auto res = cli_.Get("/streamed-cancel",
  5126. [&](const char * /*data*/, uint64_t data_length) {
  5127. if (offset < 100) {
  5128. offset += data_length;
  5129. return true;
  5130. }
  5131. return false;
  5132. });
  5133. ASSERT_TRUE(!res);
  5134. EXPECT_EQ(Error::Canceled, res.error());
  5135. }
  5136. TEST_F(ServerTest, ClientStop) {
  5137. std::atomic_size_t count{4};
  5138. std::vector<std::thread> threads;
  5139. for (auto i = count.load(); i != 0; --i) {
  5140. threads.emplace_back([&]() {
  5141. auto res = cli_.Get("/streamed-cancel",
  5142. [&](const char *, uint64_t) { return true; });
  5143. --count;
  5144. ASSERT_TRUE(!res);
  5145. EXPECT_TRUE(res.error() == Error::Canceled ||
  5146. res.error() == Error::Read || res.error() == Error::Write);
  5147. });
  5148. }
  5149. std::this_thread::sleep_for(std::chrono::seconds(2));
  5150. while (count != 0) {
  5151. cli_.stop();
  5152. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5153. }
  5154. for (auto &t : threads) {
  5155. t.join();
  5156. }
  5157. }
  5158. TEST_F(ServerTest, GetWithRange1) {
  5159. auto res = cli_.Get("/with-range", Headers{
  5160. make_range_header({{3, 5}}),
  5161. {"Accept-Encoding", ""},
  5162. });
  5163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5165. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5166. EXPECT_EQ(true, res->has_header("Content-Range"));
  5167. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5168. EXPECT_EQ(std::string("def"), res->body);
  5169. }
  5170. TEST_F(ServerTest, GetWithRange2) {
  5171. auto res = cli_.Get("/with-range", Headers{
  5172. make_range_header({{1, -1}}),
  5173. {"Accept-Encoding", ""},
  5174. });
  5175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5177. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5178. EXPECT_EQ(true, res->has_header("Content-Range"));
  5179. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5180. EXPECT_EQ(std::string("bcdefg"), res->body);
  5181. }
  5182. TEST_F(ServerTest, GetWithRange3) {
  5183. auto res = cli_.Get("/with-range", Headers{
  5184. make_range_header({{0, 0}}),
  5185. {"Accept-Encoding", ""},
  5186. });
  5187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5189. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5190. EXPECT_EQ(true, res->has_header("Content-Range"));
  5191. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5192. EXPECT_EQ(std::string("a"), res->body);
  5193. }
  5194. TEST_F(ServerTest, GetWithRange4) {
  5195. auto res = cli_.Get("/with-range", Headers{
  5196. make_range_header({{-1, 2}}),
  5197. {"Accept-Encoding", ""},
  5198. });
  5199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5200. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5201. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5202. EXPECT_EQ(true, res->has_header("Content-Range"));
  5203. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5204. EXPECT_EQ(std::string("fg"), res->body);
  5205. }
  5206. TEST_F(ServerTest, GetWithRange5) {
  5207. auto res = cli_.Get("/with-range", Headers{
  5208. make_range_header({{0, 5}}),
  5209. {"Accept-Encoding", ""},
  5210. });
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5213. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5214. EXPECT_EQ(true, res->has_header("Content-Range"));
  5215. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5216. EXPECT_EQ(std::string("abcdef"), res->body);
  5217. }
  5218. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5219. auto res =
  5220. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5222. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5223. }
  5224. TEST_F(ServerTest, GetWithRangeMultipart) {
  5225. auto res =
  5226. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5229. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5230. EXPECT_EQ(false, res->has_header("Content-Range"));
  5231. EXPECT_EQ(267U, res->body.size());
  5232. }
  5233. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5234. auto res = cli_.Get("/with-range",
  5235. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5237. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5238. }
  5239. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5240. auto res = cli_.Get("/with-range-customized-response",
  5241. Headers{{make_range_header({{1, 2}})}});
  5242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5243. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5244. EXPECT_EQ(true, res->has_header("Content-Length"));
  5245. EXPECT_EQ(false, res->has_header("Content-Range"));
  5246. EXPECT_EQ(JSON_DATA, res->body);
  5247. }
  5248. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5249. auto res = cli_.Get("/with-range-customized-response",
  5250. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5253. EXPECT_EQ(true, res->has_header("Content-Length"));
  5254. EXPECT_EQ(false, res->has_header("Content-Range"));
  5255. EXPECT_EQ(JSON_DATA, res->body);
  5256. }
  5257. TEST_F(ServerTest, Issue1772) {
  5258. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5260. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5261. }
  5262. TEST_F(ServerTest, Issue609) {
  5263. auto res = cli_.Delete("/issue609");
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. EXPECT_EQ(std::string("ok"), res->body);
  5267. }
  5268. TEST_F(ServerTest, GetStreamedChunked) {
  5269. auto res = cli_.Get("/streamed-chunked");
  5270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ(std::string("123456789"), res->body);
  5273. }
  5274. TEST_F(ServerTest, GetStreamedChunked2) {
  5275. auto res = cli_.Get("/streamed-chunked2");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::OK_200, res->status);
  5278. EXPECT_EQ(std::string("123456789"), res->body);
  5279. }
  5280. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5281. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5283. EXPECT_EQ(StatusCode::OK_200, res->status);
  5284. EXPECT_EQ(std::string("123456789"), res->body);
  5285. EXPECT_TRUE(res->has_header("Trailer"));
  5286. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5287. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5288. // Trailers are now stored separately from headers (security fix)
  5289. EXPECT_EQ(2U, res->trailers.size());
  5290. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5291. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5292. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5293. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5294. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5295. // Verify trailers are NOT in headers (security verification)
  5296. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5297. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5298. }
  5299. TEST_F(ServerTest, LargeChunkedPost) {
  5300. Request req;
  5301. req.method = "POST";
  5302. req.path = "/large-chunked";
  5303. std::string host_and_port;
  5304. host_and_port += HOST;
  5305. host_and_port += ":";
  5306. host_and_port += std::to_string(PORT);
  5307. req.headers.emplace("Host", host_and_port.c_str());
  5308. req.headers.emplace("Accept", "*/*");
  5309. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5310. req.headers.emplace("Content-Type", "text/plain");
  5311. req.headers.emplace("Content-Length", "0");
  5312. req.headers.emplace("Transfer-Encoding", "chunked");
  5313. std::string long_string(30 * 1024u, 'a');
  5314. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5315. // Attempt to make a large enough post to exceed OS buffers, to test that
  5316. // the server handles short reads if the full chunk data isn't available.
  5317. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5318. auto res = std::make_shared<Response>();
  5319. auto error = Error::Success;
  5320. auto ret = cli_.send(req, *res, error);
  5321. ASSERT_TRUE(ret);
  5322. EXPECT_EQ(StatusCode::OK_200, res->status);
  5323. }
  5324. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5325. auto res = cli_.Get("/remote_addr");
  5326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5327. EXPECT_EQ(StatusCode::OK_200, res->status);
  5328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5329. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5330. }
  5331. TEST_F(ServerTest, GetMethodLocalAddr) {
  5332. auto res = cli_.Get("/local_addr");
  5333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5336. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5337. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5338. }
  5339. TEST_F(ServerTest, HTTPResponseSplitting) {
  5340. auto res = cli_.Get("/http_response_splitting");
  5341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. }
  5344. TEST_F(ServerTest, SlowRequest) {
  5345. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5346. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5347. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5348. }
  5349. #if 0
  5350. TEST_F(ServerTest, SlowPost) {
  5351. char buffer[64 * 1024];
  5352. memset(buffer, 0x42, sizeof(buffer));
  5353. auto res = cli_.Post(
  5354. "/slowpost", 64 * 1024 * 1024,
  5355. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5356. auto ret = sink.write(buffer, sizeof(buffer));
  5357. EXPECT_TRUE(ret);
  5358. return true;
  5359. },
  5360. "text/plain");
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, SlowPostFail) {
  5365. char buffer[64 * 1024];
  5366. memset(buffer, 0x42, sizeof(buffer));
  5367. cli_.set_write_timeout(std::chrono::seconds(0));
  5368. auto res = cli_.Post(
  5369. "/slowpost", 64 * 1024 * 1024,
  5370. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5371. sink.write(buffer, sizeof(buffer));
  5372. return true;
  5373. },
  5374. "text/plain");
  5375. ASSERT_TRUE(!res);
  5376. EXPECT_EQ(Error::Write, res.error());
  5377. }
  5378. #endif
  5379. TEST_F(ServerTest, Put) {
  5380. auto res = cli_.Put("/put", "PUT", "text/plain");
  5381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ("PUT", res->body);
  5384. }
  5385. TEST_F(ServerTest, PutWithContentProvider) {
  5386. auto res = cli_.Put(
  5387. "/put", 3,
  5388. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5389. sink.os << "PUT";
  5390. return true;
  5391. },
  5392. "text/plain");
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. EXPECT_EQ("PUT", res->body);
  5396. }
  5397. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5398. auto res = cli_.Post(
  5399. "/post", 42,
  5400. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5401. return false;
  5402. },
  5403. "text/plain");
  5404. ASSERT_TRUE(!res);
  5405. EXPECT_EQ(Error::Canceled, res.error());
  5406. }
  5407. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5408. auto res = cli_.Put(
  5409. "/put",
  5410. [](size_t /*offset*/, DataSink &sink) {
  5411. sink.os << "PUT";
  5412. sink.done();
  5413. return true;
  5414. },
  5415. "text/plain");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. EXPECT_EQ(StatusCode::OK_200, res->status);
  5418. EXPECT_EQ("PUT", res->body);
  5419. }
  5420. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5421. auto res = cli_.Post(
  5422. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5423. "text/plain");
  5424. ASSERT_TRUE(!res);
  5425. EXPECT_EQ(Error::Canceled, res.error());
  5426. }
  5427. TEST_F(ServerTest, PostLoopBack) {
  5428. std::string body;
  5429. auto res = cli_.Post(
  5430. "/post-loopback", 9,
  5431. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5432. EXPECT_EQ(9u, length);
  5433. sink.write("123", 3);
  5434. sink.write("456", 3);
  5435. sink.write("789", 3);
  5436. return true;
  5437. },
  5438. "text/plain",
  5439. [&body](const char *data, size_t data_length) {
  5440. body.append(data, data_length);
  5441. return true;
  5442. });
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::OK_200, res->status);
  5445. EXPECT_EQ("123456789", body);
  5446. }
  5447. TEST_F(ServerTest, PutLoopBack) {
  5448. std::string body;
  5449. auto res = cli_.Put(
  5450. "/put-loopback", 9,
  5451. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5452. EXPECT_EQ(9u, length);
  5453. sink.write("123", 3);
  5454. sink.write("456", 3);
  5455. sink.write("789", 3);
  5456. return true;
  5457. },
  5458. "text/plain",
  5459. [&body](const char *data, size_t data_length) {
  5460. body.append(data, data_length);
  5461. return true;
  5462. });
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. EXPECT_EQ(StatusCode::OK_200, res->status);
  5465. EXPECT_EQ("123456789", body);
  5466. }
  5467. TEST_F(ServerTest, PatchLoopBack) {
  5468. std::string body;
  5469. auto res = cli_.Patch(
  5470. "/patch-loopback", 9,
  5471. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5472. EXPECT_EQ(9u, length);
  5473. sink.write("123", 3);
  5474. sink.write("456", 3);
  5475. sink.write("789", 3);
  5476. return true;
  5477. },
  5478. "text/plain",
  5479. [&body](const char *data, size_t data_length) {
  5480. body.append(data, data_length);
  5481. return true;
  5482. });
  5483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5484. EXPECT_EQ(StatusCode::OK_200, res->status);
  5485. EXPECT_EQ("123456789", body);
  5486. }
  5487. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5488. std::string body;
  5489. auto res = cli_.Post(
  5490. "/post-loopback",
  5491. [](size_t /*offset*/, DataSink &sink) {
  5492. sink.write("123", 3);
  5493. sink.write("456", 3);
  5494. sink.write("789", 3);
  5495. sink.done();
  5496. return true;
  5497. },
  5498. "text/plain",
  5499. [&body](const char *data, size_t data_length) {
  5500. body.append(data, data_length);
  5501. return true;
  5502. });
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. EXPECT_EQ("123456789", body);
  5506. }
  5507. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5508. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5509. cli_.set_compress(true);
  5510. auto res = cli_.Put(
  5511. "/put", 3,
  5512. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5513. sink.os << "PUT";
  5514. return true;
  5515. },
  5516. "text/plain");
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::OK_200, res->status);
  5519. EXPECT_EQ("PUT", res->body);
  5520. }
  5521. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5522. cli_.set_compress(true);
  5523. auto res = cli_.Post(
  5524. "/post", 42,
  5525. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5526. return false;
  5527. },
  5528. "text/plain");
  5529. ASSERT_TRUE(!res);
  5530. EXPECT_EQ(Error::Canceled, res.error());
  5531. }
  5532. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5533. cli_.set_compress(true);
  5534. auto res = cli_.Put(
  5535. "/put",
  5536. [](size_t /*offset*/, DataSink &sink) {
  5537. sink.os << "PUT";
  5538. sink.done();
  5539. return true;
  5540. },
  5541. "text/plain");
  5542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5543. EXPECT_EQ(StatusCode::OK_200, res->status);
  5544. EXPECT_EQ("PUT", res->body);
  5545. }
  5546. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5547. cli_.set_compress(true);
  5548. auto res = cli_.Post(
  5549. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5550. "text/plain");
  5551. ASSERT_TRUE(!res);
  5552. EXPECT_EQ(Error::Canceled, res.error());
  5553. }
  5554. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5555. cli_.set_compress(true);
  5556. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::OK_200, res->status);
  5559. EXPECT_EQ(LARGE_DATA, res->body);
  5560. }
  5561. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5562. #ifdef CPPHTTPLIB_SSL_ENABLED
  5563. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5564. Client cli(s.c_str());
  5565. cli.enable_server_certificate_verification(false);
  5566. #else
  5567. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5568. Client cli(s.c_str());
  5569. #endif
  5570. cli.set_compress(true);
  5571. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. EXPECT_EQ(LARGE_DATA, res->body);
  5575. // The compressed size should be less than a 10th of the original. May vary
  5576. // depending on the zlib library.
  5577. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5578. static_cast<uint64_t>(10 * 1024 * 1024));
  5579. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5580. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5581. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5582. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5583. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5584. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5585. #endif
  5586. }
  5587. TEST_F(ServerTest, PutContentWithDeflate) {
  5588. cli_.set_compress(false);
  5589. Headers headers;
  5590. headers.emplace("Content-Encoding", "deflate");
  5591. // PUT in deflate format:
  5592. auto res = cli_.Put("/put", headers,
  5593. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::OK_200, res->status);
  5596. EXPECT_EQ("PUT", res->body);
  5597. }
  5598. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5599. Headers headers;
  5600. headers.emplace("Accept-Encoding", "gzip, deflate");
  5601. auto res = cli_.Get("/streamed-chunked", headers);
  5602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. EXPECT_EQ(std::string("123456789"), res->body);
  5605. }
  5606. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "gzip, deflate");
  5609. auto res = cli_.Get("/streamed-chunked2", headers);
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. EXPECT_EQ(std::string("123456789"), res->body);
  5613. }
  5614. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5615. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::OK_200, res->status);
  5618. }
  5619. TEST(GzipDecompressor, ChunkedDecompression) {
  5620. std::string data;
  5621. for (size_t i = 0; i < 32 * 1024; ++i) {
  5622. data.push_back(static_cast<char>('a' + i % 26));
  5623. }
  5624. std::string compressed_data;
  5625. {
  5626. httplib::detail::gzip_compressor compressor;
  5627. bool result = compressor.compress(
  5628. data.data(), data.size(),
  5629. /*last=*/true,
  5630. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5631. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5632. compressed_data_size);
  5633. return true;
  5634. });
  5635. ASSERT_TRUE(result);
  5636. }
  5637. std::string decompressed_data;
  5638. {
  5639. httplib::detail::gzip_decompressor decompressor;
  5640. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5641. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5642. size_t chunk_size = 130;
  5643. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5644. chunk_begin += chunk_size) {
  5645. size_t current_chunk_size =
  5646. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5647. bool result = decompressor.decompress(
  5648. compressed_data.data() + chunk_begin, current_chunk_size,
  5649. [&](const char *decompressed_data_chunk,
  5650. size_t decompressed_data_chunk_size) {
  5651. decompressed_data.insert(decompressed_data.size(),
  5652. decompressed_data_chunk,
  5653. decompressed_data_chunk_size);
  5654. return true;
  5655. });
  5656. ASSERT_TRUE(result);
  5657. }
  5658. }
  5659. ASSERT_EQ(data, decompressed_data);
  5660. }
  5661. TEST(GzipDecompressor, DeflateDecompression) {
  5662. std::string original_text = "Raw deflate without gzip";
  5663. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5664. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5665. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5666. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5667. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5668. std::string decompressed_data;
  5669. {
  5670. httplib::detail::gzip_decompressor decompressor;
  5671. bool result = decompressor.decompress(
  5672. compressed_data.data(), compressed_data.size(),
  5673. [&](const char *decompressed_data_chunk,
  5674. size_t decompressed_data_chunk_size) {
  5675. decompressed_data.insert(decompressed_data.size(),
  5676. decompressed_data_chunk,
  5677. decompressed_data_chunk_size);
  5678. return true;
  5679. });
  5680. ASSERT_TRUE(result);
  5681. }
  5682. ASSERT_EQ(original_text, decompressed_data);
  5683. }
  5684. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5685. std::string original_text = "Raw deflate without gzip";
  5686. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5687. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5688. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5689. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5690. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5691. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5692. std::string decompressed_data;
  5693. {
  5694. httplib::detail::gzip_decompressor decompressor;
  5695. bool result = decompressor.decompress(
  5696. compressed_data.data(), compressed_data.size(),
  5697. [&](const char *decompressed_data_chunk,
  5698. size_t decompressed_data_chunk_size) {
  5699. decompressed_data.insert(decompressed_data.size(),
  5700. decompressed_data_chunk,
  5701. decompressed_data_chunk_size);
  5702. return true;
  5703. });
  5704. ASSERT_TRUE(result);
  5705. }
  5706. ASSERT_EQ(original_text, decompressed_data);
  5707. }
  5708. #endif
  5709. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5710. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5711. Headers headers;
  5712. headers.emplace("Accept-Encoding", "br");
  5713. auto res = cli_.Get("/streamed-chunked", headers);
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::OK_200, res->status);
  5716. EXPECT_EQ(std::string("123456789"), res->body);
  5717. }
  5718. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5719. Headers headers;
  5720. headers.emplace("Accept-Encoding", "br");
  5721. auto res = cli_.Get("/streamed-chunked2", headers);
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ(std::string("123456789"), res->body);
  5725. }
  5726. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5727. cli_.set_compress(true);
  5728. auto res = cli_.Put(
  5729. "/put", 3,
  5730. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5731. sink.os << "PUT";
  5732. return true;
  5733. },
  5734. "text/plain");
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. EXPECT_EQ(StatusCode::OK_200, res->status);
  5737. EXPECT_EQ("PUT", res->body);
  5738. }
  5739. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5740. cli_.set_compress(true);
  5741. auto res = cli_.Put(
  5742. "/put",
  5743. [](size_t /*offset*/, DataSink &sink) {
  5744. sink.os << "PUT";
  5745. sink.done();
  5746. return true;
  5747. },
  5748. "text/plain");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. EXPECT_EQ("PUT", res->body);
  5752. }
  5753. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5754. cli_.set_compress(true);
  5755. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::OK_200, res->status);
  5758. EXPECT_EQ(LARGE_DATA, res->body);
  5759. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5760. }
  5761. #endif
  5762. TEST_F(ServerTest, Patch) {
  5763. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5765. EXPECT_EQ(StatusCode::OK_200, res->status);
  5766. EXPECT_EQ("PATCH", res->body);
  5767. }
  5768. TEST_F(ServerTest, Delete) {
  5769. auto res = cli_.Delete("/delete");
  5770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5771. EXPECT_EQ(StatusCode::OK_200, res->status);
  5772. EXPECT_EQ("DELETE", res->body);
  5773. }
  5774. TEST_F(ServerTest, DeleteContentReceiver) {
  5775. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. EXPECT_EQ("content", res->body);
  5779. }
  5780. TEST_F(ServerTest, Options) {
  5781. auto res = cli_.Options("*");
  5782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5783. EXPECT_EQ(StatusCode::OK_200, res->status);
  5784. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5785. EXPECT_TRUE(res->body.empty());
  5786. }
  5787. TEST_F(ServerTest, URL) {
  5788. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5790. EXPECT_EQ(StatusCode::OK_200, res->status);
  5791. }
  5792. TEST_F(ServerTest, ArrayParam) {
  5793. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. }
  5797. TEST_F(ServerTest, ArrayParamValues) {
  5798. auto res =
  5799. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::OK_200, res->status);
  5802. }
  5803. TEST_F(ServerTest, NoMultipleHeaders) {
  5804. Headers headers = {{"Content-Length", "5"}};
  5805. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5806. "text/plain");
  5807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5808. EXPECT_EQ(StatusCode::OK_200, res->status);
  5809. }
  5810. TEST_F(ServerTest, PostContentReceiver) {
  5811. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5813. ASSERT_EQ(StatusCode::OK_200, res->status);
  5814. ASSERT_EQ("content", res->body);
  5815. }
  5816. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5817. UploadFormDataItems items = {
  5818. {"text1", "text default", "", ""},
  5819. {"text2", "aωb", "", ""},
  5820. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5821. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5822. {"file3", "", "", "application/octet-stream"},
  5823. };
  5824. auto res = cli_.Post("/content_receiver", items);
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::OK_200, res->status);
  5827. }
  5828. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5829. UploadFormDataItems items = {
  5830. {"text1", "text default", "", ""},
  5831. {"text2", "aωb", "", ""},
  5832. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5833. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5834. {"file3", "", "", "application/octet-stream"},
  5835. };
  5836. auto boundary = std::string("+++++");
  5837. std::string body;
  5838. for (const auto &item : items) {
  5839. body += "--" + boundary + "\r\n";
  5840. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5841. if (!item.filename.empty()) {
  5842. body += "; filename=\"" + item.filename + "\"";
  5843. }
  5844. body += "\r\n";
  5845. if (!item.content_type.empty()) {
  5846. body += "Content-Type: " + item.content_type + "\r\n";
  5847. }
  5848. body += "\r\n";
  5849. body += item.content + "\r\n";
  5850. }
  5851. body += "--" + boundary + "--\r\n";
  5852. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5853. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. }
  5857. TEST(MultipartFormDataTest, FieldEscaping) {
  5858. Server svr;
  5859. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5860. const ContentReader &content_reader) {
  5861. ASSERT_TRUE(req.is_multipart_form_data());
  5862. std::vector<FormData> received;
  5863. content_reader(
  5864. [&](const FormData &file) {
  5865. received.push_back(file);
  5866. return true;
  5867. },
  5868. [&](const char *data, size_t data_length) {
  5869. received.back().content.append(data, data_length);
  5870. return true;
  5871. });
  5872. // '"', CR and LF in names and filenames are escaped following the
  5873. // WHATWG HTML standard, so each part still parses as a single part
  5874. // with no injected headers. Content types get CR/LF escaped too,
  5875. // while '"' (legal there, e.g. quoted charset) is preserved.
  5876. ASSERT_EQ(4U, received.size());
  5877. EXPECT_EQ("na%22me", received[0].name);
  5878. EXPECT_EQ("quoted name", received[0].content);
  5879. EXPECT_EQ("file", received[1].name);
  5880. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5881. received[1].filename);
  5882. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5883. EXPECT_EQ("injected", received[1].content);
  5884. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5885. EXPECT_EQ("my%22file.txt", received[2].filename);
  5886. EXPECT_EQ("cr lf name", received[2].content);
  5887. EXPECT_EQ("typed", received[3].name);
  5888. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5889. received[3].content_type);
  5890. EXPECT_EQ("typed content", received[3].content);
  5891. });
  5892. auto port = svr.bind_to_any_port("localhost");
  5893. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5894. auto se = detail::scope_exit([&] {
  5895. svr.stop();
  5896. t.join();
  5897. ASSERT_FALSE(svr.is_running());
  5898. });
  5899. svr.wait_until_ready();
  5900. Client cli("localhost", port);
  5901. UploadFormDataItems items = {
  5902. {"na\"me", "quoted name", "", ""},
  5903. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5904. "application/octet-stream"},
  5905. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5906. {"typed", "typed content", "",
  5907. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5908. };
  5909. auto res = cli.Post("/post", items);
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. EXPECT_EQ(StatusCode::OK_200, res->status);
  5912. }
  5913. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5914. const UploadFormDataItems items = {
  5915. {"name1", "Content 1", "", ""},
  5916. {"name2", "Content 2", "file2.txt", "text/plain"},
  5917. };
  5918. Server svr;
  5919. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5920. const ContentReader &content_reader) {
  5921. ASSERT_TRUE(req.is_multipart_form_data());
  5922. std::vector<FormData> received;
  5923. content_reader(
  5924. [&](const FormData &file) {
  5925. received.push_back(file);
  5926. return true;
  5927. },
  5928. [&](const char *data, size_t data_length) {
  5929. received.back().content.append(data, data_length);
  5930. return true;
  5931. });
  5932. ASSERT_EQ(2U, received.size());
  5933. EXPECT_EQ("name1", received[0].name);
  5934. EXPECT_EQ("Content 1", received[0].content);
  5935. EXPECT_EQ("name2", received[1].name);
  5936. EXPECT_EQ("Content 2", received[1].content);
  5937. EXPECT_EQ("file2.txt", received[1].filename);
  5938. EXPECT_EQ("text/plain", received[1].content_type);
  5939. });
  5940. auto port = svr.bind_to_any_port("localhost");
  5941. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5942. auto se = detail::scope_exit([&] {
  5943. svr.stop();
  5944. t.join();
  5945. ASSERT_FALSE(svr.is_running());
  5946. });
  5947. svr.wait_until_ready();
  5948. Client cli("localhost", port);
  5949. // Whole-body serialization with a generated boundary
  5950. {
  5951. MultipartFormDataWriter writer;
  5952. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5953. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5954. writer.content_type());
  5955. auto body = writer.serialize(items);
  5956. EXPECT_EQ(body.size(), writer.content_length(items));
  5957. auto res = cli.Post("/post", body, writer.content_type());
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::OK_200, res->status);
  5960. }
  5961. // Per-part framing with a custom boundary via a content provider
  5962. {
  5963. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5964. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5965. MultipartFormDataWriter writer("custom-boundary_123");
  5966. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5967. std::string body;
  5968. for (const auto &item : items) {
  5969. body += writer.item_begin(item);
  5970. body += item.content;
  5971. body += MultipartFormDataWriter::item_end();
  5972. }
  5973. body += writer.finish();
  5974. EXPECT_EQ(body.size(), writer.content_length(items));
  5975. auto res = cli.Post(
  5976. "/post", body.size(),
  5977. [&](size_t offset, size_t length, DataSink &sink) {
  5978. sink.write(body.data() + offset, length);
  5979. return true;
  5980. },
  5981. writer.content_type());
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::OK_200, res->status);
  5984. }
  5985. }
  5986. TEST_F(ServerTest, PostContentReceiverGzip) {
  5987. cli_.set_compress(true);
  5988. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. ASSERT_EQ(StatusCode::OK_200, res->status);
  5991. ASSERT_EQ("content", res->body);
  5992. }
  5993. TEST_F(ServerTest, PutContentReceiver) {
  5994. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5996. ASSERT_EQ(StatusCode::OK_200, res->status);
  5997. ASSERT_EQ("content", res->body);
  5998. }
  5999. TEST_F(ServerTest, PatchContentReceiver) {
  6000. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. ASSERT_EQ(StatusCode::OK_200, res->status);
  6003. ASSERT_EQ("content", res->body);
  6004. }
  6005. template <typename ClientType>
  6006. void TestWithHeadersAndContentReceiver(
  6007. ClientType &cli,
  6008. std::function<Result(ClientType &, const std::string &, const Headers &,
  6009. const std::string &, const std::string &,
  6010. ContentReceiver, DownloadProgress)>
  6011. request_func) {
  6012. Headers headers;
  6013. headers.emplace("X-Custom-Header", "test-value");
  6014. std::string received_body;
  6015. auto res = request_func(
  6016. cli, "/content_receiver", headers, "content", "application/json",
  6017. [&](const char *data, size_t data_length) {
  6018. received_body.append(data, data_length);
  6019. return true;
  6020. },
  6021. nullptr);
  6022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6023. EXPECT_EQ(StatusCode::OK_200, res->status);
  6024. EXPECT_EQ("content", received_body);
  6025. }
  6026. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6027. #ifdef CPPHTTPLIB_SSL_ENABLED
  6028. using ClientT = SSLClient;
  6029. #else
  6030. using ClientT = Client;
  6031. #endif
  6032. TestWithHeadersAndContentReceiver<ClientT>(
  6033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6034. const std::string &body, const std::string &content_type,
  6035. ContentReceiver receiver, DownloadProgress progress) {
  6036. return cli.Post(path, headers, body, content_type, receiver, progress);
  6037. });
  6038. }
  6039. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6040. #ifdef CPPHTTPLIB_SSL_ENABLED
  6041. using ClientT = SSLClient;
  6042. #else
  6043. using ClientT = Client;
  6044. #endif
  6045. TestWithHeadersAndContentReceiver<ClientT>(
  6046. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6047. const std::string &body, const std::string &content_type,
  6048. ContentReceiver receiver, DownloadProgress progress) {
  6049. return cli.Put(path, headers, body, content_type, receiver, progress);
  6050. });
  6051. }
  6052. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6053. #ifdef CPPHTTPLIB_SSL_ENABLED
  6054. using ClientT = SSLClient;
  6055. #else
  6056. using ClientT = Client;
  6057. #endif
  6058. TestWithHeadersAndContentReceiver<ClientT>(
  6059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6060. const std::string &body, const std::string &content_type,
  6061. ContentReceiver receiver, DownloadProgress progress) {
  6062. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6063. });
  6064. }
  6065. template <typename ClientType>
  6066. void TestWithHeadersAndContentReceiverWithProgress(
  6067. ClientType &cli,
  6068. std::function<Result(ClientType &, const std::string &, const Headers &,
  6069. const std::string &, const std::string &,
  6070. ContentReceiver, DownloadProgress)>
  6071. request_func) {
  6072. Headers headers;
  6073. headers.emplace("X-Test-Header", "progress-test");
  6074. std::string received_body;
  6075. auto progress_called = false;
  6076. auto res = request_func(
  6077. cli, "/content_receiver", headers, "content", "text/plain",
  6078. [&](const char *data, size_t data_length) {
  6079. received_body.append(data, data_length);
  6080. return true;
  6081. },
  6082. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6083. progress_called = true;
  6084. return true;
  6085. });
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::OK_200, res->status);
  6088. EXPECT_EQ("content", received_body);
  6089. EXPECT_TRUE(progress_called);
  6090. }
  6091. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6092. #ifdef CPPHTTPLIB_SSL_ENABLED
  6093. using ClientT = SSLClient;
  6094. #else
  6095. using ClientT = Client;
  6096. #endif
  6097. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6098. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6099. const std::string &body, const std::string &content_type,
  6100. ContentReceiver receiver, DownloadProgress progress) {
  6101. return cli.Post(path, headers, body, content_type, receiver, progress);
  6102. });
  6103. }
  6104. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6105. #ifdef CPPHTTPLIB_SSL_ENABLED
  6106. using ClientT = SSLClient;
  6107. #else
  6108. using ClientT = Client;
  6109. #endif
  6110. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6111. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6112. const std::string &body, const std::string &content_type,
  6113. ContentReceiver receiver, DownloadProgress progress) {
  6114. return cli.Put(path, headers, body, content_type, receiver, progress);
  6115. });
  6116. }
  6117. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6118. #ifdef CPPHTTPLIB_SSL_ENABLED
  6119. using ClientT = SSLClient;
  6120. #else
  6121. using ClientT = Client;
  6122. #endif
  6123. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6124. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6125. const std::string &body, const std::string &content_type,
  6126. ContentReceiver receiver, DownloadProgress progress) {
  6127. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6128. });
  6129. }
  6130. template <typename ClientType>
  6131. void TestWithHeadersAndContentReceiverError(
  6132. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6133. const Headers &, const std::string &,
  6134. const std::string &, ContentReceiver)>
  6135. request_func) {
  6136. Headers headers;
  6137. headers.emplace("X-Error-Test", "true");
  6138. std::string received_body;
  6139. auto receiver_failed = false;
  6140. auto res =
  6141. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6142. [&](const char *data, size_t data_length) {
  6143. received_body.append(data, data_length);
  6144. receiver_failed = true;
  6145. return false;
  6146. });
  6147. ASSERT_FALSE(res);
  6148. EXPECT_TRUE(receiver_failed);
  6149. }
  6150. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6151. #ifdef CPPHTTPLIB_SSL_ENABLED
  6152. using ClientT = SSLClient;
  6153. #else
  6154. using ClientT = Client;
  6155. #endif
  6156. TestWithHeadersAndContentReceiverError<ClientT>(
  6157. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6158. const std::string &body, const std::string &content_type,
  6159. ContentReceiver receiver) {
  6160. return cli.Post(path, headers, body, content_type, receiver);
  6161. });
  6162. }
  6163. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6164. #ifdef CPPHTTPLIB_SSL_ENABLED
  6165. using ClientT = SSLClient;
  6166. #else
  6167. using ClientT = Client;
  6168. #endif
  6169. TestWithHeadersAndContentReceiverError<ClientT>(
  6170. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6171. const std::string &body, const std::string &content_type,
  6172. ContentReceiver receiver) {
  6173. return cli.Put(path, headers, body, content_type, receiver);
  6174. });
  6175. }
  6176. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6177. #ifdef CPPHTTPLIB_SSL_ENABLED
  6178. using ClientT = SSLClient;
  6179. #else
  6180. using ClientT = Client;
  6181. #endif
  6182. TestWithHeadersAndContentReceiverError<ClientT>(
  6183. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6184. const std::string &body, const std::string &content_type,
  6185. ContentReceiver receiver) {
  6186. return cli.Patch(path, headers, body, content_type, receiver);
  6187. });
  6188. }
  6189. TEST_F(ServerTest, PostQueryStringAndBody) {
  6190. auto res =
  6191. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::OK_200, res->status);
  6194. }
  6195. TEST_F(ServerTest, HTTP2Magic) {
  6196. Request req;
  6197. req.method = "PRI";
  6198. req.path = "*";
  6199. req.body = "SM";
  6200. auto res = std::make_shared<Response>();
  6201. auto error = Error::Success;
  6202. auto ret = cli_.send(req, *res, error);
  6203. ASSERT_TRUE(ret);
  6204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6205. }
  6206. TEST_F(ServerTest, KeepAlive) {
  6207. auto res = cli_.Get("/hi");
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::OK_200, res->status);
  6210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6211. EXPECT_EQ("Hello World!", res->body);
  6212. res = cli_.Get("/hi");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6216. EXPECT_EQ("Hello World!", res->body);
  6217. res = cli_.Get("/hi");
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::OK_200, res->status);
  6220. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6221. EXPECT_EQ("Hello World!", res->body);
  6222. res = cli_.Get("/not-exist");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6225. res = cli_.Post("/empty", "", "text/plain");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::OK_200, res->status);
  6228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6229. EXPECT_EQ("empty", res->body);
  6230. EXPECT_EQ("close", res->get_header_value("Connection"));
  6231. res = cli_.Post(
  6232. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6233. "text/plain");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::OK_200, res->status);
  6236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6237. EXPECT_EQ("empty", res->body);
  6238. cli_.set_keep_alive(false);
  6239. res = cli_.Get("/last-request");
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::OK_200, res->status);
  6242. EXPECT_EQ("close", res->get_header_value("Connection"));
  6243. }
  6244. TEST_F(ServerTest, TooManyRedirect) {
  6245. cli_.set_follow_location(true);
  6246. auto res = cli_.Get("/redirect/0");
  6247. ASSERT_TRUE(!res);
  6248. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6249. }
  6250. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6251. Request req;
  6252. req.method = "FOOBAR";
  6253. req.path = "/hi";
  6254. cli_.set_keep_alive(true);
  6255. auto res = cli_.send(req);
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6258. EXPECT_EQ("close", res->get_header_value("Connection"));
  6259. EXPECT_FALSE(cli_.is_socket_open());
  6260. }
  6261. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6263. TEST_F(ServerTest, Gzip) {
  6264. Headers headers;
  6265. headers.emplace("Accept-Encoding", "gzip, deflate");
  6266. auto res = cli_.Get("/compress", headers);
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6269. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6270. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6271. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6272. "7890123456789012345678901234567890",
  6273. res->body);
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6277. Headers headers;
  6278. headers.emplace("Accept-Encoding", "gzip, deflate");
  6279. auto res = cli_.Get("/compress-with-charset", headers);
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6282. EXPECT_EQ("application/json; charset=utf-8",
  6283. res->get_header_value("Content-Type"));
  6284. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6285. "7890123456789012345678901234567890",
  6286. res->body);
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. }
  6289. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6290. Headers headers;
  6291. headers.emplace("Accept-Encoding", "");
  6292. auto res = cli_.Get("/compress", headers);
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6295. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6296. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6297. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6298. "7890123456789012345678901234567890",
  6299. res->body);
  6300. EXPECT_EQ(StatusCode::OK_200, res->status);
  6301. }
  6302. TEST_F(ServerTest, GzipWithContentReceiver) {
  6303. Headers headers;
  6304. headers.emplace("Accept-Encoding", "gzip, deflate");
  6305. std::string body;
  6306. auto res = cli_.Get("/compress", headers,
  6307. [&](const char *data, uint64_t data_length) {
  6308. EXPECT_EQ(100U, data_length);
  6309. body.append(data, data_length);
  6310. return true;
  6311. });
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6316. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6317. "7890123456789012345678901234567890",
  6318. body);
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. }
  6321. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6322. Headers headers;
  6323. headers.emplace("Accept-Encoding", "gzip, deflate");
  6324. cli_.set_decompress(false);
  6325. auto res = cli_.Get("/compress", headers);
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6329. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6330. EXPECT_EQ(33U, res->body.size());
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6334. Headers headers;
  6335. headers.emplace("Accept-Encoding", "");
  6336. std::string body;
  6337. auto res = cli_.Get("/compress", headers,
  6338. [&](const char *data, uint64_t data_length) {
  6339. EXPECT_EQ(100U, data_length);
  6340. body.append(data, data_length);
  6341. return true;
  6342. });
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6346. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6348. "7890123456789012345678901234567890",
  6349. body);
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. }
  6352. TEST_F(ServerTest, NoGzip) {
  6353. Headers headers;
  6354. headers.emplace("Accept-Encoding", "gzip, deflate");
  6355. auto res = cli_.Get("/nocompress", headers);
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6358. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6359. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6360. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6361. "7890123456789012345678901234567890",
  6362. res->body);
  6363. EXPECT_EQ(StatusCode::OK_200, res->status);
  6364. }
  6365. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6366. Headers headers;
  6367. headers.emplace("Accept-Encoding", "gzip, deflate");
  6368. std::string body;
  6369. auto res = cli_.Get("/nocompress", headers,
  6370. [&](const char *data, uint64_t data_length) {
  6371. EXPECT_EQ(100U, data_length);
  6372. body.append(data, data_length);
  6373. return true;
  6374. });
  6375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6376. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6377. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6378. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6379. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6380. "7890123456789012345678901234567890",
  6381. body);
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. }
  6384. TEST_F(ServerTest, MultipartFormDataGzip) {
  6385. UploadFormDataItems items = {
  6386. {"key1", "test", "", ""},
  6387. {"key2", "--abcdefg123", "", ""},
  6388. };
  6389. cli_.set_compress(true);
  6390. auto res = cli_.Post("/compress-multipart", items);
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. }
  6394. #endif
  6395. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6396. TEST_F(ServerTest, Brotli) {
  6397. Headers headers;
  6398. headers.emplace("Accept-Encoding", "br");
  6399. auto res = cli_.Get("/compress", headers);
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6402. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6403. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6404. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6405. "7890123456789012345678901234567890",
  6406. res->body);
  6407. EXPECT_EQ(StatusCode::OK_200, res->status);
  6408. }
  6409. #endif
  6410. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6411. TEST_F(ServerTest, Zstd) {
  6412. Headers headers;
  6413. headers.emplace("Accept-Encoding", "zstd");
  6414. auto res = cli_.Get("/compress", headers);
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6418. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6419. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6420. "7890123456789012345678901234567890",
  6421. res->body);
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. }
  6424. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6425. Headers headers;
  6426. headers.emplace("Accept-Encoding", "");
  6427. auto res = cli_.Get("/compress", headers);
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6431. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6432. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6433. "7890123456789012345678901234567890",
  6434. res->body);
  6435. EXPECT_EQ(StatusCode::OK_200, res->status);
  6436. }
  6437. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6438. Headers headers;
  6439. headers.emplace("Accept-Encoding", "zstd");
  6440. std::string body;
  6441. auto res = cli_.Get("/compress", headers,
  6442. [&](const char *data, uint64_t data_length) {
  6443. EXPECT_EQ(100U, data_length);
  6444. body.append(data, data_length);
  6445. return true;
  6446. });
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6450. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6451. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6452. "7890123456789012345678901234567890",
  6453. body);
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. }
  6456. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6457. Headers headers;
  6458. headers.emplace("Accept-Encoding", "zstd");
  6459. cli_.set_decompress(false);
  6460. auto res = cli_.Get("/compress", headers);
  6461. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6462. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6463. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6464. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6468. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6469. EXPECT_EQ(StatusCode::OK_200, res->status);
  6470. ASSERT_EQ(26U, res->body.size());
  6471. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6472. 0);
  6473. }
  6474. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6475. Headers headers;
  6476. headers.emplace("Accept-Encoding", "");
  6477. std::string body;
  6478. auto res = cli_.Get("/compress", headers,
  6479. [&](const char *data, uint64_t data_length) {
  6480. EXPECT_EQ(100U, data_length);
  6481. body.append(data, data_length);
  6482. return true;
  6483. });
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6487. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6489. "7890123456789012345678901234567890",
  6490. body);
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. }
  6493. TEST_F(ServerTest, NoZstd) {
  6494. Headers headers;
  6495. headers.emplace("Accept-Encoding", "zstd");
  6496. auto res = cli_.Get("/nocompress", headers);
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6499. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6500. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6501. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6502. "7890123456789012345678901234567890",
  6503. res->body);
  6504. EXPECT_EQ(StatusCode::OK_200, res->status);
  6505. }
  6506. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6507. Headers headers;
  6508. headers.emplace("Accept-Encoding", "zstd");
  6509. std::string body;
  6510. auto res = cli_.Get("/nocompress", headers,
  6511. [&](const char *data, uint64_t data_length) {
  6512. EXPECT_EQ(100U, data_length);
  6513. body.append(data, data_length);
  6514. return true;
  6515. });
  6516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6517. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6518. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6519. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6521. "7890123456789012345678901234567890",
  6522. body);
  6523. EXPECT_EQ(StatusCode::OK_200, res->status);
  6524. }
  6525. // TODO: How to enable zstd ??
  6526. TEST_F(ServerTest, MultipartFormDataZstd) {
  6527. UploadFormDataItems items = {
  6528. {"key1", "test", "", ""},
  6529. {"key2", "--abcdefg123", "", ""},
  6530. };
  6531. Headers headers;
  6532. headers.emplace("Accept-Encoding", "zstd");
  6533. cli_.set_compress(true);
  6534. auto res = cli_.Post("/compress-multipart", headers, items);
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::OK_200, res->status);
  6537. }
  6538. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6539. Headers headers;
  6540. headers.emplace("Accept-Encoding", "zstd");
  6541. cli_.set_compress(true);
  6542. auto res = cli_.Put(
  6543. "/put", headers, 3,
  6544. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6545. sink.os << "PUT";
  6546. return true;
  6547. },
  6548. "text/plain");
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. EXPECT_EQ(StatusCode::OK_200, res->status);
  6551. EXPECT_EQ("PUT", res->body);
  6552. }
  6553. // Pre-compression logging tests
  6554. TEST_F(ServerTest, PreCompressionLogging) {
  6555. // Test data for compression (matches the actual /compress endpoint content)
  6556. const std::string test_content =
  6557. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6558. "3456789012345678901234567890";
  6559. // Variables to capture logging data
  6560. std::string pre_compression_body;
  6561. std::string pre_compression_content_type;
  6562. std::string pre_compression_content_encoding;
  6563. std::string post_compression_body;
  6564. std::string post_compression_content_type;
  6565. std::string post_compression_content_encoding;
  6566. // Set up pre-compression logger
  6567. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6568. const Response &res) {
  6569. pre_compression_body = res.body;
  6570. pre_compression_content_type = res.get_header_value("Content-Type");
  6571. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6572. });
  6573. // Set up post-compression logger
  6574. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6575. post_compression_body = res.body;
  6576. post_compression_content_type = res.get_header_value("Content-Type");
  6577. post_compression_content_encoding =
  6578. res.get_header_value("Content-Encoding");
  6579. });
  6580. // Test with gzip compression
  6581. Headers headers;
  6582. headers.emplace("Accept-Encoding", "gzip");
  6583. auto res = cli_.Get("/compress", headers);
  6584. // Verify response was compressed
  6585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6586. EXPECT_EQ(StatusCode::OK_200, res->status);
  6587. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6588. // Verify pre-compression logger captured uncompressed content
  6589. EXPECT_EQ(test_content, pre_compression_body);
  6590. EXPECT_EQ("text/plain", pre_compression_content_type);
  6591. EXPECT_TRUE(pre_compression_content_encoding
  6592. .empty()); // No encoding header before compression
  6593. // Verify post-compression logger captured compressed content
  6594. EXPECT_NE(test_content,
  6595. post_compression_body); // Should be different after compression
  6596. EXPECT_EQ("text/plain", post_compression_content_type);
  6597. EXPECT_EQ("gzip", post_compression_content_encoding);
  6598. // Verify compressed content is smaller
  6599. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6600. }
  6601. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6602. const std::string test_content =
  6603. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6604. "3456789012345678901234567890";
  6605. std::string pre_compression_body;
  6606. std::string post_compression_body;
  6607. svr_.set_pre_compression_logger(
  6608. [&](const Request & /*req*/, const Response &res) {
  6609. pre_compression_body = res.body;
  6610. });
  6611. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6612. post_compression_body = res.body;
  6613. });
  6614. Headers headers;
  6615. headers.emplace("Accept-Encoding", "br");
  6616. auto res = cli_.Get("/compress", headers);
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::OK_200, res->status);
  6619. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6620. // Verify pre-compression content is uncompressed
  6621. EXPECT_EQ(test_content, pre_compression_body);
  6622. // Verify post-compression content is compressed
  6623. EXPECT_NE(test_content, post_compression_body);
  6624. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6625. }
  6626. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6627. const std::string test_content =
  6628. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6629. "3456789012345678901234567890";
  6630. std::string pre_compression_body;
  6631. std::string post_compression_body;
  6632. svr_.set_pre_compression_logger(
  6633. [&](const Request & /*req*/, const Response &res) {
  6634. pre_compression_body = res.body;
  6635. });
  6636. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6637. post_compression_body = res.body;
  6638. });
  6639. // Request without compression (use /nocompress endpoint)
  6640. Headers headers;
  6641. auto res = cli_.Get("/nocompress", headers);
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6645. // Pre-compression logger should not be called when no compression is applied
  6646. EXPECT_TRUE(
  6647. pre_compression_body.empty()); // Pre-compression logger not called
  6648. EXPECT_EQ(
  6649. test_content,
  6650. post_compression_body); // Post-compression logger captures final content
  6651. }
  6652. TEST_F(ServerTest, LoggerSeesContentLength) {
  6653. size_t logged_content_length = 0;
  6654. std::string logged_content_length_header;
  6655. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6656. logged_content_length = res.content_length_;
  6657. logged_content_length_header = res.get_header_value("Content-Length");
  6658. });
  6659. auto res = cli_.Get("/nocompress");
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ(res->body.size(), logged_content_length);
  6663. EXPECT_EQ(std::to_string(logged_content_length),
  6664. logged_content_length_header);
  6665. }
  6666. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6667. const std::string test_content =
  6668. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6669. "3456789012345678901234567890";
  6670. std::string pre_compression_body;
  6671. bool pre_logger_called = false;
  6672. // Set only pre-compression logger
  6673. svr_.set_pre_compression_logger(
  6674. [&](const Request & /*req*/, const Response &res) {
  6675. pre_compression_body = res.body;
  6676. pre_logger_called = true;
  6677. });
  6678. Headers headers;
  6679. headers.emplace("Accept-Encoding", "gzip");
  6680. auto res = cli_.Get("/compress", headers);
  6681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6684. // Verify pre-compression logger was called
  6685. EXPECT_TRUE(pre_logger_called);
  6686. EXPECT_EQ(test_content, pre_compression_body);
  6687. }
  6688. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6689. {
  6690. // Test with Expect: 100-continue header - success case
  6691. // Server returns 100 Continue, client sends body, server returns 200 OK
  6692. Request req;
  6693. req.method = "POST";
  6694. req.path = "/post-large";
  6695. req.set_header("Expect", "100-continue");
  6696. req.body = LARGE_DATA;
  6697. Response res;
  6698. auto error = Error::Success;
  6699. cli_.set_keep_alive(true);
  6700. auto ret = cli_.send(req, res, error);
  6701. EXPECT_TRUE(ret);
  6702. EXPECT_EQ(StatusCode::OK_200, res.status);
  6703. EXPECT_EQ(LARGE_DATA, res.body);
  6704. }
  6705. {
  6706. // Test with Expect: 100-continue header - error case
  6707. // Client should not send the body when server returns an error
  6708. Request req;
  6709. req.method = "POST";
  6710. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6711. req.set_header("Expect", "100-continue");
  6712. req.body = LARGE_DATA;
  6713. Response res;
  6714. auto error = Error::Success;
  6715. auto start = std::chrono::high_resolution_clock::now();
  6716. cli_.set_keep_alive(true);
  6717. auto ret = cli_.send(req, res, error);
  6718. auto end = std::chrono::high_resolution_clock::now();
  6719. auto elapsed =
  6720. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6721. .count();
  6722. // With Expect: 100-continue, request completes successfully but with error
  6723. EXPECT_TRUE(ret);
  6724. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6725. EXPECT_EQ("close", res.get_header_value("Connection"));
  6726. EXPECT_FALSE(cli_.is_socket_open());
  6727. EXPECT_LE(elapsed, 2000);
  6728. }
  6729. {
  6730. // Send an extra GET request to ensure error recovery without hanging
  6731. Request req;
  6732. req.method = "GET";
  6733. req.path = "/hi";
  6734. auto start = std::chrono::high_resolution_clock::now();
  6735. auto res = cli_.send(req);
  6736. auto end = std::chrono::high_resolution_clock::now();
  6737. auto elapsed =
  6738. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6739. .count();
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::OK_200, res->status);
  6742. EXPECT_EQ("Hello World!", res->body);
  6743. EXPECT_LE(elapsed, 500);
  6744. }
  6745. }
  6746. TEST(ZstdDecompressor, ChunkedDecompression) {
  6747. std::string data;
  6748. for (size_t i = 0; i < 32 * 1024; ++i) {
  6749. data.push_back(static_cast<char>('a' + i % 26));
  6750. }
  6751. std::string compressed_data;
  6752. {
  6753. httplib::detail::zstd_compressor compressor;
  6754. bool result = compressor.compress(
  6755. data.data(), data.size(),
  6756. /*last=*/true,
  6757. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6758. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6759. compressed_data_size);
  6760. return true;
  6761. });
  6762. ASSERT_TRUE(result);
  6763. }
  6764. std::string decompressed_data;
  6765. {
  6766. httplib::detail::zstd_decompressor decompressor;
  6767. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6768. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6769. size_t chunk_size = 130;
  6770. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6771. chunk_begin += chunk_size) {
  6772. size_t current_chunk_size =
  6773. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6774. bool result = decompressor.decompress(
  6775. compressed_data.data() + chunk_begin, current_chunk_size,
  6776. [&](const char *decompressed_data_chunk,
  6777. size_t decompressed_data_chunk_size) {
  6778. decompressed_data.insert(decompressed_data.size(),
  6779. decompressed_data_chunk,
  6780. decompressed_data_chunk_size);
  6781. return true;
  6782. });
  6783. ASSERT_TRUE(result);
  6784. }
  6785. }
  6786. ASSERT_EQ(data, decompressed_data);
  6787. }
  6788. TEST(ZstdDecompressor, Decompress) {
  6789. std::string original_text = "Compressed with ZSTD";
  6790. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6791. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6792. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6793. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6794. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6795. std::string decompressed_data;
  6796. {
  6797. httplib::detail::zstd_decompressor decompressor;
  6798. bool result = decompressor.decompress(
  6799. compressed_data.data(), compressed_data.size(),
  6800. [&](const char *decompressed_data_chunk,
  6801. size_t decompressed_data_chunk_size) {
  6802. decompressed_data.insert(decompressed_data.size(),
  6803. decompressed_data_chunk,
  6804. decompressed_data_chunk_size);
  6805. return true;
  6806. });
  6807. ASSERT_TRUE(result);
  6808. }
  6809. ASSERT_EQ(original_text, decompressed_data);
  6810. }
  6811. #endif
  6812. // Sends a raw request to a server listening at HOST:PORT.
  6813. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6814. std::string *resp = nullptr) {
  6815. auto error = Error::Success;
  6816. auto client_sock = detail::create_client_socket(
  6817. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6818. /*connection_timeout_sec=*/5, 0,
  6819. /*read_timeout_sec=*/5, 0,
  6820. /*write_timeout_sec=*/5, 0, std::string(), error);
  6821. if (client_sock == INVALID_SOCKET) { return false; }
  6822. auto ret = detail::process_client_socket(
  6823. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6824. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6825. if (req.size() !=
  6826. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6827. return false;
  6828. }
  6829. char buf[512];
  6830. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6831. while (line_reader.getline()) {
  6832. if (resp) { *resp += line_reader.ptr(); }
  6833. }
  6834. return true;
  6835. });
  6836. detail::close_socket(client_sock);
  6837. return ret;
  6838. }
  6839. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6840. Server svr;
  6841. std::string header_value;
  6842. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6843. header_value = req.get_header_value("foo");
  6844. res.set_content("ok", "text/plain");
  6845. });
  6846. thread t = thread([&] { svr.listen(HOST, PORT); });
  6847. auto se = detail::scope_exit([&] {
  6848. svr.stop();
  6849. t.join();
  6850. ASSERT_FALSE(svr.is_running());
  6851. });
  6852. svr.wait_until_ready();
  6853. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6854. // like characters are not treated the same - use vertical tab and escape.
  6855. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6856. "foo: \t \v bar \x1B\t \r\n"
  6857. "Connection: close\r\n"
  6858. "\r\n";
  6859. std::string res;
  6860. ASSERT_TRUE(send_request(5, req, &res));
  6861. EXPECT_EQ(header_value, "");
  6862. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6863. }
  6864. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6865. Server svr;
  6866. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6867. auto i = new int(0);
  6868. res.set_header("Trailer", "X-Safe, X-Reflected");
  6869. res.set_chunked_content_provider(
  6870. "text/plain",
  6871. [i](size_t /*offset*/, DataSink &sink) {
  6872. if (*i == 0) {
  6873. sink.os << "body";
  6874. } else {
  6875. Headers trailer;
  6876. // A valid trailer that must survive.
  6877. trailer.emplace("X-Safe", "safe");
  6878. // Attacker-controlled value carrying CR/LF (response splitting).
  6879. trailer.emplace("X-Reflected",
  6880. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6881. // Attacker-controlled name carrying CR/LF.
  6882. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6883. sink.done_with_trailer(trailer);
  6884. }
  6885. (*i)++;
  6886. return true;
  6887. },
  6888. [i](bool /*success*/) { delete i; });
  6889. });
  6890. thread t = thread([&] { svr.listen(HOST, PORT); });
  6891. auto se = detail::scope_exit([&] {
  6892. svr.stop();
  6893. t.join();
  6894. ASSERT_FALSE(svr.is_running());
  6895. });
  6896. svr.wait_until_ready();
  6897. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6898. "Host: " + HOST +
  6899. "\r\n"
  6900. "Connection: close\r\n"
  6901. "\r\n";
  6902. std::string res;
  6903. ASSERT_TRUE(send_request(5, req, &res));
  6904. // The injected fields must not appear anywhere in the raw response.
  6905. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6906. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6907. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6908. // Invalid trailers are dropped entirely, matching set_header().
  6909. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6910. // The valid trailer still passes through.
  6911. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6912. }
  6913. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  6914. Server svr;
  6915. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  6916. // res.headers is a public field an application can populate directly,
  6917. // bypassing set_header()'s validation (e.g. reflecting a request value).
  6918. // A valid header that must survive.
  6919. res.headers.emplace("X-Safe", "safe");
  6920. // Attacker-controlled value carrying CR/LF (response splitting).
  6921. res.headers.emplace("X-Reflected",
  6922. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6923. // Attacker-controlled name carrying CR/LF.
  6924. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6925. res.set_content("body", "text/plain");
  6926. });
  6927. thread t = thread([&] { svr.listen(HOST, PORT); });
  6928. auto se = detail::scope_exit([&] {
  6929. svr.stop();
  6930. t.join();
  6931. ASSERT_FALSE(svr.is_running());
  6932. });
  6933. svr.wait_until_ready();
  6934. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  6935. "Host: " + HOST +
  6936. "\r\n"
  6937. "Connection: close\r\n"
  6938. "\r\n";
  6939. std::string res;
  6940. ASSERT_TRUE(send_request(5, req, &res));
  6941. // The injected fields must not appear anywhere in the raw response.
  6942. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6943. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6944. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6945. // Invalid headers are dropped entirely, matching set_header().
  6946. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6947. // The valid header still passes through.
  6948. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6949. }
  6950. // Forward declaration: in split builds split.py strips `inline` and moves the
  6951. // definition into httplib.cc, so detail::write_request_line is not visible from
  6952. // the public httplib.h. Re-declaring it here lets the tests link against the
  6953. // symbol in both header-only and split builds.
  6954. namespace httplib {
  6955. namespace detail {
  6956. ssize_t write_request_line(Stream &strm, const std::string &method,
  6957. const std::string &path);
  6958. } // namespace detail
  6959. } // namespace httplib
  6960. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  6961. // A well-formed target is written verbatim.
  6962. {
  6963. detail::BufferStream strm;
  6964. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  6965. EXPECT_GT(n, 0);
  6966. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  6967. }
  6968. // A target carrying CR/LF must be rejected before anything reaches the wire,
  6969. // otherwise it splits the request line and injects a header or a whole
  6970. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  6971. // when path encoding is disabled.
  6972. const std::string evil_targets[] = {
  6973. "/a\r\nInjected: pwned",
  6974. "/a\rInjected",
  6975. "/a\nInjected",
  6976. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  6977. };
  6978. for (const auto &evil : evil_targets) {
  6979. detail::BufferStream strm;
  6980. auto n = detail::write_request_line(strm, "GET", evil);
  6981. EXPECT_LT(n, 0);
  6982. EXPECT_TRUE(strm.get_buffer().empty());
  6983. }
  6984. }
  6985. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  6986. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  6987. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  6988. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  6989. // client must fail cleanly with Error::Write instead of putting a
  6990. // request-line-less, header-injecting request on the wire.
  6991. Server svr;
  6992. svr.Get("/a", [](const Request &, Response &res) {
  6993. res.set_content("ok", "text/plain");
  6994. });
  6995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6996. auto se = detail::scope_exit([&] {
  6997. svr.stop();
  6998. thread.join();
  6999. ASSERT_FALSE(svr.is_running());
  7000. });
  7001. svr.wait_until_ready();
  7002. {
  7003. Client cli(HOST, PORT);
  7004. cli.set_path_encode(false);
  7005. // The request is rejected before anything is written, so the connection
  7006. // stays silent and the subsequent response read would otherwise block for
  7007. // the full default read timeout. Shorten it -- the assertion is on the
  7008. // error, not the timeout.
  7009. cli.set_read_timeout(1, 0);
  7010. auto res = cli.Get("/a\r\nInjected: pwned");
  7011. EXPECT_FALSE(res);
  7012. EXPECT_EQ(Error::Write, res.error());
  7013. }
  7014. }
  7015. // Sends a raw request and verifies that there isn't a crash or exception.
  7016. static void test_raw_request(const std::string &req,
  7017. std::string *out = nullptr) {
  7018. Server svr;
  7019. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7020. res.set_content("ok", "text/plain");
  7021. });
  7022. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7023. res.set_content("ok", "text/plain");
  7024. });
  7025. svr.Get("/header_field_value_check",
  7026. [&](const Request & /*req*/, Response &res) {
  7027. res.set_content("ok", "text/plain");
  7028. });
  7029. // Server read timeout must be longer than the client read timeout for the
  7030. // bug to reproduce, probably to force the server to process a request
  7031. // without a trailing blank line.
  7032. const time_t client_read_timeout_sec = 1;
  7033. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7034. bool listen_thread_ok = false;
  7035. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7036. auto se = detail::scope_exit([&] {
  7037. svr.stop();
  7038. t.join();
  7039. ASSERT_FALSE(svr.is_running());
  7040. EXPECT_TRUE(listen_thread_ok);
  7041. });
  7042. svr.wait_until_ready();
  7043. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7044. }
  7045. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7046. // A certain header line causes an exception if the header property is parsed
  7047. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7048. test_raw_request(
  7049. "GET /hi HTTP/1.1\r\n"
  7050. " : "
  7051. " "
  7052. " ");
  7053. }
  7054. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7055. // A certain header line causes an exception if the header property *name* is
  7056. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7057. // greedy matcher and requires backtracking when there are a lot of ":"
  7058. // characters.
  7059. // This occurs with libc++ but not libstdc++.
  7060. test_raw_request(
  7061. "GET /hi HTTP/1.1\r\n"
  7062. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7063. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7064. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7065. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7066. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7067. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7068. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7069. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7070. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7071. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7072. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7073. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7074. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7075. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7076. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7077. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7078. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7079. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7080. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7081. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7082. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7083. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7084. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7085. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7086. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7087. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7088. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7089. "&&&%%%");
  7090. }
  7091. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7092. // Make sure this doesn't crash the server.
  7093. // In a previous version of the header line regex, the "\r" rendered the line
  7094. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7095. // a new position where the leading white space ended and the field value
  7096. // began.
  7097. // The crash occurs with libc++ but not libstdc++.
  7098. test_raw_request("GET /hi HTTP/1.1\r\n"
  7099. "a:" +
  7100. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7101. "\r\n"
  7102. "\r\n");
  7103. }
  7104. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7105. std::string out;
  7106. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7107. "Content-Type: text/plain\r\n"
  7108. "Transfer-Encoding: chunked\r\n"
  7109. "\r\n"
  7110. "nothex\r\n",
  7111. &out);
  7112. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7113. }
  7114. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7115. std::string out;
  7116. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7117. "Content-Type: text/plain\r\n"
  7118. "Transfer-Encoding: chunked\r\n"
  7119. "\r\n"
  7120. "3\r\n"
  7121. "xyz\r\n"
  7122. "NaN\r\n",
  7123. &out);
  7124. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7125. }
  7126. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7127. std::string out;
  7128. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7129. "Content-Type: text/plain\r\n"
  7130. "Transfer-Encoding: chunked\r\n"
  7131. "\r\n"
  7132. // Length is too large for 64 bits.
  7133. "1ffffffffffffffff\r\n"
  7134. "xyz\r\n",
  7135. &out);
  7136. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7137. }
  7138. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7139. test_raw_request("GET /hi HTTP/1.1\r\n"
  7140. "Content-Type: text/plain\r\n\r");
  7141. }
  7142. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7143. std::string out;
  7144. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7145. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7146. }
  7147. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7148. Server svr;
  7149. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7150. EXPECT_TRUE(!req.remote_addr.empty());
  7151. });
  7152. thread t = thread([&] { svr.listen(HOST, PORT); });
  7153. auto se = detail::scope_exit([&] {
  7154. svr.stop();
  7155. t.join();
  7156. ASSERT_FALSE(svr.is_running());
  7157. });
  7158. svr.wait_until_ready();
  7159. // Send an invalid request line to trigger Bad Request
  7160. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7161. std::string out;
  7162. ASSERT_TRUE(send_request(5, bad_req, &out));
  7163. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7164. }
  7165. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7166. std::string out;
  7167. std::string request(
  7168. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7169. test_raw_request(request, &out);
  7170. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7171. }
  7172. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7173. std::string out;
  7174. std::string request(
  7175. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7176. test_raw_request(request, &out);
  7177. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7178. }
  7179. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7180. std::string out;
  7181. std::string request(
  7182. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7183. test_raw_request(request, &out);
  7184. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7185. }
  7186. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7187. std::string out;
  7188. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7189. "Test: \r\n\r\n",
  7190. &out);
  7191. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7192. }
  7193. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7194. Server svr;
  7195. std::string x_custom;
  7196. std::string cookie;
  7197. std::string xff;
  7198. std::string x_unicode;
  7199. std::string x_iis;
  7200. svr.Get("/check", [&](const Request &req, Response &res) {
  7201. x_custom = req.get_header_value("X-Custom");
  7202. cookie = req.get_header_value("Cookie");
  7203. xff = req.get_header_value("X-Forwarded-For");
  7204. x_unicode = req.get_header_value("X-Unicode");
  7205. x_iis = req.get_header_value("X-IIS");
  7206. res.set_content("ok", "text/plain");
  7207. });
  7208. thread t = thread([&] { svr.listen(HOST, PORT); });
  7209. auto se = detail::scope_exit([&] {
  7210. svr.stop();
  7211. t.join();
  7212. ASSERT_FALSE(svr.is_running());
  7213. });
  7214. svr.wait_until_ready();
  7215. const std::string req = "GET /check HTTP/1.1\r\n"
  7216. "Host: localhost\r\n"
  7217. "X-Custom: a%0D%0AInjected: b\r\n"
  7218. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7219. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7220. "X-Unicode: %E3%81%82\r\n"
  7221. "X-IIS: %u00E9\r\n"
  7222. "Connection: close\r\n"
  7223. "\r\n";
  7224. std::string res;
  7225. ASSERT_TRUE(send_request(5, req, &res));
  7226. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7227. // Every value must be returned verbatim (wire form), with no decoding.
  7228. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7229. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7230. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7231. EXPECT_EQ("%E3%81%82", x_unicode);
  7232. EXPECT_EQ("%u00E9", x_iis);
  7233. }
  7234. // Applications that previously relied on automatic percent-decoding can
  7235. // reproduce the old behavior by explicitly calling decode_path_component()
  7236. // or, for RFC 3986 conformance, decode_uri_component().
  7237. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7238. Server svr;
  7239. std::string decoded;
  7240. svr.Get("/check", [&](const Request &req, Response &res) {
  7241. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7242. res.set_content("ok", "text/plain");
  7243. });
  7244. thread t = thread([&] { svr.listen(HOST, PORT); });
  7245. auto se = detail::scope_exit([&] {
  7246. svr.stop();
  7247. t.join();
  7248. ASSERT_FALSE(svr.is_running());
  7249. });
  7250. svr.wait_until_ready();
  7251. const std::string req = "GET /check HTTP/1.1\r\n"
  7252. "Host: localhost\r\n"
  7253. "X-Custom: hello%20world\r\n"
  7254. "Connection: close\r\n"
  7255. "\r\n";
  7256. std::string res;
  7257. ASSERT_TRUE(send_request(5, req, &res));
  7258. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7259. EXPECT_EQ("hello world", decoded);
  7260. }
  7261. // Regression test for #2033. Browsers send Referer values that include
  7262. // percent-encoded characters such as %0A inside the URL. Decoding the
  7263. // header value would either trip the post-decode CR/LF/NUL guard (the
  7264. // original bug, returning 400) or, after that guard was relaxed, silently
  7265. // store a literal LF — both unacceptable. The wire form must round-trip.
  7266. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7267. Server svr;
  7268. std::string referer;
  7269. svr.Get("/check", [&](const Request &req, Response &res) {
  7270. referer = req.get_header_value("Referer");
  7271. res.set_content("ok", "text/plain");
  7272. });
  7273. thread t = thread([&] { svr.listen(HOST, PORT); });
  7274. auto se = detail::scope_exit([&] {
  7275. svr.stop();
  7276. t.join();
  7277. ASSERT_FALSE(svr.is_running());
  7278. });
  7279. svr.wait_until_ready();
  7280. const std::string req = "GET /check HTTP/1.1\r\n"
  7281. "Host: localhost\r\n"
  7282. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7283. "Connection: close\r\n"
  7284. "\r\n";
  7285. std::string res;
  7286. ASSERT_TRUE(send_request(5, req, &res));
  7287. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7288. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7289. }
  7290. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7291. Server svr;
  7292. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7293. res.set_header("Cache-Control", "no-cache");
  7294. res.set_chunked_content_provider(
  7295. "text/event-stream", [](size_t offset, DataSink &sink) {
  7296. std::string s = "data:";
  7297. s += std::to_string(offset);
  7298. s += "\n\n";
  7299. auto ret = sink.write(s.data(), s.size());
  7300. EXPECT_TRUE(ret);
  7301. std::this_thread::sleep_for(std::chrono::seconds(1));
  7302. return true;
  7303. });
  7304. });
  7305. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7306. svr.wait_until_ready();
  7307. Client client(HOST, PORT);
  7308. const Headers headers = {{"Accept", "text/event-stream"}};
  7309. auto get_thread = std::thread([&client, &headers]() {
  7310. auto res = client.Get(
  7311. "/events", headers,
  7312. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7313. });
  7314. auto se = detail::scope_exit([&] {
  7315. svr.stop();
  7316. get_thread.join();
  7317. listen_thread.join();
  7318. ASSERT_FALSE(svr.is_running());
  7319. });
  7320. // Give GET time to get a few messages.
  7321. std::this_thread::sleep_for(std::chrono::seconds(2));
  7322. }
  7323. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7324. httplib::Server svr;
  7325. svr.Post("/hi",
  7326. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7327. res.status = StatusCode::OK_200;
  7328. });
  7329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7330. svr.wait_until_ready();
  7331. Client cli(HOST, PORT);
  7332. auto res = cli.Post("/hi", "data", "text/plain");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. svr.stop();
  7336. thread.join();
  7337. ASSERT_FALSE(svr.is_running());
  7338. res = cli.Post("/hi", "data", "text/plain");
  7339. ASSERT_FALSE(res);
  7340. }
  7341. TEST(ServerStopTest, ListenFailure) {
  7342. Server svr;
  7343. auto t = thread([&]() {
  7344. auto ret = svr.listen("????", PORT);
  7345. EXPECT_FALSE(ret);
  7346. });
  7347. svr.wait_until_ready();
  7348. svr.stop();
  7349. t.join();
  7350. }
  7351. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7352. TEST(ServerStopTest, Decommision) {
  7353. Server svr;
  7354. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7355. for (int i = 0; i < 4; i++) {
  7356. auto is_even = !(i % 2);
  7357. std::thread t{[&] {
  7358. try {
  7359. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7360. if (is_even) {
  7361. throw std::runtime_error("Some thing that happens to go wrong.");
  7362. }
  7363. svr.listen(HOST, PORT);
  7364. } catch (...) { svr.decommission(); }
  7365. }};
  7366. svr.wait_until_ready();
  7367. // Server is up
  7368. {
  7369. Client cli(HOST, PORT);
  7370. auto res = cli.Get("/hi");
  7371. if (is_even) {
  7372. EXPECT_FALSE(res);
  7373. } else {
  7374. EXPECT_TRUE(res);
  7375. EXPECT_EQ("hi...", res->body);
  7376. }
  7377. }
  7378. svr.stop();
  7379. t.join();
  7380. // Server is down...
  7381. {
  7382. Client cli(HOST, PORT);
  7383. auto res = cli.Get("/hi");
  7384. EXPECT_FALSE(res);
  7385. }
  7386. }
  7387. }
  7388. #endif
  7389. // Helper function for string body upload progress tests
  7390. template <typename SetupHandler, typename ClientCall>
  7391. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7392. ClientCall &&client_call,
  7393. const string &body) {
  7394. Server svr;
  7395. setup_handler(svr);
  7396. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7397. auto se = detail::scope_exit([&] {
  7398. svr.stop();
  7399. t.join();
  7400. });
  7401. svr.wait_until_ready();
  7402. Client cli(HOST, PORT);
  7403. vector<uint64_t> progress_values;
  7404. bool progress_called = false;
  7405. auto res =
  7406. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7407. progress_values.push_back(current);
  7408. progress_called = true;
  7409. return true;
  7410. });
  7411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7412. EXPECT_EQ(200, res->status);
  7413. EXPECT_TRUE(progress_called);
  7414. }
  7415. TEST(UploadProgressTest, PostStringBodyBasic) {
  7416. TestStringBodyUploadProgress(
  7417. [](Server &svr) {
  7418. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7419. res.set_content("received", "text/plain");
  7420. });
  7421. },
  7422. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7423. return cli.Post("/test", body, "text/plain", progress_callback);
  7424. },
  7425. "test data for upload progress");
  7426. }
  7427. TEST(UploadProgressTest, PutStringBodyBasic) {
  7428. TestStringBodyUploadProgress(
  7429. [](Server &svr) {
  7430. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7431. res.set_content("put received", "text/plain");
  7432. });
  7433. },
  7434. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7435. return cli.Put("/test", body, "text/plain", progress_callback);
  7436. },
  7437. "put test data for upload progress");
  7438. }
  7439. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7440. TestStringBodyUploadProgress(
  7441. [](Server &svr) {
  7442. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7443. res.set_content("patch received", "text/plain");
  7444. });
  7445. },
  7446. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7447. return cli.Patch("/test", body, "text/plain", progress_callback);
  7448. },
  7449. "patch test data for upload progress");
  7450. }
  7451. // Helper function for content provider upload progress tests
  7452. template <typename SetupHandler, typename ClientCall>
  7453. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7454. ClientCall &&client_call) {
  7455. Server svr;
  7456. setup_handler(svr);
  7457. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7458. auto se = detail::scope_exit([&] {
  7459. svr.stop();
  7460. t.join();
  7461. });
  7462. svr.wait_until_ready();
  7463. Client cli(HOST, PORT);
  7464. vector<uint64_t> progress_values;
  7465. auto res =
  7466. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7467. progress_values.push_back(current);
  7468. return true;
  7469. });
  7470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7471. EXPECT_EQ(200, res->status);
  7472. EXPECT_FALSE(progress_values.empty());
  7473. }
  7474. TEST(UploadProgressTest, PostContentProviderProgress) {
  7475. TestContentProviderUploadProgress(
  7476. [](Server &svr) {
  7477. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7478. res.set_content("provider received", "text/plain");
  7479. });
  7480. },
  7481. [](Client &cli, UploadProgress progress_callback) {
  7482. return cli.Post(
  7483. "/test", 10,
  7484. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7485. sink.os << "test data";
  7486. return true;
  7487. },
  7488. "text/plain", progress_callback);
  7489. });
  7490. }
  7491. // Helper function for multipart upload progress tests
  7492. template <typename SetupHandler, typename ClientCall>
  7493. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7494. ClientCall &&client_call,
  7495. const string &endpoint) {
  7496. Server svr;
  7497. setup_handler(svr);
  7498. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7499. auto se = detail::scope_exit([&] {
  7500. svr.stop();
  7501. t.join();
  7502. });
  7503. svr.wait_until_ready();
  7504. Client cli(HOST, PORT);
  7505. vector<uint64_t> progress_values;
  7506. UploadFormDataItems items = {
  7507. {"field1", "value1", "", ""},
  7508. {"field2", "longer value for progress tracking test", "", ""},
  7509. {"file1", "file content data for upload progress", "test.txt",
  7510. "text/plain"}};
  7511. auto res = client_call(cli, endpoint, items,
  7512. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7513. progress_values.push_back(current);
  7514. return true;
  7515. });
  7516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7517. EXPECT_EQ(200, res->status);
  7518. EXPECT_FALSE(progress_values.empty());
  7519. }
  7520. TEST(UploadProgressTest, PostMultipartProgress) {
  7521. TestMultipartUploadProgress(
  7522. [](Server &svr) {
  7523. svr.Post("/multipart", [](const Request &req, Response &res) {
  7524. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7525. res.set_content("multipart received", "text/plain");
  7526. });
  7527. },
  7528. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7529. UploadProgress progress_callback) {
  7530. return cli.Post(endpoint, items, progress_callback);
  7531. },
  7532. "/multipart");
  7533. }
  7534. // Helper function for basic download progress tests
  7535. template <typename SetupHandler, typename ClientCall>
  7536. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7537. ClientCall &&client_call, const string &endpoint,
  7538. size_t expected_content_size) {
  7539. Server svr;
  7540. setup_handler(svr);
  7541. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7542. auto se = detail::scope_exit([&] {
  7543. svr.stop();
  7544. t.join();
  7545. });
  7546. svr.wait_until_ready();
  7547. Client cli(HOST, PORT);
  7548. vector<uint64_t> progress_values;
  7549. auto res = client_call(cli, endpoint,
  7550. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7551. progress_values.push_back(current);
  7552. return true;
  7553. });
  7554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7555. EXPECT_EQ(200, res->status);
  7556. EXPECT_FALSE(progress_values.empty());
  7557. EXPECT_EQ(expected_content_size, res->body.size());
  7558. }
  7559. TEST(DownloadProgressTest, GetBasic) {
  7560. TestBasicDownloadProgress(
  7561. [](Server &svr) {
  7562. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7563. string content(1000, 'D');
  7564. res.set_content(content, "text/plain");
  7565. });
  7566. },
  7567. [](Client &cli, const string &endpoint,
  7568. DownloadProgress progress_callback) {
  7569. return cli.Get(endpoint, progress_callback);
  7570. },
  7571. "/download", 1000u);
  7572. }
  7573. // Helper function for content receiver download progress tests
  7574. template <typename SetupHandler, typename ClientCall>
  7575. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7576. ClientCall &&client_call,
  7577. const string &endpoint,
  7578. size_t expected_content_size) {
  7579. Server svr;
  7580. setup_handler(svr);
  7581. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7582. auto se = detail::scope_exit([&] {
  7583. svr.stop();
  7584. t.join();
  7585. });
  7586. svr.wait_until_ready();
  7587. Client cli(HOST, PORT);
  7588. vector<uint64_t> progress_values;
  7589. string received_body;
  7590. auto res = client_call(
  7591. cli, endpoint,
  7592. [&](const char *data, size_t data_length) -> bool {
  7593. received_body.append(data, data_length);
  7594. return true;
  7595. },
  7596. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7597. progress_values.push_back(current);
  7598. return true;
  7599. });
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(200, res->status);
  7602. EXPECT_FALSE(progress_values.empty());
  7603. EXPECT_EQ(expected_content_size, received_body.size());
  7604. EXPECT_TRUE(res->body.empty());
  7605. }
  7606. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7607. TestContentReceiverDownloadProgress(
  7608. [](Server &svr) {
  7609. svr.Get("/download-receiver",
  7610. [](const Request & /*req*/, Response &res) {
  7611. string content(2000, 'R');
  7612. res.set_content(content, "text/plain");
  7613. });
  7614. },
  7615. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7616. DownloadProgress progress_callback) {
  7617. return cli.Get(endpoint, content_receiver, progress_callback);
  7618. },
  7619. "/download-receiver", 2000u);
  7620. }
  7621. TEST(StreamingTest, NoContentLengthStreaming) {
  7622. Server svr;
  7623. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7624. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7625. if (offset < 6) {
  7626. sink.os << (offset < 3 ? "a" : "b");
  7627. } else {
  7628. sink.done();
  7629. }
  7630. return true;
  7631. });
  7632. });
  7633. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7634. auto listen_se = detail::scope_exit([&] {
  7635. svr.stop();
  7636. listen_thread.join();
  7637. ASSERT_FALSE(svr.is_running());
  7638. });
  7639. svr.wait_until_ready();
  7640. Client client(HOST, PORT);
  7641. auto get_thread = std::thread([&client]() {
  7642. std::string s;
  7643. auto res =
  7644. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7645. s += std::string(data, len);
  7646. return true;
  7647. });
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. EXPECT_EQ("aaabbb", s);
  7651. });
  7652. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7653. // Give GET time to get a few messages.
  7654. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7655. }
  7656. TEST(MountTest, Unmount) {
  7657. Server svr;
  7658. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7659. auto se = detail::scope_exit([&] {
  7660. svr.stop();
  7661. listen_thread.join();
  7662. ASSERT_FALSE(svr.is_running());
  7663. });
  7664. svr.wait_until_ready();
  7665. Client cli("localhost", PORT);
  7666. svr.set_mount_point("/mount2", "./www2");
  7667. auto res = cli.Get("/");
  7668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7669. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7670. res = cli.Get("/mount2/dir/test.html");
  7671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7672. EXPECT_EQ(StatusCode::OK_200, res->status);
  7673. svr.set_mount_point("/", "./www");
  7674. res = cli.Get("/dir/");
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::OK_200, res->status);
  7677. svr.remove_mount_point("/");
  7678. res = cli.Get("/dir/");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7681. svr.remove_mount_point("/mount2");
  7682. res = cli.Get("/mount2/dir/test.html");
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7685. }
  7686. TEST(MountTest, Redicect) {
  7687. Server svr;
  7688. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7689. auto se = detail::scope_exit([&] {
  7690. svr.stop();
  7691. listen_thread.join();
  7692. ASSERT_FALSE(svr.is_running());
  7693. });
  7694. svr.set_mount_point("/", "./www");
  7695. svr.wait_until_ready();
  7696. Client cli("localhost", PORT);
  7697. auto res = cli.Get("/dir/");
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. res = cli.Get("/dir");
  7701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7702. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7703. res = cli.Get("/file");
  7704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7705. EXPECT_EQ(StatusCode::OK_200, res->status);
  7706. res = cli.Get("/file/");
  7707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7709. cli.set_follow_location(true);
  7710. res = cli.Get("/dir");
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::OK_200, res->status);
  7713. }
  7714. TEST(MountTest, MultibytesPathName) {
  7715. Server svr;
  7716. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7717. auto se = detail::scope_exit([&] {
  7718. svr.stop();
  7719. listen_thread.join();
  7720. ASSERT_FALSE(svr.is_running());
  7721. });
  7722. svr.set_mount_point("/", "./www");
  7723. svr.wait_until_ready();
  7724. Client cli("localhost", PORT);
  7725. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7727. EXPECT_EQ(StatusCode::OK_200, res->status);
  7728. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7729. }
  7730. #ifdef _WIN32
  7731. // Issue #2435: mmap::open() must succeed even when another handle holds
  7732. // the file open for writing (e.g. an active log file).
  7733. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7734. const char *path = "mmap_concurrent_writer_test.txt";
  7735. const char *content = "hello";
  7736. {
  7737. std::ofstream f(path, std::ios::binary);
  7738. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7739. }
  7740. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7741. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7742. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7743. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7744. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7745. detail::mmap m(path);
  7746. ASSERT_TRUE(m.is_open());
  7747. EXPECT_EQ(strlen(content), m.size());
  7748. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7749. }
  7750. #endif
  7751. #ifndef _WIN32
  7752. // A failed ::mmap must not be reported as an open mapping. is_open() only
  7753. // compares addr_ against nullptr, so the MAP_FAILED sentinel used to pass it
  7754. // and data() handed the caller (const char *)-1. A directory opens and stats
  7755. // fine but has no mapping, so ::mmap fails for it.
  7756. TEST(MmapTest, FailedMappingIsNotOpen) {
  7757. const char *path = "./mmap_failed_mapping_test_dir";
  7758. ASSERT_EQ(0, ::mkdir(path, 0755));
  7759. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  7760. detail::mmap m(path);
  7761. EXPECT_FALSE(m.is_open());
  7762. EXPECT_NE(static_cast<const void *>(m.data()),
  7763. static_cast<const void *>(MAP_FAILED));
  7764. }
  7765. #endif
  7766. TEST(KeepAliveTest, ReadTimeout) {
  7767. Server svr;
  7768. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7769. std::this_thread::sleep_for(std::chrono::seconds(2));
  7770. res.set_content("a", "text/plain");
  7771. });
  7772. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7773. res.set_content("b", "text/plain");
  7774. });
  7775. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7776. auto se = detail::scope_exit([&] {
  7777. svr.stop();
  7778. listen_thread.join();
  7779. ASSERT_FALSE(svr.is_running());
  7780. });
  7781. svr.wait_until_ready();
  7782. Client cli("localhost", PORT);
  7783. cli.set_keep_alive(true);
  7784. cli.set_read_timeout(std::chrono::seconds(1));
  7785. auto resa = cli.Get("/a");
  7786. ASSERT_FALSE(resa);
  7787. EXPECT_EQ(Error::Read, resa.error());
  7788. auto resb = cli.Get("/b");
  7789. ASSERT_TRUE(resb);
  7790. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7791. EXPECT_EQ("b", resb->body);
  7792. }
  7793. TEST(KeepAliveTest, MaxCount) {
  7794. size_t keep_alive_max_count = 3;
  7795. Server svr;
  7796. svr.set_keep_alive_max_count(keep_alive_max_count);
  7797. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7798. res.set_content("Hello World!", "text/plain");
  7799. });
  7800. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7801. auto se = detail::scope_exit([&] {
  7802. svr.stop();
  7803. listen_thread.join();
  7804. ASSERT_FALSE(svr.is_running());
  7805. });
  7806. svr.wait_until_ready();
  7807. Client cli(HOST, PORT);
  7808. cli.set_keep_alive(true);
  7809. for (size_t i = 0; i < 5; i++) {
  7810. auto result = cli.Get("/hi");
  7811. ASSERT_TRUE(result);
  7812. EXPECT_EQ(StatusCode::OK_200, result->status);
  7813. if (i == keep_alive_max_count - 1) {
  7814. EXPECT_EQ("close", result->get_header_value("Connection"));
  7815. } else {
  7816. EXPECT_FALSE(result->has_header("Connection"));
  7817. }
  7818. }
  7819. }
  7820. TEST(KeepAliveTest, Issue1041) {
  7821. Server svr;
  7822. svr.set_keep_alive_timeout(3);
  7823. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7824. res.set_content("Hello World!", "text/plain");
  7825. });
  7826. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7827. auto se = detail::scope_exit([&] {
  7828. svr.stop();
  7829. listen_thread.join();
  7830. ASSERT_FALSE(svr.is_running());
  7831. });
  7832. svr.wait_until_ready();
  7833. Client cli(HOST, PORT);
  7834. cli.set_keep_alive(true);
  7835. auto result = cli.Get("/hi");
  7836. ASSERT_TRUE(result);
  7837. EXPECT_EQ(StatusCode::OK_200, result->status);
  7838. std::this_thread::sleep_for(std::chrono::seconds(5));
  7839. result = cli.Get("/hi");
  7840. ASSERT_TRUE(result);
  7841. EXPECT_EQ(StatusCode::OK_200, result->status);
  7842. }
  7843. TEST(KeepAliveTest, Issue1959) {
  7844. Server svr;
  7845. svr.set_keep_alive_timeout(5);
  7846. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7847. res.set_content("a", "text/plain");
  7848. });
  7849. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7850. auto se = detail::scope_exit([&] {
  7851. if (!svr.is_running()) return;
  7852. svr.stop();
  7853. listen_thread.join();
  7854. ASSERT_FALSE(svr.is_running());
  7855. });
  7856. svr.wait_until_ready();
  7857. Client cli("localhost", PORT);
  7858. cli.set_keep_alive(true);
  7859. using namespace std::chrono;
  7860. auto start = steady_clock::now();
  7861. cli.Get("/a");
  7862. svr.stop();
  7863. listen_thread.join();
  7864. auto end = steady_clock::now();
  7865. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7866. EXPECT_LT(elapsed, 5000);
  7867. }
  7868. #ifdef CPPHTTPLIB_SSL_ENABLED
  7869. TEST(KeepAliveTest, SSLClientReconnection) {
  7870. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7871. ASSERT_TRUE(svr.is_valid());
  7872. svr.set_keep_alive_timeout(1);
  7873. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7874. res.set_content("Hello World!", "text/plain");
  7875. });
  7876. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7877. auto se = detail::scope_exit([&] {
  7878. svr.stop();
  7879. listen_thread.join();
  7880. ASSERT_FALSE(svr.is_running());
  7881. });
  7882. svr.wait_until_ready();
  7883. SSLClient cli(HOST, PORT);
  7884. cli.enable_server_certificate_verification(false);
  7885. cli.set_keep_alive(true);
  7886. auto result = cli.Get("/hi");
  7887. ASSERT_TRUE(result);
  7888. EXPECT_EQ(StatusCode::OK_200, result->status);
  7889. result = cli.Get("/hi");
  7890. ASSERT_TRUE(result);
  7891. EXPECT_EQ(StatusCode::OK_200, result->status);
  7892. std::this_thread::sleep_for(std::chrono::seconds(2));
  7893. // Recoonect
  7894. result = cli.Get("/hi");
  7895. ASSERT_TRUE(result);
  7896. EXPECT_EQ(StatusCode::OK_200, result->status);
  7897. result = cli.Get("/hi");
  7898. ASSERT_TRUE(result);
  7899. EXPECT_EQ(StatusCode::OK_200, result->status);
  7900. }
  7901. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7903. ASSERT_TRUE(svr.is_valid());
  7904. svr.set_keep_alive_timeout(1);
  7905. std::string content = "reconnect";
  7906. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7907. res.set_content("Hello World!", "text/plain");
  7908. });
  7909. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7910. auto se = detail::scope_exit([&] {
  7911. svr.stop();
  7912. listen_thread.join();
  7913. ASSERT_FALSE(svr.is_running());
  7914. });
  7915. svr.wait_until_ready();
  7916. SSLClient cli(HOST, PORT);
  7917. cli.enable_server_certificate_verification(false);
  7918. cli.set_keep_alive(true);
  7919. auto result = cli.Post(
  7920. "/hi", content.size(),
  7921. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7922. sink.write(content.c_str(), content.size());
  7923. return true;
  7924. },
  7925. "text/plain");
  7926. ASSERT_TRUE(result);
  7927. EXPECT_EQ(200, result->status);
  7928. std::this_thread::sleep_for(std::chrono::seconds(2));
  7929. // Recoonect
  7930. result = cli.Post(
  7931. "/hi", content.size(),
  7932. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7933. sink.write(content.c_str(), content.size());
  7934. return true;
  7935. },
  7936. "text/plain");
  7937. ASSERT_TRUE(result);
  7938. EXPECT_EQ(200, result->status);
  7939. result = cli.Post(
  7940. "/hi", content.size(),
  7941. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7942. sink.write(content.c_str(), content.size());
  7943. return true;
  7944. },
  7945. "text/plain");
  7946. ASSERT_TRUE(result);
  7947. EXPECT_EQ(200, result->status);
  7948. }
  7949. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7950. using namespace httplib::tls;
  7951. {
  7952. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7953. ASSERT_TRUE(svr.is_valid());
  7954. svr.Get("/sni", [&](const Request &req, Response &res) {
  7955. std::string expected = req.sni();
  7956. EXPECT_EQ(expected, req.get_param_value("expected"));
  7957. res.set_content("ok", "text/plain");
  7958. });
  7959. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7960. auto se = detail::scope_exit([&] {
  7961. svr.stop();
  7962. listen_thread.join();
  7963. ASSERT_FALSE(svr.is_running());
  7964. });
  7965. svr.wait_until_ready();
  7966. {
  7967. SSLClient cli("localhost", PORT);
  7968. cli.enable_server_certificate_verification(false);
  7969. auto res = cli.Get("/sni?expected=localhost");
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. }
  7972. {
  7973. SSLClient cli("::1", PORT);
  7974. cli.enable_server_certificate_verification(false);
  7975. auto res = cli.Get("/sni?expected=");
  7976. // NOTE: This may fail if the server is listening on IPv4 only
  7977. // (e.g., when localhost resolves to 127.0.0.1 only)
  7978. if (res) {
  7979. EXPECT_EQ(StatusCode::OK_200, res->status);
  7980. } else {
  7981. EXPECT_EQ(Error::Connection, res.error());
  7982. }
  7983. }
  7984. }
  7985. }
  7986. #endif
  7987. TEST(ClientProblemDetectionTest, ContentProvider) {
  7988. Server svr;
  7989. size_t content_length = 1024 * 1024;
  7990. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7991. res.set_content_provider(
  7992. content_length, "text/plain",
  7993. [&](size_t offset, size_t length, DataSink &sink) {
  7994. auto out_len = std::min(length, static_cast<size_t>(1024));
  7995. std::string out(out_len, '@');
  7996. sink.write(out.data(), out_len);
  7997. return offset < 4096;
  7998. },
  7999. [](bool success) { ASSERT_FALSE(success); });
  8000. });
  8001. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8002. res.set_content_provider(
  8003. 0, "text/plain",
  8004. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8005. EXPECT_TRUE(false);
  8006. return true;
  8007. },
  8008. [](bool success) { ASSERT_FALSE(success); });
  8009. });
  8010. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8011. auto se = detail::scope_exit([&] {
  8012. svr.stop();
  8013. listen_thread.join();
  8014. ASSERT_FALSE(svr.is_running());
  8015. });
  8016. svr.wait_until_ready();
  8017. Client cli("localhost", PORT);
  8018. {
  8019. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8020. size_t /*data_length*/) { return false; });
  8021. ASSERT_FALSE(res);
  8022. }
  8023. {
  8024. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8025. size_t /*data_length*/) { return false; });
  8026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8027. }
  8028. }
  8029. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8030. Server svr;
  8031. svr.set_error_handler([](Request const &, Response &res) -> void {
  8032. res.set_chunked_content_provider(
  8033. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8034. sink.os << "hello";
  8035. sink.os << "world";
  8036. sink.done();
  8037. return true;
  8038. });
  8039. });
  8040. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8041. auto se = detail::scope_exit([&] {
  8042. svr.stop();
  8043. listen_thread.join();
  8044. ASSERT_FALSE(svr.is_running());
  8045. });
  8046. svr.wait_until_ready();
  8047. Client cli("localhost", PORT);
  8048. auto res = cli.Get("/");
  8049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8050. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8051. EXPECT_EQ("helloworld", res->body);
  8052. }
  8053. TEST(LongPollingTest, ClientCloseDetection) {
  8054. Server svr;
  8055. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8056. res.set_chunked_content_provider(
  8057. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8058. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8059. sink.os << "hello";
  8060. auto count = 10;
  8061. while (count > 0 && sink.is_writable()) {
  8062. this_thread::sleep_for(chrono::milliseconds(10));
  8063. count--;
  8064. }
  8065. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8066. return true;
  8067. });
  8068. });
  8069. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8070. auto se = detail::scope_exit([&] {
  8071. svr.stop();
  8072. listen_thread.join();
  8073. ASSERT_FALSE(svr.is_running());
  8074. });
  8075. svr.wait_until_ready();
  8076. Client cli("localhost", PORT);
  8077. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8078. EXPECT_EQ("hello", string(data, data_length));
  8079. return false; // close the socket immediately.
  8080. });
  8081. ASSERT_FALSE(res);
  8082. }
  8083. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8084. Server svr;
  8085. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8086. res.set_chunked_content_provider(
  8087. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8088. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8089. sink.os << "hello";
  8090. EXPECT_TRUE(sink.os.good());
  8091. // Wait for the client to close the connection
  8092. auto count = 10;
  8093. while (count > 0 && sink.is_writable()) {
  8094. this_thread::sleep_for(chrono::milliseconds(10));
  8095. count--;
  8096. }
  8097. // After client disconnect, write repeatedly until the socket
  8098. // write actually fails (small writes may be absorbed by the
  8099. // kernel buffer)
  8100. std::string chunk(1024, 'x');
  8101. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8102. sink.os << chunk;
  8103. }
  8104. EXPECT_TRUE(sink.os.fail());
  8105. return true;
  8106. });
  8107. });
  8108. auto port = svr.bind_to_any_port("localhost");
  8109. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8110. auto se = detail::scope_exit([&] {
  8111. svr.stop();
  8112. listen_thread.join();
  8113. ASSERT_FALSE(svr.is_running());
  8114. });
  8115. svr.wait_until_ready();
  8116. Client cli("localhost", port);
  8117. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8118. EXPECT_EQ("hello", string(data, data_length));
  8119. return false; // close the socket immediately.
  8120. });
  8121. ASSERT_FALSE(res);
  8122. }
  8123. TEST(GetWithParametersTest, GetWithParameters) {
  8124. Server svr;
  8125. svr.Get("/", [&](const Request &req, Response &) {
  8126. EXPECT_EQ("world", req.get_param_value("hello"));
  8127. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8128. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8129. });
  8130. svr.Get("/params", [&](const Request &req, Response &) {
  8131. EXPECT_EQ("world", req.get_param_value("hello"));
  8132. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8133. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8134. });
  8135. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8136. EXPECT_EQ("resource-id", req.matches[1]);
  8137. EXPECT_EQ("foo", req.get_param_value("param1"));
  8138. EXPECT_EQ("bar", req.get_param_value("param2"));
  8139. });
  8140. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8141. EXPECT_EQ("user-id", req.path_params.at("id"));
  8142. EXPECT_EQ("foo", req.get_param_value("param1"));
  8143. EXPECT_EQ("bar", req.get_param_value("param2"));
  8144. });
  8145. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8146. auto se = detail::scope_exit([&] {
  8147. svr.stop();
  8148. listen_thread.join();
  8149. ASSERT_FALSE(svr.is_running());
  8150. });
  8151. svr.wait_until_ready();
  8152. {
  8153. Client cli(HOST, PORT);
  8154. Params params;
  8155. params.emplace("hello", "world");
  8156. params.emplace("hello2", "world2");
  8157. params.emplace("hello3", "world3");
  8158. auto res = cli.Get("/", params, Headers{});
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::OK_200, res->status);
  8161. }
  8162. {
  8163. Client cli(HOST, PORT);
  8164. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8166. EXPECT_EQ(StatusCode::OK_200, res->status);
  8167. }
  8168. {
  8169. Client cli(HOST, PORT);
  8170. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ(StatusCode::OK_200, res->status);
  8173. }
  8174. {
  8175. Client cli(HOST, PORT);
  8176. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. }
  8180. }
  8181. TEST(GetWithParametersTest, GetWithParameters2) {
  8182. Server svr;
  8183. svr.Get("/", [&](const Request &req, Response &res) {
  8184. auto text = req.get_param_value("hello");
  8185. res.set_content(text, "text/plain");
  8186. });
  8187. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8188. auto se = detail::scope_exit([&] {
  8189. svr.stop();
  8190. listen_thread.join();
  8191. ASSERT_FALSE(svr.is_running());
  8192. });
  8193. svr.wait_until_ready();
  8194. Client cli("localhost", PORT);
  8195. Params params;
  8196. params.emplace("hello", "world");
  8197. std::string body;
  8198. auto res = cli.Get("/", params, Headers{},
  8199. [&](const char *data, size_t data_length) {
  8200. body.append(data, data_length);
  8201. return true;
  8202. });
  8203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8204. EXPECT_EQ(StatusCode::OK_200, res->status);
  8205. EXPECT_EQ("world", body);
  8206. }
  8207. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8208. Server svr;
  8209. svr.Get("/search", [&](const Request &req, Response &res) {
  8210. auto q = req.get_param_value("q");
  8211. res.set_content(q, "text/plain");
  8212. });
  8213. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8214. auto se = detail::scope_exit([&] {
  8215. svr.stop();
  8216. listen_thread.join();
  8217. ASSERT_FALSE(svr.is_running());
  8218. });
  8219. svr.wait_until_ready();
  8220. Client cli("localhost", PORT);
  8221. // Verify that Get(path, params) works without requiring Headers argument
  8222. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. EXPECT_EQ("cpp-httplib", res->body);
  8226. }
  8227. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8228. auto host = "httpbingo.org";
  8229. auto path = std::string{"/range/32"};
  8230. #ifdef CPPHTTPLIB_SSL_ENABLED
  8231. SSLClient cli(host);
  8232. #else
  8233. Client cli(host);
  8234. #endif
  8235. cli.set_default_headers({make_range_header({{1, 10}})});
  8236. cli.set_connection_timeout(5);
  8237. {
  8238. auto res = cli.Get(path);
  8239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8240. EXPECT_EQ("bcdefghijk", res->body);
  8241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8242. }
  8243. {
  8244. auto res = cli.Get(path);
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ("bcdefghijk", res->body);
  8247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8248. }
  8249. }
  8250. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8251. Server svr;
  8252. svr.set_default_headers({{"Hello", "World"}});
  8253. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8254. res.set_content("ok", "text/plain");
  8255. });
  8256. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8257. auto se = detail::scope_exit([&] {
  8258. svr.stop();
  8259. listen_thread.join();
  8260. ASSERT_FALSE(svr.is_running());
  8261. });
  8262. svr.wait_until_ready();
  8263. Client cli("localhost", PORT);
  8264. auto res = cli.Get("/");
  8265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8266. EXPECT_EQ(StatusCode::OK_200, res->status);
  8267. EXPECT_EQ("ok", res->body);
  8268. EXPECT_EQ("World", res->get_header_value("Hello"));
  8269. }
  8270. #ifdef CPPHTTPLIB_SSL_ENABLED
  8271. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8273. ASSERT_TRUE(svr.is_valid());
  8274. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8275. std::this_thread::sleep_for(std::chrono::seconds(2));
  8276. res.set_content("a", "text/plain");
  8277. });
  8278. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8279. res.set_content("b", "text/plain");
  8280. });
  8281. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8282. auto se = detail::scope_exit([&] {
  8283. svr.stop();
  8284. listen_thread.join();
  8285. ASSERT_FALSE(svr.is_running());
  8286. });
  8287. svr.wait_until_ready();
  8288. SSLClient cli("localhost", PORT);
  8289. cli.enable_server_certificate_verification(false);
  8290. cli.set_keep_alive(true);
  8291. cli.set_read_timeout(std::chrono::seconds(1));
  8292. auto resa = cli.Get("/a");
  8293. ASSERT_TRUE(!resa);
  8294. EXPECT_EQ(Error::Read, resa.error());
  8295. auto resb = cli.Get("/b");
  8296. ASSERT_TRUE(resb);
  8297. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8298. EXPECT_EQ("b", resb->body);
  8299. }
  8300. #endif
  8301. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8302. protected:
  8303. ServerTestWithAI_PASSIVE()
  8304. : cli_(HOST, PORT)
  8305. #ifdef CPPHTTPLIB_SSL_ENABLED
  8306. ,
  8307. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8308. #endif
  8309. {
  8310. #ifdef CPPHTTPLIB_SSL_ENABLED
  8311. cli_.enable_server_certificate_verification(false);
  8312. #endif
  8313. }
  8314. virtual void SetUp() {
  8315. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8316. res.set_content("Hello World!", "text/plain");
  8317. });
  8318. t_ = thread(
  8319. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8320. svr_.wait_until_ready();
  8321. }
  8322. virtual void TearDown() {
  8323. svr_.stop();
  8324. t_.join();
  8325. }
  8326. #ifdef CPPHTTPLIB_SSL_ENABLED
  8327. SSLClient cli_;
  8328. SSLServer svr_;
  8329. #else
  8330. Client cli_;
  8331. Server svr_;
  8332. #endif
  8333. thread t_;
  8334. };
  8335. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8336. auto res = cli_.Get("/hi");
  8337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8338. EXPECT_EQ(StatusCode::OK_200, res->status);
  8339. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8340. EXPECT_EQ("Hello World!", res->body);
  8341. }
  8342. class ServerUpDownTest : public ::testing::Test {
  8343. protected:
  8344. ServerUpDownTest() : cli_(HOST, PORT) {}
  8345. virtual void SetUp() {
  8346. t_ = thread([&]() {
  8347. svr_.bind_to_any_port(HOST);
  8348. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8349. ASSERT_TRUE(svr_.listen_after_bind());
  8350. });
  8351. svr_.wait_until_ready();
  8352. }
  8353. virtual void TearDown() {
  8354. svr_.stop();
  8355. t_.join();
  8356. }
  8357. Client cli_;
  8358. Server svr_;
  8359. thread t_;
  8360. };
  8361. TEST_F(ServerUpDownTest, QuickStartStop) {
  8362. // Should not crash, especially when run with
  8363. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8364. }
  8365. class PayloadMaxLengthTest : public ::testing::Test {
  8366. protected:
  8367. PayloadMaxLengthTest()
  8368. : cli_(HOST, PORT)
  8369. #ifdef CPPHTTPLIB_SSL_ENABLED
  8370. ,
  8371. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8372. #endif
  8373. {
  8374. #ifdef CPPHTTPLIB_SSL_ENABLED
  8375. cli_.enable_server_certificate_verification(false);
  8376. #endif
  8377. }
  8378. virtual void SetUp() {
  8379. svr_.set_payload_max_length(8);
  8380. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8381. res.set_content("test", "text/plain");
  8382. });
  8383. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8384. svr_.wait_until_ready();
  8385. }
  8386. virtual void TearDown() {
  8387. svr_.stop();
  8388. t_.join();
  8389. }
  8390. #ifdef CPPHTTPLIB_SSL_ENABLED
  8391. SSLClient cli_;
  8392. SSLServer svr_;
  8393. #else
  8394. Client cli_;
  8395. Server svr_;
  8396. #endif
  8397. thread t_;
  8398. };
  8399. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8400. auto res = cli_.Post("/test", "123456789", "text/plain");
  8401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8402. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8403. res = cli_.Post("/test", "12345678", "text/plain");
  8404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8405. EXPECT_EQ(StatusCode::OK_200, res->status);
  8406. }
  8407. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8408. // Test chunked encoding with payload exceeding the 8-byte limit
  8409. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8410. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8413. }
  8414. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8415. // Test chunked encoding with payload within the 8-byte limit
  8416. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8417. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8419. EXPECT_EQ(StatusCode::OK_200, res->status);
  8420. }
  8421. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8422. // Test using send_request to send chunked data exceeding payload limit
  8423. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8424. "Host: " +
  8425. std::string(HOST) + ":" + std::to_string(PORT) +
  8426. "\r\n"
  8427. "Transfer-Encoding: chunked\r\n"
  8428. "Connection: close\r\n"
  8429. "\r\n"
  8430. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8431. "0123456789\r\n"
  8432. "0\r\n" // End chunk
  8433. "\r\n";
  8434. std::string response;
  8435. bool result = send_request(1, chunked_request, &response);
  8436. if (!result) {
  8437. // If send_request fails, it might be because the server closed the
  8438. // connection due to payload limit enforcement, which is acceptable
  8439. SUCCEED()
  8440. << "Server rejected oversized chunked request (connection closed)";
  8441. } else {
  8442. // If we got a response, check if it's an error response or connection was
  8443. // closed early Short response length indicates connection was closed due to
  8444. // payload limit
  8445. if (response.length() <= 10) {
  8446. SUCCEED() << "Server closed connection for oversized chunked request";
  8447. } else {
  8448. // Check for error status codes
  8449. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8450. response.find("Payload Too Large") != std::string::npos ||
  8451. response.find("400") != std::string::npos);
  8452. }
  8453. }
  8454. }
  8455. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8456. // Test request without Content-Length header exceeding payload limit
  8457. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8458. "Host: " +
  8459. std::string(HOST) + ":" +
  8460. std::to_string(PORT) +
  8461. "\r\n"
  8462. "Connection: close\r\n"
  8463. "\r\n";
  8464. // Add payload exceeding the 8-byte limit
  8465. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8466. request_without_content_length += large_payload;
  8467. std::string response;
  8468. bool result = send_request(1, request_without_content_length, &response);
  8469. if (!result) {
  8470. // If send_request fails, server likely closed connection due to payload
  8471. // limit
  8472. SUCCEED() << "Server rejected oversized request without Content-Length "
  8473. "(connection closed)";
  8474. } else {
  8475. // Check if server responded with error or closed connection early
  8476. if (response.length() <= 10) {
  8477. SUCCEED() << "Server closed connection for oversized request without "
  8478. "Content-Length";
  8479. } else {
  8480. // Check for error status codes
  8481. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8482. response.find("Payload Too Large") != std::string::npos ||
  8483. response.find("400") != std::string::npos);
  8484. }
  8485. }
  8486. }
  8487. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8488. // Test request without Content-Length header within payload limit
  8489. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8490. "Host: " +
  8491. std::string(HOST) + ":" +
  8492. std::to_string(PORT) +
  8493. "\r\n"
  8494. "Connection: close\r\n"
  8495. "\r\n";
  8496. // Add payload within the 8-byte limit
  8497. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8498. request_without_content_length += small_payload;
  8499. std::string response;
  8500. bool result = send_request(1, request_without_content_length, &response);
  8501. // For requests without Content-Length, the server may have different behavior
  8502. // The key is that it should not reject due to payload limit for small
  8503. // payloads
  8504. if (result) {
  8505. // Check for any HTTP response (success or error, but not connection closed)
  8506. if (response.length() > 10) {
  8507. SUCCEED()
  8508. << "Server processed request without Content-Length within limit";
  8509. } else {
  8510. // Short response might indicate connection closed, which is acceptable
  8511. SUCCEED() << "Server closed connection for request without "
  8512. "Content-Length (acceptable behavior)";
  8513. }
  8514. } else {
  8515. // Connection failure might be due to protocol requirements
  8516. SUCCEED() << "Connection issue with request without Content-Length "
  8517. "(environment-specific)";
  8518. }
  8519. }
  8520. class LargePayloadMaxLengthTest : public ::testing::Test {
  8521. protected:
  8522. LargePayloadMaxLengthTest()
  8523. : cli_(HOST, PORT)
  8524. #ifdef CPPHTTPLIB_SSL_ENABLED
  8525. ,
  8526. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8527. #endif
  8528. {
  8529. #ifdef CPPHTTPLIB_SSL_ENABLED
  8530. cli_.enable_server_certificate_verification(false);
  8531. #endif
  8532. }
  8533. virtual void SetUp() {
  8534. // Set 10MB payload limit
  8535. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8536. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8537. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8538. res.set_content("Large payload test", "text/plain");
  8539. });
  8540. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8541. svr_.wait_until_ready();
  8542. }
  8543. virtual void TearDown() {
  8544. svr_.stop();
  8545. t_.join();
  8546. }
  8547. #ifdef CPPHTTPLIB_SSL_ENABLED
  8548. SSLClient cli_;
  8549. SSLServer svr_;
  8550. #else
  8551. Client cli_;
  8552. Server svr_;
  8553. #endif
  8554. thread t_;
  8555. };
  8556. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8557. // Test chunked encoding with payload within 10MB limit
  8558. std::string medium_payload(5 * 1024 * 1024,
  8559. 'A'); // 5MB payload, within 10MB limit
  8560. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. }
  8564. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8565. // Test chunked encoding with payload exceeding 10MB limit
  8566. std::string large_payload(12 * 1024 * 1024,
  8567. 'B'); // 12MB payload, exceeds 10MB limit
  8568. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8569. // Server may either return 413 or close the connection
  8570. if (res) {
  8571. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8572. } else {
  8573. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8574. }
  8575. }
  8576. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8577. // Test request without Content-Length header within 10MB limit
  8578. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8579. "Host: " +
  8580. std::string(HOST) + ":" +
  8581. std::to_string(PORT) +
  8582. "\r\n"
  8583. "Connection: close\r\n"
  8584. "\r\n";
  8585. // Add 1MB payload (within 10MB limit)
  8586. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8587. request_without_content_length += medium_payload;
  8588. std::string response;
  8589. bool result = send_request(5, request_without_content_length, &response);
  8590. if (result) {
  8591. // Should get a proper HTTP response for payloads within limit
  8592. if (response.length() > 10) {
  8593. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8594. "10MB limit";
  8595. } else {
  8596. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8597. "Content-Length)";
  8598. }
  8599. } else {
  8600. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8601. }
  8602. }
  8603. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8604. // Test request without Content-Length header exceeding 10MB limit
  8605. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8606. "Host: " +
  8607. std::string(HOST) + ":" +
  8608. std::to_string(PORT) +
  8609. "\r\n"
  8610. "Connection: close\r\n"
  8611. "\r\n";
  8612. // Add 12MB payload (exceeds 10MB limit)
  8613. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8614. request_without_content_length += large_payload;
  8615. std::string response;
  8616. bool result = send_request(10, request_without_content_length, &response);
  8617. if (!result) {
  8618. // Server should close connection due to payload limit
  8619. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8620. "(connection closed)";
  8621. } else {
  8622. // Check for error response
  8623. if (response.length() <= 10) {
  8624. SUCCEED()
  8625. << "Server closed connection for 12MB request exceeding 10MB limit";
  8626. } else {
  8627. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8628. response.find("Payload Too Large") != std::string::npos ||
  8629. response.find("400") != std::string::npos);
  8630. }
  8631. }
  8632. }
  8633. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8634. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8635. // path.
  8636. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8637. Server svr;
  8638. const size_t LIMIT = 64 * 1024; // 64KB
  8639. svr.set_payload_max_length(LIMIT);
  8640. size_t total = 0;
  8641. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8642. const ContentReader &content_reader) {
  8643. content_reader([&](const char * /*data*/, size_t len) {
  8644. total += len;
  8645. return true;
  8646. });
  8647. res.status = 200;
  8648. res.set_content("stream_ok", "text/plain");
  8649. });
  8650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8651. auto se = detail::scope_exit([&] {
  8652. svr.stop();
  8653. thread.join();
  8654. ASSERT_FALSE(svr.is_running());
  8655. });
  8656. svr.wait_until_ready();
  8657. // Prepare 256KB raw data and gzip-compress it
  8658. std::string raw(256 * 1024, 'A');
  8659. std::string gz;
  8660. {
  8661. z_stream zs{};
  8662. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8663. Z_DEFAULT_STRATEGY);
  8664. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8665. zs.avail_in = static_cast<uInt>(raw.size());
  8666. char outbuf[4096];
  8667. int ret;
  8668. do {
  8669. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8670. zs.avail_out = sizeof(outbuf);
  8671. ret = deflate(&zs, Z_FINISH);
  8672. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8673. } while (ret != Z_STREAM_END);
  8674. deflateEnd(&zs);
  8675. }
  8676. Client cli(HOST, PORT);
  8677. cli.set_connection_timeout(std::chrono::seconds(5));
  8678. Headers headers = {{"Content-Encoding", "gzip"}};
  8679. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8680. "application/octet-stream");
  8681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8682. // Server must reject oversized decompressed payloads with 413.
  8683. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8684. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8685. EXPECT_LE(total, LIMIT);
  8686. }
  8687. #endif
  8688. // Regression test for DoS vulnerability: a malicious server sending a response
  8689. // without Content-Length header must not cause unbounded memory consumption on
  8690. // the client side. The client should stop reading after a reasonable limit,
  8691. // similar to the server-side set_payload_max_length protection.
  8692. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8693. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8694. #ifndef _WIN32
  8695. signal(SIGPIPE, SIG_IGN);
  8696. #endif
  8697. auto server_thread = std::thread([] {
  8698. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8699. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8700. default_socket_options(srv);
  8701. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8702. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8703. sockaddr_in addr{};
  8704. addr.sin_family = AF_INET;
  8705. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8706. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8707. int opt = 1;
  8708. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8709. #ifdef _WIN32
  8710. reinterpret_cast<const char *>(&opt),
  8711. #else
  8712. &opt,
  8713. #endif
  8714. sizeof(opt));
  8715. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8716. ::listen(srv, 1);
  8717. sockaddr_in cli_addr{};
  8718. socklen_t cli_len = sizeof(cli_addr);
  8719. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8720. if (cli != INVALID_SOCKET) {
  8721. char buf[4096];
  8722. ::recv(cli, buf, sizeof(buf), 0);
  8723. // Malicious response: no Content-Length, no chunked encoding
  8724. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8725. "Connection: close\r\n"
  8726. "\r\n";
  8727. ::send(cli,
  8728. #ifdef _WIN32
  8729. static_cast<const char *>(response_header.c_str()),
  8730. static_cast<int>(response_header.size()),
  8731. #else
  8732. response_header.c_str(), response_header.size(),
  8733. #endif
  8734. 0);
  8735. // Send 10MB of data
  8736. std::string chunk(64 * 1024, 'A');
  8737. size_t total_sent = 0;
  8738. while (total_sent < MALICIOUS_DATA_SIZE) {
  8739. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8740. auto sent = ::send(cli,
  8741. #ifdef _WIN32
  8742. static_cast<const char *>(chunk.c_str()),
  8743. static_cast<int>(to_send),
  8744. #else
  8745. chunk.c_str(), to_send,
  8746. #endif
  8747. 0);
  8748. if (sent <= 0) break;
  8749. total_sent += static_cast<size_t>(sent);
  8750. }
  8751. detail::close_socket(cli);
  8752. }
  8753. detail::close_socket(srv);
  8754. });
  8755. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8756. size_t total_read = 0;
  8757. {
  8758. Client cli("127.0.0.1", PORT + 2);
  8759. cli.set_read_timeout(5, 0);
  8760. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8761. auto stream = cli.open_stream("GET", "/malicious");
  8762. ASSERT_TRUE(stream.is_valid());
  8763. char buffer[64 * 1024];
  8764. ssize_t n;
  8765. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8766. total_read += static_cast<size_t>(n);
  8767. }
  8768. } // StreamHandle and Client destroyed here, closing the socket
  8769. server_thread.join();
  8770. // With set_payload_max_length, the client must stop reading before consuming
  8771. // all 10MB. The read loop should be cut off at or near the configured limit.
  8772. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8773. << "Client read " << total_read << " bytes, exceeding the configured "
  8774. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8775. }
  8776. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8777. // the entire response body without truncation.
  8778. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8779. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8780. #ifndef _WIN32
  8781. signal(SIGPIPE, SIG_IGN);
  8782. #endif
  8783. auto server_thread = std::thread([] {
  8784. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8785. default_socket_options(srv);
  8786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8787. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8788. sockaddr_in addr{};
  8789. addr.sin_family = AF_INET;
  8790. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8791. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8792. int opt = 1;
  8793. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8794. #ifdef _WIN32
  8795. reinterpret_cast<const char *>(&opt),
  8796. #else
  8797. &opt,
  8798. #endif
  8799. sizeof(opt));
  8800. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8801. ::listen(srv, 1);
  8802. sockaddr_in cli_addr{};
  8803. socklen_t cli_len = sizeof(cli_addr);
  8804. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8805. if (cli != INVALID_SOCKET) {
  8806. char buf[4096];
  8807. ::recv(cli, buf, sizeof(buf), 0);
  8808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8809. "Connection: close\r\n"
  8810. "\r\n";
  8811. ::send(cli,
  8812. #ifdef _WIN32
  8813. static_cast<const char *>(response_header.c_str()),
  8814. static_cast<int>(response_header.size()),
  8815. #else
  8816. response_header.c_str(), response_header.size(),
  8817. #endif
  8818. 0);
  8819. std::string chunk(64 * 1024, 'A');
  8820. size_t total_sent = 0;
  8821. while (total_sent < DATA_SIZE) {
  8822. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8823. auto sent = ::send(cli,
  8824. #ifdef _WIN32
  8825. static_cast<const char *>(chunk.c_str()),
  8826. static_cast<int>(to_send),
  8827. #else
  8828. chunk.c_str(), to_send,
  8829. #endif
  8830. 0);
  8831. if (sent <= 0) break;
  8832. total_sent += static_cast<size_t>(sent);
  8833. }
  8834. #ifdef _WIN32
  8835. ::shutdown(cli, SD_SEND);
  8836. #else
  8837. ::shutdown(cli, SHUT_WR);
  8838. #endif
  8839. // Drain until the client closes its end, ensuring all data is delivered
  8840. char drain[1024];
  8841. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8842. detail::close_socket(cli);
  8843. }
  8844. detail::close_socket(srv);
  8845. });
  8846. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8847. size_t total_read = 0;
  8848. {
  8849. Client cli("127.0.0.1", PORT + 2);
  8850. cli.set_read_timeout(5, 0);
  8851. cli.set_payload_max_length(0); // 0 means no limit
  8852. auto stream = cli.open_stream("GET", "/data");
  8853. ASSERT_TRUE(stream.is_valid());
  8854. char buffer[64 * 1024];
  8855. ssize_t n;
  8856. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8857. total_read += static_cast<size_t>(n);
  8858. }
  8859. }
  8860. server_thread.join();
  8861. EXPECT_EQ(total_read, DATA_SIZE)
  8862. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8863. << " bytes without truncation, but only read " << total_read << " bytes.";
  8864. }
  8865. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8866. // enormous Content-Length must not cause the client to pre-allocate a huge
  8867. // response body buffer. The reservation is capped at payload_max_length_, and
  8868. // the read itself fails when the body exceeds the limit.
  8869. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8870. #ifndef _WIN32
  8871. signal(SIGPIPE, SIG_IGN);
  8872. #endif
  8873. auto server_thread = std::thread([] {
  8874. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8875. default_socket_options(srv);
  8876. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8877. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8878. sockaddr_in addr{};
  8879. addr.sin_family = AF_INET;
  8880. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8881. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8882. int opt = 1;
  8883. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8884. #ifdef _WIN32
  8885. reinterpret_cast<const char *>(&opt),
  8886. #else
  8887. &opt,
  8888. #endif
  8889. sizeof(opt));
  8890. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8891. ::listen(srv, 1);
  8892. sockaddr_in cli_addr{};
  8893. socklen_t cli_len = sizeof(cli_addr);
  8894. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8895. if (cli != INVALID_SOCKET) {
  8896. char buf[4096];
  8897. ::recv(cli, buf, sizeof(buf), 0);
  8898. // Malicious response: claim a 20GB body but send only a tiny payload.
  8899. std::string response = "HTTP/1.1 200 OK\r\n"
  8900. "Content-Length: 20000000000\r\n"
  8901. "\r\n"
  8902. "abc";
  8903. ::send(cli,
  8904. #ifdef _WIN32
  8905. static_cast<const char *>(response.c_str()),
  8906. static_cast<int>(response.size()),
  8907. #else
  8908. response.c_str(), response.size(),
  8909. #endif
  8910. 0);
  8911. detail::close_socket(cli);
  8912. }
  8913. detail::close_socket(srv);
  8914. });
  8915. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8916. {
  8917. Client cli("127.0.0.1", PORT + 2);
  8918. cli.set_read_timeout(5, 0);
  8919. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8920. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8921. // (server claims more bytes than payload_max_length permits), but it must
  8922. // not exhaust memory before getting there.
  8923. auto res = cli.Get("/malicious");
  8924. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8925. }
  8926. server_thread.join();
  8927. }
  8928. // Verify that content_receiver bypasses the default payload_max_length,
  8929. // allowing streaming downloads larger than 100MB without requiring an explicit
  8930. // set_payload_max_length call.
  8931. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8932. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8933. #ifndef _WIN32
  8934. signal(SIGPIPE, SIG_IGN);
  8935. #endif
  8936. auto server_thread = std::thread([] {
  8937. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8938. default_socket_options(srv);
  8939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8940. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8941. sockaddr_in addr{};
  8942. addr.sin_family = AF_INET;
  8943. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8944. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8945. int opt = 1;
  8946. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8947. #ifdef _WIN32
  8948. reinterpret_cast<const char *>(&opt),
  8949. #else
  8950. &opt,
  8951. #endif
  8952. sizeof(opt));
  8953. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8954. ::listen(srv, 1);
  8955. sockaddr_in cli_addr{};
  8956. socklen_t cli_len = sizeof(cli_addr);
  8957. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8958. if (cli != INVALID_SOCKET) {
  8959. char buf[4096];
  8960. ::recv(cli, buf, sizeof(buf), 0);
  8961. // Response with Content-Length larger than default 100MB limit
  8962. auto content_length = std::to_string(DATA_SIZE);
  8963. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8964. "Content-Length: " +
  8965. content_length +
  8966. "\r\n"
  8967. "Connection: close\r\n"
  8968. "\r\n";
  8969. ::send(cli,
  8970. #ifdef _WIN32
  8971. static_cast<const char *>(response_header.c_str()),
  8972. static_cast<int>(response_header.size()),
  8973. #else
  8974. response_header.c_str(), response_header.size(),
  8975. #endif
  8976. 0);
  8977. std::string chunk(64 * 1024, 'A');
  8978. size_t total_sent = 0;
  8979. while (total_sent < DATA_SIZE) {
  8980. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8981. auto sent = ::send(cli,
  8982. #ifdef _WIN32
  8983. static_cast<const char *>(chunk.c_str()),
  8984. static_cast<int>(to_send),
  8985. #else
  8986. chunk.c_str(), to_send,
  8987. #endif
  8988. 0);
  8989. if (sent <= 0) break;
  8990. total_sent += static_cast<size_t>(sent);
  8991. }
  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. // Do NOT call set_payload_max_length — use the default 100MB 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) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::OK_200, res->status);
  9009. }
  9010. server_thread.join();
  9011. EXPECT_EQ(total_received, DATA_SIZE)
  9012. << "With content_receiver, the client should read all " << DATA_SIZE
  9013. << " bytes despite the default 100MB payload_max_length, but only read "
  9014. << total_received << " bytes.";
  9015. }
  9016. // Verify that an explicit set_payload_max_length smaller than the response is
  9017. // enforced even when a content_receiver is used.
  9018. TEST(ClientVulnerabilityTest,
  9019. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9020. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9021. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9022. #ifndef _WIN32
  9023. signal(SIGPIPE, SIG_IGN);
  9024. #endif
  9025. auto server_thread = std::thread([] {
  9026. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9027. default_socket_options(srv);
  9028. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9029. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9030. sockaddr_in addr{};
  9031. addr.sin_family = AF_INET;
  9032. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9033. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9034. int opt = 1;
  9035. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9036. #ifdef _WIN32
  9037. reinterpret_cast<const char *>(&opt),
  9038. #else
  9039. &opt,
  9040. #endif
  9041. sizeof(opt));
  9042. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9043. ::listen(srv, 1);
  9044. sockaddr_in cli_addr{};
  9045. socklen_t cli_len = sizeof(cli_addr);
  9046. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9047. if (cli != INVALID_SOCKET) {
  9048. char buf[4096];
  9049. ::recv(cli, buf, sizeof(buf), 0);
  9050. auto content_length = std::to_string(DATA_SIZE);
  9051. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9052. "Content-Length: " +
  9053. content_length +
  9054. "\r\n"
  9055. "Connection: close\r\n"
  9056. "\r\n";
  9057. ::send(cli,
  9058. #ifdef _WIN32
  9059. static_cast<const char *>(response_header.c_str()),
  9060. static_cast<int>(response_header.size()),
  9061. #else
  9062. response_header.c_str(), response_header.size(),
  9063. #endif
  9064. 0);
  9065. std::string chunk(64 * 1024, 'A');
  9066. size_t total_sent = 0;
  9067. while (total_sent < DATA_SIZE) {
  9068. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9069. auto sent = ::send(cli,
  9070. #ifdef _WIN32
  9071. static_cast<const char *>(chunk.c_str()),
  9072. static_cast<int>(to_send),
  9073. #else
  9074. chunk.c_str(), to_send,
  9075. #endif
  9076. 0);
  9077. if (sent <= 0) break;
  9078. total_sent += static_cast<size_t>(sent);
  9079. }
  9080. detail::close_socket(cli);
  9081. }
  9082. detail::close_socket(srv);
  9083. });
  9084. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9085. size_t total_received = 0;
  9086. {
  9087. Client cli("127.0.0.1", PORT + 2);
  9088. cli.set_read_timeout(10, 0);
  9089. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9090. auto res =
  9091. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9092. total_received += data_length;
  9093. return true;
  9094. });
  9095. // Should fail because 200MB exceeds the explicit 150MB limit
  9096. EXPECT_FALSE(res);
  9097. }
  9098. server_thread.join();
  9099. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9100. << "Client with content_receiver should respect the explicit "
  9101. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9102. << total_received << " bytes.";
  9103. }
  9104. // Verify that an explicit set_payload_max_length larger than the response
  9105. // allows the content_receiver to read all data successfully.
  9106. TEST(ClientVulnerabilityTest,
  9107. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9108. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9109. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9110. #ifndef _WIN32
  9111. signal(SIGPIPE, SIG_IGN);
  9112. #endif
  9113. auto server_thread = std::thread([] {
  9114. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9115. default_socket_options(srv);
  9116. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9117. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9118. sockaddr_in addr{};
  9119. addr.sin_family = AF_INET;
  9120. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9121. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9122. int opt = 1;
  9123. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9124. #ifdef _WIN32
  9125. reinterpret_cast<const char *>(&opt),
  9126. #else
  9127. &opt,
  9128. #endif
  9129. sizeof(opt));
  9130. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9131. ::listen(srv, 1);
  9132. sockaddr_in cli_addr{};
  9133. socklen_t cli_len = sizeof(cli_addr);
  9134. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9135. if (cli != INVALID_SOCKET) {
  9136. char buf[4096];
  9137. ::recv(cli, buf, sizeof(buf), 0);
  9138. auto content_length = std::to_string(DATA_SIZE);
  9139. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9140. "Content-Length: " +
  9141. content_length +
  9142. "\r\n"
  9143. "Connection: close\r\n"
  9144. "\r\n";
  9145. ::send(cli,
  9146. #ifdef _WIN32
  9147. static_cast<const char *>(response_header.c_str()),
  9148. static_cast<int>(response_header.size()),
  9149. #else
  9150. response_header.c_str(), response_header.size(),
  9151. #endif
  9152. 0);
  9153. std::string chunk(64 * 1024, 'A');
  9154. size_t total_sent = 0;
  9155. while (total_sent < DATA_SIZE) {
  9156. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9157. auto sent = ::send(cli,
  9158. #ifdef _WIN32
  9159. static_cast<const char *>(chunk.c_str()),
  9160. static_cast<int>(to_send),
  9161. #else
  9162. chunk.c_str(), to_send,
  9163. #endif
  9164. 0);
  9165. if (sent <= 0) break;
  9166. total_sent += static_cast<size_t>(sent);
  9167. }
  9168. #ifdef _WIN32
  9169. ::shutdown(cli, SD_SEND);
  9170. #else
  9171. ::shutdown(cli, SHUT_WR);
  9172. #endif
  9173. char drain[1024];
  9174. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9175. detail::close_socket(cli);
  9176. }
  9177. detail::close_socket(srv);
  9178. });
  9179. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9180. size_t total_received = 0;
  9181. {
  9182. Client cli("127.0.0.1", PORT + 2);
  9183. cli.set_read_timeout(10, 0);
  9184. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9185. auto res =
  9186. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9187. total_received += data_length;
  9188. return true;
  9189. });
  9190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9191. EXPECT_EQ(StatusCode::OK_200, res->status);
  9192. }
  9193. server_thread.join();
  9194. EXPECT_EQ(total_received, DATA_SIZE)
  9195. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9196. << " bytes (larger than " << DATA_SIZE
  9197. << " bytes response), content_receiver should read all data, but only "
  9198. "read "
  9199. << total_received << " bytes.";
  9200. }
  9201. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9202. // Regression test for "zip bomb" attack on the client side: a malicious server
  9203. // sends a small gzip-compressed response that decompresses to a huge payload.
  9204. // The client must enforce payload_max_length on the decompressed size.
  9205. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9206. constexpr size_t DECOMPRESSED_SIZE =
  9207. 10 * 1024 * 1024; // 10MB after decompression
  9208. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9209. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9210. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9211. std::string compressed;
  9212. {
  9213. httplib::detail::gzip_compressor compressor;
  9214. bool ok =
  9215. compressor.compress(uncompressed.data(), uncompressed.size(),
  9216. /*last=*/true, [&](const char *buf, size_t len) {
  9217. compressed.append(buf, len);
  9218. return true;
  9219. });
  9220. ASSERT_TRUE(ok);
  9221. }
  9222. // Sanity: compressed data should be much smaller than the decompressed size
  9223. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9224. #ifndef _WIN32
  9225. signal(SIGPIPE, SIG_IGN);
  9226. #endif
  9227. // Set up the listening socket in the main thread so the server is guaranteed
  9228. // to be ready before the client connects (eliminates race condition).
  9229. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9230. default_socket_options(srv);
  9231. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9232. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9233. sockaddr_in addr{};
  9234. addr.sin_family = AF_INET;
  9235. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9236. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9237. int opt = 1;
  9238. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9239. #ifdef _WIN32
  9240. reinterpret_cast<const char *>(&opt),
  9241. #else
  9242. &opt,
  9243. #endif
  9244. sizeof(opt));
  9245. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9246. ASSERT_EQ(0, ::listen(srv, 1));
  9247. auto server_thread = std::thread([&compressed, srv] {
  9248. sockaddr_in cli_addr{};
  9249. socklen_t cli_len = sizeof(cli_addr);
  9250. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9251. if (cli != INVALID_SOCKET) {
  9252. // Read the full HTTP request (until \r\n\r\n)
  9253. char buf[4096];
  9254. size_t total = 0;
  9255. while (total < sizeof(buf)) {
  9256. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9257. if (n <= 0) break;
  9258. total += static_cast<size_t>(n);
  9259. // Check for end of headers
  9260. if (total >= 4) {
  9261. std::string req(buf, total);
  9262. if (req.find("\r\n\r\n") != std::string::npos) break;
  9263. }
  9264. }
  9265. // Malicious response: gzip-compressed body, no Content-Length
  9266. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9267. "Content-Encoding: gzip\r\n"
  9268. "Connection: close\r\n"
  9269. "\r\n";
  9270. ::send(cli,
  9271. #ifdef _WIN32
  9272. static_cast<const char *>(response_header.c_str()),
  9273. static_cast<int>(response_header.size()),
  9274. #else
  9275. response_header.c_str(), response_header.size(),
  9276. #endif
  9277. 0);
  9278. // Send the compressed payload (small on the wire, huge when decompressed)
  9279. size_t total_sent = 0;
  9280. while (total_sent < compressed.size()) {
  9281. auto to_send = std::min(compressed.size() - total_sent,
  9282. static_cast<size_t>(64 * 1024));
  9283. auto sent =
  9284. ::send(cli,
  9285. #ifdef _WIN32
  9286. static_cast<const char *>(compressed.c_str() + total_sent),
  9287. static_cast<int>(to_send),
  9288. #else
  9289. compressed.c_str() + total_sent, to_send,
  9290. #endif
  9291. 0);
  9292. if (sent <= 0) break;
  9293. total_sent += static_cast<size_t>(sent);
  9294. }
  9295. detail::close_socket(cli);
  9296. }
  9297. });
  9298. auto se = detail::scope_exit([&] {
  9299. detail::close_socket(srv);
  9300. server_thread.join();
  9301. });
  9302. size_t total_decompressed = 0;
  9303. {
  9304. Client cli("127.0.0.1", PORT + 3);
  9305. cli.set_read_timeout(5, 0);
  9306. cli.set_decompress(true);
  9307. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9308. auto stream = cli.open_stream("GET", "/zipbomb");
  9309. ASSERT_TRUE(stream.is_valid());
  9310. char buffer[64 * 1024];
  9311. ssize_t n;
  9312. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9313. total_decompressed += static_cast<size_t>(n);
  9314. }
  9315. }
  9316. // The decompressed size must be capped by payload_max_length. Without
  9317. // protection, the client would decompress the full 10MB from a tiny
  9318. // compressed payload, enabling a zip bomb DoS attack.
  9319. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9320. << "Client decompressed " << total_decompressed
  9321. << " bytes from a gzip response. The decompressed size should be "
  9322. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9323. }
  9324. #endif
  9325. TEST(HostAndPortPropertiesTest, NoSSL) {
  9326. httplib::Client cli("www.google.com", 1234);
  9327. ASSERT_EQ("www.google.com", cli.host());
  9328. ASSERT_EQ(1234, cli.port());
  9329. }
  9330. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9331. httplib::Client cli("www.google.com:1234");
  9332. ASSERT_EQ("www.google.com", cli.host());
  9333. ASSERT_EQ(1234, cli.port());
  9334. }
  9335. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9336. // Port number that overflows int — should not crash, client becomes invalid
  9337. httplib::Client cli("http://www.google.com:99999999999999999999");
  9338. ASSERT_FALSE(cli.is_valid());
  9339. }
  9340. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9341. // Port 99999 exceeds valid range (1-65535) — should not crash
  9342. httplib::Client cli("http://www.google.com:99999");
  9343. ASSERT_FALSE(cli.is_valid());
  9344. }
  9345. #ifdef CPPHTTPLIB_SSL_ENABLED
  9346. TEST(HostAndPortPropertiesTest, SSL) {
  9347. httplib::SSLClient cli("www.google.com");
  9348. ASSERT_EQ("www.google.com", cli.host());
  9349. ASSERT_EQ(443, cli.port());
  9350. }
  9351. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9352. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9353. std::string cert;
  9354. read_file(CA_CERT_FILE, cert);
  9355. httplib::SSLClient httplib_client("www.google.com");
  9356. // Load CA store first time
  9357. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9358. // Load CA store second time (update)
  9359. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9360. // Verify client is still valid and can make connections
  9361. httplib_client.enable_server_certificate_verification(true);
  9362. auto res = httplib_client.Get("/");
  9363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9364. // Google may return 200 or 301 depending on various factors
  9365. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9366. res->status == StatusCode::MovedPermanently_301);
  9367. }
  9368. TEST(SSLClientTest, ServerNameIndication_Online) {
  9369. auto host = "httpbingo.org";
  9370. auto path = std::string{"/get"};
  9371. SSLClient cli(host, 443);
  9372. auto res = cli.Get(path);
  9373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9374. ASSERT_EQ(StatusCode::OK_200, res->status);
  9375. }
  9376. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9377. // Use a site that will cause SSL verification failure due to self-signed cert
  9378. SSLClient cli("self-signed.badssl.com", 443);
  9379. cli.enable_server_certificate_verification(true);
  9380. auto res = cli.Get("/");
  9381. ASSERT_TRUE(!res);
  9382. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9383. // Verify backend error is captured for SSLServerVerification
  9384. // This occurs when certificate verification fails
  9385. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9386. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9387. EXPECT_NE(0UL, res.ssl_backend_error());
  9388. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9389. // For OpenSSL, ssl_error is 0 for verification errors
  9390. EXPECT_EQ(0, res.ssl_error());
  9391. #if !defined(_WIN32) || \
  9392. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9393. // On non-Windows or when Windows Schannel is disabled, the error comes
  9394. // from OpenSSL's verification
  9395. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9396. res.ssl_backend_error());
  9397. #endif
  9398. #endif
  9399. }
  9400. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9401. // Use a site where hostname doesn't match the certificate
  9402. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9403. SSLClient cli("wrong.host.badssl.com", 443);
  9404. cli.enable_server_certificate_verification(true);
  9405. cli.enable_server_hostname_verification(true);
  9406. auto res = cli.Get("/");
  9407. ASSERT_TRUE(!res);
  9408. // The error type depends on when hostname verification occurs:
  9409. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9410. // - Mbed TLS: SSLServerVerification (during handshake)
  9411. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9412. res.error() == Error::SSLServerVerification);
  9413. // Verify backend error is captured for hostname verification failure
  9414. EXPECT_NE(0UL, res.ssl_backend_error());
  9415. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9416. // For OpenSSL, ssl_error is 0 for verification errors
  9417. EXPECT_EQ(0, res.ssl_error());
  9418. #if !defined(_WIN32) || \
  9419. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9420. // On non-Windows or when Windows Schannel is disabled, the error comes
  9421. // from OpenSSL's hostname verification
  9422. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9423. res.ssl_backend_error());
  9424. #endif
  9425. #endif
  9426. }
  9427. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9428. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9429. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9430. SSLClient cli("www.google.com", 443);
  9431. cli.enable_server_certificate_verification(true);
  9432. auto res = cli.Get("/");
  9433. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9434. }
  9435. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9436. SSLClient cli("www.google.com", 443);
  9437. cli.enable_server_certificate_verification(true);
  9438. cli.enable_windows_certificate_verification(false);
  9439. auto res = cli.Get("/");
  9440. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9441. }
  9442. #endif
  9443. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9444. Client cli("https://google.com");
  9445. auto res = cli.Get("/");
  9446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9447. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9448. }
  9449. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9450. SSLClient cli("google.com");
  9451. cli.set_ca_cert_path(CA_CERT_FILE);
  9452. auto res = cli.Get("/");
  9453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9454. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9455. }
  9456. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9457. SSLClient cli("google.com");
  9458. cli.enable_server_certificate_verification(true);
  9459. cli.set_ca_cert_path("hello");
  9460. auto res = cli.Get("/");
  9461. ASSERT_TRUE(!res);
  9462. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9463. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9464. // should be set
  9465. EXPECT_EQ(0, res.ssl_error());
  9466. // Verify backend error is captured for SSLLoadingCerts
  9467. // This error occurs when loading CA certificates fails
  9468. EXPECT_NE(0UL, res.ssl_backend_error());
  9469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9470. // OpenSSL specific error codes:
  9471. // > openssl errstr 0x80000002
  9472. // error:80000002:system library::No such file or directory
  9473. // > openssl errstr 0xA000126
  9474. // error:0A000126:SSL routines::unexpected eof while reading
  9475. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9476. res.ssl_backend_error() == 0xA000126);
  9477. #endif
  9478. }
  9479. TEST(SSLClientTest, ServerCertificateVerification4) {
  9480. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9481. ASSERT_TRUE(svr.is_valid());
  9482. svr.Get("/test", [&](const Request &, Response &res) {
  9483. res.set_content("test", "text/plain");
  9484. svr.stop();
  9485. ASSERT_TRUE(true);
  9486. });
  9487. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9488. auto se = detail::scope_exit([&] {
  9489. t.join();
  9490. ASSERT_FALSE(svr.is_running());
  9491. });
  9492. svr.wait_until_ready();
  9493. SSLClient cli("127.0.0.1", PORT);
  9494. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9495. cli.enable_server_certificate_verification(true);
  9496. cli.set_connection_timeout(30);
  9497. auto res = cli.Get("/test");
  9498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9499. ASSERT_EQ(StatusCode::OK_200, res->status);
  9500. }
  9501. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9502. std::string cert;
  9503. read_file(CA_CERT_FILE, cert);
  9504. SSLClient cli("google.com");
  9505. cli.load_ca_cert_store(cert.data(), cert.size());
  9506. const auto res = cli.Get("/");
  9507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9508. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9509. }
  9510. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9511. // clang-format off
  9512. static constexpr char cert[] =
  9513. "GlobalSign Root CA\n"
  9514. "==================\n"
  9515. "-----BEGIN CERTIFICATE-----\n"
  9516. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9517. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9518. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9519. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9520. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9521. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9522. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9523. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9524. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9525. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9526. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9527. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9528. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9529. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9530. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9531. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9532. "-----END CERTIFICATE-----\n";
  9533. // clang-format on
  9534. SSLClient cli("google.com");
  9535. cli.load_ca_cert_store(cert, sizeof(cert));
  9536. const auto res = cli.Get("/");
  9537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9538. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9539. }
  9540. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9541. SSLClient cli("www.youtube.com");
  9542. cli.set_ca_cert_path(CA_CERT_FILE);
  9543. cli.enable_server_certificate_verification(true);
  9544. cli.set_follow_location(true);
  9545. auto res = cli.Get("/");
  9546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9547. ASSERT_EQ(StatusCode::OK_200, res->status);
  9548. }
  9549. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9550. SSLClient cli("wWw.YouTube.Com");
  9551. cli.set_ca_cert_path(CA_CERT_FILE);
  9552. cli.enable_server_certificate_verification(true);
  9553. cli.enable_server_hostname_verification(true);
  9554. cli.set_follow_location(true);
  9555. auto res = cli.Get("/");
  9556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9557. ASSERT_EQ(StatusCode::OK_200, res->status);
  9558. }
  9559. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9560. SSLClient cli("gOoGlE.COm");
  9561. cli.enable_server_certificate_verification(true);
  9562. cli.enable_server_hostname_verification(true);
  9563. cli.set_follow_location(true);
  9564. auto res = cli.Get("/");
  9565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9566. ASSERT_EQ(StatusCode::OK_200, res->status);
  9567. }
  9568. TEST(SSLClientTest, Issue2004_Online) {
  9569. Client client("https://google.com");
  9570. client.set_follow_location(true);
  9571. auto res = client.Get("/");
  9572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9573. ASSERT_EQ(StatusCode::OK_200, res->status);
  9574. auto body = res->body;
  9575. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9576. }
  9577. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9578. // Create SSLClient with invalid cert/key to make is_valid() return false
  9579. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9580. "nonexistent_key.pem");
  9581. // is_valid() should be false due to cert loading failure
  9582. ASSERT_FALSE(cli.is_valid());
  9583. auto res = cli.Get("/");
  9584. ASSERT_FALSE(res);
  9585. EXPECT_EQ(Error::SSLConnection, res.error());
  9586. }
  9587. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9588. // Test for Issue #2251: SSL error not properly reported when client cert
  9589. // and key paths are swapped or mismatched
  9590. // This simulates the scenario where user accidentally swaps the cert and key
  9591. // files
  9592. // Using client cert file as private key and vice versa (completely wrong)
  9593. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9594. // Should fail validation due to cert/key mismatch
  9595. ASSERT_FALSE(cli.is_valid());
  9596. // Attempt to make a request should fail with proper error
  9597. auto res = cli.Get("/");
  9598. ASSERT_FALSE(res);
  9599. EXPECT_EQ(Error::SSLConnection, res.error());
  9600. // SSL error should be recorded in the Result object (this is the key fix for
  9601. // Issue #2251)
  9602. auto backend_error = res.ssl_backend_error();
  9603. EXPECT_NE(0u, backend_error);
  9604. }
  9605. // Tests cert/key mismatch detection at the TLS context level
  9606. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9607. // Test that using mismatched cert/key causes connection failure.
  9608. // We verify this at the SSLClient level rather than through internal
  9609. // TLS API functions.
  9610. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9611. cli.enable_server_certificate_verification(false);
  9612. cli.set_connection_timeout(2);
  9613. // The mismatch should cause a connection or handshake error
  9614. auto res = cli.Get("/test");
  9615. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9616. // Either way, the request should fail
  9617. EXPECT_FALSE(res);
  9618. }
  9619. #endif
  9620. #if 0
  9621. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9622. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9623. ASSERT_TRUE(cli != nullptr);
  9624. cli->set_address_family(AF_INET6);
  9625. cli->set_interface("en0");
  9626. auto res = cli->Get("/get");
  9627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9628. ASSERT_EQ(StatusCode::OK_200, res->status);
  9629. }
  9630. #endif
  9631. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9632. #ifdef CPPHTTPLIB_SSL_ENABLED
  9633. void ClientCertPresent(
  9634. const std::string &client_cert_file,
  9635. const std::string &client_private_key_file,
  9636. const std::string &client_encrypted_private_key_pass = std::string()) {
  9637. using namespace httplib::tls;
  9638. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9639. CLIENT_CA_CERT_DIR);
  9640. ASSERT_TRUE(svr.is_valid());
  9641. svr.Get("/test", [&](const Request &req, Response &res) {
  9642. res.set_content("test", "text/plain");
  9643. auto cert = req.peer_cert();
  9644. ASSERT_TRUE(static_cast<bool>(cert));
  9645. std::string common_name = cert.subject_cn();
  9646. EXPECT_EQ("Common Name", common_name);
  9647. });
  9648. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9649. auto se = detail::scope_exit([&] {
  9650. svr.stop();
  9651. t.join();
  9652. ASSERT_FALSE(svr.is_running());
  9653. });
  9654. svr.wait_until_ready();
  9655. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9656. client_encrypted_private_key_pass);
  9657. cli.enable_server_certificate_verification(false);
  9658. cli.set_connection_timeout(30);
  9659. auto res = cli.Get("/test");
  9660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9661. ASSERT_EQ(StatusCode::OK_200, res->status);
  9662. }
  9663. TEST(SSLClientServerTest, ClientCertPresent) {
  9664. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9665. }
  9666. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9667. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9668. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9669. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9670. }
  9671. // PEM memory-based constructor tests (works with all TLS backends)
  9672. void PemMemoryClientCertPresent(
  9673. const std::string &client_cert_file,
  9674. const std::string &client_private_key_file,
  9675. const std::string &client_encrypted_private_key_pass = std::string()) {
  9676. // Read PEM files into memory
  9677. std::string server_cert_pem, server_key_pem;
  9678. std::string client_ca_pem;
  9679. std::string client_cert_pem, client_key_pem;
  9680. read_file(SERVER_CERT_FILE, server_cert_pem);
  9681. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9682. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9683. read_file(client_cert_file, client_cert_pem);
  9684. read_file(client_private_key_file, client_key_pem);
  9685. // Create server with PEM memory
  9686. SSLServer::PemMemory server_pem = {
  9687. server_cert_pem.c_str(),
  9688. server_cert_pem.size(),
  9689. server_key_pem.c_str(),
  9690. server_key_pem.size(),
  9691. client_ca_pem.c_str(),
  9692. client_ca_pem.size(),
  9693. nullptr // no password for server key
  9694. };
  9695. SSLServer svr(server_pem);
  9696. ASSERT_TRUE(svr.is_valid());
  9697. svr.Get("/test", [&](const Request &, Response &res) {
  9698. res.set_content("test", "text/plain");
  9699. });
  9700. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9701. auto se = detail::scope_exit([&] {
  9702. svr.stop();
  9703. t.join();
  9704. ASSERT_FALSE(svr.is_running());
  9705. });
  9706. svr.wait_until_ready();
  9707. // Create client with PEM memory
  9708. const char *password = client_encrypted_private_key_pass.empty()
  9709. ? nullptr
  9710. : client_encrypted_private_key_pass.c_str();
  9711. SSLClient::PemMemory client_pem = {
  9712. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9713. client_key_pem.size(), password};
  9714. SSLClient cli(HOST, PORT, client_pem);
  9715. cli.enable_server_certificate_verification(false);
  9716. cli.set_connection_timeout(30);
  9717. auto res = cli.Get("/test");
  9718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9719. ASSERT_EQ(StatusCode::OK_200, res->status);
  9720. }
  9721. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9722. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9723. }
  9724. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9725. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9726. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9727. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9728. }
  9729. TEST(SSLClientServerTest, ClientCertMissing) {
  9730. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9731. CLIENT_CA_CERT_DIR);
  9732. ASSERT_TRUE(svr.is_valid());
  9733. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9734. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9735. auto se = detail::scope_exit([&] {
  9736. svr.stop();
  9737. t.join();
  9738. ASSERT_FALSE(svr.is_running());
  9739. });
  9740. svr.wait_until_ready();
  9741. SSLClient cli(HOST, PORT);
  9742. cli.set_connection_timeout(30);
  9743. auto res = cli.Get("/test");
  9744. ASSERT_TRUE(!res);
  9745. // When client cert is missing and server requires it, connection fails
  9746. // Error type depends on backend implementation
  9747. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9748. res.error() == Error::SSLConnection);
  9749. // Verify backend error is captured
  9750. // Note: This test may have different error codes depending on the exact
  9751. // verification failure
  9752. EXPECT_NE(0UL, res.ssl_backend_error());
  9753. }
  9754. TEST(SSLClientServerTest, TrustDirOptional) {
  9755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9756. ASSERT_TRUE(svr.is_valid());
  9757. svr.Get("/test", [&](const Request &, Response &res) {
  9758. res.set_content("test", "text/plain");
  9759. });
  9760. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9761. auto se = detail::scope_exit([&] {
  9762. svr.stop();
  9763. t.join();
  9764. ASSERT_FALSE(svr.is_running());
  9765. });
  9766. svr.wait_until_ready();
  9767. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9768. cli.enable_server_certificate_verification(false);
  9769. cli.set_connection_timeout(30);
  9770. auto res = cli.Get("/test");
  9771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9772. ASSERT_EQ(StatusCode::OK_200, res->status);
  9773. }
  9774. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9775. class NoListenSSLServer : public SSLServer {
  9776. public:
  9777. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9778. const char *client_ca_cert_file_path,
  9779. const char *client_ca_cert_dir_path = nullptr)
  9780. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9781. client_ca_cert_dir_path),
  9782. stop_(false) {}
  9783. std::atomic_bool stop_;
  9784. private:
  9785. bool process_and_close_socket(socket_t /*sock*/) override {
  9786. // Don't create SSL context
  9787. while (!stop_.load()) {
  9788. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9789. }
  9790. return true;
  9791. }
  9792. };
  9793. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9794. CLIENT_CA_CERT_FILE);
  9795. ASSERT_TRUE(svr.is_valid());
  9796. svr.Get("/test", [&](const Request &, Response &res) {
  9797. res.set_content("test", "text/plain");
  9798. });
  9799. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9800. auto se = detail::scope_exit([&] {
  9801. svr.stop_ = true;
  9802. svr.stop();
  9803. t.join();
  9804. ASSERT_FALSE(svr.is_running());
  9805. });
  9806. svr.wait_until_ready();
  9807. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9808. cli.enable_server_certificate_verification(false);
  9809. cli.set_connection_timeout(1);
  9810. auto res = cli.Get("/test");
  9811. ASSERT_TRUE(!res);
  9812. EXPECT_EQ(Error::SSLConnection, res.error());
  9813. // Timeout results in WantRead error code (maps to backend-specific value)
  9814. EXPECT_NE(0, res.ssl_error());
  9815. }
  9816. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9817. // Test SSLServer with client certificate verification using the standard
  9818. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9820. CLIENT_CA_CERT_DIR);
  9821. ASSERT_TRUE(svr.is_valid());
  9822. svr.Get("/test", [&](const Request &req, Response &res) {
  9823. res.set_content("test", "text/plain");
  9824. auto cert = req.peer_cert();
  9825. ASSERT_TRUE(static_cast<bool>(cert));
  9826. auto common_name = cert.subject_cn();
  9827. EXPECT_EQ("Common Name", common_name);
  9828. });
  9829. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9830. auto se = detail::scope_exit([&] {
  9831. svr.stop();
  9832. t.join();
  9833. ASSERT_FALSE(svr.is_running());
  9834. });
  9835. svr.wait_until_ready();
  9836. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9837. cli.enable_server_certificate_verification(false);
  9838. cli.set_connection_timeout(30);
  9839. auto res = cli.Get("/test");
  9840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9841. ASSERT_EQ(StatusCode::OK_200, res->status);
  9842. }
  9843. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9844. // Verifies that wildcard matching and exact matching work consistently
  9845. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9846. using namespace httplib::tls;
  9847. // We need a running server to test against
  9848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9849. ASSERT_TRUE(svr.is_valid());
  9850. svr.Get("/test", [](const Request &, Response &res) {
  9851. res.set_content("ok", "text/plain");
  9852. });
  9853. thread t([&]() { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. });
  9858. svr.wait_until_ready();
  9859. bool verify_callback_called = false;
  9860. bool verify_result_wrong = false;
  9861. SSLClient cli(HOST, PORT);
  9862. cli.enable_server_certificate_verification(true);
  9863. cli.set_ca_cert_path(CA_CERT_FILE);
  9864. cli.set_connection_timeout(5);
  9865. // Note: Test certificate has CN="Common Name", not "localhost"
  9866. bool verify_result_cn = false;
  9867. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9868. verify_callback_called = true;
  9869. if (!ctx.cert) return false;
  9870. // Test 1: "Common Name" should match (our test server cert CN)
  9871. verify_result_cn = ctx.check_hostname("Common Name");
  9872. // Test 2: wrong hostname should not match
  9873. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9874. return true; // Accept for the purpose of this test
  9875. });
  9876. auto res = cli.Get("/test");
  9877. // The request may succeed or fail depending on cert configuration
  9878. // but the callback should have been called
  9879. ASSERT_TRUE(verify_callback_called)
  9880. << "Verify callback should have been called";
  9881. // CN="Common Name" should match our test certificate
  9882. //
  9883. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9884. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9885. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9886. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9887. // <openssl/base.h>, which is included transitively when
  9888. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9889. #if defined(OPENSSL_IS_BORINGSSL)
  9890. EXPECT_FALSE(verify_result_cn)
  9891. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9892. #else
  9893. EXPECT_TRUE(verify_result_cn)
  9894. << "verify_hostname should match 'Common Name' (certificate CN)";
  9895. #endif
  9896. // Wrong hostname should not match
  9897. EXPECT_FALSE(verify_result_wrong)
  9898. << "verify_hostname should not match 'wronghost.example.com'";
  9899. }
  9900. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9901. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9902. // X509_check_ip behavior and must hold for every backend.
  9903. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9904. using namespace httplib::tls;
  9905. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9906. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9907. ASSERT_TRUE(svr.is_valid());
  9908. svr.Get("/test", [](const Request &, Response &res) {
  9909. res.set_content("ok", "text/plain");
  9910. });
  9911. thread t([&]() { svr.listen(HOST, PORT); });
  9912. auto se = detail::scope_exit([&] {
  9913. svr.stop();
  9914. t.join();
  9915. });
  9916. svr.wait_until_ready();
  9917. bool verify_callback_called = false;
  9918. bool ip_matched_via_cn = true;
  9919. SSLClient cli(HOST, PORT);
  9920. cli.enable_server_certificate_verification(true);
  9921. cli.set_ca_cert_path(CA_CERT_FILE);
  9922. cli.set_connection_timeout(5);
  9923. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9924. verify_callback_called = true;
  9925. if (!ctx.cert) return false;
  9926. // The IP appears only in the CN, so it must NOT be accepted.
  9927. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9928. return true; // Accept for the purpose of this test
  9929. });
  9930. cli.Get("/test");
  9931. ASSERT_TRUE(verify_callback_called)
  9932. << "Verify callback should have been called";
  9933. EXPECT_FALSE(ip_matched_via_cn)
  9934. << "An IP host must not be authenticated via the certificate CN";
  9935. }
  9936. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9937. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9938. using namespace httplib::tls;
  9939. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9940. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9941. ASSERT_TRUE(svr.is_valid());
  9942. svr.Get("/test", [](const Request &, Response &res) {
  9943. res.set_content("ok", "text/plain");
  9944. });
  9945. thread t([&]() { svr.listen(HOST, PORT); });
  9946. auto se = detail::scope_exit([&] {
  9947. svr.stop();
  9948. t.join();
  9949. });
  9950. svr.wait_until_ready();
  9951. bool verify_callback_called = false;
  9952. bool san_matched = false;
  9953. bool wrong_ipv6_matched = true;
  9954. bool cn_ipv6_matched = true;
  9955. SSLClient cli(HOST, PORT);
  9956. cli.enable_server_certificate_verification(true);
  9957. cli.set_ca_cert_path(CA_CERT_FILE);
  9958. cli.set_connection_timeout(5);
  9959. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9960. verify_callback_called = true;
  9961. if (!ctx.cert) return false;
  9962. // Matches the IPv6 iPAddress SAN.
  9963. san_matched = ctx.check_hostname("2001:db8::1");
  9964. // A different IPv6 address must not match.
  9965. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9966. // "::1" lives only in the CN, so it must not be accepted.
  9967. cn_ipv6_matched = ctx.check_hostname("::1");
  9968. return true; // Accept for the purpose of this test
  9969. });
  9970. cli.Get("/test");
  9971. ASSERT_TRUE(verify_callback_called)
  9972. << "Verify callback should have been called";
  9973. EXPECT_TRUE(san_matched)
  9974. << "verify_hostname should match an IPv6 iPAddress SAN";
  9975. EXPECT_FALSE(wrong_ipv6_matched)
  9976. << "verify_hostname should not match a non-matching IPv6 address";
  9977. EXPECT_FALSE(cn_ipv6_matched)
  9978. << "An IPv6 host must not be authenticated via the certificate CN";
  9979. }
  9980. #endif
  9981. // mbedTLS-specific callback constructor test
  9982. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9983. #ifdef CPPHTTPLIB_SSL_ENABLED
  9984. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9986. ASSERT_TRUE(svr.is_valid());
  9987. // Set up a handler to verify client certificate is present
  9988. bool client_cert_verified = false;
  9989. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9990. // Verify that client certificate was provided
  9991. client_cert_verified = true;
  9992. res.set_content("success", "text/plain");
  9993. });
  9994. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9995. auto se = detail::scope_exit([&] {
  9996. svr.stop();
  9997. t.join();
  9998. ASSERT_FALSE(svr.is_running());
  9999. });
  10000. svr.wait_until_ready();
  10001. // Client with certificate
  10002. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10003. cli.enable_server_certificate_verification(false);
  10004. cli.set_connection_timeout(30);
  10005. auto res = cli.Get("/test");
  10006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10007. ASSERT_EQ(StatusCode::OK_200, res->status);
  10008. ASSERT_TRUE(client_cert_verified);
  10009. EXPECT_EQ("success", res->body);
  10010. }
  10011. #endif
  10012. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10013. // backends
  10014. #ifdef CPPHTTPLIB_SSL_ENABLED
  10015. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10016. using namespace httplib::tls;
  10017. // Test that when client CA cert file is provided,
  10018. // the server properly requests and validates client certificates
  10019. // Create a server with client authentication
  10020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10021. ASSERT_TRUE(svr.is_valid());
  10022. bool handler_called = false;
  10023. svr.Get("/test", [&](const Request &req, Response &res) {
  10024. handler_called = true;
  10025. // Verify that a client certificate was provided
  10026. auto cert = req.peer_cert();
  10027. ASSERT_TRUE(static_cast<bool>(cert));
  10028. // Get the issuer name
  10029. std::string issuer_str = cert.issuer_name();
  10030. ASSERT_FALSE(issuer_str.empty());
  10031. // The client certificate should be issued by our test CA
  10032. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10033. res.set_content("authenticated", "text/plain");
  10034. });
  10035. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10036. auto se = detail::scope_exit([&] {
  10037. svr.stop();
  10038. t.join();
  10039. ASSERT_FALSE(svr.is_running());
  10040. });
  10041. svr.wait_until_ready();
  10042. // Connect with a client certificate issued by the CA
  10043. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10044. cli.enable_server_certificate_verification(false);
  10045. cli.set_connection_timeout(30);
  10046. auto res = cli.Get("/test");
  10047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10048. ASSERT_EQ(StatusCode::OK_200, res->status);
  10049. ASSERT_TRUE(handler_called);
  10050. EXPECT_EQ("authenticated", res->body);
  10051. }
  10052. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10053. using namespace httplib::tls;
  10054. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10055. ASSERT_TRUE(svr.is_valid());
  10056. svr.Get("/test", [](const Request &, Response &res) {
  10057. res.set_content("ok", "text/plain");
  10058. });
  10059. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10060. auto se = detail::scope_exit([&] {
  10061. svr.stop();
  10062. t.join();
  10063. });
  10064. svr.wait_until_ready();
  10065. SSLClient cli(HOST, PORT);
  10066. cli.enable_server_certificate_verification(false);
  10067. cli.set_connection_timeout(30);
  10068. bool cert_checked = false;
  10069. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10070. if (ctx.cert) {
  10071. auto sans = ctx.sans();
  10072. // Test certificate may or may not have SANs - just verify the API
  10073. // works If SANs exist, verify the types are valid
  10074. for (const auto &san : sans) {
  10075. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10076. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10077. san.type == SanType::OTHER);
  10078. EXPECT_FALSE(san.value.empty());
  10079. }
  10080. cert_checked = true;
  10081. }
  10082. return true;
  10083. });
  10084. auto res = cli.Get("/test");
  10085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10086. EXPECT_TRUE(cert_checked);
  10087. }
  10088. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10089. using namespace httplib::tls;
  10090. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10091. ASSERT_TRUE(svr.is_valid());
  10092. svr.Get("/test", [](const Request &, Response &res) {
  10093. res.set_content("ok", "text/plain");
  10094. });
  10095. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10096. auto se = detail::scope_exit([&] {
  10097. svr.stop();
  10098. t.join();
  10099. });
  10100. svr.wait_until_ready();
  10101. SSLClient cli(HOST, PORT);
  10102. cli.enable_server_certificate_verification(false);
  10103. cli.set_connection_timeout(30);
  10104. bool validity_checked = false;
  10105. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10106. if (ctx.cert) {
  10107. time_t not_before = 0, not_after = 0;
  10108. bool result = ctx.validity(not_before, not_after);
  10109. EXPECT_TRUE(result);
  10110. // Verify that not_before < now < not_after for a valid cert
  10111. time_t now = time(nullptr);
  10112. EXPECT_LT(not_before, now);
  10113. EXPECT_GT(not_after, now);
  10114. validity_checked = true;
  10115. }
  10116. return true;
  10117. });
  10118. auto res = cli.Get("/test");
  10119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10120. EXPECT_TRUE(validity_checked);
  10121. }
  10122. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10123. using namespace httplib::tls;
  10124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10125. ASSERT_TRUE(svr.is_valid());
  10126. svr.Get("/test", [](const Request &, Response &res) {
  10127. res.set_content("ok", "text/plain");
  10128. });
  10129. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10130. auto se = detail::scope_exit([&] {
  10131. svr.stop();
  10132. t.join();
  10133. });
  10134. svr.wait_until_ready();
  10135. SSLClient cli(HOST, PORT);
  10136. cli.enable_server_certificate_verification(false);
  10137. cli.set_connection_timeout(30);
  10138. bool serial_checked = false;
  10139. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10140. if (ctx.cert) {
  10141. std::string serial = ctx.serial();
  10142. EXPECT_FALSE(serial.empty());
  10143. // Serial should be a hex string
  10144. for (char c : serial) {
  10145. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10146. (c >= 'a' && c <= 'f'));
  10147. }
  10148. serial_checked = true;
  10149. }
  10150. return true;
  10151. });
  10152. auto res = cli.Get("/test");
  10153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10154. EXPECT_TRUE(serial_checked);
  10155. }
  10156. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10157. // Test 1: Valid CA file - no error should be recorded
  10158. {
  10159. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10160. CLIENT_CA_CERT_FILE);
  10161. ASSERT_TRUE(svr.is_valid());
  10162. // With valid setup, last_ssl_error should be 0
  10163. EXPECT_EQ(0, svr.ssl_last_error());
  10164. }
  10165. // Test 2: Invalid CA file content
  10166. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10167. {
  10168. // Create a temporary file with completely invalid content
  10169. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10170. {
  10171. std::ofstream ofs(temp_invalid_ca);
  10172. ofs << "This is not a certificate file at all\n";
  10173. ofs << "Just plain text content\n";
  10174. }
  10175. // Create server with invalid CA file
  10176. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10177. // Clean up temporary file
  10178. std::remove(temp_invalid_ca);
  10179. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10180. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10181. // Note: SSL_CTX_load_verify_locations typically fails first,
  10182. // but our error handling code path is still exercised
  10183. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10184. }
  10185. }
  10186. TEST(VerifyCallbackTest, VerifyContextFields) {
  10187. using namespace httplib::tls;
  10188. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10189. ASSERT_TRUE(svr.is_valid());
  10190. svr.Get("/test", [](const Request &, Response &res) {
  10191. res.set_content("ok", "text/plain");
  10192. });
  10193. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10194. auto se = detail::scope_exit([&] {
  10195. svr.stop();
  10196. t.join();
  10197. });
  10198. svr.wait_until_ready();
  10199. SSLClient cli(HOST, PORT);
  10200. cli.enable_server_certificate_verification(false);
  10201. cli.set_connection_timeout(30);
  10202. int callback_count = 0;
  10203. bool saw_leaf_cert = false;
  10204. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10205. if (ctx.cert) {
  10206. callback_count++;
  10207. // We should see at least one certificate (the leaf)
  10208. std::string cn = ctx.subject_cn();
  10209. if (!cn.empty()) { saw_leaf_cert = true; }
  10210. // Verify context fields are populated
  10211. EXPECT_NE(ctx.session, nullptr);
  10212. EXPECT_GE(ctx.depth, 0);
  10213. }
  10214. return true;
  10215. });
  10216. auto res = cli.Get("/test");
  10217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10218. EXPECT_GT(callback_count, 0);
  10219. EXPECT_TRUE(saw_leaf_cert);
  10220. }
  10221. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10222. using httplib::tls::TlsError;
  10223. // Test that verify_error_to_string returns empty for success
  10224. std::string success_str = TlsError::verify_error_to_string(0);
  10225. EXPECT_TRUE(success_str.empty());
  10226. // Test that verify_error_to_string returns non-empty for error codes
  10227. // Using a common error code (certificate expired)
  10228. std::string error_str =
  10229. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10230. EXPECT_FALSE(error_str.empty());
  10231. }
  10232. TEST(SessionVerifierTest, CertificateAccepted) {
  10233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10234. ASSERT_TRUE(svr.is_valid());
  10235. svr.Get("/test", [](const Request &, Response &res) {
  10236. res.set_content("ok", "text/plain");
  10237. });
  10238. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10239. auto se = detail::scope_exit([&] {
  10240. svr.stop();
  10241. t.join();
  10242. });
  10243. svr.wait_until_ready();
  10244. SSLClient cli(HOST, PORT);
  10245. cli.enable_server_certificate_verification(false);
  10246. cli.set_connection_timeout(30);
  10247. bool callback_called = false;
  10248. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10249. EXPECT_NE(session, nullptr);
  10250. callback_called = true;
  10251. return SSLVerifierResponse::CertificateAccepted;
  10252. });
  10253. auto res = cli.Get("/test");
  10254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10255. EXPECT_EQ(200, res->status);
  10256. EXPECT_TRUE(callback_called);
  10257. }
  10258. TEST(SessionVerifierTest, CertificateRejected) {
  10259. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10260. ASSERT_TRUE(svr.is_valid());
  10261. svr.Get("/test", [](const Request &, Response &res) {
  10262. res.set_content("ok", "text/plain");
  10263. });
  10264. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10265. auto se = detail::scope_exit([&] {
  10266. svr.stop();
  10267. t.join();
  10268. });
  10269. svr.wait_until_ready();
  10270. SSLClient cli(HOST, PORT);
  10271. cli.enable_server_certificate_verification(false);
  10272. cli.set_connection_timeout(30);
  10273. bool callback_called = false;
  10274. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10275. EXPECT_NE(session, nullptr);
  10276. callback_called = true;
  10277. return SSLVerifierResponse::CertificateRejected;
  10278. });
  10279. auto res = cli.Get("/test");
  10280. EXPECT_FALSE(res);
  10281. EXPECT_TRUE(callback_called);
  10282. }
  10283. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10285. ASSERT_TRUE(svr.is_valid());
  10286. svr.Get("/test", [](const Request &, Response &res) {
  10287. res.set_content("ok", "text/plain");
  10288. });
  10289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10290. auto se = detail::scope_exit([&] {
  10291. svr.stop();
  10292. t.join();
  10293. });
  10294. svr.wait_until_ready();
  10295. // NoDecisionMade with verification disabled should succeed (no default check)
  10296. SSLClient cli(HOST, PORT);
  10297. cli.enable_server_certificate_verification(false);
  10298. cli.set_connection_timeout(30);
  10299. bool callback_called = false;
  10300. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10301. EXPECT_NE(session, nullptr);
  10302. callback_called = true;
  10303. return SSLVerifierResponse::NoDecisionMade;
  10304. });
  10305. auto res = cli.Get("/test");
  10306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10307. EXPECT_EQ(200, res->status);
  10308. EXPECT_TRUE(callback_called);
  10309. }
  10310. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10312. ASSERT_TRUE(svr.is_valid());
  10313. svr.Get("/test", [](const Request &, Response &res) {
  10314. res.set_content("ok", "text/plain");
  10315. });
  10316. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10317. auto se = detail::scope_exit([&] {
  10318. svr.stop();
  10319. t.join();
  10320. });
  10321. svr.wait_until_ready();
  10322. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10323. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10324. // so we only check that the request fails, not whether the callback was
  10325. // called.
  10326. SSLClient cli(HOST, PORT);
  10327. cli.enable_server_certificate_verification(true);
  10328. cli.set_connection_timeout(30);
  10329. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10330. EXPECT_NE(session, nullptr);
  10331. return SSLVerifierResponse::NoDecisionMade;
  10332. });
  10333. auto res = cli.Get("/test");
  10334. EXPECT_FALSE(res);
  10335. }
  10336. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10337. // Test SSL server using PemMemory constructor with client CA certificates
  10338. // Read PEM files
  10339. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10340. read_file(SERVER_CERT_FILE, server_cert_pem);
  10341. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10342. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10343. // Create SSLServer with PemMemory constructor including client CA
  10344. SSLServer::PemMemory server_pem = {
  10345. server_cert_pem.c_str(),
  10346. server_cert_pem.size(),
  10347. server_key_pem.c_str(),
  10348. server_key_pem.size(),
  10349. client_ca_pem.c_str(),
  10350. client_ca_pem.size(),
  10351. nullptr // no password for server key
  10352. };
  10353. SSLServer svr(server_pem);
  10354. ASSERT_TRUE(svr.is_valid());
  10355. // No SSL error should be recorded for valid setup
  10356. EXPECT_EQ(0, svr.ssl_last_error());
  10357. // Set up server endpoints
  10358. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10359. res.set_content("ok", "text/plain");
  10360. });
  10361. // Start server in a thread
  10362. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10363. svr.wait_until_ready();
  10364. // Connect with client certificate (using constructor with paths)
  10365. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10366. cli.enable_server_certificate_verification(false);
  10367. auto res = cli.Get("/test-pem-ca");
  10368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10369. EXPECT_EQ(200, res->status);
  10370. EXPECT_EQ("ok", res->body);
  10371. svr.stop();
  10372. server_thread.join();
  10373. }
  10374. #endif
  10375. #ifdef _WIN32
  10376. TEST(CleanupTest, WSACleanup) {
  10377. int ret = WSACleanup();
  10378. ASSERT_EQ(0, ret);
  10379. }
  10380. #endif
  10381. #ifndef CPPHTTPLIB_SSL_ENABLED
  10382. TEST(NoSSLSupport, SimpleInterface) {
  10383. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10384. }
  10385. #endif
  10386. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10387. TEST(InvalidScheme, SimpleInterface) {
  10388. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10389. }
  10390. #endif
  10391. TEST(NoScheme, SimpleInterface) {
  10392. Client cli("yahoo.com:80");
  10393. ASSERT_TRUE(cli.is_valid());
  10394. }
  10395. TEST(SendAPI, SimpleInterface_Online) {
  10396. Client cli("http://yahoo.com");
  10397. Request req;
  10398. req.method = "GET";
  10399. req.path = "/";
  10400. auto res = cli.send(req);
  10401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10402. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10403. }
  10404. TEST(SendAPI, WithParamsInRequest) {
  10405. Server svr;
  10406. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10407. EXPECT_TRUE(req.has_param("test"));
  10408. EXPECT_EQ("test_value", req.get_param_value("test"));
  10409. });
  10410. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10411. auto se = detail::scope_exit([&] {
  10412. svr.stop();
  10413. t.join();
  10414. ASSERT_FALSE(svr.is_running());
  10415. });
  10416. svr.wait_until_ready();
  10417. Client cli(HOST, PORT);
  10418. {
  10419. Request req;
  10420. req.method = "GET";
  10421. req.path = "/";
  10422. req.params.emplace("test", "test_value");
  10423. auto res = cli.send(req);
  10424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10425. }
  10426. {
  10427. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10429. }
  10430. }
  10431. TEST(ClientImplMethods, GetSocketTest) {
  10432. httplib::Server svr;
  10433. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10434. res.status = StatusCode::OK_200;
  10435. });
  10436. auto port = svr.bind_to_any_port("127.0.0.1");
  10437. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10438. auto se = detail::scope_exit([&] {
  10439. svr.stop();
  10440. thread.join();
  10441. ASSERT_FALSE(svr.is_running());
  10442. });
  10443. svr.wait_until_ready();
  10444. {
  10445. httplib::Client cli("127.0.0.1", port);
  10446. cli.set_keep_alive(true);
  10447. // Use the behavior of cpp-httplib of opening the connection
  10448. // only when the first request happens. If that changes,
  10449. // this test would be obsolete.
  10450. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10451. // This also implicitly tests the server. But other tests would fail much
  10452. // earlier than this one to be considered.
  10453. auto res = cli.Get("/");
  10454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10455. EXPECT_EQ(StatusCode::OK_200, res->status);
  10456. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10457. }
  10458. }
  10459. #ifdef CPPHTTPLIB_SSL_ENABLED
  10460. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10461. Client cli("http://yahoo.com");
  10462. auto res = cli.Get("/");
  10463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10464. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10465. cli.set_follow_location(true);
  10466. res = cli.Get("/");
  10467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10468. EXPECT_EQ(StatusCode::OK_200, res->status);
  10469. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10470. }
  10471. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10472. Client cli("https://yahoo.com");
  10473. auto res = cli.Get("/");
  10474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10475. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10476. cli.set_follow_location(true);
  10477. res = cli.Get("/");
  10478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10479. EXPECT_EQ(StatusCode::OK_200, res->status);
  10480. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10481. }
  10482. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10483. Client cli("https://yahoo.com");
  10484. auto res = cli.Get("/");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. ASSERT_FALSE(!res);
  10487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10488. ASSERT_FALSE(res == nullptr);
  10489. ASSERT_TRUE(res != nullptr);
  10490. EXPECT_EQ(Error::Success, res.error());
  10491. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10492. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10493. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10494. cli.set_follow_location(true);
  10495. res = cli.Get("/");
  10496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10497. EXPECT_EQ(Error::Success, res.error());
  10498. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10499. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10500. EXPECT_EQ(StatusCode::OK_200, res->status);
  10501. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10502. }
  10503. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10504. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10505. Client cli("https://cdnjs.cloudflare.com");
  10506. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10507. Headers{{"Accept-Encoding", "br"}});
  10508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10509. EXPECT_EQ(StatusCode::OK_200, res->status);
  10510. EXPECT_EQ(287630U, res->body.size());
  10511. EXPECT_EQ("application/javascript; charset=utf-8",
  10512. res->get_header_value("Content-Type"));
  10513. }
  10514. #endif
  10515. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10516. #undef REDIR_HOST // Silence compiler warning
  10517. #define REDIR_HOST "https://httpbingo.org"
  10518. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10519. Client cli(REDIR_HOST);
  10520. cli.set_follow_location(true);
  10521. auto res =
  10522. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10524. EXPECT_EQ(StatusCode::OK_200, res->status);
  10525. }
  10526. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10527. Client cli(REDIR_HOST);
  10528. cli.set_follow_location(true);
  10529. Params params;
  10530. params.emplace("url", "http://example.com");
  10531. params.emplace("status_code", "302");
  10532. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10534. EXPECT_EQ(StatusCode::OK_200, res->status);
  10535. }
  10536. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10537. Client cli(REDIR_HOST);
  10538. cli.set_follow_location(true);
  10539. Params params;
  10540. params.emplace("url", "http://example.com");
  10541. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10543. EXPECT_EQ(StatusCode::OK_200, res->status);
  10544. }
  10545. TEST(HttpToHttpsRedirectTest, CertFile) {
  10546. auto ssl_port = PORT + 1;
  10547. Server svr;
  10548. ASSERT_TRUE(svr.is_valid());
  10549. svr.Get("/index", [&](const Request &, Response &res) {
  10550. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10551. "/index");
  10552. svr.stop();
  10553. });
  10554. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10555. ASSERT_TRUE(ssl_svr.is_valid());
  10556. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10557. res.set_content("test", "text/plain");
  10558. ssl_svr.stop();
  10559. });
  10560. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10561. thread t2 =
  10562. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10563. auto se = detail::scope_exit([&] {
  10564. t2.join();
  10565. t.join();
  10566. ASSERT_FALSE(svr.is_running());
  10567. });
  10568. svr.wait_until_ready();
  10569. ssl_svr.wait_until_ready();
  10570. Client cli("127.0.0.1", PORT);
  10571. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10572. cli.enable_server_certificate_verification(true);
  10573. cli.set_follow_location(true);
  10574. cli.set_connection_timeout(30);
  10575. auto res = cli.Get("/index");
  10576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10577. ASSERT_EQ(StatusCode::OK_200, res->status);
  10578. }
  10579. TEST(SSLClientRedirectTest, CertFile) {
  10580. auto ssl_port = PORT + 1;
  10581. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10582. ASSERT_TRUE(ssl_svr1.is_valid());
  10583. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10584. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10585. "/index");
  10586. ssl_svr1.stop();
  10587. });
  10588. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10589. ASSERT_TRUE(ssl_svr2.is_valid());
  10590. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10591. res.set_content("test", "text/plain");
  10592. ssl_svr2.stop();
  10593. });
  10594. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10595. thread t2 =
  10596. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10597. auto se = detail::scope_exit([&] {
  10598. t2.join();
  10599. t.join();
  10600. ASSERT_FALSE(ssl_svr1.is_running());
  10601. });
  10602. ssl_svr1.wait_until_ready();
  10603. ssl_svr2.wait_until_ready();
  10604. SSLClient cli("127.0.0.1", PORT);
  10605. std::string cert;
  10606. read_file(SERVER_CERT2_FILE, cert);
  10607. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10608. cli.enable_server_certificate_verification(true);
  10609. cli.set_follow_location(true);
  10610. cli.set_connection_timeout(30);
  10611. auto res = cli.Get("/index");
  10612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10613. ASSERT_EQ(StatusCode::OK_200, res->status);
  10614. }
  10615. #endif
  10616. #ifdef CPPHTTPLIB_SSL_ENABLED
  10617. // Test that set_ca_cert_store() skips system certs (consistent with
  10618. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10619. // should be trusted - system certs should NOT be loaded.
  10620. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10621. // Load a specific cert that is NOT a system CA cert
  10622. std::string cert;
  10623. read_file(SERVER_CERT2_FILE, cert);
  10624. SSLClient cli("google.com");
  10625. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10626. cli.enable_server_certificate_verification(true);
  10627. // This should FAIL because:
  10628. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10629. // 2. System certs should NOT be loaded when custom store is set
  10630. // If system certs WERE loaded, this would succeed
  10631. auto res = cli.Get("/");
  10632. ASSERT_FALSE(res);
  10633. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10634. }
  10635. // Same as above, but through the native store handle path. Regression test:
  10636. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10637. // merged system certs into the user-provided store.
  10638. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10639. std::string cert;
  10640. read_file(SERVER_CERT2_FILE, cert);
  10641. SSLClient cli("google.com");
  10642. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10643. cli.enable_server_certificate_verification(true);
  10644. auto res = cli.Get("/");
  10645. ASSERT_FALSE(res);
  10646. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10647. }
  10648. // A custom store set via the native handle must still verify a server whose
  10649. // cert it does contain.
  10650. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10651. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10652. ASSERT_TRUE(svr.is_valid());
  10653. svr.Get("/test", [&](const Request &, Response &res) {
  10654. res.set_content("test", "text/plain");
  10655. });
  10656. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10657. auto se = detail::scope_exit([&] {
  10658. svr.stop();
  10659. t.join();
  10660. ASSERT_FALSE(svr.is_running());
  10661. });
  10662. svr.wait_until_ready();
  10663. SSLClient cli("127.0.0.1", PORT);
  10664. std::string cert;
  10665. read_file(SERVER_CERT2_FILE, cert);
  10666. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10667. cli.enable_server_certificate_verification(true);
  10668. cli.set_connection_timeout(30);
  10669. auto res = cli.Get("/test");
  10670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10671. ASSERT_EQ(StatusCode::OK_200, res->status);
  10672. }
  10673. // CA certs loaded through the universal Client must be transferred to the
  10674. // client created internally for following an HTTPS redirect. Regression test:
  10675. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10676. // the CA data for redirect transfer.
  10677. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10678. auto ssl_port = PORT + 1;
  10679. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10680. ASSERT_TRUE(ssl_svr1.is_valid());
  10681. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10682. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10683. "/index");
  10684. });
  10685. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10686. ASSERT_TRUE(ssl_svr2.is_valid());
  10687. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10688. res.set_content("test", "text/plain");
  10689. });
  10690. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10691. thread t2 =
  10692. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10693. auto se = detail::scope_exit([&] {
  10694. ssl_svr2.stop();
  10695. ssl_svr1.stop();
  10696. t2.join();
  10697. t.join();
  10698. ASSERT_FALSE(ssl_svr1.is_running());
  10699. });
  10700. ssl_svr1.wait_until_ready();
  10701. ssl_svr2.wait_until_ready();
  10702. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10703. std::string cert;
  10704. read_file(SERVER_CERT2_FILE, cert);
  10705. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10706. cli.enable_server_certificate_verification(true);
  10707. cli.set_follow_location(true);
  10708. cli.set_connection_timeout(30);
  10709. auto res = cli.Get("/index");
  10710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10711. ASSERT_EQ(StatusCode::OK_200, res->status);
  10712. }
  10713. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10714. // so a host signed by a system CA verifies even though a custom CA is set
  10715. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10716. std::string cert;
  10717. read_file(SERVER_CERT2_FILE, cert);
  10718. SSLClient cli("google.com");
  10719. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10720. cli.enable_system_ca(true);
  10721. cli.enable_server_certificate_verification(true);
  10722. auto res = cli.Get("/");
  10723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10724. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10725. }
  10726. // The custom CA remains effective when combined with the system CA
  10727. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10728. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10729. ASSERT_TRUE(svr.is_valid());
  10730. svr.Get("/test", [&](const Request &, Response &res) {
  10731. res.set_content("test", "text/plain");
  10732. });
  10733. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10734. auto se = detail::scope_exit([&] {
  10735. svr.stop();
  10736. t.join();
  10737. ASSERT_FALSE(svr.is_running());
  10738. });
  10739. svr.wait_until_ready();
  10740. SSLClient cli("127.0.0.1", PORT);
  10741. std::string cert;
  10742. read_file(SERVER_CERT2_FILE, cert);
  10743. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10744. cli.enable_system_ca(true);
  10745. cli.enable_server_certificate_verification(true);
  10746. cli.set_connection_timeout(30);
  10747. auto res = cli.Get("/test");
  10748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10749. ASSERT_EQ(StatusCode::OK_200, res->status);
  10750. }
  10751. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10752. // skip chain verification entirely (only the certificate identity was
  10753. // checked), so a server presenting an untrusted certificate with a matching
  10754. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10755. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10756. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10757. ASSERT_TRUE(svr.is_valid());
  10758. svr.Get("/test", [&](const Request &, Response &res) {
  10759. res.set_content("test", "text/plain");
  10760. });
  10761. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10762. auto se = detail::scope_exit([&] {
  10763. svr.stop();
  10764. t.join();
  10765. ASSERT_FALSE(svr.is_running());
  10766. });
  10767. svr.wait_until_ready();
  10768. SSLClient cli("127.0.0.1", PORT);
  10769. std::string cert;
  10770. // A trusted CA that did not sign the server certificate. The server cert
  10771. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10772. // this connection.
  10773. read_file(CLIENT_CA_CERT_FILE, cert);
  10774. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10775. cli.enable_server_certificate_verification(true);
  10776. cli.set_connection_timeout(30);
  10777. auto res = cli.Get("/test");
  10778. ASSERT_FALSE(res);
  10779. }
  10780. // enable_system_ca(false) prevents system CA loading entirely
  10781. TEST(SSLClientTest, DisableSystemCa_Online) {
  10782. SSLClient cli("google.com");
  10783. cli.enable_system_ca(false);
  10784. cli.enable_server_certificate_verification(true);
  10785. auto res = cli.Get("/");
  10786. ASSERT_FALSE(res);
  10787. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10788. // itself when the CA chain is empty
  10789. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10790. res.error() == Error::SSLConnection);
  10791. }
  10792. // The universal Client forwards enable_system_ca()
  10793. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10794. std::string cert;
  10795. read_file(SERVER_CERT2_FILE, cert);
  10796. Client cli("https://google.com");
  10797. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10798. cli.enable_system_ca(true);
  10799. cli.enable_server_certificate_verification(true);
  10800. auto res = cli.Get("/");
  10801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10802. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10803. }
  10804. // The system CA policy must carry over to the client created internally for
  10805. // following a cross-host HTTPS redirect
  10806. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10807. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10808. ASSERT_TRUE(svr.is_valid());
  10809. svr.Get("/index", [&](const Request &, Response &res) {
  10810. res.set_redirect("https://www.google.com/");
  10811. });
  10812. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10813. auto se = detail::scope_exit([&] {
  10814. svr.stop();
  10815. t.join();
  10816. ASSERT_FALSE(svr.is_running());
  10817. });
  10818. svr.wait_until_ready();
  10819. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10820. std::string cert;
  10821. read_file(SERVER_CERT2_FILE, cert);
  10822. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10823. cli.enable_system_ca(true);
  10824. cli.enable_server_certificate_verification(true);
  10825. cli.set_follow_location(true);
  10826. cli.set_connection_timeout(30);
  10827. // Receiving any response proves the redirect client completed the TLS
  10828. // handshake with a system-CA-signed host
  10829. auto res = cli.Get("/index");
  10830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10831. }
  10832. TEST(MultipartFormDataTest, LargeData) {
  10833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10834. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10835. const ContentReader &content_reader) {
  10836. if (req.is_multipart_form_data()) {
  10837. std::vector<FormData> items;
  10838. content_reader(
  10839. [&](const FormData &file) {
  10840. items.push_back(file);
  10841. return true;
  10842. },
  10843. [&](const char *data, size_t data_length) {
  10844. items.back().content.append(data, data_length);
  10845. return true;
  10846. });
  10847. EXPECT_TRUE(std::string(items[0].name) == "document");
  10848. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10849. EXPECT_TRUE(items[0].filename == "2MB_data");
  10850. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10851. EXPECT_TRUE(items[1].name == "hello");
  10852. EXPECT_TRUE(items[1].content == "world");
  10853. EXPECT_TRUE(items[1].filename == "");
  10854. EXPECT_TRUE(items[1].content_type == "");
  10855. } else {
  10856. std::string body;
  10857. content_reader([&](const char *data, size_t data_length) {
  10858. body.append(data, data_length);
  10859. return true;
  10860. });
  10861. }
  10862. });
  10863. auto port = svr.bind_to_any_port(HOST);
  10864. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10865. auto se = detail::scope_exit([&] {
  10866. svr.stop();
  10867. t.join();
  10868. ASSERT_FALSE(svr.is_running());
  10869. });
  10870. svr.wait_until_ready();
  10871. {
  10872. std::string data(1024 * 1024 * 2, '.');
  10873. std::stringstream buffer;
  10874. buffer << data;
  10875. SSLClient cli(HOST, port);
  10876. cli.enable_server_certificate_verification(false);
  10877. UploadFormDataItems items{
  10878. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10879. {"hello", "world", "", ""},
  10880. };
  10881. auto res = cli.Post("/post", items);
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. ASSERT_EQ(StatusCode::OK_200, res->status);
  10884. }
  10885. }
  10886. TEST(MultipartFormDataTest, DataProviderItems) {
  10887. std::random_device seed_gen;
  10888. std::mt19937 random(seed_gen());
  10889. std::string rand1;
  10890. rand1.resize(1000);
  10891. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10892. std::string rand2;
  10893. rand2.resize(3000);
  10894. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10896. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10897. const ContentReader &content_reader) {
  10898. ASSERT_FALSE(req.is_multipart_form_data());
  10899. std::string body;
  10900. content_reader([&](const char *data, size_t data_length) {
  10901. body.append(data, data_length);
  10902. return true;
  10903. });
  10904. EXPECT_EQ(body, "");
  10905. });
  10906. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10907. const ContentReader &content_reader) {
  10908. ASSERT_TRUE(req.is_multipart_form_data());
  10909. std::vector<FormData> items;
  10910. content_reader(
  10911. [&](const FormData &file) {
  10912. items.push_back(file);
  10913. return true;
  10914. },
  10915. [&](const char *data, size_t data_length) {
  10916. items.back().content.append(data, data_length);
  10917. return true;
  10918. });
  10919. ASSERT_TRUE(items.size() == 2);
  10920. EXPECT_EQ(std::string(items[0].name), "name1");
  10921. EXPECT_EQ(items[0].content, "Testing123");
  10922. EXPECT_EQ(items[0].filename, "filename1");
  10923. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10924. EXPECT_EQ(items[1].name, "name2");
  10925. EXPECT_EQ(items[1].content, "Testing456");
  10926. EXPECT_EQ(items[1].filename, "");
  10927. EXPECT_EQ(items[1].content_type, "");
  10928. });
  10929. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10930. const ContentReader &content_reader) {
  10931. ASSERT_TRUE(req.is_multipart_form_data());
  10932. std::vector<FormData> items;
  10933. content_reader(
  10934. [&](const FormData &file) {
  10935. items.push_back(file);
  10936. return true;
  10937. },
  10938. [&](const char *data, size_t data_length) {
  10939. items.back().content.append(data, data_length);
  10940. return true;
  10941. });
  10942. ASSERT_TRUE(items.size() == 2);
  10943. EXPECT_EQ(items[0].name, "name3");
  10944. EXPECT_EQ(items[0].content, rand1);
  10945. EXPECT_EQ(items[0].filename, "filename3");
  10946. EXPECT_EQ(items[0].content_type, "");
  10947. EXPECT_EQ(items[1].name, "name4");
  10948. EXPECT_EQ(items[1].content, rand2);
  10949. EXPECT_EQ(items[1].filename, "filename4");
  10950. EXPECT_EQ(items[1].content_type, "");
  10951. });
  10952. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10953. const ContentReader &content_reader) {
  10954. ASSERT_TRUE(req.is_multipart_form_data());
  10955. std::vector<FormData> items;
  10956. content_reader(
  10957. [&](const FormData &file) {
  10958. items.push_back(file);
  10959. return true;
  10960. },
  10961. [&](const char *data, size_t data_length) {
  10962. items.back().content.append(data, data_length);
  10963. return true;
  10964. });
  10965. ASSERT_TRUE(items.size() == 4);
  10966. EXPECT_EQ(std::string(items[0].name), "name1");
  10967. EXPECT_EQ(items[0].content, "Testing123");
  10968. EXPECT_EQ(items[0].filename, "filename1");
  10969. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10970. EXPECT_EQ(items[1].name, "name2");
  10971. EXPECT_EQ(items[1].content, "Testing456");
  10972. EXPECT_EQ(items[1].filename, "");
  10973. EXPECT_EQ(items[1].content_type, "");
  10974. EXPECT_EQ(items[2].name, "name3");
  10975. EXPECT_EQ(items[2].content, rand1);
  10976. EXPECT_EQ(items[2].filename, "filename3");
  10977. EXPECT_EQ(items[2].content_type, "");
  10978. EXPECT_EQ(items[3].name, "name4");
  10979. EXPECT_EQ(items[3].content, rand2);
  10980. EXPECT_EQ(items[3].filename, "filename4");
  10981. EXPECT_EQ(items[3].content_type, "");
  10982. });
  10983. auto port = svr.bind_to_any_port("localhost");
  10984. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10985. auto se = detail::scope_exit([&] {
  10986. svr.stop();
  10987. t.join();
  10988. ASSERT_FALSE(svr.is_running());
  10989. });
  10990. svr.wait_until_ready();
  10991. {
  10992. SSLClient cli("localhost", port);
  10993. cli.enable_server_certificate_verification(false);
  10994. UploadFormDataItems items{
  10995. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10996. {"name2", "Testing456", "", ""}, // not a file
  10997. };
  10998. {
  10999. auto res = cli.Post("/post-none", {}, {}, {});
  11000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11001. ASSERT_EQ(StatusCode::OK_200, res->status);
  11002. }
  11003. FormDataProviderItems providers;
  11004. {
  11005. auto res =
  11006. cli.Post("/post-items", {}, items, providers); // empty providers
  11007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11008. ASSERT_EQ(StatusCode::OK_200, res->status);
  11009. }
  11010. providers.push_back({"name3",
  11011. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11012. // test the offset is given correctly at each step
  11013. if (!offset)
  11014. sink.os.write(rand1.data(), 30);
  11015. else if (offset == 30)
  11016. sink.os.write(rand1.data() + 30, 300);
  11017. else if (offset == 330)
  11018. sink.os.write(rand1.data() + 330, 670);
  11019. else if (offset == rand1.size())
  11020. sink.done();
  11021. return true;
  11022. },
  11023. "filename3",
  11024. {}});
  11025. providers.push_back({"name4",
  11026. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11027. // test the offset is given correctly at each step
  11028. if (!offset)
  11029. sink.os.write(rand2.data(), 2000);
  11030. else if (offset == 2000)
  11031. sink.os.write(rand2.data() + 2000, 1);
  11032. else if (offset == 2001)
  11033. sink.os.write(rand2.data() + 2001, 999);
  11034. else if (offset == rand2.size())
  11035. sink.done();
  11036. return true;
  11037. },
  11038. "filename4",
  11039. {}});
  11040. {
  11041. auto res = cli.Post("/post-providers", {}, {}, providers);
  11042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11043. ASSERT_EQ(StatusCode::OK_200, res->status);
  11044. }
  11045. {
  11046. auto res = cli.Post("/post-both", {}, items, providers);
  11047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11048. ASSERT_EQ(StatusCode::OK_200, res->status);
  11049. }
  11050. }
  11051. }
  11052. TEST(MultipartFormDataTest, BadHeader) {
  11053. Server svr;
  11054. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11055. res.set_content("ok", "text/plain");
  11056. });
  11057. thread t = thread([&] { svr.listen(HOST, PORT); });
  11058. auto se = detail::scope_exit([&] {
  11059. svr.stop();
  11060. t.join();
  11061. ASSERT_FALSE(svr.is_running());
  11062. });
  11063. svr.wait_until_ready();
  11064. const std::string body =
  11065. "This is the preamble. It is to be ignored, though it\r\n"
  11066. "is a handy place for composition agents to include an\r\n"
  11067. "explanatory note to non-MIME conformant readers.\r\n"
  11068. "\r\n"
  11069. "\r\n"
  11070. "--simple boundary\r\n"
  11071. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11072. ": BAD...\r\n"
  11073. "\r\n"
  11074. "value1\r\n"
  11075. "--simple boundary\r\n"
  11076. "Content-Disposition: form-data; name=\"field2\"; "
  11077. "filename=\"example.txt\"\r\n"
  11078. "\r\n"
  11079. "value2\r\n"
  11080. "--simple boundary--\r\n"
  11081. "This is the epilogue. It is also to be ignored.\r\n";
  11082. std::string content_type =
  11083. R"(multipart/form-data; boundary="simple boundary")";
  11084. Client cli(HOST, PORT);
  11085. auto res = cli.Post("/post", body, content_type.c_str());
  11086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11087. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11088. }
  11089. TEST(MultipartFormDataTest, WithPreamble) {
  11090. Server svr;
  11091. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11092. res.set_content("ok", "text/plain");
  11093. });
  11094. thread t = thread([&] { svr.listen(HOST, PORT); });
  11095. auto se = detail::scope_exit([&] {
  11096. svr.stop();
  11097. t.join();
  11098. ASSERT_FALSE(svr.is_running());
  11099. });
  11100. svr.wait_until_ready();
  11101. const std::string body =
  11102. "This is the preamble. It is to be ignored, though it\r\n"
  11103. "is a handy place for composition agents to include an\r\n"
  11104. "explanatory note to non-MIME conformant readers.\r\n"
  11105. "\r\n"
  11106. "\r\n"
  11107. "--simple boundary\r\n"
  11108. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11109. "\r\n"
  11110. "value1\r\n"
  11111. "--simple boundary\r\n"
  11112. "Content-Disposition: form-data; name=\"field2\"; "
  11113. "filename=\"example.txt\"\r\n"
  11114. "\r\n"
  11115. "value2\r\n"
  11116. "--simple boundary--\r\n"
  11117. "This is the epilogue. It is also to be ignored.\r\n";
  11118. std::string content_type =
  11119. R"(multipart/form-data; boundary="simple boundary")";
  11120. Client cli(HOST, PORT);
  11121. auto res = cli.Post("/post", body, content_type.c_str());
  11122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11123. EXPECT_EQ(StatusCode::OK_200, res->status);
  11124. }
  11125. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11127. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11128. const ContentReader &content_reader) {
  11129. if (req.is_multipart_form_data()) {
  11130. std::vector<FormData> items;
  11131. content_reader(
  11132. [&](const FormData &file) {
  11133. items.push_back(file);
  11134. return true;
  11135. },
  11136. [&](const char *data, size_t data_length) {
  11137. items.back().content.append(data, data_length);
  11138. return true;
  11139. });
  11140. EXPECT_TRUE(std::string(items[0].name) == "document");
  11141. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11142. EXPECT_TRUE(items[0].filename == "2MB_data");
  11143. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11144. EXPECT_TRUE(items[1].name == "hello");
  11145. EXPECT_TRUE(items[1].content == "world");
  11146. EXPECT_TRUE(items[1].filename == "");
  11147. EXPECT_TRUE(items[1].content_type == "");
  11148. } else {
  11149. std::string body;
  11150. content_reader([&](const char *data, size_t data_length) {
  11151. body.append(data, data_length);
  11152. return true;
  11153. });
  11154. }
  11155. });
  11156. auto port = svr.bind_to_any_port("localhost");
  11157. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11158. auto se = detail::scope_exit([&] {
  11159. svr.stop();
  11160. t.join();
  11161. ASSERT_FALSE(svr.is_running());
  11162. });
  11163. svr.wait_until_ready();
  11164. {
  11165. std::string data(1024 * 1024 * 2, '.');
  11166. std::stringstream buffer;
  11167. buffer << data;
  11168. SSLClient cli("localhost", port);
  11169. cli.enable_server_certificate_verification(false);
  11170. UploadFormDataItems items{
  11171. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11172. {"hello", "world", "", ""},
  11173. };
  11174. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11176. ASSERT_EQ(StatusCode::OK_200, res->status);
  11177. }
  11178. }
  11179. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11180. std::string data(1024 * 1024 * 2, '&');
  11181. std::stringstream buffer;
  11182. buffer << data;
  11183. Client cli("https://localhost:8080");
  11184. UploadFormDataItems items{
  11185. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11186. {"hello", "world", "", ""},
  11187. };
  11188. for (const char &c : " \t\r\n") {
  11189. auto res =
  11190. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11191. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11192. ASSERT_FALSE(res);
  11193. }
  11194. }
  11195. TEST(MultipartFormDataTest, PutFormData) {
  11196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11197. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11198. const ContentReader &content_reader) {
  11199. if (req.is_multipart_form_data()) {
  11200. std::vector<FormData> items;
  11201. content_reader(
  11202. [&](const FormData &file) {
  11203. items.push_back(file);
  11204. return true;
  11205. },
  11206. [&](const char *data, size_t data_length) {
  11207. items.back().content.append(data, data_length);
  11208. return true;
  11209. });
  11210. EXPECT_TRUE(std::string(items[0].name) == "document");
  11211. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11212. EXPECT_TRUE(items[0].filename == "2MB_data");
  11213. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11214. EXPECT_TRUE(items[1].name == "hello");
  11215. EXPECT_TRUE(items[1].content == "world");
  11216. EXPECT_TRUE(items[1].filename == "");
  11217. EXPECT_TRUE(items[1].content_type == "");
  11218. } else {
  11219. std::string body;
  11220. content_reader([&](const char *data, size_t data_length) {
  11221. body.append(data, data_length);
  11222. return true;
  11223. });
  11224. }
  11225. });
  11226. auto port = svr.bind_to_any_port("localhost");
  11227. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11228. auto se = detail::scope_exit([&] {
  11229. svr.stop();
  11230. t.join();
  11231. ASSERT_FALSE(svr.is_running());
  11232. });
  11233. svr.wait_until_ready();
  11234. {
  11235. std::string data(1024 * 1024 * 2, '&');
  11236. std::stringstream buffer;
  11237. buffer << data;
  11238. SSLClient cli("localhost", port);
  11239. cli.enable_server_certificate_verification(false);
  11240. UploadFormDataItems items{
  11241. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11242. {"hello", "world", "", ""},
  11243. };
  11244. auto res = cli.Put("/put", items);
  11245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11246. ASSERT_EQ(StatusCode::OK_200, res->status);
  11247. }
  11248. }
  11249. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11251. svr.Put("/put_customboundary",
  11252. [&](const Request &req, const Response & /*res*/,
  11253. const ContentReader &content_reader) {
  11254. if (req.is_multipart_form_data()) {
  11255. std::vector<FormData> items;
  11256. content_reader(
  11257. [&](const FormData &file) {
  11258. items.push_back(file);
  11259. return true;
  11260. },
  11261. [&](const char *data, size_t data_length) {
  11262. items.back().content.append(data, data_length);
  11263. return true;
  11264. });
  11265. EXPECT_TRUE(std::string(items[0].name) == "document");
  11266. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11267. EXPECT_TRUE(items[0].filename == "2MB_data");
  11268. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11269. EXPECT_TRUE(items[1].name == "hello");
  11270. EXPECT_TRUE(items[1].content == "world");
  11271. EXPECT_TRUE(items[1].filename == "");
  11272. EXPECT_TRUE(items[1].content_type == "");
  11273. } else {
  11274. std::string body;
  11275. content_reader([&](const char *data, size_t data_length) {
  11276. body.append(data, data_length);
  11277. return true;
  11278. });
  11279. }
  11280. });
  11281. auto port = svr.bind_to_any_port("localhost");
  11282. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11283. auto se = detail::scope_exit([&] {
  11284. svr.stop();
  11285. t.join();
  11286. ASSERT_FALSE(svr.is_running());
  11287. });
  11288. svr.wait_until_ready();
  11289. {
  11290. std::string data(1024 * 1024 * 2, '&');
  11291. std::stringstream buffer;
  11292. buffer << data;
  11293. SSLClient cli("localhost", port);
  11294. cli.enable_server_certificate_verification(false);
  11295. UploadFormDataItems items{
  11296. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11297. {"hello", "world", "", ""},
  11298. };
  11299. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. ASSERT_EQ(StatusCode::OK_200, res->status);
  11302. }
  11303. }
  11304. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11305. std::string data(1024 * 1024 * 2, '&');
  11306. std::stringstream buffer;
  11307. buffer << data;
  11308. Client cli("https://localhost:8080");
  11309. cli.enable_server_certificate_verification(false);
  11310. UploadFormDataItems items{
  11311. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11312. {"hello", "world", "", ""},
  11313. };
  11314. for (const char &c : " \t\r\n") {
  11315. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11316. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11317. ASSERT_FALSE(res);
  11318. }
  11319. }
  11320. TEST(MultipartFormDataTest, AlternateFilename) {
  11321. auto handled = false;
  11322. Server svr;
  11323. svr.Post("/test", [&](const Request &req, Response &res) {
  11324. ASSERT_EQ(2u, req.form.files.size());
  11325. ASSERT_EQ(1u, req.form.fields.size());
  11326. // Test files
  11327. const auto &file1 = req.form.get_file("file1");
  11328. ASSERT_EQ("file1", file1.name);
  11329. ASSERT_EQ("A.txt", file1.filename);
  11330. ASSERT_EQ("text/plain", file1.content_type);
  11331. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11332. const auto &file2 = req.form.get_file("file2");
  11333. ASSERT_EQ("file2", file2.name);
  11334. ASSERT_EQ("a.html", file2.filename);
  11335. ASSERT_EQ("text/html", file2.content_type);
  11336. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11337. file2.content);
  11338. // Test text field
  11339. const auto &text = req.form.get_field("text");
  11340. ASSERT_EQ("text default", text);
  11341. res.set_content("ok", "text/plain");
  11342. handled = true;
  11343. });
  11344. thread t = thread([&] { svr.listen(HOST, PORT); });
  11345. auto se = detail::scope_exit([&] {
  11346. svr.stop();
  11347. t.join();
  11348. ASSERT_FALSE(svr.is_running());
  11349. ASSERT_TRUE(handled);
  11350. });
  11351. svr.wait_until_ready();
  11352. auto req = "POST /test HTTP/1.1\r\n"
  11353. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11354. "Content-Length: 399\r\n"
  11355. "\r\n"
  11356. "----------\r\n"
  11357. "Content-Disposition: form-data; name=\"text\"\r\n"
  11358. "\r\n"
  11359. "text default\r\n"
  11360. "----------\r\n"
  11361. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11362. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11363. "Content-Type: text/plain\r\n"
  11364. "\r\n"
  11365. "Content of a.txt.\r\n"
  11366. "\r\n"
  11367. "----------\r\n"
  11368. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11369. "\"a.html\"\r\n"
  11370. "Content-Type: text/html\r\n"
  11371. "\r\n"
  11372. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11373. "\r\n"
  11374. "------------\r\n";
  11375. ASSERT_TRUE(send_request(1, req));
  11376. }
  11377. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11378. auto handled = false;
  11379. Server svr;
  11380. svr.Post("/test", [&](const Request &req, Response &res) {
  11381. // Case-insensitive "utf-8''" prefix with a long value
  11382. const auto &file = req.form.get_file("file1");
  11383. ASSERT_EQ("file1", file.name);
  11384. // 8000 chars exercises both the Content-Disposition parser and the
  11385. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11386. // Prior to the fix, std::regex_match on this header would cause O(N)
  11387. // stack recursion in libstdc++, leading to SIGSEGV.
  11388. std::string expected_filename(8000, 'A');
  11389. ASSERT_EQ(expected_filename, file.filename);
  11390. res.set_content("ok", "text/plain");
  11391. handled = true;
  11392. });
  11393. thread t = thread([&] { svr.listen(HOST, PORT); });
  11394. auto se = detail::scope_exit([&] {
  11395. svr.stop();
  11396. t.join();
  11397. ASSERT_FALSE(svr.is_running());
  11398. ASSERT_TRUE(handled);
  11399. });
  11400. svr.wait_until_ready();
  11401. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11402. // Regression test for GHSA-qq6v-r583-3h69
  11403. std::string long_filename(8000, 'A');
  11404. std::string body = "----------\r\n"
  11405. "Content-Disposition: form-data; name=\"file1\"; "
  11406. "filename*=\"Utf-8''" +
  11407. long_filename +
  11408. "\"\r\n"
  11409. "\r\n"
  11410. "hello\r\n"
  11411. "------------\r\n";
  11412. auto req = "POST /test HTTP/1.1\r\n"
  11413. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11414. "Content-Length: " +
  11415. std::to_string(body.size()) + "\r\n\r\n" + body;
  11416. ASSERT_TRUE(send_request(1, req));
  11417. }
  11418. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11419. auto handled = false;
  11420. Server svr;
  11421. svr.Post("/test", [&](const Request &req, Response &) {
  11422. ASSERT_EQ(2u, req.form.fields.size());
  11423. const auto &text1 = req.form.get_field("text1");
  11424. ASSERT_EQ("text1", text1);
  11425. const auto &text2 = req.form.get_field("text2");
  11426. ASSERT_EQ("text2", text2);
  11427. handled = true;
  11428. });
  11429. thread t = thread([&] { svr.listen(HOST, PORT); });
  11430. auto se = detail::scope_exit([&] {
  11431. svr.stop();
  11432. t.join();
  11433. ASSERT_FALSE(svr.is_running());
  11434. ASSERT_TRUE(handled);
  11435. });
  11436. svr.wait_until_ready();
  11437. auto req = "POST /test HTTP/1.1\r\n"
  11438. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11439. "Content-Length: 146\r\n"
  11440. "\r\n----------\r\n"
  11441. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11442. "\r\n"
  11443. "text1"
  11444. "\r\n----------\r\n"
  11445. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11446. "\r\n"
  11447. "text2"
  11448. "\r\n------------";
  11449. std::string response;
  11450. ASSERT_TRUE(send_request(1, req, &response));
  11451. ASSERT_EQ("200", response.substr(9, 3));
  11452. }
  11453. TEST(MultipartFormDataTest, ContentLength) {
  11454. auto handled = false;
  11455. Server svr;
  11456. svr.Post("/test", [&](const Request &req, Response &) {
  11457. ASSERT_EQ(2u, req.form.fields.size());
  11458. const auto &text1 = req.form.get_field("text1");
  11459. ASSERT_EQ("text1", text1);
  11460. const auto &text2 = req.form.get_field("text2");
  11461. ASSERT_EQ("text2", text2);
  11462. handled = true;
  11463. });
  11464. thread t = thread([&] { svr.listen(HOST, PORT); });
  11465. auto se = detail::scope_exit([&] {
  11466. svr.stop();
  11467. t.join();
  11468. ASSERT_FALSE(svr.is_running());
  11469. ASSERT_TRUE(handled);
  11470. });
  11471. svr.wait_until_ready();
  11472. auto req = "POST /test HTTP/1.1\r\n"
  11473. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11474. "Content-Length: 167\r\n"
  11475. "\r\n----------\r\n"
  11476. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11477. "Content-Length: 5\r\n"
  11478. "\r\n"
  11479. "text1"
  11480. "\r\n----------\r\n"
  11481. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11482. "\r\n"
  11483. "text2"
  11484. "\r\n------------\r\n";
  11485. std::string response;
  11486. ASSERT_TRUE(send_request(1, req, &response));
  11487. ASSERT_EQ("200", response.substr(9, 3));
  11488. }
  11489. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11490. auto handled = false;
  11491. Server svr;
  11492. svr.Post("/test", [&](const Request &req, Response &) {
  11493. ASSERT_EQ(2u, req.form.fields.size());
  11494. const auto &text1 = req.form.get_field("text1");
  11495. ASSERT_EQ("text1", text1);
  11496. // TODO: Add header access for text fields if needed
  11497. const auto &text2 = req.form.get_field("text2");
  11498. ASSERT_EQ("text2", text2);
  11499. // TODO: Header access for text fields needs to be implemented
  11500. // auto &headers = it->second.headers;
  11501. // ASSERT_EQ(3U, headers.size());
  11502. // auto custom_header = headers.find("x-whatever");
  11503. // ASSERT_TRUE(custom_header != headers.end());
  11504. // ASSERT_NE("customvalue", custom_header->second);
  11505. // ASSERT_EQ("CustomValue", custom_header->second);
  11506. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11507. handled = true;
  11508. });
  11509. thread t = thread([&] { svr.listen(HOST, PORT); });
  11510. auto se = detail::scope_exit([&] {
  11511. svr.stop();
  11512. t.join();
  11513. ASSERT_FALSE(svr.is_running());
  11514. ASSERT_TRUE(handled);
  11515. });
  11516. svr.wait_until_ready();
  11517. auto req = "POST /test HTTP/1.1\r\n"
  11518. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11519. "Content-Length: 232\r\n"
  11520. "\r\n----------\r\n"
  11521. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11522. "Content-Length: 5\r\n"
  11523. "X-Test: 1\r\n"
  11524. "\r\n"
  11525. "text1"
  11526. "\r\n----------\r\n"
  11527. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11528. "Content-Type: text/plain\r\n"
  11529. "X-Whatever: CustomValue\r\n"
  11530. "\r\n"
  11531. "text2"
  11532. "\r\n------------\r\n"
  11533. "That should be disregarded. Not even read";
  11534. std::string response;
  11535. ASSERT_TRUE(send_request(1, req, &response));
  11536. ASSERT_EQ("200", response.substr(9, 3));
  11537. }
  11538. TEST(MultipartFormDataTest, LargeHeader) {
  11539. auto handled = false;
  11540. Server svr;
  11541. svr.Post("/test", [&](const Request &req, Response &) {
  11542. ASSERT_EQ(1u, req.form.fields.size());
  11543. const auto &text = req.form.get_field("name1");
  11544. ASSERT_EQ("text1", text);
  11545. handled = true;
  11546. });
  11547. thread t = thread([&] { svr.listen(HOST, PORT); });
  11548. auto se = detail::scope_exit([&] {
  11549. svr.stop();
  11550. t.join();
  11551. ASSERT_FALSE(svr.is_running());
  11552. ASSERT_TRUE(handled);
  11553. });
  11554. svr.wait_until_ready();
  11555. auto boundary = std::string("cpp-httplib-multipart-data");
  11556. std::string content = "--" + boundary +
  11557. "\r\n"
  11558. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11559. "\r\n"
  11560. "text1\r\n"
  11561. "--" +
  11562. boundary + "--\r\n";
  11563. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11564. "Content-Type: multipart/form-data;boundary=" +
  11565. boundary +
  11566. "\r\n"
  11567. "Content-Length: " +
  11568. std::to_string(content.size()) +
  11569. "\r\n"
  11570. "Dummy-Header: ";
  11571. std::string header_suffix = "\r\n"
  11572. "\r\n";
  11573. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11574. size_t header_dummy_size =
  11575. read_buff_size -
  11576. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11577. auto header_dummy = std::string(header_dummy_size, '@');
  11578. auto req = header_prefix + header_dummy + header_suffix + content;
  11579. std::string response;
  11580. ASSERT_TRUE(send_request(1, req, &response));
  11581. ASSERT_EQ("200", response.substr(9, 3));
  11582. }
  11583. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11584. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11585. // (not chunked Transfer-Encoding) after the streaming refactor.
  11586. auto handled = false;
  11587. Server svr;
  11588. svr.Post("/upload", [&](const Request &req, Response &res) {
  11589. auto cl_it = req.headers.find("Content-Length");
  11590. EXPECT_TRUE(cl_it != req.headers.end());
  11591. auto te_it = req.headers.find("Transfer-Encoding");
  11592. EXPECT_TRUE(te_it == req.headers.end());
  11593. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11594. res.set_content("ok", "text/plain");
  11595. handled = true;
  11596. });
  11597. auto port = svr.bind_to_any_port(HOST);
  11598. auto t = thread([&] { svr.listen_after_bind(); });
  11599. auto se = detail::scope_exit([&] {
  11600. svr.stop();
  11601. t.join();
  11602. ASSERT_FALSE(svr.is_running());
  11603. ASSERT_TRUE(handled);
  11604. });
  11605. svr.wait_until_ready();
  11606. UploadFormDataItems items = {
  11607. {"field1", "hello", "", "text/plain"},
  11608. {"file1", "world", "test.txt", "application/octet-stream"},
  11609. };
  11610. Client cli(HOST, port);
  11611. auto res = cli.Post("/upload", {}, items);
  11612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11613. EXPECT_EQ(StatusCode::OK_200, res->status);
  11614. }
  11615. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11616. // Verify that make_multipart_content_provider coalesces many small segments
  11617. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11618. constexpr size_t kItemCount = 1000;
  11619. UploadFormDataItems items;
  11620. items.reserve(kItemCount);
  11621. for (size_t i = 0; i < kItemCount; i++) {
  11622. items.push_back(
  11623. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11624. }
  11625. const std::string boundary = "----test-boundary";
  11626. auto content_length = detail::get_multipart_content_length(items, boundary);
  11627. auto provider = detail::make_multipart_content_provider(items, boundary);
  11628. // Drive the provider the same way write_content_with_progress does
  11629. size_t write_count = 0;
  11630. size_t total_bytes = 0;
  11631. DataSink sink;
  11632. size_t offset = 0;
  11633. sink.write = [&](const char *d, size_t l) -> bool {
  11634. (void)d;
  11635. write_count++;
  11636. total_bytes += l;
  11637. offset += l;
  11638. return true;
  11639. };
  11640. sink.is_writable = []() -> bool { return true; };
  11641. while (offset < content_length) {
  11642. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11643. }
  11644. EXPECT_EQ(content_length, total_bytes);
  11645. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11646. // With buffering into 64KB blocks, write_count should be much smaller.
  11647. auto segment_count = 3 * kItemCount + 1;
  11648. EXPECT_LT(write_count, segment_count / 10);
  11649. }
  11650. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11651. // Integration test: send many UploadFormDataItems and verify the server
  11652. // receives all of them correctly (#2410).
  11653. constexpr size_t kItemCount = 500;
  11654. auto handled = false;
  11655. Server svr;
  11656. svr.Post("/upload", [&](const Request &req, Response &res) {
  11657. EXPECT_EQ(kItemCount, req.form.fields.size());
  11658. for (size_t i = 0; i < kItemCount; i++) {
  11659. auto key = "field" + std::to_string(i);
  11660. auto val = "value" + std::to_string(i);
  11661. auto it = req.form.fields.find(key);
  11662. if (it != req.form.fields.end()) {
  11663. EXPECT_EQ(val, it->second.content);
  11664. } else {
  11665. ADD_FAILURE() << "Missing field: " << key;
  11666. }
  11667. }
  11668. res.set_content("ok", "text/plain");
  11669. handled = true;
  11670. });
  11671. auto port = svr.bind_to_any_port(HOST);
  11672. auto t = thread([&] { svr.listen_after_bind(); });
  11673. auto se = detail::scope_exit([&] {
  11674. svr.stop();
  11675. t.join();
  11676. ASSERT_FALSE(svr.is_running());
  11677. ASSERT_TRUE(handled);
  11678. });
  11679. svr.wait_until_ready();
  11680. UploadFormDataItems items;
  11681. items.reserve(kItemCount);
  11682. for (size_t i = 0; i < kItemCount; i++) {
  11683. items.push_back(
  11684. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11685. }
  11686. Client cli(HOST, port);
  11687. auto res = cli.Post("/upload", items);
  11688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11689. EXPECT_EQ(StatusCode::OK_200, res->status);
  11690. }
  11691. TEST(MultipartFormDataTest, MakeFileProvider) {
  11692. // Verify make_file_provider sends a file's contents correctly.
  11693. const std::string file_content(4096, 'Z');
  11694. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11695. {
  11696. std::ofstream ofs(tmp_path, std::ios::binary);
  11697. ofs.write(file_content.data(),
  11698. static_cast<std::streamsize>(file_content.size()));
  11699. }
  11700. auto handled = false;
  11701. Server svr;
  11702. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11703. const ContentReader &content_reader) {
  11704. ASSERT_TRUE(req.is_multipart_form_data());
  11705. std::vector<FormData> items;
  11706. content_reader(
  11707. [&](const FormData &file) {
  11708. items.push_back(file);
  11709. return true;
  11710. },
  11711. [&](const char *data, size_t data_length) {
  11712. items.back().content.append(data, data_length);
  11713. return true;
  11714. });
  11715. ASSERT_EQ(1u, items.size());
  11716. EXPECT_EQ("myfile", items[0].name);
  11717. EXPECT_EQ("data.bin", items[0].filename);
  11718. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11719. EXPECT_EQ(file_content, items[0].content);
  11720. handled = true;
  11721. });
  11722. auto port = svr.bind_to_any_port(HOST);
  11723. auto t = thread([&] { svr.listen_after_bind(); });
  11724. auto se = detail::scope_exit([&] {
  11725. svr.stop();
  11726. t.join();
  11727. ASSERT_FALSE(svr.is_running());
  11728. ASSERT_TRUE(handled);
  11729. std::remove(tmp_path.c_str());
  11730. });
  11731. svr.wait_until_ready();
  11732. FormDataProviderItems providers;
  11733. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11734. "application/octet-stream"));
  11735. Client cli(HOST, port);
  11736. auto res = cli.Post("/upload", {}, {}, providers);
  11737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11738. EXPECT_EQ(StatusCode::OK_200, res->status);
  11739. }
  11740. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11741. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11742. // (100) headers is rejected with a 400 Bad Request response.
  11743. Server svr;
  11744. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11745. res.set_content("ok", "text/plain");
  11746. });
  11747. thread t = thread([&] { svr.listen(HOST, PORT); });
  11748. auto se = detail::scope_exit([&] {
  11749. svr.stop();
  11750. t.join();
  11751. ASSERT_FALSE(svr.is_running());
  11752. });
  11753. svr.wait_until_ready();
  11754. // Build a multipart part with 101 custom headers (exceeding
  11755. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11756. std::stringstream body;
  11757. body << "--simpleboundary\r\n"
  11758. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11759. for (int i = 0; i < 101; i++) {
  11760. body << "X-Custom-Header-" << i << ": value\r\n";
  11761. }
  11762. body << "\r\n"
  11763. << "value1\r\n"
  11764. << "--simpleboundary--\r\n";
  11765. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11766. Client cli(HOST, PORT);
  11767. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11769. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11770. }
  11771. TEST(MakeFileBodyTest, Basic) {
  11772. const std::string file_content(4096, 'Z');
  11773. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11774. {
  11775. std::ofstream ofs(tmp_path, std::ios::binary);
  11776. ofs.write(file_content.data(),
  11777. static_cast<std::streamsize>(file_content.size()));
  11778. }
  11779. auto handled = false;
  11780. Server svr;
  11781. svr.Post("/upload", [&](const Request &req, Response &res) {
  11782. EXPECT_EQ(file_content, req.body);
  11783. handled = true;
  11784. res.status = StatusCode::OK_200;
  11785. });
  11786. auto port = svr.bind_to_any_port(HOST);
  11787. auto t = thread([&] { svr.listen_after_bind(); });
  11788. auto se = detail::scope_exit([&] {
  11789. svr.stop();
  11790. t.join();
  11791. ASSERT_FALSE(svr.is_running());
  11792. ASSERT_TRUE(handled);
  11793. std::remove(tmp_path.c_str());
  11794. });
  11795. svr.wait_until_ready();
  11796. auto fb = make_file_body(tmp_path);
  11797. ASSERT_GT(fb.first, 0u);
  11798. Client cli(HOST, port);
  11799. auto res =
  11800. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11802. EXPECT_EQ(StatusCode::OK_200, res->status);
  11803. }
  11804. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11805. static constexpr unsigned int number_of_tasks{1000000};
  11806. std::atomic_uint count{0};
  11807. std::unique_ptr<TaskQueue> task_queue{
  11808. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11809. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11810. auto queued = task_queue->enqueue(
  11811. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11812. EXPECT_TRUE(queued);
  11813. }
  11814. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11815. task_queue->shutdown();
  11816. #else
  11817. EXPECT_NO_THROW(task_queue->shutdown());
  11818. #endif
  11819. EXPECT_EQ(number_of_tasks, count.load());
  11820. }
  11821. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11822. static constexpr unsigned int number_of_tasks{1000000};
  11823. static constexpr unsigned int qlimit{2};
  11824. unsigned int queued_count{0};
  11825. std::atomic_uint count{0};
  11826. std::unique_ptr<TaskQueue> task_queue{
  11827. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11828. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11829. if (task_queue->enqueue(
  11830. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11831. queued_count++;
  11832. }
  11833. }
  11834. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11835. task_queue->shutdown();
  11836. #else
  11837. EXPECT_NO_THROW(task_queue->shutdown());
  11838. #endif
  11839. EXPECT_EQ(queued_count, count.load());
  11840. EXPECT_TRUE(queued_count <= number_of_tasks);
  11841. EXPECT_TRUE(queued_count >= qlimit);
  11842. }
  11843. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11844. // Use a short idle timeout so a dynamic thread spawns, times out and
  11845. // exits during the test, and the pool keeps working afterwards.
  11846. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11847. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11848. /*idle_timeout_sec=*/1}};
  11849. std::atomic_uint count{0};
  11850. std::condition_variable cv;
  11851. std::mutex mtx;
  11852. bool release = false;
  11853. // Block the base thread so the second task spawns a dynamic thread.
  11854. EXPECT_TRUE(task_queue->enqueue([&] {
  11855. std::unique_lock<std::mutex> lock(mtx);
  11856. while (!release) {
  11857. cv.wait(lock);
  11858. }
  11859. count++;
  11860. }));
  11861. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11862. // Let the dynamic thread finish its task and exceed the idle timeout.
  11863. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11864. {
  11865. std::unique_lock<std::mutex> lock(mtx);
  11866. release = true;
  11867. }
  11868. cv.notify_all();
  11869. // The pool must still accept and run tasks after the dynamic thread exited.
  11870. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11871. task_queue->shutdown();
  11872. EXPECT_EQ(3u, count.load());
  11873. }
  11874. TEST(TaskQueueTest, MaxQueuedRequests) {
  11875. static constexpr unsigned int qlimit{3};
  11876. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11877. std::condition_variable sem_cv;
  11878. std::mutex sem_mtx;
  11879. int credits = 0;
  11880. bool queued;
  11881. /* Fill up the queue with tasks that will block until we give them credits to
  11882. * complete. */
  11883. for (unsigned int n = 0; n <= qlimit;) {
  11884. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11885. std::unique_lock<std::mutex> lock(sem_mtx);
  11886. while (credits <= 0) {
  11887. sem_cv.wait(lock);
  11888. }
  11889. /* Consume the credit and signal the test code if they are all gone. */
  11890. if (--credits == 0) { sem_cv.notify_one(); }
  11891. });
  11892. if (n < qlimit) {
  11893. /* The first qlimit enqueues must succeed. */
  11894. EXPECT_TRUE(queued);
  11895. } else {
  11896. /* The last one will succeed only when the worker thread
  11897. * starts and dequeues the first blocking task. Although
  11898. * not necessary for the correctness of this test, we sleep for
  11899. * a short while to avoid busy waiting. */
  11900. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11901. }
  11902. if (queued) { n++; }
  11903. }
  11904. /* Further enqueues must fail since the queue is full. */
  11905. for (auto i = 0; i < 4; i++) {
  11906. queued = task_queue->enqueue([] {});
  11907. EXPECT_FALSE(queued);
  11908. }
  11909. /* Give the credits to allow the previous tasks to complete. */
  11910. {
  11911. std::unique_lock<std::mutex> lock(sem_mtx);
  11912. credits += qlimit + 1;
  11913. }
  11914. sem_cv.notify_all();
  11915. /* Wait for all the credits to be consumed. */
  11916. {
  11917. std::unique_lock<std::mutex> lock(sem_mtx);
  11918. while (credits > 0) {
  11919. sem_cv.wait(lock);
  11920. }
  11921. }
  11922. /* Check that we are able again to enqueue at least qlimit tasks. */
  11923. for (unsigned int i = 0; i < qlimit; i++) {
  11924. queued = task_queue->enqueue([] {});
  11925. EXPECT_TRUE(queued);
  11926. }
  11927. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11928. task_queue->shutdown();
  11929. #else
  11930. EXPECT_NO_THROW(task_queue->shutdown());
  11931. #endif
  11932. }
  11933. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11934. Server svr;
  11935. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11936. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11937. });
  11938. svr.Get("/hello", [](const Request &req, Response &res) {
  11939. res.set_content(req.get_param_value("key"), "text/plain");
  11940. });
  11941. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11942. auto se = detail::scope_exit([&] {
  11943. svr.stop();
  11944. thread.join();
  11945. ASSERT_FALSE(svr.is_running());
  11946. });
  11947. svr.wait_until_ready();
  11948. {
  11949. Client cli(HOST, PORT);
  11950. cli.set_follow_location(true);
  11951. auto res = cli.Get("/");
  11952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11953. EXPECT_EQ(StatusCode::OK_200, res->status);
  11954. EXPECT_EQ("val&key2=val2", res->body);
  11955. }
  11956. }
  11957. #endif
  11958. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11959. Server svr;
  11960. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11961. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11962. });
  11963. svr.Get("/hello", [](const Request &req, Response &res) {
  11964. res.set_content(req.get_param_value("key"), "text/plain");
  11965. });
  11966. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11967. auto se = detail::scope_exit([&] {
  11968. svr.stop();
  11969. thread.join();
  11970. ASSERT_FALSE(svr.is_running());
  11971. });
  11972. svr.wait_until_ready();
  11973. {
  11974. Client cli(HOST, PORT);
  11975. cli.set_follow_location(true);
  11976. auto res = cli.Get("/");
  11977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11978. EXPECT_EQ(StatusCode::OK_200, res->status);
  11979. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11980. }
  11981. }
  11982. TEST(RedirectTest, RedirectWithPlusInPath) {
  11983. Server svr;
  11984. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11985. res.set_redirect("/a+b");
  11986. });
  11987. // Route pattern uses regex; escape + as \\+
  11988. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11989. res.set_content(req.path, "text/plain");
  11990. });
  11991. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11992. auto se = detail::scope_exit([&] {
  11993. svr.stop();
  11994. thread.join();
  11995. ASSERT_FALSE(svr.is_running());
  11996. });
  11997. svr.wait_until_ready();
  11998. {
  11999. Client cli(HOST, PORT);
  12000. cli.set_follow_location(true);
  12001. auto res = cli.Get("/");
  12002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12003. EXPECT_EQ(StatusCode::OK_200, res->status);
  12004. EXPECT_EQ("/a+b", res->body);
  12005. }
  12006. }
  12007. #ifdef CPPHTTPLIB_SSL_ENABLED
  12008. TEST(RedirectTest, Issue2185_Online) {
  12009. SSLClient client("github.com");
  12010. client.set_follow_location(true);
  12011. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12012. "Coollab-Windows.zip");
  12013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12014. EXPECT_EQ(StatusCode::OK_200, res->status);
  12015. EXPECT_EQ(9920427U, res->body.size());
  12016. }
  12017. #endif
  12018. TEST(VulnerabilityTest, CRLFInjection) {
  12019. Server svr;
  12020. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12021. res.set_content("Hello 1", "text/plain");
  12022. });
  12023. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12024. res.set_content("Hello 2", "text/plain");
  12025. });
  12026. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12027. res.set_content("Hello 3", "text/plain");
  12028. });
  12029. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12030. res.set_content("Hello 4", "text/plain");
  12031. });
  12032. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12033. for (const auto &x : req.headers) {
  12034. auto key = x.first;
  12035. EXPECT_STRNE("evil", key.c_str());
  12036. }
  12037. });
  12038. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12039. auto se = detail::scope_exit([&] {
  12040. svr.stop();
  12041. thread.join();
  12042. ASSERT_FALSE(svr.is_running());
  12043. });
  12044. svr.wait_until_ready();
  12045. {
  12046. Client cli(HOST, PORT);
  12047. cli.Post("/test1", "A=B",
  12048. "application/x-www-form-urlencoded\r\nevil: hello1");
  12049. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12050. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12051. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12052. }
  12053. }
  12054. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12055. auto server_thread = std::thread([] {
  12056. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12057. default_socket_options(srv);
  12058. sockaddr_in addr{};
  12059. addr.sin_family = AF_INET;
  12060. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12061. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12062. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12063. ::listen(srv, 1);
  12064. sockaddr_in cli_addr{};
  12065. socklen_t cli_len = sizeof(cli_addr);
  12066. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12067. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12068. std::string buf_all;
  12069. char buf[2048];
  12070. ssize_t n;
  12071. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12072. buf_all.append(buf, static_cast<size_t>(n));
  12073. size_t pos;
  12074. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12075. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12076. auto e = request_block.find("\r\n");
  12077. if (e != std::string::npos) {
  12078. auto request_line = request_block.substr(0, e);
  12079. std::string msg =
  12080. "CRLF injection detected in request line: '" + request_line + "'";
  12081. EXPECT_FALSE(true) << msg;
  12082. }
  12083. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12084. ::send(cli,
  12085. #ifdef _WIN32
  12086. static_cast<const char *>(resp.c_str()),
  12087. static_cast<int>(resp.size()),
  12088. #else
  12089. resp.c_str(), resp.size(),
  12090. #endif
  12091. 0);
  12092. buf_all.erase(0, pos + 4);
  12093. }
  12094. }
  12095. detail::close_socket(cli);
  12096. detail::close_socket(srv);
  12097. });
  12098. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12099. auto cli = Client("127.0.0.1", PORT + 1);
  12100. auto headers = Headers{
  12101. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12102. {"Connection", "keep-alive"}};
  12103. auto res = cli.Get("/hi", headers);
  12104. EXPECT_FALSE(res);
  12105. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12106. server_thread.join();
  12107. }
  12108. TEST(PathParamsTest, StaticMatch) {
  12109. const auto pattern = "/users/all";
  12110. detail::PathParamsMatcher matcher(pattern);
  12111. Request request;
  12112. request.path = "/users/all";
  12113. ASSERT_TRUE(matcher.match(request));
  12114. std::unordered_map<std::string, std::string> expected_params = {};
  12115. EXPECT_EQ(request.path_params, expected_params);
  12116. }
  12117. TEST(PathParamsTest, StaticMismatch) {
  12118. const auto pattern = "/users/all";
  12119. detail::PathParamsMatcher matcher(pattern);
  12120. Request request;
  12121. request.path = "/users/1";
  12122. ASSERT_FALSE(matcher.match(request));
  12123. }
  12124. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12125. const auto pattern = "/users/:id/subscriptions";
  12126. detail::PathParamsMatcher matcher(pattern);
  12127. Request request;
  12128. request.path = "/users/42/subscriptions";
  12129. ASSERT_TRUE(matcher.match(request));
  12130. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12131. EXPECT_EQ(request.path_params, expected_params);
  12132. }
  12133. TEST(PathParamsTest, SingleParamInTheEnd) {
  12134. const auto pattern = "/users/:id";
  12135. detail::PathParamsMatcher matcher(pattern);
  12136. Request request;
  12137. request.path = "/users/24";
  12138. ASSERT_TRUE(matcher.match(request));
  12139. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12140. EXPECT_EQ(request.path_params, expected_params);
  12141. }
  12142. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12143. const auto pattern = "/users/:id/";
  12144. detail::PathParamsMatcher matcher(pattern);
  12145. Request request;
  12146. request.path = "/users/42/";
  12147. ASSERT_TRUE(matcher.match(request));
  12148. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12149. EXPECT_EQ(request.path_params, expected_params);
  12150. }
  12151. TEST(PathParamsTest, EmptyParam) {
  12152. const auto pattern = "/users/:id/";
  12153. detail::PathParamsMatcher matcher(pattern);
  12154. Request request;
  12155. request.path = "/users//";
  12156. ASSERT_TRUE(matcher.match(request));
  12157. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12158. EXPECT_EQ(request.path_params, expected_params);
  12159. }
  12160. TEST(PathParamsTest, FragmentMismatch) {
  12161. const auto pattern = "/users/:id/";
  12162. detail::PathParamsMatcher matcher(pattern);
  12163. Request request;
  12164. request.path = "/admins/24/";
  12165. ASSERT_FALSE(matcher.match(request));
  12166. }
  12167. TEST(PathParamsTest, ExtraFragments) {
  12168. const auto pattern = "/users/:id";
  12169. detail::PathParamsMatcher matcher(pattern);
  12170. Request request;
  12171. request.path = "/users/42/subscriptions";
  12172. ASSERT_FALSE(matcher.match(request));
  12173. }
  12174. TEST(PathParamsTest, MissingTrailingParam) {
  12175. const auto pattern = "/users/:id";
  12176. detail::PathParamsMatcher matcher(pattern);
  12177. Request request;
  12178. request.path = "/users";
  12179. ASSERT_FALSE(matcher.match(request));
  12180. }
  12181. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12182. const auto pattern = "/users/:id/subscriptions";
  12183. detail::PathParamsMatcher matcher(pattern);
  12184. Request request;
  12185. request.path = "/users/subscriptions";
  12186. ASSERT_FALSE(matcher.match(request));
  12187. }
  12188. TEST(PathParamsTest, MultipleParams) {
  12189. const auto pattern = "/users/:userid/subscriptions/:subid";
  12190. detail::PathParamsMatcher matcher(pattern);
  12191. Request request;
  12192. request.path = "/users/42/subscriptions/2";
  12193. ASSERT_TRUE(matcher.match(request));
  12194. std::unordered_map<std::string, std::string> expected_params = {
  12195. {"userid", "42"}, {"subid", "2"}};
  12196. EXPECT_EQ(request.path_params, expected_params);
  12197. }
  12198. TEST(PathParamsTest, SequenceOfParams) {
  12199. const auto pattern = "/values/:x/:y/:z";
  12200. detail::PathParamsMatcher matcher(pattern);
  12201. Request request;
  12202. request.path = "/values/1/2/3";
  12203. ASSERT_TRUE(matcher.match(request));
  12204. std::unordered_map<std::string, std::string> expected_params = {
  12205. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12206. EXPECT_EQ(request.path_params, expected_params);
  12207. }
  12208. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12209. const auto pattern = "/prefix:suffix";
  12210. detail::PathParamsMatcher matcher(pattern);
  12211. Request request;
  12212. request.path = "/prefix:suffix";
  12213. ASSERT_TRUE(matcher.match(request));
  12214. const std::unordered_map<std::string, std::string> expected_params = {};
  12215. EXPECT_EQ(request.path_params, expected_params);
  12216. }
  12217. TEST(ParseUrlTest, VariousPatterns) {
  12218. {
  12219. detail::UrlComponents uc;
  12220. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12221. EXPECT_EQ("http", uc.scheme);
  12222. EXPECT_EQ("example.com", uc.host);
  12223. EXPECT_EQ("8080", uc.port);
  12224. EXPECT_EQ("/path", uc.path);
  12225. EXPECT_EQ("?q=1", uc.query);
  12226. }
  12227. {
  12228. detail::UrlComponents uc;
  12229. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12230. EXPECT_EQ("https", uc.scheme);
  12231. EXPECT_EQ("example.com", uc.host);
  12232. EXPECT_TRUE(uc.port.empty());
  12233. EXPECT_EQ("/path", uc.path);
  12234. }
  12235. {
  12236. detail::UrlComponents uc;
  12237. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12238. EXPECT_EQ("::1", uc.host);
  12239. EXPECT_EQ("8080", uc.port);
  12240. EXPECT_EQ("/path", uc.path);
  12241. }
  12242. {
  12243. detail::UrlComponents uc;
  12244. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12245. }
  12246. {
  12247. detail::UrlComponents uc;
  12248. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12249. EXPECT_TRUE(uc.scheme.empty());
  12250. EXPECT_EQ("example.com", uc.host);
  12251. EXPECT_EQ("/path", uc.path);
  12252. EXPECT_EQ("?q=1", uc.query);
  12253. }
  12254. {
  12255. detail::UrlComponents uc;
  12256. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12257. EXPECT_TRUE(uc.host.empty());
  12258. EXPECT_EQ("/path", uc.path);
  12259. EXPECT_EQ("?q=1", uc.query);
  12260. }
  12261. {
  12262. detail::UrlComponents uc;
  12263. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12264. EXPECT_EQ("example.com", uc.host);
  12265. EXPECT_EQ("8080", uc.port);
  12266. }
  12267. {
  12268. // Unix socket path — must not be parsed as host
  12269. detail::UrlComponents uc;
  12270. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12271. EXPECT_TRUE(uc.host.empty());
  12272. }
  12273. {
  12274. detail::UrlComponents uc;
  12275. ASSERT_TRUE(detail::parse_url("", uc));
  12276. EXPECT_TRUE(uc.host.empty());
  12277. EXPECT_TRUE(uc.path.empty());
  12278. }
  12279. {
  12280. detail::UrlComponents uc;
  12281. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12282. }
  12283. {
  12284. detail::UrlComponents uc;
  12285. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12286. }
  12287. {
  12288. // Accepted by parse_url; callers restrict to http/https
  12289. detail::UrlComponents uc;
  12290. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12291. EXPECT_EQ("ftp", uc.scheme);
  12292. }
  12293. {
  12294. detail::UrlComponents uc;
  12295. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12296. }
  12297. {
  12298. detail::UrlComponents uc;
  12299. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12300. }
  12301. }
  12302. TEST(ParseUrlTest, FragmentHandling) {
  12303. {
  12304. detail::UrlComponents uc;
  12305. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12306. EXPECT_EQ("/path", uc.path);
  12307. EXPECT_TRUE(uc.query.empty());
  12308. }
  12309. {
  12310. detail::UrlComponents uc;
  12311. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12312. EXPECT_TRUE(uc.path.empty());
  12313. EXPECT_TRUE(uc.query.empty());
  12314. }
  12315. }
  12316. TEST(ParseUrlTest, UserinfoHandling) {
  12317. // Userinfo with @ but no colon — host includes @
  12318. detail::UrlComponents uc;
  12319. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12320. EXPECT_EQ("user@host.com", uc.host);
  12321. EXPECT_EQ("/path", uc.path);
  12322. }
  12323. TEST(ParseUrlTest, IPv6EdgeCases) {
  12324. {
  12325. detail::UrlComponents uc;
  12326. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12327. EXPECT_TRUE(uc.scheme.empty());
  12328. EXPECT_EQ("::1", uc.host);
  12329. EXPECT_EQ("8080", uc.port);
  12330. }
  12331. {
  12332. // Zone ID '%25' is not in [a-fA-F0-9:]
  12333. detail::UrlComponents uc;
  12334. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12335. }
  12336. }
  12337. TEST(ParseUrlTest, SchemeEdgeCases) {
  12338. {
  12339. detail::UrlComponents uc;
  12340. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12341. }
  12342. {
  12343. detail::UrlComponents uc;
  12344. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12345. }
  12346. {
  12347. detail::UrlComponents uc;
  12348. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12349. }
  12350. }
  12351. TEST(ParseUrlTest, PortEdgeCases) {
  12352. {
  12353. detail::UrlComponents uc;
  12354. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12355. EXPECT_TRUE(uc.port.empty());
  12356. EXPECT_EQ("/path", uc.path);
  12357. }
  12358. {
  12359. // parse_url accepts any port string; validation is done by parse_port
  12360. detail::UrlComponents uc;
  12361. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12362. EXPECT_EQ("abc", uc.port);
  12363. }
  12364. }
  12365. TEST(ParseUrlTest, WebSocketPatterns) {
  12366. {
  12367. detail::UrlComponents uc;
  12368. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12369. EXPECT_EQ("ws", uc.scheme);
  12370. EXPECT_EQ("echo.example.com", uc.host);
  12371. EXPECT_EQ("8080", uc.port);
  12372. EXPECT_EQ("/ws", uc.path);
  12373. }
  12374. {
  12375. detail::UrlComponents uc;
  12376. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12377. EXPECT_EQ("wss", uc.scheme);
  12378. EXPECT_EQ("echo.example.com", uc.host);
  12379. EXPECT_TRUE(uc.port.empty());
  12380. EXPECT_EQ("/ws", uc.path);
  12381. }
  12382. }
  12383. TEST(ParseUrlTest, QueryOnly) {
  12384. detail::UrlComponents uc;
  12385. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12386. EXPECT_TRUE(uc.host.empty());
  12387. EXPECT_TRUE(uc.path.empty());
  12388. EXPECT_EQ("?q=1&r=2", uc.query);
  12389. }
  12390. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12391. detail::UrlComponents uc;
  12392. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12393. EXPECT_TRUE(uc.scheme.empty());
  12394. EXPECT_EQ("example.com", uc.host);
  12395. EXPECT_EQ("443", uc.port);
  12396. EXPECT_EQ("/path", uc.path);
  12397. }
  12398. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12399. // If ipv6 regex working, regex match codepath is taken.
  12400. // else port will default to 80 in Client impl
  12401. int clientImplMagicPort = 80;
  12402. int port = 4321;
  12403. // above ports must be different to avoid false negative
  12404. EXPECT_NE(clientImplMagicPort, port);
  12405. std::string ipV6TestURL = "http://[ff06::c3]";
  12406. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12407. CLIENT_PRIVATE_KEY_FILE);
  12408. EXPECT_EQ(cli.port(), port);
  12409. }
  12410. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12411. auto file_path = "./www/dir/index.html";
  12412. auto dir_path = "./www/dir";
  12413. detail::FileStat stat_file(file_path);
  12414. EXPECT_TRUE(stat_file.is_file());
  12415. EXPECT_FALSE(stat_file.is_dir());
  12416. detail::FileStat stat_dir(dir_path);
  12417. EXPECT_FALSE(stat_dir.is_file());
  12418. EXPECT_TRUE(stat_dir.is_dir());
  12419. }
  12420. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12421. // IPv4 with default HTTP port (80)
  12422. EXPECT_EQ("example.com",
  12423. detail::make_host_and_port_string("example.com", 80, false));
  12424. // IPv4 with default HTTPS port (443)
  12425. EXPECT_EQ("example.com",
  12426. detail::make_host_and_port_string("example.com", 443, true));
  12427. // IPv4 with non-default HTTP port
  12428. EXPECT_EQ("example.com:8080",
  12429. detail::make_host_and_port_string("example.com", 8080, false));
  12430. // IPv4 with non-default HTTPS port
  12431. EXPECT_EQ("example.com:8443",
  12432. detail::make_host_and_port_string("example.com", 8443, true));
  12433. // IPv6 with default HTTP port (80)
  12434. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12435. // IPv6 with default HTTPS port (443)
  12436. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12437. // IPv6 with non-default HTTP port
  12438. EXPECT_EQ("[::1]:8080",
  12439. detail::make_host_and_port_string("::1", 8080, false));
  12440. // IPv6 with non-default HTTPS port
  12441. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12442. // IPv6 full address with default port
  12443. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12444. detail::make_host_and_port_string(
  12445. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12446. // IPv6 full address with non-default port
  12447. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12448. detail::make_host_and_port_string(
  12449. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12450. // IPv6 localhost with non-default port
  12451. EXPECT_EQ("[::1]:3000",
  12452. detail::make_host_and_port_string("::1", 3000, false));
  12453. // IPv6 with zone ID (link-local address) with default port
  12454. EXPECT_EQ("[fe80::1%eth0]",
  12455. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12456. // IPv6 with zone ID (link-local address) with non-default port
  12457. EXPECT_EQ("[fe80::1%eth0]:8080",
  12458. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12459. // Edge case: Port 443 with is_ssl=false (should add port)
  12460. EXPECT_EQ("example.com:443",
  12461. detail::make_host_and_port_string("example.com", 443, false));
  12462. // Edge case: Port 80 with is_ssl=true (should add port)
  12463. EXPECT_EQ("example.com:80",
  12464. detail::make_host_and_port_string("example.com", 80, true));
  12465. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12466. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12467. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12468. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12469. // Security fix: Already bracketed IPv6 should not get double brackets
  12470. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12471. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12472. EXPECT_EQ("[::1]:8080",
  12473. detail::make_host_and_port_string("[::1]", 8080, false));
  12474. EXPECT_EQ("[2001:db8::1]:8080",
  12475. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12476. EXPECT_EQ("[fe80::1%eth0]",
  12477. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12478. EXPECT_EQ("[fe80::1%eth0]:8080",
  12479. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12480. // Edge case: Empty host (should return as-is)
  12481. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12482. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12483. // This is a known limitation but shouldn't crash
  12484. EXPECT_EQ("[host:name]",
  12485. detail::make_host_and_port_string("host:name", 80, false));
  12486. // Port number edge cases (no validation, but should not crash)
  12487. EXPECT_EQ("example.com:0",
  12488. detail::make_host_and_port_string("example.com", 0, false));
  12489. EXPECT_EQ("example.com:-1",
  12490. detail::make_host_and_port_string("example.com", -1, false));
  12491. EXPECT_EQ("example.com:65535",
  12492. detail::make_host_and_port_string("example.com", 65535, false));
  12493. EXPECT_EQ("example.com:65536",
  12494. detail::make_host_and_port_string("example.com", 65536, false));
  12495. }
  12496. #ifdef CPPHTTPLIB_SSL_ENABLED
  12497. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12498. httplib::SSLClient cli("roblox.com", 443);
  12499. cli.set_follow_location(true);
  12500. auto res = cli.Get("/");
  12501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12502. EXPECT_EQ(StatusCode::OK_200, res->status);
  12503. }
  12504. #endif
  12505. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12506. Server svr;
  12507. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12508. EXPECT_EQ(res.status, 400);
  12509. });
  12510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12511. auto se = detail::scope_exit([&] {
  12512. svr.stop();
  12513. thread.join();
  12514. ASSERT_FALSE(svr.is_running());
  12515. });
  12516. svr.wait_until_ready();
  12517. Client cli(HOST, PORT);
  12518. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12519. }
  12520. TEST(InvalidHeaderCharsTest, is_field_name) {
  12521. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12522. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12523. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12524. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12525. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12526. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12527. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12528. EXPECT_FALSE(detail::fields::is_field_name(""));
  12529. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12530. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12531. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12532. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12533. }
  12534. TEST(InvalidHeaderCharsTest, is_field_value) {
  12535. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12536. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12537. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12538. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12539. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12540. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12541. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12542. EXPECT_TRUE(detail::fields::is_field_value(""));
  12543. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12544. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12545. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12546. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12547. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12548. }
  12549. TEST(InvalidHeaderCharsTest, OnServer) {
  12550. Server svr;
  12551. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12552. std::string header = "Not Set";
  12553. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12554. res.set_header(header, "value");
  12555. res.set_content("Page Content Page Content", "text/plain");
  12556. });
  12557. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12558. std::string header = "Not Set";
  12559. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12560. res.set_header("X-Test", header);
  12561. res.set_content("Page Content Page Content", "text/plain");
  12562. });
  12563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12564. auto se = detail::scope_exit([&] {
  12565. svr.stop();
  12566. thread.join();
  12567. ASSERT_FALSE(svr.is_running());
  12568. });
  12569. svr.wait_until_ready();
  12570. Client cli(HOST, PORT);
  12571. {
  12572. auto res = cli.Get(
  12573. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12575. EXPECT_EQ("Page Content Page Content", res->body);
  12576. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12577. }
  12578. {
  12579. auto res = cli.Get(
  12580. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12582. EXPECT_EQ("Page Content Page Content", res->body);
  12583. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12584. }
  12585. }
  12586. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12587. auto handled = false;
  12588. Server svr;
  12589. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12590. thread t = thread([&] { svr.listen(HOST, PORT); });
  12591. auto se = detail::scope_exit([&] {
  12592. svr.stop();
  12593. t.join();
  12594. ASSERT_FALSE(svr.is_running());
  12595. ASSERT_FALSE(handled);
  12596. });
  12597. svr.wait_until_ready();
  12598. auto req = "POST /test HTTP/1.1\r\n"
  12599. "Content-Length: x\r\n"
  12600. "\r\n";
  12601. std::string response;
  12602. ASSERT_TRUE(send_request(1, req, &response));
  12603. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12604. response.substr(0, response.find("\r\n")));
  12605. }
  12606. #ifndef _WIN32
  12607. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12608. static constexpr char reject[] = "Unauthorized";
  12609. static constexpr char accept[] = "Upload accepted";
  12610. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12611. Server svr;
  12612. svr.set_expect_100_continue_handler(
  12613. [](const Request & /*req*/, Response &res) {
  12614. res.status = StatusCode::Unauthorized_401;
  12615. res.set_content(reject, "text/plain");
  12616. return res.status;
  12617. });
  12618. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12619. res.set_content(accept, "text/plain");
  12620. });
  12621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12622. auto se = detail::scope_exit([&] {
  12623. svr.stop();
  12624. thread.join();
  12625. ASSERT_FALSE(svr.is_running());
  12626. });
  12627. svr.wait_until_ready();
  12628. {
  12629. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12630. curl_easy_init(), &curl_easy_cleanup};
  12631. ASSERT_NE(curl, nullptr);
  12632. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12633. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12634. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12635. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12636. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12637. &curl_slist_free_all};
  12638. ASSERT_NE(list, nullptr);
  12639. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12640. struct read_data {
  12641. size_t read_size;
  12642. size_t total_size;
  12643. } data = {0, total_size};
  12644. using read_callback_t =
  12645. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12646. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12647. void *userdata) -> size_t {
  12648. read_data *d = (read_data *)userdata;
  12649. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12650. std::fill_n(ptr, size * nmemb, 'A');
  12651. d->read_size += size * nmemb;
  12652. return size * nmemb;
  12653. };
  12654. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12655. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12656. std::vector<char> buffer;
  12657. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12658. using write_callback_t =
  12659. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12660. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12661. void *userdata) -> size_t {
  12662. std::vector<char> *buf = (std::vector<char> *)userdata;
  12663. buf->reserve(buf->size() + size * nmemb + 1);
  12664. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12665. return size * nmemb;
  12666. };
  12667. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12668. {
  12669. const auto res = curl_easy_perform(curl.get());
  12670. ASSERT_EQ(res, CURLE_OK);
  12671. }
  12672. {
  12673. auto response_code = long{};
  12674. const auto res =
  12675. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12676. ASSERT_EQ(res, CURLE_OK);
  12677. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12678. }
  12679. {
  12680. auto dl = curl_off_t{};
  12681. const auto res =
  12682. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12683. ASSERT_EQ(res, CURLE_OK);
  12684. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12685. }
  12686. {
  12687. buffer.push_back('\0');
  12688. ASSERT_STRCASEEQ(buffer.data(), reject);
  12689. }
  12690. }
  12691. }
  12692. #endif
  12693. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12694. // Regression test for #2458.
  12695. //
  12696. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12697. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12698. // ticket can make the client socket spuriously readable during the
  12699. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12700. // the client withholds the body and then blocks reading a response that never
  12701. // comes, failing with `Failed to read connection`.
  12702. //
  12703. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12704. // within the timeout. This raw OpenSSL server deliberately never sends
  12705. // `100 Continue`; the client must still deliver the body and receive 200.
  12706. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12707. signal(SIGPIPE, SIG_IGN);
  12708. const auto port = PORT + 4;
  12709. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12710. ASSERT_NE(srv, INVALID_SOCKET);
  12711. int opt = 1;
  12712. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12713. sockaddr_in addr{};
  12714. addr.sin_family = AF_INET;
  12715. addr.sin_port = htons(static_cast<uint16_t>(port));
  12716. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12717. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12718. ASSERT_EQ(0, ::listen(srv, 1));
  12719. std::atomic<size_t> server_body_bytes{0};
  12720. auto server_thread = std::thread([&] {
  12721. sockaddr_in cli_addr{};
  12722. socklen_t cli_len = sizeof(cli_addr);
  12723. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12724. if (cli == INVALID_SOCKET) { return; }
  12725. // Bound the lifetime of the server side so a buggy client (which never
  12726. // sends the body) cannot make this thread block forever on join.
  12727. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12728. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12729. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12730. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12731. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12732. SSL *ssl = SSL_new(ctx);
  12733. SSL_set_fd(ssl, static_cast<int>(cli));
  12734. if (SSL_accept(ssl) > 0) {
  12735. // Read the request headers. Reading here also flushes the TLS 1.3
  12736. // session tickets to the client. Deliberately do NOT send
  12737. // `100 Continue`.
  12738. std::string buf;
  12739. char tmp[1024];
  12740. while (buf.find("\r\n\r\n") == std::string::npos) {
  12741. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12742. if (n <= 0) { break; }
  12743. buf.append(tmp, static_cast<size_t>(n));
  12744. }
  12745. // A correct client sends the body now; count what arrives.
  12746. auto pos = buf.find("\r\n\r\n");
  12747. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12748. while (body < 4096) {
  12749. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12750. if (n <= 0) { break; }
  12751. body += static_cast<size_t>(n);
  12752. }
  12753. server_body_bytes = body;
  12754. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12755. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12756. SSL_shutdown(ssl);
  12757. }
  12758. SSL_free(ssl);
  12759. detail::close_socket(cli);
  12760. SSL_CTX_free(ctx);
  12761. });
  12762. auto se = detail::scope_exit([&] {
  12763. server_thread.join();
  12764. detail::close_socket(srv);
  12765. });
  12766. SSLClient cli("127.0.0.1", port);
  12767. cli.enable_server_certificate_verification(false);
  12768. cli.set_connection_timeout(5, 0);
  12769. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12770. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12771. std::string body(4096, 'A');
  12772. auto res = cli.Put("/api/test", body, "application/json");
  12773. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12774. EXPECT_EQ(StatusCode::OK_200, res->status);
  12775. EXPECT_EQ(body.size(), server_body_bytes.load());
  12776. }
  12777. #endif
  12778. template <typename S, typename C>
  12779. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12780. svr.Get("/stream", [&](const Request &, Response &res) {
  12781. auto data = new std::string("01234567890123456789");
  12782. res.set_content_provider(
  12783. data->size(), "text/plain",
  12784. [&, data](size_t offset, size_t length, DataSink &sink) {
  12785. const size_t DATA_CHUNK_SIZE = 4;
  12786. const auto &d = *data;
  12787. std::this_thread::sleep_for(std::chrono::seconds(1));
  12788. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12789. return true;
  12790. },
  12791. [data](bool success) {
  12792. EXPECT_FALSE(success);
  12793. delete data;
  12794. });
  12795. });
  12796. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12797. auto i = new size_t(0);
  12798. res.set_content_provider(
  12799. "text/plain",
  12800. [i](size_t, DataSink &sink) {
  12801. if (*i < 5) {
  12802. std::this_thread::sleep_for(std::chrono::seconds(1));
  12803. sink.write("abcd", 4);
  12804. (*i)++;
  12805. } else {
  12806. sink.done();
  12807. }
  12808. return true;
  12809. },
  12810. [i](bool success) {
  12811. EXPECT_FALSE(success);
  12812. delete i;
  12813. });
  12814. });
  12815. svr.Get("/chunked", [&](const Request &, Response &res) {
  12816. auto i = new size_t(0);
  12817. res.set_chunked_content_provider(
  12818. "text/plain",
  12819. [i](size_t, DataSink &sink) {
  12820. if (*i < 5) {
  12821. std::this_thread::sleep_for(std::chrono::seconds(1));
  12822. sink.os << "abcd";
  12823. (*i)++;
  12824. } else {
  12825. sink.done();
  12826. }
  12827. return true;
  12828. },
  12829. [i](bool success) {
  12830. EXPECT_FALSE(success);
  12831. delete i;
  12832. });
  12833. });
  12834. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12835. auto se = detail::scope_exit([&] {
  12836. svr.stop();
  12837. listen_thread.join();
  12838. ASSERT_FALSE(svr.is_running());
  12839. });
  12840. svr.wait_until_ready();
  12841. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12842. {
  12843. auto start = std::chrono::steady_clock::now();
  12844. auto res = cli.Get("/stream");
  12845. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12846. std::chrono::steady_clock::now() - start)
  12847. .count();
  12848. ASSERT_FALSE(res);
  12849. EXPECT_EQ(Error::Read, res.error());
  12850. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12851. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12852. }
  12853. {
  12854. auto start = std::chrono::steady_clock::now();
  12855. auto res = cli.Get("/stream_without_length");
  12856. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12857. std::chrono::steady_clock::now() - start)
  12858. .count();
  12859. ASSERT_FALSE(res);
  12860. EXPECT_EQ(Error::Read, res.error());
  12861. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12862. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12863. }
  12864. {
  12865. auto start = std::chrono::steady_clock::now();
  12866. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12867. EXPECT_EQ("abcd", string(data, data_length));
  12868. return true;
  12869. });
  12870. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12871. std::chrono::steady_clock::now() - start)
  12872. .count();
  12873. ASSERT_FALSE(res);
  12874. EXPECT_EQ(Error::Read, res.error());
  12875. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12876. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12877. }
  12878. }
  12879. TEST(MaxTimeoutTest, ContentStream) {
  12880. time_t timeout = 2000;
  12881. time_t threshold = 200;
  12882. Server svr;
  12883. Client cli("localhost", PORT);
  12884. max_timeout_test(svr, cli, timeout, threshold);
  12885. }
  12886. #ifdef CPPHTTPLIB_SSL_ENABLED
  12887. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12888. time_t timeout = 2000;
  12889. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12891. SSLClient cli("localhost", PORT);
  12892. cli.enable_server_certificate_verification(false);
  12893. max_timeout_test(svr, cli, timeout, threshold);
  12894. }
  12895. #endif
  12896. class EventDispatcher {
  12897. public:
  12898. EventDispatcher() {}
  12899. bool wait_event(DataSink *sink) {
  12900. unique_lock<mutex> lk(m_);
  12901. int id = id_;
  12902. // Wait with timeout to prevent hanging if client disconnects
  12903. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12904. [&] { return cid_ == id; })) {
  12905. return false; // Timeout occurred
  12906. }
  12907. sink->write(message_.data(), message_.size());
  12908. return true;
  12909. }
  12910. void send_event(const string &message) {
  12911. lock_guard<mutex> lk(m_);
  12912. cid_ = id_++;
  12913. message_ = message;
  12914. cv_.notify_all();
  12915. }
  12916. private:
  12917. mutex m_;
  12918. condition_variable cv_;
  12919. atomic_int id_{0};
  12920. atomic_int cid_{-1};
  12921. string message_;
  12922. };
  12923. TEST(ClientInThreadTest, Issue2068) {
  12924. EventDispatcher ed;
  12925. Server svr;
  12926. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12927. res.set_chunked_content_provider("text/event-stream",
  12928. [&](size_t /*offset*/, DataSink &sink) {
  12929. return ed.wait_event(&sink);
  12930. });
  12931. });
  12932. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12933. svr.wait_until_ready();
  12934. thread event_thread([&] {
  12935. int id = 0;
  12936. while (svr.is_running()) {
  12937. this_thread::sleep_for(chrono::milliseconds(500));
  12938. std::stringstream ss;
  12939. ss << "data: " << id << "\n\n";
  12940. ed.send_event(ss.str());
  12941. id++;
  12942. }
  12943. });
  12944. auto se = detail::scope_exit([&] {
  12945. svr.stop();
  12946. listen_thread.join();
  12947. event_thread.join();
  12948. ASSERT_FALSE(svr.is_running());
  12949. });
  12950. {
  12951. auto client = detail::make_unique<Client>(HOST, PORT);
  12952. client->set_read_timeout(std::chrono::minutes(10));
  12953. std::atomic<bool> stop{false};
  12954. std::thread t([&] {
  12955. client->Get("/event1",
  12956. [&](const char *, size_t) -> bool { return !stop; });
  12957. });
  12958. std::this_thread::sleep_for(std::chrono::seconds(2));
  12959. stop = true;
  12960. client->stop();
  12961. t.join();
  12962. // Reset client after thread has finished
  12963. client.reset();
  12964. }
  12965. }
  12966. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12967. auto handled = false;
  12968. Server svr;
  12969. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12970. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12971. auto se = detail::scope_exit([&] {
  12972. svr.stop();
  12973. t.join();
  12974. ASSERT_FALSE(svr.is_running());
  12975. ASSERT_FALSE(handled);
  12976. });
  12977. svr.wait_until_ready();
  12978. // Two Content-Length headers with different values — must be rejected
  12979. auto req = "POST /test HTTP/1.1\r\n"
  12980. "Content-Length: 5\r\n"
  12981. "Content-Length: 10\r\n"
  12982. "\r\n"
  12983. "hello";
  12984. std::string response;
  12985. ASSERT_TRUE(send_request(1, req, &response));
  12986. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12987. response.substr(0, response.find("\r\n")));
  12988. }
  12989. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12990. auto handled = false;
  12991. Server svr;
  12992. svr.Post("/test", [&](const Request &, Response &res) {
  12993. handled = true;
  12994. res.set_content("ok", "text/plain");
  12995. });
  12996. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12997. auto se = detail::scope_exit([&] {
  12998. svr.stop();
  12999. t.join();
  13000. ASSERT_FALSE(svr.is_running());
  13001. ASSERT_TRUE(handled);
  13002. });
  13003. svr.wait_until_ready();
  13004. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13005. auto req = "POST /test HTTP/1.1\r\n"
  13006. "Content-Length: 5\r\n"
  13007. "Content-Length: 5\r\n"
  13008. "\r\n"
  13009. "hello";
  13010. std::string response;
  13011. ASSERT_TRUE(send_request(1, req, &response));
  13012. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13013. }
  13014. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13015. Server svr;
  13016. svr.Get("/", [](const Request &req, Response &res) {
  13017. EXPECT_EQ(2U, req.trailers.size());
  13018. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13019. // Denied
  13020. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13021. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13022. // Accepted
  13023. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13024. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13025. EXPECT_TRUE(req.has_trailer("X-World"));
  13026. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13027. res.set_content("ok", "text/plain");
  13028. });
  13029. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13030. auto se = detail::scope_exit([&] {
  13031. svr.stop();
  13032. t.join();
  13033. ASSERT_FALSE(svr.is_running());
  13034. });
  13035. svr.wait_until_ready();
  13036. const std::string req = "GET / HTTP/1.1\r\n"
  13037. "Transfer-Encoding: chunked\r\n"
  13038. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13039. "\r\n"
  13040. "0\r\n"
  13041. "Content-Length: 10\r\n"
  13042. "Host: internal.local\r\n"
  13043. "Content-Type: malicious/content\r\n"
  13044. "Cookie: any\r\n"
  13045. "Set-Cookie: any\r\n"
  13046. "X-Forwarded-For: attacker.com\r\n"
  13047. "X-Real-Ip: 1.1.1.1\r\n"
  13048. "X-Hello: hello\r\n"
  13049. "X-World: world\r\n"
  13050. "\r\n";
  13051. std::string res;
  13052. ASSERT_TRUE(send_request(1, req, &res));
  13053. }
  13054. // A direct client that is not listed in trusted_proxies must not be able to
  13055. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13056. // the peer address on the actual TCP connection determines whether the
  13057. // header is honored.
  13058. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13059. Server svr;
  13060. // Deliberately does NOT include the loopback address the test client
  13061. // actually connects from, so the direct connection is not a trusted proxy.
  13062. svr.set_trusted_proxies({"203.0.113.66"});
  13063. std::string observed_remote_addr;
  13064. svr.Get("/ip", [&](const Request &req, Response &res) {
  13065. observed_remote_addr = req.remote_addr;
  13066. res.set_content("ok", "text/plain");
  13067. });
  13068. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13069. auto se = detail::scope_exit([&] {
  13070. svr.stop();
  13071. t.join();
  13072. ASSERT_FALSE(svr.is_running());
  13073. });
  13074. svr.wait_until_ready();
  13075. Client cli(HOST, PORT);
  13076. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13078. EXPECT_EQ(StatusCode::OK_200, res->status);
  13079. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13080. // ignored entirely and the real connection-level address retained.
  13081. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13082. observed_remote_addr == "127.0.0.1");
  13083. }
  13084. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13085. Server svr;
  13086. std::string observed_remote_addr;
  13087. std::string observed_xff;
  13088. svr.Get("/ip", [&](const Request &req, Response &res) {
  13089. observed_remote_addr = req.remote_addr;
  13090. observed_xff = req.get_header_value("X-Forwarded-For");
  13091. res.set_content("ok", "text/plain");
  13092. });
  13093. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13094. auto se = detail::scope_exit([&] {
  13095. svr.stop();
  13096. t.join();
  13097. ASSERT_FALSE(svr.is_running());
  13098. });
  13099. svr.wait_until_ready();
  13100. Client cli(HOST, PORT);
  13101. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13103. EXPECT_EQ(StatusCode::OK_200, res->status);
  13104. EXPECT_EQ(observed_xff, "203.0.113.66");
  13105. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13106. observed_remote_addr == "127.0.0.1");
  13107. }
  13108. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13109. Server svr;
  13110. svr.set_trusted_proxies({"203.0.113.66"});
  13111. std::string observed_remote_addr;
  13112. std::string observed_xff;
  13113. svr.Get("/ip", [&](const Request &req, Response &res) {
  13114. observed_remote_addr = req.remote_addr;
  13115. observed_xff = req.get_header_value("X-Forwarded-For");
  13116. res.set_content("ok", "text/plain");
  13117. });
  13118. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13119. auto se = detail::scope_exit([&] {
  13120. svr.stop();
  13121. t.join();
  13122. ASSERT_FALSE(svr.is_running());
  13123. });
  13124. svr.wait_until_ready();
  13125. Client cli(HOST, PORT);
  13126. auto res = cli.Get("/ip");
  13127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13128. EXPECT_EQ(StatusCode::OK_200, res->status);
  13129. EXPECT_EQ(observed_xff, "");
  13130. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13131. observed_remote_addr == "127.0.0.1");
  13132. }
  13133. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13134. Server svr;
  13135. // Include the loopback address the test client actually connects from, so
  13136. // the direct connection itself is recognized as the trusted proxy hop.
  13137. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13138. std::string observed_remote_addr;
  13139. std::string observed_xff;
  13140. svr.Get("/ip", [&](const Request &req, Response &res) {
  13141. observed_remote_addr = req.remote_addr;
  13142. observed_xff = req.get_header_value("X-Forwarded-For");
  13143. res.set_content("ok", "text/plain");
  13144. });
  13145. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13146. auto se = detail::scope_exit([&] {
  13147. svr.stop();
  13148. t.join();
  13149. ASSERT_FALSE(svr.is_running());
  13150. });
  13151. svr.wait_until_ready();
  13152. Client cli(HOST, PORT);
  13153. auto res = cli.Get(
  13154. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13156. EXPECT_EQ(StatusCode::OK_200, res->status);
  13157. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13158. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13159. }
  13160. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13161. Server svr;
  13162. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13163. std::string observed_remote_addr;
  13164. std::string observed_xff;
  13165. svr.Get("/ip", [&](const Request &req, Response &res) {
  13166. observed_remote_addr = req.remote_addr;
  13167. observed_xff = req.get_header_value("X-Forwarded-For");
  13168. res.set_content("ok", "text/plain");
  13169. });
  13170. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13171. auto se = detail::scope_exit([&] {
  13172. svr.stop();
  13173. t.join();
  13174. ASSERT_FALSE(svr.is_running());
  13175. });
  13176. svr.wait_until_ready();
  13177. Client cli(HOST, PORT);
  13178. auto res = cli.Get(
  13179. "/ip",
  13180. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13182. EXPECT_EQ(StatusCode::OK_200, res->status);
  13183. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13184. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13185. }
  13186. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13187. Server svr;
  13188. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13189. std::string observed_remote_addr;
  13190. std::string observed_xff;
  13191. svr.Get("/ip", [&](const Request &req, Response &res) {
  13192. observed_remote_addr = req.remote_addr;
  13193. observed_xff = req.get_header_value("X-Forwarded-For");
  13194. res.set_content("ok", "text/plain");
  13195. });
  13196. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13197. auto se = detail::scope_exit([&] {
  13198. svr.stop();
  13199. t.join();
  13200. ASSERT_FALSE(svr.is_running());
  13201. });
  13202. svr.wait_until_ready();
  13203. Client cli(HOST, PORT);
  13204. auto res = cli.Get(
  13205. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13207. EXPECT_EQ(StatusCode::OK_200, res->status);
  13208. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13209. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13210. // and must not be selected.
  13211. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13212. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13213. }
  13214. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13215. Server svr;
  13216. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13217. std::string observed_remote_addr;
  13218. svr.Get("/ip", [&](const Request &req, Response &res) {
  13219. observed_remote_addr = req.remote_addr;
  13220. res.set_content("ok", "text/plain");
  13221. });
  13222. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13223. auto se = detail::scope_exit([&] {
  13224. svr.stop();
  13225. t.join();
  13226. ASSERT_FALSE(svr.is_running());
  13227. });
  13228. svr.wait_until_ready();
  13229. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13230. // a forged address and the trusted proxy's own address; the forged value must
  13231. // not win over the address the trusted proxy actually recorded.
  13232. Client cli(HOST, PORT);
  13233. auto res = cli.Get(
  13234. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13236. EXPECT_EQ(StatusCode::OK_200, res->status);
  13237. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13238. }
  13239. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13240. Server svr;
  13241. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13242. std::string observed_remote_addr;
  13243. std::string observed_xff;
  13244. svr.Get("/ip", [&](const Request &req, Response &res) {
  13245. observed_remote_addr = req.remote_addr;
  13246. observed_xff = req.get_header_value("X-Forwarded-For");
  13247. res.set_content("ok", "text/plain");
  13248. });
  13249. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13250. auto se = detail::scope_exit([&] {
  13251. svr.stop();
  13252. t.join();
  13253. ASSERT_FALSE(svr.is_running());
  13254. });
  13255. svr.wait_until_ready();
  13256. Client cli(HOST, PORT);
  13257. auto res = cli.Get(
  13258. "/ip",
  13259. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13261. EXPECT_EQ(StatusCode::OK_200, res->status);
  13262. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13263. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13264. }
  13265. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13266. Server svr;
  13267. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13268. std::string observed_remote_addr;
  13269. std::string observed_xff;
  13270. svr.Get("/ip", [&](const Request &req, Response &res) {
  13271. observed_remote_addr = req.remote_addr;
  13272. observed_xff = req.get_header_value("X-Forwarded-For");
  13273. res.set_content("ok", "text/plain");
  13274. });
  13275. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13276. auto se = detail::scope_exit([&] {
  13277. svr.stop();
  13278. t.join();
  13279. ASSERT_FALSE(svr.is_running());
  13280. });
  13281. svr.wait_until_ready();
  13282. std::string raw_req =
  13283. "GET /ip HTTP/1.1\r\n"
  13284. "Host: localhost\r\n"
  13285. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13286. "Connection: close\r\n"
  13287. "\r\n";
  13288. std::string out;
  13289. ASSERT_TRUE(send_request(5, raw_req, &out));
  13290. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13291. // Header parser trims surrounding whitespace of the header value
  13292. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13293. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13294. }
  13295. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13296. // crash the server (it used to call front() on an empty vector inside
  13297. // get_client_ip). The connection-level remote address must be retained instead.
  13298. static void run_malformed_xff_test(const std::string &xff_value) {
  13299. Server svr;
  13300. svr.set_trusted_proxies({"192.0.2.45"});
  13301. std::string observed_remote_addr;
  13302. svr.Get("/ip", [&](const Request &req, Response &res) {
  13303. observed_remote_addr = req.remote_addr;
  13304. res.set_content("ok", "text/plain");
  13305. });
  13306. int port = 0;
  13307. thread t = thread([&]() {
  13308. port = svr.bind_to_any_port(HOST);
  13309. svr.listen_after_bind();
  13310. });
  13311. auto se = detail::scope_exit([&] {
  13312. svr.stop();
  13313. t.join();
  13314. ASSERT_FALSE(svr.is_running());
  13315. });
  13316. svr.wait_until_ready();
  13317. Client cli(HOST, port);
  13318. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13320. EXPECT_EQ(StatusCode::OK_200, res->status);
  13321. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13322. observed_remote_addr == "127.0.0.1");
  13323. }
  13324. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13325. run_malformed_xff_test("");
  13326. }
  13327. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13328. run_malformed_xff_test(",");
  13329. }
  13330. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13331. run_malformed_xff_test(", , ,");
  13332. }
  13333. #ifndef _WIN32
  13334. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13335. Server svr;
  13336. svr.Post("/post", [&](const Request &req, Response &res) {
  13337. res.set_content(req.body, "text/plain");
  13338. });
  13339. svr.Put("/put", [&](const Request &req, Response &res) {
  13340. res.set_content(req.body, "text/plain");
  13341. });
  13342. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13343. res.set_content(req.body, "text/plain");
  13344. });
  13345. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13346. res.set_content(req.body, "text/plain");
  13347. });
  13348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13349. auto se = detail::scope_exit([&] {
  13350. svr.stop();
  13351. t.join();
  13352. ASSERT_FALSE(svr.is_running());
  13353. });
  13354. svr.wait_until_ready();
  13355. std::string resp;
  13356. // POST without Content-Length
  13357. ASSERT_TRUE(send_request(5,
  13358. "POST /post HTTP/1.1\r\n"
  13359. "Host: localhost\r\n"
  13360. "Connection: close\r\n"
  13361. "\r\n",
  13362. &resp));
  13363. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13364. // PUT without Content-Length
  13365. resp.clear();
  13366. ASSERT_TRUE(send_request(5,
  13367. "PUT /put HTTP/1.1\r\n"
  13368. "Host: localhost\r\n"
  13369. "Connection: close\r\n"
  13370. "\r\n",
  13371. &resp));
  13372. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13373. // PATCH without Content-Length
  13374. resp.clear();
  13375. ASSERT_TRUE(send_request(5,
  13376. "PATCH /patch HTTP/1.1\r\n"
  13377. "Host: localhost\r\n"
  13378. "Connection: close\r\n"
  13379. "\r\n",
  13380. &resp));
  13381. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13382. // DELETE without Content-Length
  13383. resp.clear();
  13384. ASSERT_TRUE(send_request(5,
  13385. "DELETE /delete HTTP/1.1\r\n"
  13386. "Host: localhost\r\n"
  13387. "Connection: close\r\n"
  13388. "\r\n",
  13389. &resp));
  13390. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13391. }
  13392. #endif
  13393. //==============================================================================
  13394. // open_stream() Tests
  13395. //==============================================================================
  13396. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13397. std::string result;
  13398. char buf[8192];
  13399. ssize_t n;
  13400. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13401. result.append(buf, static_cast<size_t>(n));
  13402. }
  13403. return result;
  13404. }
  13405. // Mock stream for unit tests
  13406. class MockStream : public Stream {
  13407. public:
  13408. std::string data;
  13409. size_t pos = 0;
  13410. ssize_t error_after = -1; // -1 = no error
  13411. explicit MockStream(const std::string &d, ssize_t err = -1)
  13412. : data(d), error_after(err) {}
  13413. bool is_readable() const override { return true; }
  13414. bool wait_readable() const override { return true; }
  13415. bool wait_writable() const override { return true; }
  13416. ssize_t read(char *ptr, size_t size) override {
  13417. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13418. if (pos >= data.size()) return 0;
  13419. size_t limit =
  13420. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13421. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13422. std::memcpy(ptr, data.data() + pos, to_read);
  13423. pos += to_read;
  13424. return static_cast<ssize_t>(to_read);
  13425. }
  13426. ssize_t write(const char *, size_t) override { return -1; }
  13427. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13428. ip = "127.0.0.1";
  13429. port = 0;
  13430. }
  13431. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13432. ip = "127.0.0.1";
  13433. port = 0;
  13434. }
  13435. socket_t socket() const override { return INVALID_SOCKET; }
  13436. time_t duration() const override { return 0; }
  13437. };
  13438. TEST(StreamHandleTest, Basic) {
  13439. ClientImpl::StreamHandle handle;
  13440. EXPECT_FALSE(handle.is_valid());
  13441. handle.response = detail::make_unique<Response>();
  13442. handle.error = Error::Connection;
  13443. EXPECT_FALSE(handle.is_valid());
  13444. handle.error = Error::Success;
  13445. EXPECT_TRUE(handle.is_valid());
  13446. }
  13447. TEST(BodyReaderTest, Basic) {
  13448. MockStream stream("Hello, World!");
  13449. detail::BodyReader reader;
  13450. reader.stream = &stream;
  13451. reader.content_length = 13;
  13452. char buf[32];
  13453. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13454. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13455. EXPECT_TRUE(reader.eof);
  13456. }
  13457. TEST(BodyReaderTest, NoStream) {
  13458. detail::BodyReader reader;
  13459. char buf[32];
  13460. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13461. EXPECT_EQ(Error::Connection, reader.last_error);
  13462. }
  13463. TEST(BodyReaderTest, Error) {
  13464. MockStream stream("Hello, World!", 5);
  13465. detail::BodyReader reader;
  13466. reader.stream = &stream;
  13467. reader.content_length = 13;
  13468. char buf[32];
  13469. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13470. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13471. EXPECT_EQ(Error::Read, reader.last_error);
  13472. }
  13473. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13474. // Mock-based StreamHandle tests relying on private internals are removed.
  13475. class OpenStreamTest : public ::testing::Test {
  13476. protected:
  13477. void SetUp() override {
  13478. svr_.Get("/hello", [](const Request &, Response &res) {
  13479. res.set_content("Hello World!", "text/plain");
  13480. });
  13481. svr_.Get("/large", [](const Request &, Response &res) {
  13482. res.set_content(std::string(10000, 'X'), "text/plain");
  13483. });
  13484. svr_.Get("/chunked", [](const Request &, Response &res) {
  13485. res.set_chunked_content_provider("text/plain",
  13486. [](size_t offset, DataSink &sink) {
  13487. if (offset < 15) {
  13488. sink.write("chunk", 5);
  13489. return true;
  13490. }
  13491. sink.done();
  13492. return true;
  13493. });
  13494. });
  13495. svr_.Get("/compressible", [](const Request &, Response &res) {
  13496. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13497. DataSink &sink) {
  13498. if (offset < 100 * 1024) {
  13499. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13500. sink.write(chunk.data(), chunk.size());
  13501. return true;
  13502. }
  13503. sink.done();
  13504. return true;
  13505. });
  13506. });
  13507. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13508. [](const Request & /*req*/, Response &res) {
  13509. auto i = new int(0);
  13510. res.set_header("Trailer", "Content-Length, X-Allowed");
  13511. res.set_chunked_content_provider(
  13512. "text/plain",
  13513. [i](size_t /*offset*/, DataSink &sink) {
  13514. switch (*i) {
  13515. case 0: sink.os << "123"; break;
  13516. case 1: sink.os << "456"; break;
  13517. case 2: sink.os << "789"; break;
  13518. case 3: {
  13519. sink.done_with_trailer(
  13520. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13521. } break;
  13522. }
  13523. (*i)++;
  13524. return true;
  13525. },
  13526. [i](bool success) {
  13527. EXPECT_TRUE(success);
  13528. delete i;
  13529. });
  13530. });
  13531. // Echo headers endpoint for header-related tests
  13532. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13533. std::string body;
  13534. for (const auto &h : req.headers) {
  13535. body.append(h.first);
  13536. body.push_back(':');
  13537. body.append(h.second);
  13538. body.push_back('\n');
  13539. }
  13540. res.set_content(body, "text/plain");
  13541. });
  13542. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13543. std::string body;
  13544. for (const auto &h : req.headers) {
  13545. body.append(h.first);
  13546. body.push_back(':');
  13547. body.append(h.second);
  13548. body.push_back('\n');
  13549. }
  13550. res.set_content(body, "text/plain");
  13551. });
  13552. port_ = svr_.bind_to_any_port("127.0.0.1");
  13553. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13554. svr_.wait_until_ready();
  13555. }
  13556. void TearDown() override {
  13557. svr_.stop();
  13558. if (thread_.joinable()) thread_.join();
  13559. }
  13560. Server svr_;
  13561. std::thread thread_;
  13562. int port_ = 0;
  13563. };
  13564. TEST_F(OpenStreamTest, Basic) {
  13565. Client cli("127.0.0.1", port_);
  13566. auto handle = cli.open_stream("GET", "/hello");
  13567. EXPECT_TRUE(handle.is_valid());
  13568. EXPECT_EQ("Hello World!", read_all(handle));
  13569. }
  13570. TEST_F(OpenStreamTest, SmallBuffer) {
  13571. Client cli("127.0.0.1", port_);
  13572. auto handle = cli.open_stream("GET", "/hello");
  13573. std::string result;
  13574. char buf[4];
  13575. ssize_t n;
  13576. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13577. result.append(buf, static_cast<size_t>(n));
  13578. EXPECT_EQ("Hello World!", result);
  13579. }
  13580. TEST_F(OpenStreamTest, DefaultHeaders) {
  13581. Client cli("127.0.0.1", port_);
  13582. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13583. {
  13584. auto handle = cli.open_stream("GET", "/echo-headers");
  13585. ASSERT_TRUE(handle.is_valid());
  13586. auto body = read_all(handle);
  13587. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13588. std::string::npos);
  13589. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13590. std::string::npos);
  13591. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13592. }
  13593. // open_stream POST with body and no explicit content_type should NOT add
  13594. // text/plain Content-Type (behavior differs from non-streaming path), but
  13595. // should include Content-Length
  13596. {
  13597. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13598. ASSERT_TRUE(handle.is_valid());
  13599. auto body = read_all(handle);
  13600. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13601. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13602. }
  13603. // open_stream POST with explicit Content-Type should preserve it
  13604. {
  13605. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13606. {{"Content-Type", "application/custom"}},
  13607. "{}", "application/custom");
  13608. ASSERT_TRUE(handle.is_valid());
  13609. auto body = read_all(handle);
  13610. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13611. }
  13612. // User-specified User-Agent must not be overwritten for stream API
  13613. {
  13614. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13615. {{"User-Agent", "MyAgent/1.2"}});
  13616. ASSERT_TRUE(handle.is_valid());
  13617. auto body = read_all(handle);
  13618. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13619. }
  13620. }
  13621. TEST_F(OpenStreamTest, Large) {
  13622. Client cli("127.0.0.1", port_);
  13623. auto handle = cli.open_stream("GET", "/large");
  13624. EXPECT_EQ(10000u, read_all(handle).size());
  13625. }
  13626. TEST_F(OpenStreamTest, ConnectionError) {
  13627. Client cli("127.0.0.1", 9999);
  13628. auto handle = cli.open_stream("GET", "/hello");
  13629. EXPECT_FALSE(handle.is_valid());
  13630. }
  13631. TEST_F(OpenStreamTest, Chunked) {
  13632. Client cli("127.0.0.1", port_);
  13633. auto handle = cli.open_stream("GET", "/chunked");
  13634. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13635. "Transfer-Encoding") == "chunked");
  13636. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13637. }
  13638. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13639. Client cli("127.0.0.1", port_);
  13640. auto handle =
  13641. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13642. ASSERT_TRUE(handle.is_valid());
  13643. // Consume body to allow trailers to be received/parsed
  13644. auto body = read_all(handle);
  13645. // Explicitly parse trailers (ensure trailers are available for assertion)
  13646. handle.parse_trailers_if_needed();
  13647. EXPECT_EQ(std::string("123456789"), body);
  13648. // The response should include a Trailer header declaring both names
  13649. ASSERT_TRUE(handle.response);
  13650. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13651. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13652. handle.response->get_header_value("Trailer"));
  13653. // Prohibited trailer must not be present
  13654. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13655. // Allowed trailer should be present
  13656. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13657. EXPECT_EQ(std::string("yes"),
  13658. handle.response->get_trailer_value("X-Allowed"));
  13659. // Verify trailers are NOT present as regular headers
  13660. EXPECT_EQ(std::string(""),
  13661. handle.response->get_header_value("Content-Length"));
  13662. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13663. }
  13664. static std::thread serve_single_response(std::promise<int> &port_promise,
  13665. const std::string &response) {
  13666. return std::thread([&port_promise, response] {
  13667. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13668. default_socket_options(srv);
  13669. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13670. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13671. sockaddr_in addr{};
  13672. addr.sin_family = AF_INET;
  13673. addr.sin_port = htons(0); // Let OS assign a free port
  13674. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13675. int opt = 1;
  13676. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13677. #ifdef _WIN32
  13678. reinterpret_cast<const char *>(&opt),
  13679. #else
  13680. &opt,
  13681. #endif
  13682. sizeof(opt));
  13683. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13684. ::listen(srv, 1) != 0) {
  13685. port_promise.set_value(-1);
  13686. detail::close_socket(srv);
  13687. return;
  13688. }
  13689. socklen_t addr_len = sizeof(addr);
  13690. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13691. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13692. sockaddr_in cli_addr{};
  13693. socklen_t cli_len = sizeof(cli_addr);
  13694. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13695. if (cli != INVALID_SOCKET) {
  13696. // Read the complete HTTP request (until the blank line that terminates
  13697. // headers) before sending the response. If the server closes the socket
  13698. // while the client's request data is still unread in the kernel receive
  13699. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13700. // connection on both sides: it discards the client's receive buffer
  13701. // (which already holds our response) and causes any in-progress write on
  13702. // the client to fail with ECONNRESET. Reading all request data first
  13703. // ensures close() emits a graceful FIN.
  13704. {
  13705. char rbuf[256];
  13706. std::string req;
  13707. while (req.find("\r\n\r\n") == std::string::npos) {
  13708. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13709. if (n <= 0) { break; }
  13710. req.append(rbuf, static_cast<size_t>(n));
  13711. }
  13712. }
  13713. ::send(cli,
  13714. #ifdef _WIN32
  13715. static_cast<const char *>(response.c_str()),
  13716. static_cast<int>(response.size()),
  13717. #else
  13718. response.c_str(), response.size(),
  13719. #endif
  13720. 0);
  13721. detail::close_socket(cli);
  13722. }
  13723. detail::close_socket(srv);
  13724. });
  13725. }
  13726. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13727. #ifndef _WIN32
  13728. signal(SIGPIPE, SIG_IGN);
  13729. #endif
  13730. std::promise<int> port_promise;
  13731. auto port_future = port_promise.get_future();
  13732. auto server_thread =
  13733. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13734. "Content-Type: text/plain\r\n"
  13735. "Content-Length: not-a-number\r\n"
  13736. "Connection: close\r\n"
  13737. "\r\n"
  13738. "hello");
  13739. auto port = port_future.get();
  13740. ASSERT_GT(port, 0);
  13741. Client cli("127.0.0.1", port);
  13742. auto handle = cli.open_stream("GET", "/");
  13743. EXPECT_FALSE(handle.is_valid());
  13744. server_thread.join();
  13745. }
  13746. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13747. #ifndef _WIN32
  13748. signal(SIGPIPE, SIG_IGN);
  13749. #endif
  13750. std::promise<int> port_promise;
  13751. auto port_future = port_promise.get_future();
  13752. auto server_thread = serve_single_response(
  13753. port_promise, "HTTP/1.1 200 OK\r\n"
  13754. "Content-Type: text/plain\r\n"
  13755. "Content-Length: 99999999999999999999999999\r\n"
  13756. "Connection: close\r\n"
  13757. "\r\n"
  13758. "hello");
  13759. auto port = port_future.get();
  13760. ASSERT_GT(port, 0);
  13761. // Historically std::stoull would throw std::out_of_range here and crash
  13762. // the process, then parsing silently clamped to a bogus framing length and
  13763. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13764. // so the stream fails to open, matching the not-a-number case above. The
  13765. // process still must NOT terminate.
  13766. Client cli("127.0.0.1", port);
  13767. auto handle = cli.open_stream("GET", "/");
  13768. EXPECT_FALSE(handle.is_valid());
  13769. server_thread.join();
  13770. }
  13771. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13772. TEST_F(OpenStreamTest, Gzip) {
  13773. Client cli("127.0.0.1", port_);
  13774. auto handle = cli.open_stream("GET", "/compressible", {},
  13775. {{"Accept-Encoding", "gzip"}});
  13776. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13777. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13778. }
  13779. #endif
  13780. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13781. TEST_F(OpenStreamTest, Brotli) {
  13782. Client cli("127.0.0.1", port_);
  13783. auto handle =
  13784. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13785. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13786. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13787. }
  13788. #endif
  13789. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13790. TEST_F(OpenStreamTest, Zstd) {
  13791. Client cli("127.0.0.1", port_);
  13792. auto handle = cli.open_stream("GET", "/compressible", {},
  13793. {{"Accept-Encoding", "zstd"}});
  13794. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13795. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13796. }
  13797. #endif
  13798. #ifdef CPPHTTPLIB_SSL_ENABLED
  13799. class SSLOpenStreamTest : public ::testing::Test {
  13800. protected:
  13801. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13802. void SetUp() override {
  13803. svr_.Get("/hello", [](const Request &, Response &res) {
  13804. res.set_content("Hello SSL World!", "text/plain");
  13805. });
  13806. svr_.Get("/chunked", [](const Request &, Response &res) {
  13807. res.set_chunked_content_provider("text/plain",
  13808. [](size_t offset, DataSink &sink) {
  13809. if (offset < 15) {
  13810. sink.write("chunk", 5);
  13811. return true;
  13812. }
  13813. sink.done();
  13814. return true;
  13815. });
  13816. });
  13817. svr_.Post("/echo", [](const Request &req, Response &res) {
  13818. res.set_content(req.body, req.get_header_value("Content-Type"));
  13819. });
  13820. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13821. std::string body = req.body;
  13822. res.set_chunked_content_provider(
  13823. "text/plain", [body](size_t offset, DataSink &sink) {
  13824. if (offset < body.size()) {
  13825. sink.write(body.data() + offset, body.size() - offset);
  13826. }
  13827. sink.done();
  13828. return true;
  13829. });
  13830. });
  13831. port_ = svr_.bind_to_any_port("127.0.0.1");
  13832. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13833. svr_.wait_until_ready();
  13834. }
  13835. void TearDown() override {
  13836. svr_.stop();
  13837. if (thread_.joinable()) thread_.join();
  13838. }
  13839. SSLServer svr_;
  13840. std::thread thread_;
  13841. int port_ = 0;
  13842. };
  13843. TEST_F(SSLOpenStreamTest, Basic) {
  13844. SSLClient cli("127.0.0.1", port_);
  13845. cli.enable_server_certificate_verification(false);
  13846. auto handle = cli.open_stream("GET", "/hello");
  13847. ASSERT_TRUE(handle.is_valid());
  13848. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13849. }
  13850. TEST_F(SSLOpenStreamTest, Chunked) {
  13851. SSLClient cli("127.0.0.1", port_);
  13852. cli.enable_server_certificate_verification(false);
  13853. auto handle = cli.open_stream("GET", "/chunked");
  13854. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13855. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13856. "Transfer-Encoding") == "chunked");
  13857. auto body = read_all(handle);
  13858. EXPECT_EQ("chunkchunkchunk", body);
  13859. }
  13860. TEST_F(SSLOpenStreamTest, Post) {
  13861. SSLClient cli("127.0.0.1", port_);
  13862. cli.enable_server_certificate_verification(false);
  13863. auto handle =
  13864. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13865. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13866. EXPECT_EQ(200, handle.response->status);
  13867. auto body = read_all(handle);
  13868. EXPECT_EQ("Hello SSL POST", body);
  13869. }
  13870. TEST_F(SSLOpenStreamTest, PostChunked) {
  13871. SSLClient cli("127.0.0.1", port_);
  13872. cli.enable_server_certificate_verification(false);
  13873. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13874. "Chunked SSL Data", "text/plain");
  13875. ASSERT_TRUE(handle.is_valid());
  13876. EXPECT_EQ(200, handle.response->status);
  13877. auto body = read_all(handle);
  13878. EXPECT_EQ("Chunked SSL Data", body);
  13879. }
  13880. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13881. // Content-Length is terminated by the server closing the connection. When the
  13882. // SSL peer sends a close_notify after the body, the client must treat it as a
  13883. // clean EOF and return a successful response rather than an error.
  13884. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13886. ASSERT_TRUE(svr.is_valid());
  13887. svr.set_keep_alive_max_count(1);
  13888. const std::string expected_body = "Hello from connection-close response!";
  13889. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13890. res.set_content_provider("text/plain",
  13891. [&](size_t offset, DataSink &sink) -> bool {
  13892. if (offset < expected_body.size()) {
  13893. sink.write(expected_body.data() + offset,
  13894. expected_body.size() - offset);
  13895. }
  13896. sink.done();
  13897. return true;
  13898. });
  13899. });
  13900. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13901. auto se = detail::scope_exit([&] {
  13902. svr.stop();
  13903. listen_thread.join();
  13904. ASSERT_FALSE(svr.is_running());
  13905. });
  13906. svr.wait_until_ready();
  13907. SSLClient cli(HOST, PORT);
  13908. cli.enable_server_certificate_verification(false);
  13909. auto res = cli.Get("/no-content-length");
  13910. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13911. EXPECT_EQ(StatusCode::OK_200, res->status);
  13912. EXPECT_EQ(expected_body, res->body);
  13913. }
  13914. #endif // CPPHTTPLIB_SSL_ENABLED
  13915. //==============================================================================
  13916. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13917. // results for various scenarios.
  13918. //==============================================================================
  13919. TEST(ParityTest, GetVsOpenStream) {
  13920. Server svr;
  13921. const std::string path = "/parity";
  13922. const std::string content = "Parity test content: hello world";
  13923. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13924. res.set_content(content, "text/plain");
  13925. });
  13926. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13927. auto se = detail::scope_exit([&] {
  13928. svr.stop();
  13929. t.join();
  13930. ASSERT_FALSE(svr.is_running());
  13931. });
  13932. svr.wait_until_ready();
  13933. Client cli(HOST, PORT);
  13934. // Non-stream path
  13935. auto r1 = cli.Get(path);
  13936. ASSERT_TRUE(r1);
  13937. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13938. // Stream path
  13939. auto h = cli.open_stream("GET", path);
  13940. ASSERT_TRUE(h.is_valid());
  13941. EXPECT_EQ(r1->body, read_all(h));
  13942. }
  13943. // Helper to compress data with provided compressor type T
  13944. template <typename Compressor>
  13945. static std::string compress_payload_for_parity(const std::string &in) {
  13946. std::string out;
  13947. Compressor compressor;
  13948. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13949. [&](const char *data, size_t n) {
  13950. out.append(data, n);
  13951. return true;
  13952. });
  13953. EXPECT_TRUE(ok);
  13954. return out;
  13955. }
  13956. // Helper function for compression parity tests
  13957. template <typename Compressor>
  13958. static void test_compression_parity(const std::string &original,
  13959. const std::string &path,
  13960. const std::string &encoding) {
  13961. const std::string compressed =
  13962. compress_payload_for_parity<Compressor>(original);
  13963. Server svr;
  13964. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13965. res.set_content(compressed, "application/octet-stream");
  13966. res.set_header("Content-Encoding", encoding);
  13967. });
  13968. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13969. auto se = detail::scope_exit([&] {
  13970. svr.stop();
  13971. t.join();
  13972. ASSERT_FALSE(svr.is_running());
  13973. });
  13974. svr.wait_until_ready();
  13975. Client cli(HOST, PORT);
  13976. // Non-streaming
  13977. {
  13978. auto res = cli.Get(path);
  13979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13980. EXPECT_EQ(StatusCode::OK_200, res->status);
  13981. EXPECT_EQ(original, res->body);
  13982. }
  13983. // Streaming
  13984. {
  13985. auto h = cli.open_stream("GET", path);
  13986. ASSERT_TRUE(h.is_valid());
  13987. EXPECT_EQ(original, read_all(h));
  13988. }
  13989. }
  13990. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13991. TEST(ParityTest, Gzip) {
  13992. test_compression_parity<detail::gzip_compressor>(
  13993. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13994. }
  13995. #endif
  13996. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13997. TEST(ParityTest, Brotli) {
  13998. test_compression_parity<detail::brotli_compressor>(
  13999. "Hello, brotli parity test payload", "/parity-br", "br");
  14000. }
  14001. #endif
  14002. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14003. TEST(ParityTest, Zstd) {
  14004. test_compression_parity<detail::zstd_compressor>(
  14005. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14006. }
  14007. #endif
  14008. //==============================================================================
  14009. // New Stream API Tests
  14010. //==============================================================================
  14011. inline std::string read_body(httplib::stream::Result &result) {
  14012. std::string body;
  14013. while (result.next()) {
  14014. body.append(result.data(), result.size());
  14015. }
  14016. return body;
  14017. }
  14018. TEST(ClientConnectionTest, Basic) {
  14019. httplib::ClientConnection conn;
  14020. EXPECT_FALSE(conn.is_open());
  14021. conn.sock = 1;
  14022. EXPECT_TRUE(conn.is_open());
  14023. httplib::ClientConnection conn2(std::move(conn));
  14024. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14025. conn2.sock = INVALID_SOCKET;
  14026. }
  14027. // Unified test server for all stream::* tests
  14028. class StreamApiTest : public ::testing::Test {
  14029. protected:
  14030. void SetUp() override {
  14031. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14032. res.set_content("Hello World!", "text/plain");
  14033. });
  14034. svr_.Get("/echo-params",
  14035. [](const httplib::Request &req, httplib::Response &res) {
  14036. std::string r;
  14037. for (const auto &p : req.params) {
  14038. if (!r.empty()) r += "&";
  14039. r += p.first + "=" + p.second;
  14040. }
  14041. res.set_content(r, "text/plain");
  14042. });
  14043. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14044. res.set_content(req.body, req.get_header_value("Content-Type"));
  14045. });
  14046. svr_.Post("/echo-headers",
  14047. [](const httplib::Request &req, httplib::Response &res) {
  14048. std::string r;
  14049. for (const auto &h : req.headers)
  14050. r += h.first + ": " + h.second + "\n";
  14051. res.set_content(r, "text/plain");
  14052. });
  14053. svr_.Post("/echo-params",
  14054. [](const httplib::Request &req, httplib::Response &res) {
  14055. std::string r = "params:";
  14056. for (const auto &p : req.params)
  14057. r += p.first + "=" + p.second + ";";
  14058. res.set_content(r + " body:" + req.body, "text/plain");
  14059. });
  14060. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14061. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14062. });
  14063. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14064. res.set_content("PUT:" + req.body, "text/plain");
  14065. });
  14066. svr_.Patch("/echo",
  14067. [](const httplib::Request &req, httplib::Response &res) {
  14068. res.set_content("PATCH:" + req.body, "text/plain");
  14069. });
  14070. svr_.Delete(
  14071. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14072. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14073. "text/plain");
  14074. });
  14075. svr_.Get("/head-test",
  14076. [](const httplib::Request &, httplib::Response &res) {
  14077. res.set_content("body for HEAD", "text/plain");
  14078. });
  14079. svr_.Options("/options",
  14080. [](const httplib::Request &, httplib::Response &res) {
  14081. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14082. });
  14083. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14084. svr_.wait_until_ready();
  14085. }
  14086. void TearDown() override {
  14087. svr_.stop();
  14088. if (thread_.joinable()) thread_.join();
  14089. }
  14090. httplib::Server svr_;
  14091. std::thread thread_;
  14092. };
  14093. // stream::Get tests
  14094. TEST_F(StreamApiTest, GetBasic) {
  14095. httplib::Client cli(HOST, PORT);
  14096. auto result = httplib::stream::Get(cli, "/hello");
  14097. ASSERT_TRUE(result.is_valid());
  14098. EXPECT_EQ(200, result.status());
  14099. EXPECT_EQ("Hello World!", read_body(result));
  14100. }
  14101. TEST_F(StreamApiTest, GetWithParams) {
  14102. httplib::Client cli(HOST, PORT);
  14103. httplib::Params params{{"foo", "bar"}};
  14104. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14105. ASSERT_TRUE(result.is_valid());
  14106. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14107. }
  14108. TEST_F(StreamApiTest, GetConnectionError) {
  14109. httplib::Client cli(HOST, 9999);
  14110. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14111. }
  14112. TEST_F(StreamApiTest, Get404) {
  14113. httplib::Client cli(HOST, PORT);
  14114. auto result = httplib::stream::Get(cli, "/nonexistent");
  14115. EXPECT_TRUE(result.is_valid());
  14116. EXPECT_EQ(404, result.status());
  14117. }
  14118. // stream::Post tests
  14119. TEST_F(StreamApiTest, PostBasic) {
  14120. httplib::Client cli(HOST, PORT);
  14121. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14122. "application/json");
  14123. ASSERT_TRUE(result.is_valid());
  14124. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14125. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14126. }
  14127. TEST_F(StreamApiTest, PostWithHeaders) {
  14128. httplib::Client cli(HOST, PORT);
  14129. httplib::Headers headers{{"X-Custom", "value"}};
  14130. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14131. "text/plain");
  14132. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14133. }
  14134. TEST_F(StreamApiTest, PostWithParams) {
  14135. httplib::Client cli(HOST, PORT);
  14136. httplib::Params params{{"k", "v"}};
  14137. auto result =
  14138. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14139. auto body = read_body(result);
  14140. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14141. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14142. }
  14143. TEST_F(StreamApiTest, PostLarge) {
  14144. httplib::Client cli(HOST, PORT);
  14145. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14146. size_t total = 0;
  14147. while (result.next()) {
  14148. total += result.size();
  14149. }
  14150. EXPECT_EQ(100u * 1024u, total);
  14151. }
  14152. // stream::Put/Patch tests
  14153. TEST_F(StreamApiTest, PutAndPatch) {
  14154. httplib::Client cli(HOST, PORT);
  14155. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14156. EXPECT_EQ("PUT:test", read_body(put));
  14157. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14158. EXPECT_EQ("PATCH:test", read_body(patch));
  14159. }
  14160. // stream::Delete tests
  14161. TEST_F(StreamApiTest, Delete) {
  14162. httplib::Client cli(HOST, PORT);
  14163. auto del1 = httplib::stream::Delete(cli, "/resource");
  14164. EXPECT_EQ("Deleted", read_body(del1));
  14165. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14166. EXPECT_EQ("Deleted:data", read_body(del2));
  14167. }
  14168. // stream::Head/Options tests
  14169. TEST_F(StreamApiTest, HeadAndOptions) {
  14170. httplib::Client cli(HOST, PORT);
  14171. auto head = httplib::stream::Head(cli, "/head-test");
  14172. EXPECT_TRUE(head.is_valid());
  14173. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14174. auto opts = httplib::stream::Options(cli, "/options");
  14175. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14176. }
  14177. // SSL stream::* tests
  14178. #ifdef CPPHTTPLIB_SSL_ENABLED
  14179. class SSLStreamApiTest : public ::testing::Test {
  14180. protected:
  14181. void SetUp() override {
  14182. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14183. res.set_content("Hello SSL!", "text/plain");
  14184. });
  14185. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14186. res.set_content(req.body, "text/plain");
  14187. });
  14188. port_ = svr_.bind_to_any_port("127.0.0.1");
  14189. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14190. svr_.wait_until_ready();
  14191. }
  14192. void TearDown() override {
  14193. svr_.stop();
  14194. if (thread_.joinable()) thread_.join();
  14195. }
  14196. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14197. std::thread thread_;
  14198. int port_ = 0;
  14199. };
  14200. TEST_F(SSLStreamApiTest, GetAndPost) {
  14201. httplib::SSLClient cli("127.0.0.1", port_);
  14202. cli.enable_server_certificate_verification(false);
  14203. auto get = httplib::stream::Get(cli, "/hello");
  14204. EXPECT_EQ("Hello SSL!", read_body(get));
  14205. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14206. EXPECT_EQ("test", read_body(post));
  14207. }
  14208. #endif
  14209. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14210. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14211. // BodyReader
  14212. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14213. // Test that read timeout during streaming is detected
  14214. // Use a large content-length response where server delays mid-stream
  14215. Server svr;
  14216. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14217. // Send a large response with delay in the middle
  14218. res.set_content_provider(
  14219. 1000, // content_length
  14220. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14221. if (offset < 100) {
  14222. // Send first 100 bytes immediately
  14223. std::string data(100, 'A');
  14224. sink.write(data.c_str(), data.size());
  14225. return true;
  14226. }
  14227. // Then delay longer than client timeout
  14228. std::this_thread::sleep_for(std::chrono::seconds(3));
  14229. std::string data(900, 'B');
  14230. sink.write(data.c_str(), data.size());
  14231. return true;
  14232. });
  14233. });
  14234. auto port = 8091;
  14235. std::thread t([&]() { svr.listen("localhost", port); });
  14236. svr.wait_until_ready();
  14237. Client cli("localhost", port);
  14238. cli.set_read_timeout(1, 0); // 1 second timeout
  14239. auto handle = cli.open_stream("GET", "/slow-stream");
  14240. ASSERT_TRUE(handle.is_valid());
  14241. char buf[256];
  14242. ssize_t total = 0;
  14243. ssize_t n;
  14244. bool got_error = false;
  14245. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14246. total += n;
  14247. }
  14248. if (n < 0) {
  14249. got_error = true;
  14250. // Should be timeout or read error
  14251. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14252. handle.get_read_error() == Error::Read)
  14253. << "Actual error: " << to_string(handle.get_read_error());
  14254. }
  14255. // Either we got an error, or we got less data than expected
  14256. EXPECT_TRUE(got_error || total < 1000)
  14257. << "Expected timeout but got all " << total << " bytes";
  14258. svr.stop();
  14259. t.join();
  14260. }
  14261. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14262. // Test connection closed detection via BodyReader
  14263. Server svr;
  14264. std::atomic<bool> close_now{false};
  14265. svr.Get("/will-close", [&](const Request &, Response &res) {
  14266. res.set_content_provider(
  14267. 10000, // Large content_length that we won't fully send
  14268. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14269. if (offset < 100) {
  14270. std::string data(100, 'X');
  14271. sink.write(data.c_str(), data.size());
  14272. return true;
  14273. }
  14274. // Wait for signal then abort
  14275. while (!close_now) {
  14276. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14277. }
  14278. return false; // Abort - server will close connection
  14279. });
  14280. });
  14281. auto port = 8092;
  14282. std::thread t([&]() { svr.listen("localhost", port); });
  14283. svr.wait_until_ready();
  14284. Client cli("localhost", port);
  14285. auto handle = cli.open_stream("GET", "/will-close");
  14286. ASSERT_TRUE(handle.is_valid());
  14287. char buf[256];
  14288. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14289. EXPECT_GT(n, 0) << "First read should succeed";
  14290. // Signal server to close
  14291. close_now = true;
  14292. // Keep reading until error or EOF
  14293. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14294. // Keep reading
  14295. }
  14296. // Should get an error since content_length wasn't satisfied
  14297. if (n < 0) {
  14298. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14299. handle.get_read_error() == Error::Read)
  14300. << "Actual error: " << to_string(handle.get_read_error());
  14301. }
  14302. svr.stop();
  14303. t.join();
  14304. }
  14305. #ifdef CPPHTTPLIB_SSL_ENABLED
  14306. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14307. // Test that read timeout during SSL streaming is detected
  14308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14309. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14310. res.set_content_provider(
  14311. 1000, "text/plain",
  14312. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14313. if (offset < 100) {
  14314. std::string data(100, 'A');
  14315. sink.write(data.c_str(), data.size());
  14316. return true;
  14317. }
  14318. std::this_thread::sleep_for(std::chrono::seconds(3));
  14319. std::string data(900, 'B');
  14320. sink.write(data.c_str(), data.size());
  14321. return true;
  14322. });
  14323. });
  14324. auto port = 8093;
  14325. std::thread t([&]() { svr.listen("localhost", port); });
  14326. svr.wait_until_ready();
  14327. SSLClient cli("localhost", port);
  14328. cli.enable_server_certificate_verification(false);
  14329. cli.set_read_timeout(1, 0); // 1 second timeout
  14330. auto handle = cli.open_stream("GET", "/slow-stream");
  14331. ASSERT_TRUE(handle.is_valid());
  14332. char buf[256];
  14333. ssize_t total = 0;
  14334. ssize_t n;
  14335. bool got_error = false;
  14336. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14337. total += n;
  14338. }
  14339. if (n < 0) {
  14340. got_error = true;
  14341. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14342. handle.get_read_error() == Error::Read)
  14343. << "Actual error: " << to_string(handle.get_read_error());
  14344. }
  14345. EXPECT_TRUE(got_error || total < 1000)
  14346. << "Expected timeout but got all " << total << " bytes";
  14347. svr.stop();
  14348. t.join();
  14349. }
  14350. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14351. // Test SSL connection closed detection
  14352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14353. std::atomic<bool> close_now{false};
  14354. svr.Get("/will-close", [&](const Request &, Response &res) {
  14355. res.set_content_provider(
  14356. 10000, "text/plain",
  14357. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14358. if (offset < 100) {
  14359. std::string data(100, 'X');
  14360. sink.write(data.c_str(), data.size());
  14361. return true;
  14362. }
  14363. while (!close_now) {
  14364. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14365. }
  14366. return false;
  14367. });
  14368. });
  14369. auto port = 8094;
  14370. std::thread t([&]() { svr.listen("localhost", port); });
  14371. svr.wait_until_ready();
  14372. SSLClient cli("localhost", port);
  14373. cli.enable_server_certificate_verification(false);
  14374. auto handle = cli.open_stream("GET", "/will-close");
  14375. ASSERT_TRUE(handle.is_valid());
  14376. char buf[256];
  14377. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14378. EXPECT_GT(n, 0);
  14379. // Signal server to close
  14380. close_now = true;
  14381. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14382. // Keep reading
  14383. }
  14384. if (n < 0) {
  14385. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14386. handle.get_read_error() == Error::Read)
  14387. << "Actual error: " << to_string(handle.get_read_error());
  14388. }
  14389. svr.stop();
  14390. t.join();
  14391. }
  14392. #endif
  14393. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14394. using namespace httplib;
  14395. // Create a test file
  14396. const char *fname = "etag_testfile.txt";
  14397. const char *content = "etag-content";
  14398. {
  14399. std::ofstream ofs(fname);
  14400. ofs << content;
  14401. ASSERT_TRUE(ofs.good());
  14402. }
  14403. Server svr;
  14404. svr.set_mount_point("/static", ".");
  14405. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14406. svr.wait_until_ready();
  14407. Client cli(HOST, PORT);
  14408. // First request: should get 200 with ETag header
  14409. auto res1 = cli.Get("/static/etag_testfile.txt");
  14410. ASSERT_TRUE(res1);
  14411. ASSERT_EQ(200, res1->status);
  14412. ASSERT_TRUE(res1->has_header("ETag"));
  14413. std::string etag = res1->get_header_value("ETag");
  14414. EXPECT_FALSE(etag.empty());
  14415. // Verify ETag format: W/"hex-hex"
  14416. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14417. EXPECT_EQ('W', etag[0]);
  14418. EXPECT_EQ('/', etag[1]);
  14419. EXPECT_EQ('"', etag[2]);
  14420. EXPECT_EQ('"', etag.back());
  14421. // Exact match: expect 304 Not Modified
  14422. Headers h2 = {{"If-None-Match", etag}};
  14423. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14424. ASSERT_TRUE(res2);
  14425. EXPECT_EQ(304, res2->status);
  14426. // Wildcard match: expect 304 Not Modified
  14427. Headers h3 = {{"If-None-Match", "*"}};
  14428. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14429. ASSERT_TRUE(res3);
  14430. EXPECT_EQ(304, res3->status);
  14431. // Non-matching ETag: expect 200
  14432. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14433. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14434. ASSERT_TRUE(res4);
  14435. EXPECT_EQ(200, res4->status);
  14436. // Multiple ETags with one matching: expect 304
  14437. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14438. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14439. ASSERT_TRUE(res5);
  14440. EXPECT_EQ(304, res5->status);
  14441. svr.stop();
  14442. t.join();
  14443. std::remove(fname);
  14444. }
  14445. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14446. using namespace httplib;
  14447. Server svr;
  14448. svr.set_mount_point("/static", ".");
  14449. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14450. svr.wait_until_ready();
  14451. Client cli(HOST, PORT);
  14452. // Send If-None-Match: * to a non-existent file
  14453. Headers h = {{"If-None-Match", "*"}};
  14454. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14456. EXPECT_EQ(404, res->status);
  14457. svr.stop();
  14458. t.join();
  14459. }
  14460. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14461. using namespace httplib;
  14462. // Create a test file
  14463. const char *fname = "etag_boundary_testfile.txt";
  14464. const char *content = "boundary-test";
  14465. {
  14466. std::ofstream ofs(fname);
  14467. ofs << content;
  14468. ASSERT_TRUE(ofs.good());
  14469. }
  14470. Server svr;
  14471. svr.set_mount_point("/static", ".");
  14472. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14473. svr.wait_until_ready();
  14474. Client cli(HOST, PORT);
  14475. // Get the actual ETag
  14476. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14477. ASSERT_TRUE(res1);
  14478. ASSERT_EQ(200, res1->status);
  14479. ASSERT_TRUE(res1->has_header("ETag"));
  14480. std::string etag = res1->get_header_value("ETag");
  14481. // Test 1: Very long ETag value (longer than actual ETag)
  14482. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14483. Headers h1 = {{"If-None-Match", "W/"
  14484. "\"very-long-etag-value-that-is-much-longer-"
  14485. "than-the-actual-etag-value\""}};
  14486. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14487. ASSERT_TRUE(res2);
  14488. EXPECT_EQ(200, res2->status); // Should not match
  14489. // Test 2: Long string followed by wildcard
  14490. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14491. // string)
  14492. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14493. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14494. ASSERT_TRUE(res3);
  14495. EXPECT_EQ(304, res3->status); // Should match on "*"
  14496. // Test 3: Wildcard followed by long string
  14497. // Should match on "*" immediately and return 304
  14498. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14499. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14500. ASSERT_TRUE(res4);
  14501. EXPECT_EQ(304, res4->status); // Should match on "*"
  14502. // Test 4: Multiple long non-matching values
  14503. // Should NOT match and return 200 (test that all comparisons are safe)
  14504. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14505. "W/\"second-long-non-matching-value\", "
  14506. "W/\"third-long-non-matching-value\""}};
  14507. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14508. ASSERT_TRUE(res5);
  14509. EXPECT_EQ(200, res5->status); // Should not match
  14510. // Test 5: Single character that is not "*" (edge case)
  14511. Headers h5 = {{"If-None-Match", "X"}};
  14512. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14513. ASSERT_TRUE(res6);
  14514. EXPECT_EQ(200, res6->status); // Should not match
  14515. svr.stop();
  14516. t.join();
  14517. std::remove(fname);
  14518. }
  14519. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14520. using namespace httplib;
  14521. // Create a test file
  14522. const char *fname = "ims_testfile.txt";
  14523. const char *content = "if-modified-since-test";
  14524. {
  14525. std::ofstream ofs(fname);
  14526. ofs << content;
  14527. ASSERT_TRUE(ofs.good());
  14528. }
  14529. Server svr;
  14530. svr.set_mount_point("/static", ".");
  14531. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14532. svr.wait_until_ready();
  14533. Client cli(HOST, PORT);
  14534. // First request: should get 200 with Last-Modified header
  14535. auto res1 = cli.Get("/static/ims_testfile.txt");
  14536. ASSERT_TRUE(res1);
  14537. ASSERT_EQ(200, res1->status);
  14538. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14539. std::string last_modified = res1->get_header_value("Last-Modified");
  14540. EXPECT_FALSE(last_modified.empty());
  14541. // If-Modified-Since with same time: expect 304
  14542. Headers h2 = {{"If-Modified-Since", last_modified}};
  14543. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14544. ASSERT_TRUE(res2);
  14545. EXPECT_EQ(304, res2->status);
  14546. // If-Modified-Since with future time: expect 304
  14547. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14548. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14549. ASSERT_TRUE(res3);
  14550. EXPECT_EQ(304, res3->status);
  14551. // If-Modified-Since with past time: expect 200
  14552. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14553. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14554. ASSERT_TRUE(res4);
  14555. EXPECT_EQ(200, res4->status);
  14556. // If-None-Match takes precedence over If-Modified-Since
  14557. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14558. ASSERT_TRUE(res1->has_header("ETag"));
  14559. std::string etag = res1->get_header_value("ETag");
  14560. Headers h5 = {{"If-None-Match", etag},
  14561. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14562. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14563. ASSERT_TRUE(res5);
  14564. EXPECT_EQ(304, res5->status);
  14565. svr.stop();
  14566. t.join();
  14567. std::remove(fname);
  14568. }
  14569. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14570. using namespace httplib;
  14571. Server svr;
  14572. // Endpoint that returns compressible content
  14573. svr.Get("/compressible", [](const Request &, Response &res) {
  14574. // Return a large enough body to trigger compression
  14575. std::string body(1000, 'a');
  14576. res.set_content(body, "text/plain");
  14577. });
  14578. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14579. svr.wait_until_ready();
  14580. Client cli(HOST, PORT);
  14581. // Request with gzip support: should get Vary header when compressed
  14582. cli.set_compress(true);
  14583. auto res1 = cli.Get("/compressible");
  14584. ASSERT_TRUE(res1);
  14585. EXPECT_EQ(200, res1->status);
  14586. // If Content-Encoding is set, Vary should also be set
  14587. if (res1->has_header("Content-Encoding")) {
  14588. EXPECT_TRUE(res1->has_header("Vary"));
  14589. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14590. }
  14591. // Request without Accept-Encoding header: should not have compression
  14592. Headers h_no_compress;
  14593. auto res2 = cli.Get("/compressible", h_no_compress);
  14594. ASSERT_TRUE(res2);
  14595. EXPECT_EQ(200, res2->status);
  14596. // Verify Vary header is present when compression is applied
  14597. // (the exact behavior depends on server configuration)
  14598. svr.stop();
  14599. t.join();
  14600. }
  14601. TEST(ETagTest, IfRangeWithETag) {
  14602. using namespace httplib;
  14603. // Create a test file with known content
  14604. const char *fname = "if_range_testfile.txt";
  14605. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14606. {
  14607. std::ofstream ofs(fname);
  14608. ofs << content;
  14609. ASSERT_TRUE(ofs.good());
  14610. }
  14611. Server svr;
  14612. svr.set_mount_point("/static", ".");
  14613. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14614. svr.wait_until_ready();
  14615. Client cli(HOST, PORT);
  14616. // First request: get ETag
  14617. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14618. ASSERT_TRUE(res1);
  14619. ASSERT_EQ(200, res1->status);
  14620. ASSERT_TRUE(res1->has_header("ETag"));
  14621. std::string etag = res1->get_header_value("ETag");
  14622. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14623. // Since our server generates weak ETags (W/"..."), If-Range with our
  14624. // ETag should NOT result in partial content - it should return full content.
  14625. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14626. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14627. ASSERT_TRUE(res2);
  14628. // Weak ETag in If-Range -> full content (200), not partial (206)
  14629. EXPECT_EQ(200, res2->status);
  14630. EXPECT_EQ(content, res2->body);
  14631. EXPECT_FALSE(res2->has_header("Content-Range"));
  14632. // Range request with non-matching If-Range (ETag): should get 200 (full
  14633. // content)
  14634. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14635. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14636. ASSERT_TRUE(res3);
  14637. EXPECT_EQ(200, res3->status);
  14638. EXPECT_EQ(content, res3->body);
  14639. EXPECT_FALSE(res3->has_header("Content-Range"));
  14640. // Range request with strong ETag (hypothetical - our server doesn't generate
  14641. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14642. // should return full content)
  14643. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14644. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14645. ASSERT_TRUE(res4);
  14646. EXPECT_EQ(200, res4->status);
  14647. EXPECT_EQ(content, res4->body);
  14648. EXPECT_FALSE(res4->has_header("Content-Range"));
  14649. svr.stop();
  14650. t.join();
  14651. std::remove(fname);
  14652. }
  14653. TEST(ETagTest, IfRangeWithDate) {
  14654. using namespace httplib;
  14655. // Create a test file
  14656. const char *fname = "if_range_date_testfile.txt";
  14657. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14658. {
  14659. std::ofstream ofs(fname);
  14660. ofs << content;
  14661. ASSERT_TRUE(ofs.good());
  14662. }
  14663. Server svr;
  14664. svr.set_mount_point("/static", ".");
  14665. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14666. svr.wait_until_ready();
  14667. Client cli(HOST, PORT);
  14668. // First request: get Last-Modified
  14669. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14670. ASSERT_TRUE(res1);
  14671. ASSERT_EQ(200, res1->status);
  14672. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14673. std::string last_modified = res1->get_header_value("Last-Modified");
  14674. // Range request with matching If-Range (date): should get 206
  14675. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14676. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14677. ASSERT_TRUE(res2);
  14678. EXPECT_EQ(206, res2->status);
  14679. EXPECT_EQ("FGHIJ", res2->body);
  14680. // Range request with old If-Range date: should get 200 (full content)
  14681. Headers h3 = {{"Range", "bytes=5-9"},
  14682. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14683. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14684. ASSERT_TRUE(res3);
  14685. EXPECT_EQ(200, res3->status);
  14686. EXPECT_EQ(content, res3->body);
  14687. // Range request with future If-Range date: should get 206
  14688. Headers h4 = {{"Range", "bytes=0-4"},
  14689. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14690. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14691. ASSERT_TRUE(res4);
  14692. EXPECT_EQ(206, res4->status);
  14693. EXPECT_EQ("ABCDE", res4->body);
  14694. svr.stop();
  14695. t.join();
  14696. std::remove(fname);
  14697. }
  14698. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14699. using namespace httplib;
  14700. const char *fname = "etag_malformed.txt";
  14701. const char *content = "malformed-etag";
  14702. {
  14703. std::ofstream ofs(fname);
  14704. ofs << content;
  14705. ASSERT_TRUE(ofs.good());
  14706. }
  14707. Server svr;
  14708. svr.set_mount_point("/static", ".");
  14709. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14710. svr.wait_until_ready();
  14711. Client cli(HOST, PORT);
  14712. // baseline: should get 200 and an ETag
  14713. auto res1 = cli.Get("/static/etag_malformed.txt");
  14714. ASSERT_TRUE(res1);
  14715. ASSERT_EQ(200, res1->status);
  14716. ASSERT_TRUE(res1->has_header("ETag"));
  14717. // Malformed ETag value (missing quotes) should be treated as non-matching
  14718. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14719. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14720. ASSERT_TRUE(res_bad);
  14721. EXPECT_EQ(200, res_bad->status);
  14722. // Whitespace-only header value should be considered invalid / non-matching
  14723. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14724. "Host: localhost\r\n"
  14725. "If-None-Match: \r\n"
  14726. "Connection: close\r\n"
  14727. "\r\n";
  14728. std::string out;
  14729. ASSERT_TRUE(send_request(5, raw_req, &out));
  14730. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14731. svr.stop();
  14732. t.join();
  14733. std::remove(fname);
  14734. }
  14735. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14736. using namespace httplib;
  14737. const char *fname = "ims_invalid_format.txt";
  14738. const char *content = "ims-bad-format";
  14739. {
  14740. std::ofstream ofs(fname);
  14741. ofs << content;
  14742. ASSERT_TRUE(ofs.good());
  14743. }
  14744. Server svr;
  14745. svr.set_mount_point("/static", ".");
  14746. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14747. svr.wait_until_ready();
  14748. Client cli(HOST, PORT);
  14749. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14750. ASSERT_TRUE(res1);
  14751. ASSERT_EQ(200, res1->status);
  14752. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14753. // If-Modified-Since with invalid format should not result in 304
  14754. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14755. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14756. ASSERT_TRUE(res_bad);
  14757. EXPECT_EQ(200, res_bad->status);
  14758. // If-Range with invalid date format should be treated as mismatch -> full
  14759. // content (200)
  14760. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14761. {"If-Range", "invalid-date"}};
  14762. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14763. ASSERT_TRUE(res_ifrange);
  14764. EXPECT_EQ(200, res_ifrange->status);
  14765. svr.stop();
  14766. t.join();
  14767. std::remove(fname);
  14768. }
  14769. TEST(ETagTest, IfRangeWithMalformedETag) {
  14770. using namespace httplib;
  14771. const char *fname = "ifrange_malformed.txt";
  14772. const std::string content = "0123456789";
  14773. {
  14774. std::ofstream ofs(fname);
  14775. ofs << content;
  14776. ASSERT_TRUE(ofs.good());
  14777. }
  14778. Server svr;
  14779. svr.set_mount_point("/static", ".");
  14780. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14781. svr.wait_until_ready();
  14782. Client cli(HOST, PORT);
  14783. // First request: get ETag
  14784. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14785. ASSERT_TRUE(res1);
  14786. ASSERT_EQ(200, res1->status);
  14787. ASSERT_TRUE(res1->has_header("ETag"));
  14788. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14789. // full content (200)
  14790. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14791. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14792. ASSERT_TRUE(res2);
  14793. EXPECT_EQ(200, res2->status);
  14794. EXPECT_EQ(content, res2->body);
  14795. svr.stop();
  14796. t.join();
  14797. std::remove(fname);
  14798. }
  14799. TEST(ETagTest, ExtremeLargeDateValues) {
  14800. using namespace httplib;
  14801. const char *fname = "ims_extreme_date.txt";
  14802. const char *content = "ims-extreme-date";
  14803. {
  14804. std::ofstream ofs(fname);
  14805. ofs << content;
  14806. ASSERT_TRUE(ofs.good());
  14807. }
  14808. Server svr;
  14809. svr.set_mount_point("/static", ".");
  14810. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14811. svr.wait_until_ready();
  14812. Client cli(HOST, PORT);
  14813. auto res1 = cli.Get(std::string("/static/") + fname);
  14814. ASSERT_TRUE(res1);
  14815. ASSERT_EQ(200, res1->status);
  14816. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14817. // Extremely large year that may overflow date parsing routines.
  14818. Headers h_large_date = {
  14819. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14820. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14821. ASSERT_TRUE(res_bad);
  14822. // Expect server to treat this as invalid/mismatch and return full content
  14823. EXPECT_EQ(200, res_bad->status);
  14824. // If-Range with extremely large date should be treated as mismatch -> full
  14825. // content (200)
  14826. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14827. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14828. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14829. ASSERT_TRUE(res_ifrange);
  14830. EXPECT_EQ(200, res_ifrange->status);
  14831. svr.stop();
  14832. t.join();
  14833. std::remove(fname);
  14834. }
  14835. TEST(ETagTest, NegativeFileModificationTime) {
  14836. using namespace httplib;
  14837. const char *fname = "ims_negative_mtime.txt";
  14838. const std::string content = "negative-mtime";
  14839. {
  14840. std::ofstream ofs(fname);
  14841. ofs << content;
  14842. ASSERT_TRUE(ofs.good());
  14843. }
  14844. // Try to set file mtime to a negative value. This may fail on some
  14845. // platforms/filesystems; if it fails, the test will still verify server
  14846. // behaves safely by performing a regular conditional request.
  14847. #if defined(__APPLE__) || defined(__linux__)
  14848. bool set_negative = false;
  14849. do {
  14850. struct timeval times[2];
  14851. // access time: now
  14852. times[0].tv_sec = time(nullptr);
  14853. times[0].tv_usec = 0;
  14854. // modification time: negative (e.g., -1)
  14855. times[1].tv_sec = -1;
  14856. times[1].tv_usec = 0;
  14857. if (utimes(fname, times) == 0) { set_negative = true; }
  14858. } while (0);
  14859. #else
  14860. bool set_negative = false;
  14861. #endif
  14862. Server svr;
  14863. svr.set_mount_point("/static", ".");
  14864. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14865. svr.wait_until_ready();
  14866. Client cli(HOST, PORT);
  14867. auto res1 = cli.Get(std::string("/static/") + fname);
  14868. ASSERT_TRUE(res1);
  14869. ASSERT_EQ(200, res1->status);
  14870. bool has_last_modified = res1->has_header("Last-Modified");
  14871. std::string last_modified;
  14872. if (has_last_modified) {
  14873. last_modified = res1->get_header_value("Last-Modified");
  14874. }
  14875. if (set_negative) {
  14876. // If we successfully set a negative mtime, ensure server returns a
  14877. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14878. // with an old date and ensure server handles it without crash.
  14879. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14880. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14881. ASSERT_TRUE(res2);
  14882. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14883. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14884. } else {
  14885. // Could not set negative mtime on this platform; fall back to verifying
  14886. // that normal invalid/malformed dates are treated safely (non-304).
  14887. Headers h_bad_date = {
  14888. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14889. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14890. ASSERT_TRUE(res_bad);
  14891. EXPECT_EQ(200, res_bad->status);
  14892. }
  14893. svr.stop();
  14894. t.join();
  14895. std::remove(fname);
  14896. }
  14897. //==============================================================================
  14898. // SSE Parsing Tests
  14899. //==============================================================================
  14900. class SSEParsingTest : public ::testing::Test {
  14901. protected:
  14902. // Test helper that mimics SSE parsing behavior
  14903. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14904. int &retry_ms) {
  14905. // Blank line signals end of event
  14906. if (line.empty() || line == "\r") { return true; }
  14907. // Lines starting with ':' are comments (ignored)
  14908. if (!line.empty() && line[0] == ':') { return false; }
  14909. // Find the colon separator
  14910. auto colon_pos = line.find(':');
  14911. if (colon_pos == std::string::npos) {
  14912. // Line with no colon is treated as field name with empty value
  14913. return false;
  14914. }
  14915. std::string field = line.substr(0, colon_pos);
  14916. std::string value;
  14917. // Value starts after colon, skip optional single space
  14918. if (colon_pos + 1 < line.size()) {
  14919. size_t value_start = colon_pos + 1;
  14920. if (line[value_start] == ' ') { value_start++; }
  14921. value = line.substr(value_start);
  14922. // Remove trailing \r if present
  14923. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14924. }
  14925. // Handle known fields
  14926. if (field == "event") {
  14927. msg.event = value;
  14928. } else if (field == "data") {
  14929. // Multiple data lines are concatenated with newlines
  14930. if (!msg.data.empty()) { msg.data += "\n"; }
  14931. msg.data += value;
  14932. } else if (field == "id") {
  14933. // Empty id is valid (clears the last event ID)
  14934. msg.id = value;
  14935. } else if (field == "retry") {
  14936. // Parse retry interval in milliseconds
  14937. {
  14938. int v = 0;
  14939. auto res =
  14940. detail::from_chars(value.data(), value.data() + value.size(), v);
  14941. if (res.ec == std::errc{}) { retry_ms = v; }
  14942. }
  14943. }
  14944. // Unknown fields are ignored per SSE spec
  14945. return false;
  14946. }
  14947. };
  14948. // Test: Single-line data
  14949. TEST_F(SSEParsingTest, SingleLineData) {
  14950. sse::SSEMessage msg;
  14951. int retry_ms = 3000;
  14952. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14953. EXPECT_EQ(msg.data, "hello");
  14954. EXPECT_EQ(msg.event, "message");
  14955. // Blank line ends event
  14956. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14957. }
  14958. // Test: Multi-line data
  14959. TEST_F(SSEParsingTest, MultiLineData) {
  14960. sse::SSEMessage msg;
  14961. int retry_ms = 3000;
  14962. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14963. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14964. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14965. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14966. }
  14967. // Test: Custom event types
  14968. TEST_F(SSEParsingTest, CustomEventType) {
  14969. sse::SSEMessage msg;
  14970. int retry_ms = 3000;
  14971. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14972. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14973. EXPECT_EQ(msg.event, "update");
  14974. EXPECT_EQ(msg.data, "payload");
  14975. }
  14976. // Test: Event ID handling
  14977. TEST_F(SSEParsingTest, EventIdHandling) {
  14978. sse::SSEMessage msg;
  14979. int retry_ms = 3000;
  14980. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14981. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14982. EXPECT_EQ(msg.id, "12345");
  14983. }
  14984. // Test: Empty event ID (clears last event ID)
  14985. TEST_F(SSEParsingTest, EmptyEventId) {
  14986. sse::SSEMessage msg;
  14987. msg.id = "previous";
  14988. int retry_ms = 3000;
  14989. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14990. EXPECT_EQ(msg.id, "");
  14991. }
  14992. // Test: Retry field parsing
  14993. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14994. sse::SSEMessage msg;
  14995. int retry_ms = 3000;
  14996. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14997. EXPECT_EQ(retry_ms, 5000);
  14998. }
  14999. // Test: Invalid retry value
  15000. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15001. sse::SSEMessage msg;
  15002. int retry_ms = 3000;
  15003. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15004. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15005. }
  15006. // Test: Comments (lines starting with :)
  15007. TEST_F(SSEParsingTest, CommentsIgnored) {
  15008. sse::SSEMessage msg;
  15009. int retry_ms = 3000;
  15010. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15011. EXPECT_EQ(msg.data, "");
  15012. EXPECT_EQ(msg.event, "message");
  15013. }
  15014. // Test: Colon in value
  15015. TEST_F(SSEParsingTest, ColonInValue) {
  15016. sse::SSEMessage msg;
  15017. int retry_ms = 3000;
  15018. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15019. EXPECT_EQ(msg.data, "hello:world:test");
  15020. }
  15021. // Test: Line with no colon (field name only)
  15022. TEST_F(SSEParsingTest, FieldNameOnly) {
  15023. sse::SSEMessage msg;
  15024. int retry_ms = 3000;
  15025. // According to SSE spec, this is treated as field name with empty value
  15026. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15027. // Since we don't recognize "data" without colon, data should be empty
  15028. EXPECT_EQ(msg.data, "");
  15029. }
  15030. // Test: Trailing \r handling
  15031. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15032. sse::SSEMessage msg;
  15033. int retry_ms = 3000;
  15034. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15035. EXPECT_EQ(msg.data, "hello");
  15036. }
  15037. // Test: Unknown fields ignored
  15038. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15039. sse::SSEMessage msg;
  15040. int retry_ms = 3000;
  15041. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15042. EXPECT_EQ(msg.data, "");
  15043. EXPECT_EQ(msg.event, "message");
  15044. }
  15045. // Test: Space after colon is optional
  15046. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15047. sse::SSEMessage msg1, msg2;
  15048. int retry_ms = 3000;
  15049. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15050. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15051. EXPECT_EQ(msg1.data, "hello");
  15052. EXPECT_EQ(msg2.data, "hello");
  15053. }
  15054. // Test: SSEMessage clear
  15055. TEST_F(SSEParsingTest, MessageClear) {
  15056. sse::SSEMessage msg;
  15057. msg.event = "custom";
  15058. msg.data = "some data";
  15059. msg.id = "123";
  15060. msg.clear();
  15061. EXPECT_EQ(msg.event, "message");
  15062. EXPECT_EQ(msg.data, "");
  15063. EXPECT_EQ(msg.id, "");
  15064. }
  15065. // Test: Complete event parsing
  15066. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15067. sse::SSEMessage msg;
  15068. int retry_ms = 3000;
  15069. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15070. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15071. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15072. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15073. // Blank line ends event
  15074. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15075. EXPECT_EQ(msg.event, "notification");
  15076. EXPECT_EQ(msg.id, "evt-42");
  15077. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15078. EXPECT_EQ(retry_ms, 1000);
  15079. }
  15080. //==============================================================================
  15081. // Integration Tests with Server
  15082. //==============================================================================
  15083. class SSEIntegrationTest : public ::testing::Test {
  15084. protected:
  15085. void SetUp() override {
  15086. stop_server_.store(false);
  15087. events_.clear();
  15088. server_ = httplib::detail::make_unique<Server>();
  15089. setup_server();
  15090. start_server();
  15091. }
  15092. void TearDown() override {
  15093. stop_server_.store(true);
  15094. event_cv_.notify_all();
  15095. server_->stop();
  15096. if (server_thread_.joinable()) { server_thread_.join(); }
  15097. }
  15098. void setup_server() {
  15099. // Simple SSE endpoint
  15100. server_->Get("/events", [this](const Request &req, Response &res) {
  15101. auto last_id = req.get_header_value("Last-Event-ID");
  15102. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15103. res.set_chunked_content_provider(
  15104. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15105. std::unique_lock<std::mutex> lock(event_mutex_);
  15106. if (event_cv_.wait_for(
  15107. lock, std::chrono::milliseconds(200), [this] {
  15108. return !events_.empty() || stop_server_.load();
  15109. })) {
  15110. if (stop_server_.load()) { return false; }
  15111. if (!events_.empty()) {
  15112. std::string event = events_.front();
  15113. events_.erase(events_.begin());
  15114. sink.write(event.data(), event.size());
  15115. return true;
  15116. }
  15117. }
  15118. return !stop_server_.load();
  15119. });
  15120. });
  15121. // Endpoint that returns error
  15122. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15123. res.status = 500;
  15124. res.set_content("Internal Server Error", "text/plain");
  15125. });
  15126. // Endpoint for custom event types
  15127. server_->Get("/custom-events", [](const Request &, Response &res) {
  15128. res.set_chunked_content_provider(
  15129. "text/event-stream", [](size_t offset, DataSink &sink) {
  15130. if (offset == 0) {
  15131. std::string event = "event: update\ndata: updated\n\n"
  15132. "event: delete\ndata: deleted\n\n";
  15133. sink.write(event.data(), event.size());
  15134. }
  15135. return false; // End stream after sending
  15136. });
  15137. });
  15138. }
  15139. void start_server() {
  15140. port_ = server_->bind_to_any_port(HOST);
  15141. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15142. // Wait for server to start
  15143. while (!server_->is_running()) {
  15144. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15145. }
  15146. }
  15147. int get_port() const { return port_; }
  15148. void send_event(const std::string &event) {
  15149. std::lock_guard<std::mutex> lock(event_mutex_);
  15150. events_.push_back(event);
  15151. event_cv_.notify_all();
  15152. }
  15153. std::unique_ptr<Server> server_;
  15154. std::thread server_thread_;
  15155. std::mutex event_mutex_;
  15156. std::condition_variable event_cv_;
  15157. std::vector<std::string> events_;
  15158. std::atomic<bool> stop_server_{false};
  15159. std::string last_received_event_id_;
  15160. int port_ = 0;
  15161. };
  15162. // Test: Successful connection and on_open callback
  15163. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15164. // Add a simple endpoint that sends one event and closes
  15165. server_->Get("/simple-event", [](const Request &, Response &res) {
  15166. res.set_chunked_content_provider(
  15167. "text/event-stream", [](size_t offset, DataSink &sink) {
  15168. if (offset == 0) {
  15169. std::string event = "data: hello\n\n";
  15170. sink.write(event.data(), event.size());
  15171. }
  15172. return false; // Close stream after sending
  15173. });
  15174. });
  15175. Client client("localhost", get_port());
  15176. sse::SSEClient sse(client, "/simple-event");
  15177. std::atomic<bool> open_called{false};
  15178. std::atomic<bool> message_received{false};
  15179. sse.on_open([&open_called]() { open_called.store(true); });
  15180. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15181. if (msg.data == "hello") { message_received.store(true); }
  15182. });
  15183. sse.set_reconnect_interval(100);
  15184. sse.set_max_reconnect_attempts(1);
  15185. // Start async
  15186. sse.start_async();
  15187. // Wait for message to be processed
  15188. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15189. sse.stop();
  15190. EXPECT_TRUE(open_called.load());
  15191. EXPECT_TRUE(message_received.load());
  15192. }
  15193. // Test: on_message callback
  15194. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15195. // Endpoint that sends multiple events then closes
  15196. server_->Get("/multi-event", [](const Request &, Response &res) {
  15197. res.set_chunked_content_provider(
  15198. "text/event-stream", [](size_t offset, DataSink &sink) {
  15199. if (offset == 0) {
  15200. std::string events = "data: message1\n\ndata: message2\n\n";
  15201. sink.write(events.data(), events.size());
  15202. }
  15203. return false;
  15204. });
  15205. });
  15206. Client client("localhost", get_port());
  15207. sse::SSEClient sse(client, "/multi-event");
  15208. std::vector<std::string> received_messages;
  15209. std::mutex messages_mutex;
  15210. sse.on_message([&](const sse::SSEMessage &msg) {
  15211. std::lock_guard<std::mutex> lock(messages_mutex);
  15212. received_messages.push_back(msg.data);
  15213. });
  15214. sse.set_reconnect_interval(100);
  15215. sse.set_max_reconnect_attempts(1);
  15216. sse.start_async();
  15217. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15218. sse.stop();
  15219. std::lock_guard<std::mutex> lock(messages_mutex);
  15220. EXPECT_GE(received_messages.size(), 2u);
  15221. if (received_messages.size() >= 2) {
  15222. EXPECT_EQ(received_messages[0], "message1");
  15223. EXPECT_EQ(received_messages[1], "message2");
  15224. }
  15225. }
  15226. // Test: on_event for specific types
  15227. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15228. Client client("localhost", get_port());
  15229. sse::SSEClient sse(client, "/custom-events");
  15230. std::atomic<bool> update_received{false};
  15231. std::atomic<bool> delete_received{false};
  15232. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15233. if (msg.data == "updated") { update_received.store(true); }
  15234. });
  15235. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15236. if (msg.data == "deleted") { delete_received.store(true); }
  15237. });
  15238. sse.set_max_reconnect_attempts(1);
  15239. sse.start_async();
  15240. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15241. sse.stop();
  15242. EXPECT_TRUE(update_received.load());
  15243. EXPECT_TRUE(delete_received.load());
  15244. }
  15245. // Test: on_error callback on connection failure
  15246. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15247. // Connect to a non-existent port
  15248. Client client("localhost", 59999);
  15249. sse::SSEClient sse(client, "/events");
  15250. std::atomic<bool> error_called{false};
  15251. Error received_error = Error::Success;
  15252. sse.on_error([&](Error err) {
  15253. error_called.store(true);
  15254. received_error = err;
  15255. });
  15256. sse.set_reconnect_interval(50);
  15257. sse.set_max_reconnect_attempts(1);
  15258. sse.start_async();
  15259. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15260. sse.stop();
  15261. EXPECT_TRUE(error_called.load());
  15262. EXPECT_NE(received_error, Error::Success);
  15263. }
  15264. // Test: Last-Event-ID header sent on reconnect
  15265. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15266. // Endpoint that sends event with ID
  15267. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15268. res.set_chunked_content_provider(
  15269. "text/event-stream", [](size_t offset, DataSink &sink) {
  15270. if (offset == 0) {
  15271. std::string event = "id: evt-123\ndata: test\n\n";
  15272. sink.write(event.data(), event.size());
  15273. }
  15274. return false;
  15275. });
  15276. });
  15277. Client client("localhost", get_port());
  15278. sse::SSEClient sse(client, "/event-with-id");
  15279. std::atomic<bool> id_received{false};
  15280. sse.on_message([&](const sse::SSEMessage &msg) {
  15281. if (!msg.id.empty()) { id_received.store(true); }
  15282. });
  15283. sse.set_reconnect_interval(100);
  15284. sse.set_max_reconnect_attempts(1);
  15285. sse.start_async();
  15286. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15287. sse.stop();
  15288. EXPECT_TRUE(id_received.load());
  15289. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15290. }
  15291. // Test: Manual stop
  15292. TEST_F(SSEIntegrationTest, ManualStop) {
  15293. // Endpoint that sends one event and stays open briefly
  15294. std::atomic<bool> handler_running{true};
  15295. server_->Get("/stay-open", [&handler_running](const Request &,
  15296. Response &res) {
  15297. res.set_chunked_content_provider(
  15298. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15299. if (offset == 0) {
  15300. std::string event = "data: connected\n\n";
  15301. sink.write(event.data(), event.size());
  15302. }
  15303. // Keep connection open while handler_running is true
  15304. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15305. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15306. }
  15307. return false;
  15308. });
  15309. });
  15310. Client client("localhost", get_port());
  15311. sse::SSEClient sse(client, "/stay-open");
  15312. std::atomic<bool> connected{false};
  15313. sse.on_open([&connected]() { connected.store(true); });
  15314. sse.set_reconnect_interval(100);
  15315. sse.set_max_reconnect_attempts(1);
  15316. sse.start_async();
  15317. // Wait for connection to establish
  15318. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15319. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15320. }
  15321. EXPECT_TRUE(connected.load());
  15322. EXPECT_TRUE(sse.is_connected());
  15323. // Signal handler to stop
  15324. handler_running.store(false);
  15325. // Stop SSE client
  15326. sse.stop();
  15327. EXPECT_FALSE(sse.is_connected());
  15328. }
  15329. // Test: SSEClient with custom headers
  15330. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15331. // Setup a server endpoint that checks for custom header
  15332. std::atomic<bool> header_received{false};
  15333. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15334. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15335. header_received.store(true);
  15336. }
  15337. res.set_chunked_content_provider("text/event-stream",
  15338. [](size_t, DataSink &) { return false; });
  15339. });
  15340. Client client("localhost", get_port());
  15341. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15342. sse::SSEClient sse(client, "/header-check", headers);
  15343. sse.set_max_reconnect_attempts(1);
  15344. sse.start_async();
  15345. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15346. sse.stop();
  15347. EXPECT_TRUE(header_received.load());
  15348. }
  15349. // Test: Reconnect interval configuration
  15350. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15351. Client client("localhost", get_port());
  15352. sse::SSEClient sse(client, "/events");
  15353. auto &result = sse.set_reconnect_interval(500);
  15354. // Builder pattern should return reference to self
  15355. EXPECT_EQ(&result, &sse);
  15356. }
  15357. // Test: Max reconnect attempts
  15358. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15359. // Connect to non-existent port to force reconnects
  15360. Client client("localhost", 59998);
  15361. sse::SSEClient sse(client, "/events");
  15362. std::atomic<int> error_count{0};
  15363. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15364. sse.set_reconnect_interval(50);
  15365. sse.set_max_reconnect_attempts(2);
  15366. auto start = std::chrono::steady_clock::now();
  15367. sse.start(); // Blocking call
  15368. auto end = std::chrono::steady_clock::now();
  15369. // Should have stopped after 2 failed attempts
  15370. EXPECT_GE(error_count.load(), 2);
  15371. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15372. auto duration =
  15373. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15374. #ifdef _WIN32
  15375. // Windows is much slower for socket connection failures
  15376. EXPECT_LT(duration.count(), 7000);
  15377. #else
  15378. EXPECT_LT(duration.count(), 1000);
  15379. #endif
  15380. }
  15381. // Test: Multi-line data in integration
  15382. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15383. // Endpoint with multi-line data
  15384. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15385. res.set_chunked_content_provider(
  15386. "text/event-stream", [](size_t offset, DataSink &sink) {
  15387. if (offset == 0) {
  15388. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15389. sink.write(event.data(), event.size());
  15390. }
  15391. return false;
  15392. });
  15393. });
  15394. Client client("localhost", get_port());
  15395. sse::SSEClient sse(client, "/multiline-data");
  15396. std::string received_data;
  15397. std::mutex data_mutex;
  15398. sse.on_message([&](const sse::SSEMessage &msg) {
  15399. std::lock_guard<std::mutex> lock(data_mutex);
  15400. received_data = msg.data;
  15401. });
  15402. sse.set_reconnect_interval(100);
  15403. sse.set_max_reconnect_attempts(1);
  15404. sse.start_async();
  15405. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15406. sse.stop();
  15407. std::lock_guard<std::mutex> lock(data_mutex);
  15408. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15409. }
  15410. // Test: Auto-reconnect after server disconnection
  15411. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15412. std::atomic<int> connection_count{0};
  15413. std::atomic<int> message_count{0};
  15414. // Endpoint that sends one event and closes, forcing reconnect
  15415. server_->Get("/reconnect-test",
  15416. [&connection_count](const Request &, Response &res) {
  15417. connection_count.fetch_add(1);
  15418. res.set_chunked_content_provider(
  15419. "text/event-stream", [](size_t offset, DataSink &sink) {
  15420. if (offset == 0) {
  15421. std::string event = "data: hello\n\n";
  15422. sink.write(event.data(), event.size());
  15423. }
  15424. return false; // Close connection after sending
  15425. });
  15426. });
  15427. Client client("localhost", get_port());
  15428. sse::SSEClient sse(client, "/reconnect-test");
  15429. sse.on_message([&message_count](const sse::SSEMessage &) {
  15430. message_count.fetch_add(1);
  15431. });
  15432. sse.set_reconnect_interval(100);
  15433. sse.set_max_reconnect_attempts(3);
  15434. sse.start_async();
  15435. // Wait long enough for multiple reconnects
  15436. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15437. sse.stop();
  15438. // Should have connected multiple times (initial + reconnects)
  15439. EXPECT_GE(connection_count.load(), 2);
  15440. // Should have received messages from multiple connections
  15441. EXPECT_GE(message_count.load(), 2);
  15442. }
  15443. // Test: Last-Event-ID sent on reconnect
  15444. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15445. std::atomic<int> connection_count{0};
  15446. std::vector<std::string> received_last_event_ids;
  15447. std::mutex id_mutex;
  15448. // Endpoint that checks Last-Event-ID header and sends event with ID
  15449. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15450. int conn = connection_count.fetch_add(1);
  15451. // Capture the Last-Event-ID header from each connection
  15452. {
  15453. std::lock_guard<std::mutex> lock(id_mutex);
  15454. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15455. }
  15456. res.set_chunked_content_provider(
  15457. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15458. if (offset == 0) {
  15459. std::string event =
  15460. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15461. sink.write(event.data(), event.size());
  15462. }
  15463. return false;
  15464. });
  15465. });
  15466. Client client("localhost", get_port());
  15467. sse::SSEClient sse(client, "/reconnect-with-id");
  15468. sse.set_reconnect_interval(100);
  15469. sse.set_max_reconnect_attempts(3);
  15470. sse.start_async();
  15471. // Wait for at least 2 connections
  15472. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15473. sse.stop();
  15474. // Verify behavior
  15475. std::lock_guard<std::mutex> lock(id_mutex);
  15476. EXPECT_GE(received_last_event_ids.size(), 2u);
  15477. // First connection should have no Last-Event-ID
  15478. if (!received_last_event_ids.empty()) {
  15479. EXPECT_EQ(received_last_event_ids[0], "");
  15480. }
  15481. // Second connection should have Last-Event-ID from first connection
  15482. if (received_last_event_ids.size() >= 2) {
  15483. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15484. }
  15485. }
  15486. // Test: set_headers updates headers used on reconnect
  15487. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15488. std::vector<std::string> received_tokens;
  15489. std::mutex token_mutex;
  15490. // Endpoint that captures Authorization header
  15491. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15492. {
  15493. std::lock_guard<std::mutex> lock(token_mutex);
  15494. received_tokens.push_back(req.get_header_value("Authorization"));
  15495. }
  15496. res.set_chunked_content_provider(
  15497. "text/event-stream", [](size_t offset, DataSink &sink) {
  15498. if (offset == 0) {
  15499. std::string event = "data: hello\n\n";
  15500. sink.write(event.data(), event.size());
  15501. }
  15502. return false; // Close connection to trigger reconnect
  15503. });
  15504. });
  15505. Client client("localhost", get_port());
  15506. Headers headers = {{"Authorization", "Bearer old-token"}};
  15507. sse::SSEClient sse(client, "/auth-check", headers);
  15508. // Update headers on each successful connection
  15509. sse.on_open(
  15510. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15511. sse.set_reconnect_interval(100);
  15512. sse.set_max_reconnect_attempts(3);
  15513. sse.start_async();
  15514. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15515. sse.stop();
  15516. std::lock_guard<std::mutex> lock(token_mutex);
  15517. ASSERT_GE(received_tokens.size(), 2u);
  15518. // First connection uses original header
  15519. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15520. // Second connection uses updated header from set_headers
  15521. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15522. }
  15523. // Test: 401 allows reconnection (so on_error can refresh headers)
  15524. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15525. std::atomic<int> connection_count{0};
  15526. // Endpoint: returns 401 on first attempt, 200 on second
  15527. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15528. int conn = connection_count.fetch_add(1);
  15529. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15530. res.status = StatusCode::Unauthorized_401;
  15531. res.set_content("Unauthorized", "text/plain");
  15532. return;
  15533. }
  15534. res.set_chunked_content_provider(
  15535. "text/event-stream", [](size_t offset, DataSink &sink) {
  15536. if (offset == 0) {
  15537. std::string event = "data: authenticated\n\n";
  15538. sink.write(event.data(), event.size());
  15539. }
  15540. return false;
  15541. });
  15542. });
  15543. Client client("localhost", get_port());
  15544. Headers headers = {{"Authorization", "Bearer expired"}};
  15545. sse::SSEClient sse(client, "/auth-retry", headers);
  15546. std::atomic<bool> message_received{false};
  15547. // Refresh token on error
  15548. sse.on_error(
  15549. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15550. sse.on_message([&](const sse::SSEMessage &msg) {
  15551. if (msg.data == "authenticated") { message_received.store(true); }
  15552. });
  15553. sse.set_reconnect_interval(100);
  15554. sse.set_max_reconnect_attempts(3);
  15555. sse.start_async();
  15556. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15557. sse.stop();
  15558. // Should have reconnected after 401 and succeeded with new token
  15559. EXPECT_GE(connection_count.load(), 2);
  15560. EXPECT_TRUE(message_received.load());
  15561. }
  15562. TEST(Issue2318Test, EmptyHostString) {
  15563. {
  15564. httplib::Client cli_empty("", PORT);
  15565. auto res = cli_empty.Get("/");
  15566. ASSERT_FALSE(res);
  15567. EXPECT_EQ(httplib::Error::Connection, res.error());
  15568. }
  15569. {
  15570. httplib::Client cli(" ", PORT);
  15571. auto res = cli.Get("/");
  15572. ASSERT_FALSE(res);
  15573. EXPECT_EQ(httplib::Error::Connection, res.error());
  15574. }
  15575. }
  15576. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15577. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15578. Server svr;
  15579. // Set a small payload limit (1KB)
  15580. svr.set_payload_max_length(1024);
  15581. svr.Post("/test", [&](const Request &req, Response &res) {
  15582. res.set_content("Body size: " + std::to_string(req.body.size()),
  15583. "text/plain");
  15584. });
  15585. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15586. auto se = detail::scope_exit([&] {
  15587. svr.stop();
  15588. listen_thread.join();
  15589. });
  15590. svr.wait_until_ready();
  15591. // Create data that compresses well but exceeds limit when decompressed
  15592. // 8KB of repeated null bytes compresses to a very small size
  15593. std::string original_data(8 * 1024, '\0');
  15594. // Compress the data using gzip
  15595. std::string compressed_data;
  15596. detail::gzip_compressor compressor;
  15597. compressor.compress(original_data.data(), original_data.size(), true,
  15598. [&](const char *data, size_t size) {
  15599. compressed_data.append(data, size);
  15600. return true;
  15601. });
  15602. // Verify compression worked (compressed should be much smaller)
  15603. ASSERT_LT(compressed_data.size(), original_data.size());
  15604. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15605. // Send compressed data with Content-Encoding: gzip
  15606. Client cli(HOST, PORT);
  15607. Headers headers = {{"Content-Encoding", "gzip"}};
  15608. auto res =
  15609. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15610. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15612. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15613. }
  15614. #endif
  15615. // ============================================================================
  15616. // OpenSSL-Specific Tests
  15617. // ============================================================================
  15618. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15619. X509 *readCertificate(const std::string &strFileName) {
  15620. std::ifstream inStream(strFileName);
  15621. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15622. std::istreambuf_iterator<char>());
  15623. if (strCertPEM.empty()) return (nullptr);
  15624. BIO *pbCert = BIO_new(BIO_s_mem());
  15625. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15626. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15627. BIO_free(pbCert);
  15628. return (pCert);
  15629. }
  15630. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15631. std::ifstream inStream(strFileName);
  15632. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15633. std::istreambuf_iterator<char>());
  15634. if (strPrivateKeyPEM.empty()) return (nullptr);
  15635. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15636. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15637. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15638. BIO_free(pbPrivKey);
  15639. return (pPrivateKey);
  15640. }
  15641. TEST(BindServerTest, UpdateCerts) {
  15642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15643. int port = svr.bind_to_any_port("0.0.0.0");
  15644. ASSERT_TRUE(svr.is_valid());
  15645. ASSERT_TRUE(port > 0);
  15646. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15647. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15648. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15649. ASSERT_TRUE(cert != nullptr);
  15650. ASSERT_TRUE(ca_cert != nullptr);
  15651. ASSERT_TRUE(key != nullptr);
  15652. X509_STORE *cert_store = X509_STORE_new();
  15653. X509_STORE_add_cert(cert_store, ca_cert);
  15654. // svr.update_certs(cert, key, cert_store); // deprecated
  15655. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15656. CLIENT_CA_CERT_FILE);
  15657. ASSERT_TRUE(svr.is_valid());
  15658. svr.stop();
  15659. X509_STORE_free(cert_store);
  15660. X509_free(cert);
  15661. X509_free(ca_cert);
  15662. EVP_PKEY_free(key);
  15663. }
  15664. // Test that update_certs() updates client CA list correctly
  15665. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15666. // Start with file-based constructor
  15667. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15668. ASSERT_TRUE(svr.is_valid());
  15669. // Initially no client CA list should be set
  15670. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15671. ASSERT_TRUE(ssl_ctx != nullptr);
  15672. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15673. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15674. EXPECT_EQ(0, count_before);
  15675. // Now update with client CA (PEM string)
  15676. std::string cert_pem, key_pem, ca_pem;
  15677. read_file(SERVER_CERT_FILE, cert_pem);
  15678. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15679. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15680. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15681. ASSERT_TRUE(svr.is_valid());
  15682. // Now client CA list should be set
  15683. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15684. ASSERT_TRUE(ca_list_after != nullptr);
  15685. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15686. }
  15687. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15688. // Test that the file-path SSLServer constructor properly sets the client CA
  15689. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15691. ASSERT_TRUE(svr.is_valid());
  15692. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15693. ASSERT_TRUE(ssl_ctx != nullptr);
  15694. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15695. ASSERT_TRUE(ca_list != nullptr);
  15696. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15697. }
  15698. #endif
  15699. // ============================================================================
  15700. // MbedTLS-Specific Tests
  15701. // ============================================================================
  15702. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15703. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15704. using namespace httplib::tls;
  15705. // Track if callback was invoked
  15706. bool callback_invoked = false;
  15707. // The callback receives void* ctx which is actually MbedTlsContext*
  15708. // We can access the mbedtls_ssl_config via the context
  15709. auto setup_callback = [&callback_invoked](void *ctx) {
  15710. callback_invoked = true;
  15711. // Cast to MbedTlsContext* to access the ssl config
  15712. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15713. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15714. // Use static variables to hold certificate data (simplified for test)
  15715. static mbedtls_x509_crt own_cert;
  15716. static mbedtls_pk_context own_key;
  15717. static mbedtls_x509_crt ca_chain;
  15718. static bool initialized = false;
  15719. if (!initialized) {
  15720. mbedtls_x509_crt_init(&own_cert);
  15721. mbedtls_pk_init(&own_key);
  15722. mbedtls_x509_crt_init(&ca_chain);
  15723. // Load server certificate
  15724. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15725. return false;
  15726. }
  15727. // Load server private key.
  15728. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15729. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15730. #if MBEDTLS_VERSION_MAJOR == 3
  15731. ,
  15732. mbedtls_ctr_drbg_random, nullptr
  15733. #endif
  15734. ) != 0) {
  15735. return false;
  15736. }
  15737. // Load CA chain for client verification
  15738. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15739. return false;
  15740. }
  15741. initialized = true;
  15742. }
  15743. // Configure the SSL config
  15744. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15745. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15746. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15747. // Set minimum TLS version using mbedTLS native API
  15748. #if MBEDTLS_VERSION_MAJOR >= 3
  15749. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15750. #else
  15751. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15752. MBEDTLS_SSL_MINOR_VERSION_3);
  15753. #endif
  15754. return true;
  15755. };
  15756. SSLServer svr(setup_callback);
  15757. ASSERT_TRUE(svr.is_valid());
  15758. ASSERT_TRUE(callback_invoked);
  15759. svr.Get("/test", [&](const Request &req, Response &res) {
  15760. res.set_content("test", "text/plain");
  15761. auto cert = req.peer_cert();
  15762. ASSERT_TRUE(static_cast<bool>(cert));
  15763. auto common_name = cert.subject_cn();
  15764. EXPECT_EQ("Common Name", common_name);
  15765. });
  15766. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15767. auto se = detail::scope_exit([&] {
  15768. svr.stop();
  15769. t.join();
  15770. ASSERT_FALSE(svr.is_running());
  15771. });
  15772. svr.wait_until_ready();
  15773. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15774. cli.enable_server_certificate_verification(false);
  15775. cli.set_connection_timeout(30);
  15776. auto res = cli.Get("/test");
  15777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15778. ASSERT_EQ(StatusCode::OK_200, res->status);
  15779. }
  15780. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15781. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15782. // keep-alive SSL session, which reads through that config in
  15783. // mbedtls_ssl_close_notify.
  15784. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15786. ASSERT_TRUE(svr.is_valid());
  15787. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15788. res.set_content("test", "text/plain");
  15789. });
  15790. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15791. auto se = detail::scope_exit([&] {
  15792. svr.stop();
  15793. t.join();
  15794. ASSERT_FALSE(svr.is_running());
  15795. });
  15796. svr.wait_until_ready();
  15797. {
  15798. SSLClient cli(HOST, PORT);
  15799. cli.enable_server_certificate_verification(false);
  15800. cli.set_keep_alive(true);
  15801. auto res = cli.Get("/test");
  15802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15803. ASSERT_EQ(StatusCode::OK_200, res->status);
  15804. // cli is destructed here with the keep-alive SSL session still open.
  15805. }
  15806. }
  15807. #endif
  15808. // WebSocket Tests
  15809. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15810. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15811. // defining the meaning of these bits has been negotiated.
  15812. auto make_frame = [](uint8_t first_byte) {
  15813. std::string frame;
  15814. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15815. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15816. frame += "Hello";
  15817. return frame;
  15818. };
  15819. // RSV1 set (0x40)
  15820. {
  15821. detail::BufferStream strm;
  15822. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15823. ws::Opcode opcode;
  15824. std::string payload;
  15825. bool fin;
  15826. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15827. false, 1024));
  15828. }
  15829. // RSV2 set (0x20)
  15830. {
  15831. detail::BufferStream strm;
  15832. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15833. ws::Opcode opcode;
  15834. std::string payload;
  15835. bool fin;
  15836. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15837. false, 1024));
  15838. }
  15839. // RSV3 set (0x10)
  15840. {
  15841. detail::BufferStream strm;
  15842. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15843. ws::Opcode opcode;
  15844. std::string payload;
  15845. bool fin;
  15846. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15847. false, 1024));
  15848. }
  15849. // No RSV bits set - should succeed
  15850. {
  15851. detail::BufferStream strm;
  15852. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15853. ws::Opcode opcode;
  15854. std::string payload;
  15855. bool fin;
  15856. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15857. false, 1024));
  15858. EXPECT_EQ(ws::Opcode::Text, opcode);
  15859. EXPECT_EQ("Hello", payload);
  15860. EXPECT_TRUE(fin);
  15861. }
  15862. }
  15863. TEST(WebSocketTest, ControlFrameValidation) {
  15864. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15865. // payload length <= 125.
  15866. // Ping with FIN=0 - must be rejected
  15867. {
  15868. detail::BufferStream strm;
  15869. std::string frame;
  15870. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15871. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15872. strm.write(frame.data(), frame.size());
  15873. ws::Opcode opcode;
  15874. std::string payload;
  15875. bool fin;
  15876. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15877. false, 1024));
  15878. }
  15879. // Close with FIN=0 - must be rejected
  15880. {
  15881. detail::BufferStream strm;
  15882. std::string frame;
  15883. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15884. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15885. strm.write(frame.data(), frame.size());
  15886. ws::Opcode opcode;
  15887. std::string payload;
  15888. bool fin;
  15889. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15890. false, 1024));
  15891. }
  15892. // Ping with payload_len=126 (extended length) - must be rejected
  15893. {
  15894. detail::BufferStream strm;
  15895. std::string frame;
  15896. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15897. frame += static_cast<char>(126); // payload_len=126 (>125)
  15898. frame += static_cast<char>(0x00); // extended length high byte
  15899. frame += static_cast<char>(126); // extended length low byte
  15900. frame += std::string(126, 'x');
  15901. strm.write(frame.data(), frame.size());
  15902. ws::Opcode opcode;
  15903. std::string payload;
  15904. bool fin;
  15905. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15906. false, 1024));
  15907. }
  15908. // Ping with FIN=1 and payload_len=125 - should succeed
  15909. {
  15910. detail::BufferStream strm;
  15911. std::string frame;
  15912. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15913. frame += static_cast<char>(125); // payload_len=125
  15914. frame += std::string(125, 'x');
  15915. strm.write(frame.data(), frame.size());
  15916. ws::Opcode opcode;
  15917. std::string payload;
  15918. bool fin;
  15919. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15920. false, 1024));
  15921. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15922. EXPECT_EQ(125u, payload.size());
  15923. EXPECT_TRUE(fin);
  15924. }
  15925. }
  15926. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15927. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15928. // length MUST be 0.
  15929. // MSB set - must be rejected
  15930. {
  15931. detail::BufferStream strm;
  15932. std::string frame;
  15933. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15934. frame += static_cast<char>(127); // 64-bit extended length
  15935. frame += static_cast<char>(0x80); // MSB set (invalid)
  15936. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15937. strm.write(frame.data(), frame.size());
  15938. ws::Opcode opcode;
  15939. std::string payload;
  15940. bool fin;
  15941. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15942. false, 1024));
  15943. }
  15944. // MSB clear - should pass length parsing (will be rejected by max_len,
  15945. // but that's a different check; use a small length to verify)
  15946. {
  15947. detail::BufferStream strm;
  15948. std::string frame;
  15949. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15950. frame += static_cast<char>(127); // 64-bit extended length
  15951. frame += std::string(7, '\0'); // high bytes = 0
  15952. frame += static_cast<char>(0x03); // length = 3
  15953. frame += "abc";
  15954. strm.write(frame.data(), frame.size());
  15955. ws::Opcode opcode;
  15956. std::string payload;
  15957. bool fin;
  15958. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15959. false, 1024));
  15960. EXPECT_EQ(ws::Opcode::Text, opcode);
  15961. EXPECT_EQ("abc", payload);
  15962. }
  15963. }
  15964. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15965. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15966. // Valid UTF-8
  15967. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15968. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15969. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15970. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15971. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15972. // Invalid UTF-8
  15973. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15974. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15975. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15976. EXPECT_FALSE(
  15977. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15978. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15979. }
  15980. TEST(WebSocketTest, ConnectAndDisconnect) {
  15981. Server svr;
  15982. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15983. std::string msg;
  15984. while (ws.read(msg)) {}
  15985. });
  15986. auto port = svr.bind_to_any_port(HOST);
  15987. std::thread t([&]() { svr.listen_after_bind(); });
  15988. svr.wait_until_ready();
  15989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15990. ASSERT_TRUE(client.connect());
  15991. EXPECT_TRUE(client.is_open());
  15992. client.close();
  15993. EXPECT_FALSE(client.is_open());
  15994. svr.stop();
  15995. t.join();
  15996. }
  15997. TEST(WebSocketTest, ValidURL) {
  15998. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15999. EXPECT_TRUE(ws1.is_valid());
  16000. ws::WebSocketClient ws2("ws://example.com/path");
  16001. EXPECT_TRUE(ws2.is_valid());
  16002. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16003. EXPECT_TRUE(ws3.is_valid());
  16004. #ifdef CPPHTTPLIB_SSL_ENABLED
  16005. ws::WebSocketClient wss1("wss://example.com/path");
  16006. EXPECT_TRUE(wss1.is_valid());
  16007. ws::WebSocketClient wss2("wss://example.com:443/path");
  16008. EXPECT_TRUE(wss2.is_valid());
  16009. #endif
  16010. }
  16011. TEST(WebSocketTest, InvalidURL) {
  16012. // No scheme
  16013. ws::WebSocketClient ws1("localhost:8080/path");
  16014. EXPECT_FALSE(ws1.is_valid());
  16015. // No path
  16016. ws::WebSocketClient ws2("ws://localhost:8080");
  16017. EXPECT_FALSE(ws2.is_valid());
  16018. // Empty string
  16019. ws::WebSocketClient ws3("");
  16020. EXPECT_FALSE(ws3.is_valid());
  16021. // Missing host
  16022. ws::WebSocketClient ws4("ws://:8080/path");
  16023. EXPECT_FALSE(ws4.is_valid());
  16024. // Port number overflow — should not crash
  16025. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16026. EXPECT_FALSE(ws5.is_valid());
  16027. // Port out of range
  16028. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16029. EXPECT_FALSE(ws6.is_valid());
  16030. }
  16031. TEST(WebSocketTest, UnsupportedScheme) {
  16032. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16033. ws::WebSocketClient ws1("http://localhost:8080/path");
  16034. EXPECT_FALSE(ws1.is_valid());
  16035. ws::WebSocketClient ws2("https://localhost:8080/path");
  16036. EXPECT_FALSE(ws2.is_valid());
  16037. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16038. EXPECT_FALSE(ws3.is_valid());
  16039. #else
  16040. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16041. std::invalid_argument);
  16042. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16043. std::invalid_argument);
  16044. #endif
  16045. }
  16046. TEST(WebSocketTest, ConnectWhenInvalid) {
  16047. ws::WebSocketClient ws("not a valid url");
  16048. EXPECT_FALSE(ws.is_valid());
  16049. EXPECT_FALSE(ws.connect());
  16050. }
  16051. TEST(WebSocketTest, DefaultPort) {
  16052. ws::WebSocketClient ws1("ws://example.com/path");
  16053. EXPECT_TRUE(ws1.is_valid());
  16054. // ws:// defaults to port 80 (verified by successful parse)
  16055. #ifdef CPPHTTPLIB_SSL_ENABLED
  16056. ws::WebSocketClient ws2("wss://example.com/path");
  16057. EXPECT_TRUE(ws2.is_valid());
  16058. // wss:// defaults to port 443 (verified by successful parse)
  16059. #endif
  16060. }
  16061. TEST(WebSocketTest, IPv6LiteralAddress) {
  16062. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16063. EXPECT_TRUE(ws1.is_valid());
  16064. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16065. EXPECT_TRUE(ws2.is_valid());
  16066. }
  16067. TEST(WebSocketTest, ComplexPath) {
  16068. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16069. EXPECT_TRUE(ws1.is_valid());
  16070. ws::WebSocketClient ws2("ws://localhost:8080/");
  16071. EXPECT_TRUE(ws2.is_valid());
  16072. }
  16073. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16074. Server svr;
  16075. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16076. std::string msg;
  16077. while (ws.read(msg)) {}
  16078. });
  16079. auto port = svr.bind_to_any_port(HOST);
  16080. std::thread t([&]() { svr.listen_after_bind(); });
  16081. svr.wait_until_ready();
  16082. auto another_host = "example.com";
  16083. auto wrong_ip = "192.0.2.1";
  16084. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16085. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16086. ASSERT_TRUE(client.connect());
  16087. EXPECT_TRUE(client.is_open());
  16088. client.close();
  16089. svr.stop();
  16090. t.join();
  16091. }
  16092. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16093. Server svr;
  16094. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16095. std::string msg;
  16096. while (ws.read(msg)) {}
  16097. });
  16098. auto port = svr.bind_to_any_port(HOST);
  16099. std::thread t([&]() { svr.listen_after_bind(); });
  16100. svr.wait_until_ready();
  16101. auto wrong_ip = "192.0.2.1";
  16102. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16103. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16104. client.set_connection_timeout(1);
  16105. client.set_read_timeout(1);
  16106. client.set_write_timeout(1);
  16107. EXPECT_FALSE(client.connect());
  16108. EXPECT_FALSE(client.is_open());
  16109. svr.stop();
  16110. t.join();
  16111. }
  16112. class WebSocketIntegrationTest : public ::testing::Test {
  16113. protected:
  16114. void SetUp() override {
  16115. server_ = httplib::detail::make_unique<Server>();
  16116. setup_server();
  16117. start_server();
  16118. }
  16119. void TearDown() override {
  16120. server_->stop();
  16121. if (server_thread_.joinable()) { server_thread_.join(); }
  16122. }
  16123. void setup_server() {
  16124. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16125. std::string msg;
  16126. ws::ReadResult ret;
  16127. while ((ret = ws.read(msg))) {
  16128. if (ret == ws::Binary) {
  16129. ws.send(msg.data(), msg.size());
  16130. } else {
  16131. ws.send(msg);
  16132. }
  16133. }
  16134. });
  16135. server_->WebSocket("/ws-echo-string",
  16136. [](const Request &, ws::WebSocket &ws) {
  16137. std::string msg;
  16138. while (ws.read(msg)) {
  16139. ws.send("echo: " + msg);
  16140. }
  16141. });
  16142. server_->WebSocket(
  16143. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16144. // Echo back request metadata
  16145. ws.send("path:" + req.path);
  16146. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16147. std::string msg;
  16148. while (ws.read(msg)) {}
  16149. });
  16150. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16151. std::string msg;
  16152. ws.read(msg); // wait for a message
  16153. ws.close();
  16154. });
  16155. server_->WebSocket("/ws-close-status",
  16156. [](const Request &, ws::WebSocket &ws) {
  16157. std::string msg;
  16158. ws.read(msg); // wait for a message
  16159. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16160. });
  16161. server_->WebSocket(
  16162. "/ws-subprotocol",
  16163. [](const Request &, ws::WebSocket &ws) {
  16164. std::string msg;
  16165. while (ws.read(msg)) {
  16166. ws.send(msg);
  16167. }
  16168. },
  16169. [](const std::vector<std::string> &protocols) -> std::string {
  16170. for (const auto &p : protocols) {
  16171. if (p == "graphql-ws") { return p; }
  16172. }
  16173. return "";
  16174. });
  16175. }
  16176. void start_server() {
  16177. port_ = server_->bind_to_any_port(HOST);
  16178. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16179. server_->wait_until_ready();
  16180. }
  16181. std::unique_ptr<Server> server_;
  16182. std::thread server_thread_;
  16183. int port_ = 0;
  16184. };
  16185. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16187. "/ws-echo");
  16188. ASSERT_TRUE(client.connect());
  16189. ASSERT_TRUE(client.is_open());
  16190. ASSERT_TRUE(client.send("Hello WebSocket"));
  16191. std::string msg;
  16192. EXPECT_EQ(ws::Text, client.read(msg));
  16193. EXPECT_EQ("Hello WebSocket", msg);
  16194. client.close();
  16195. }
  16196. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16198. "/ws-echo");
  16199. ASSERT_TRUE(client.connect());
  16200. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16201. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16202. std::string msg;
  16203. EXPECT_EQ(ws::Binary, client.read(msg));
  16204. EXPECT_EQ(binary_data, msg);
  16205. client.close();
  16206. }
  16207. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16208. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16209. "/ws-echo");
  16210. ASSERT_TRUE(client.connect());
  16211. for (int i = 0; i < 10; i++) {
  16212. auto text = "message " + std::to_string(i);
  16213. ASSERT_TRUE(client.send(text));
  16214. std::string msg;
  16215. ASSERT_TRUE(client.read(msg));
  16216. EXPECT_EQ(text, msg);
  16217. }
  16218. client.close();
  16219. }
  16220. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16222. "/ws-close");
  16223. ASSERT_TRUE(client.connect());
  16224. // Send a message to trigger the server to close
  16225. ASSERT_TRUE(client.send("trigger close"));
  16226. // The server will close, so read should return false
  16227. std::string msg;
  16228. EXPECT_FALSE(client.read(msg));
  16229. EXPECT_FALSE(client.is_open());
  16230. }
  16231. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16232. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16233. "/ws-echo");
  16234. ASSERT_TRUE(client.connect());
  16235. // 128KB message
  16236. std::string large_data(128 * 1024, 'X');
  16237. ASSERT_TRUE(client.send(large_data));
  16238. std::string msg;
  16239. ASSERT_TRUE(client.read(msg));
  16240. EXPECT_EQ(large_data, msg);
  16241. client.close();
  16242. }
  16243. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16244. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16245. "/ws-echo");
  16246. ASSERT_TRUE(client.connect());
  16247. const int num_threads = 4;
  16248. std::vector<std::thread> threads;
  16249. std::atomic<int> send_count{0};
  16250. for (int t = 0; t < num_threads; t++) {
  16251. threads.emplace_back([&client, &send_count, t]() {
  16252. for (int i = 0; i < 5; i++) {
  16253. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16254. if (client.send(text)) { send_count++; }
  16255. }
  16256. });
  16257. }
  16258. for (auto &th : threads) {
  16259. th.join();
  16260. }
  16261. int received = 0;
  16262. std::string msg;
  16263. while (received < send_count.load()) {
  16264. if (!client.read(msg)) { break; }
  16265. received++;
  16266. }
  16267. EXPECT_EQ(send_count.load(), received);
  16268. client.close();
  16269. }
  16270. TEST_F(WebSocketIntegrationTest, ReadString) {
  16271. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16272. "/ws-echo-string");
  16273. ASSERT_TRUE(client.connect());
  16274. ASSERT_TRUE(client.send("hello"));
  16275. std::string msg;
  16276. ASSERT_TRUE(client.read(msg));
  16277. EXPECT_EQ("echo: hello", msg);
  16278. ASSERT_TRUE(client.send("world"));
  16279. ASSERT_TRUE(client.read(msg));
  16280. EXPECT_EQ("echo: world", msg);
  16281. client.close();
  16282. }
  16283. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16284. Headers headers = {{"X-Test-Header", "test-value"}};
  16285. ws::WebSocketClient client(
  16286. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16287. ASSERT_TRUE(client.connect());
  16288. std::string msg;
  16289. ASSERT_TRUE(client.read(msg));
  16290. EXPECT_EQ("path:/ws-request-info", msg);
  16291. ASSERT_TRUE(client.read(msg));
  16292. EXPECT_EQ("header:test-value", msg);
  16293. client.close();
  16294. }
  16295. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16296. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16297. "/ws-echo");
  16298. client.set_read_timeout(1, 0); // 1 second
  16299. ASSERT_TRUE(client.connect());
  16300. // Don't send anything — server echo handler waits for a message,
  16301. // so read() should time out and return false.
  16302. std::string msg;
  16303. EXPECT_FALSE(client.read(msg));
  16304. }
  16305. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16306. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16307. "/ws-echo");
  16308. client.set_read_timeout(5, 0);
  16309. ASSERT_TRUE(client.connect());
  16310. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16311. // The server should reject it and close the connection.
  16312. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16313. client.send(oversized);
  16314. // The server's read() should have failed due to payload limit,
  16315. // so our read() should return false (connection closed).
  16316. std::string msg;
  16317. EXPECT_FALSE(client.read(msg));
  16318. }
  16319. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16320. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16321. "/ws-echo");
  16322. client.set_read_timeout(10, 0);
  16323. ASSERT_TRUE(client.connect());
  16324. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16325. // This should succeed.
  16326. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16327. ASSERT_TRUE(client.send(at_limit));
  16328. std::string msg;
  16329. ASSERT_TRUE(client.read(msg));
  16330. EXPECT_EQ(at_limit.size(), msg.size());
  16331. client.close();
  16332. }
  16333. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16335. "/nonexistent");
  16336. EXPECT_FALSE(client.connect());
  16337. EXPECT_FALSE(client.is_open());
  16338. }
  16339. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16340. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16341. "/ws-echo");
  16342. ASSERT_TRUE(client.connect());
  16343. ASSERT_TRUE(client.send(""));
  16344. std::string msg;
  16345. EXPECT_EQ(ws::Text, client.read(msg));
  16346. EXPECT_EQ("", msg);
  16347. client.close();
  16348. }
  16349. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16350. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16351. "/ws-echo");
  16352. // First connection
  16353. ASSERT_TRUE(client.connect());
  16354. ASSERT_TRUE(client.send("first"));
  16355. std::string msg;
  16356. ASSERT_TRUE(client.read(msg));
  16357. EXPECT_EQ("first", msg);
  16358. client.close();
  16359. EXPECT_FALSE(client.is_open());
  16360. // Reconnect using the same client object
  16361. ASSERT_TRUE(client.connect());
  16362. ASSERT_TRUE(client.is_open());
  16363. ASSERT_TRUE(client.send("second"));
  16364. ASSERT_TRUE(client.read(msg));
  16365. EXPECT_EQ("second", msg);
  16366. client.close();
  16367. }
  16368. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16369. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16370. "/ws-close-status");
  16371. ASSERT_TRUE(client.connect());
  16372. // Trigger the server to close with GoingAway status
  16373. ASSERT_TRUE(client.send("trigger"));
  16374. // read() should return false after receiving the close frame
  16375. std::string msg;
  16376. EXPECT_FALSE(client.read(msg));
  16377. EXPECT_FALSE(client.is_open());
  16378. }
  16379. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16380. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16381. "/ws-echo");
  16382. ASSERT_TRUE(client.connect());
  16383. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16384. EXPECT_FALSE(client.is_open());
  16385. }
  16386. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16387. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16388. ws::WebSocketClient client(
  16389. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16390. ASSERT_TRUE(client.connect());
  16391. // Server should have selected graphql-ws
  16392. EXPECT_EQ("graphql-ws", client.subprotocol());
  16393. client.close();
  16394. }
  16395. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16396. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16397. ws::WebSocketClient client(
  16398. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16399. ASSERT_TRUE(client.connect());
  16400. // Server should not have selected any subprotocol
  16401. EXPECT_TRUE(client.subprotocol().empty());
  16402. client.close();
  16403. }
  16404. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16405. // Connect without requesting any subprotocol
  16406. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16407. "/ws-subprotocol");
  16408. ASSERT_TRUE(client.connect());
  16409. EXPECT_TRUE(client.subprotocol().empty());
  16410. client.close();
  16411. }
  16412. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16413. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16414. "/ws-echo");
  16415. client.set_tcp_nodelay(true);
  16416. client.set_connection_timeout(3, 0);
  16417. bool socket_options_called = false;
  16418. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16419. ASSERT_TRUE(client.connect());
  16420. ASSERT_TRUE(client.is_open());
  16421. EXPECT_TRUE(socket_options_called);
  16422. ASSERT_TRUE(client.send("hello"));
  16423. std::string msg;
  16424. auto result = client.read(msg);
  16425. EXPECT_EQ(result, ws::ReadResult::Text);
  16426. EXPECT_EQ(msg, "hello");
  16427. client.close();
  16428. }
  16429. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16430. Server svr;
  16431. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16432. if (!req.has_header("Authorization")) {
  16433. res.status = StatusCode::Unauthorized_401;
  16434. res.set_content("Unauthorized", "text/plain");
  16435. return Server::HandlerResponse::Handled;
  16436. }
  16437. return Server::HandlerResponse::Unhandled;
  16438. });
  16439. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16440. std::string msg;
  16441. while (ws.read(msg)) {
  16442. ws.send(msg);
  16443. }
  16444. });
  16445. auto port = svr.bind_to_any_port("localhost");
  16446. std::thread t([&]() { svr.listen_after_bind(); });
  16447. svr.wait_until_ready();
  16448. // Without Authorization header - should be rejected before upgrade
  16449. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16450. EXPECT_FALSE(client1.connect());
  16451. // With Authorization header - should succeed
  16452. Headers headers = {{"Authorization", "Bearer token123"}};
  16453. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16454. headers);
  16455. ASSERT_TRUE(client2.connect());
  16456. ASSERT_TRUE(client2.send("hello"));
  16457. std::string msg;
  16458. ASSERT_TRUE(client2.read(msg));
  16459. EXPECT_EQ("hello", msg);
  16460. client2.close();
  16461. svr.stop();
  16462. t.join();
  16463. }
  16464. TEST(WebSocketTest, QueryStringInHandshake) {
  16465. Server svr;
  16466. std::mutex mtx;
  16467. std::string received_target;
  16468. std::string received_token;
  16469. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16470. {
  16471. std::lock_guard<std::mutex> lock(mtx);
  16472. received_target = req.target;
  16473. if (req.has_param("token")) {
  16474. received_token = req.get_param_value("token");
  16475. }
  16476. }
  16477. std::string msg;
  16478. while (ws.read(msg)) {
  16479. ws.send(msg);
  16480. }
  16481. });
  16482. auto port = svr.bind_to_any_port("localhost");
  16483. std::thread t([&]() { svr.listen_after_bind(); });
  16484. svr.wait_until_ready();
  16485. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16486. "/ws?token=ABC&session=123");
  16487. ASSERT_TRUE(client.connect());
  16488. // Round-trip ensures the handler has run and captured the request.
  16489. ASSERT_TRUE(client.send("hello"));
  16490. std::string msg;
  16491. ASSERT_TRUE(client.read(msg));
  16492. EXPECT_EQ("hello", msg);
  16493. client.close();
  16494. {
  16495. std::lock_guard<std::mutex> lock(mtx);
  16496. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16497. EXPECT_EQ("ABC", received_token);
  16498. }
  16499. svr.stop();
  16500. t.join();
  16501. }
  16502. TEST(WebSocketTest, HostHeaderInHandshake) {
  16503. Server svr;
  16504. std::mutex mtx;
  16505. std::string received_host;
  16506. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16507. {
  16508. std::lock_guard<std::mutex> lock(mtx);
  16509. received_host = req.get_header_value("Host");
  16510. }
  16511. std::string msg;
  16512. while (ws.read(msg)) {
  16513. ws.send(msg);
  16514. }
  16515. });
  16516. auto port = svr.bind_to_any_port("localhost");
  16517. std::thread t([&]() { svr.listen_after_bind(); });
  16518. svr.wait_until_ready();
  16519. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16520. ASSERT_TRUE(client.connect());
  16521. // Round-trip ensures the handler has run and captured the request.
  16522. ASSERT_TRUE(client.send("hello"));
  16523. std::string msg;
  16524. ASSERT_TRUE(client.read(msg));
  16525. client.close();
  16526. {
  16527. std::lock_guard<std::mutex> lock(mtx);
  16528. // Non-default port must be present in the Host header. Default ports
  16529. // (80/443) are omitted; that logic is covered by
  16530. // MakeHostAndPortStringTest.
  16531. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16532. }
  16533. svr.stop();
  16534. t.join();
  16535. }
  16536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16537. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16538. protected:
  16539. void SetUp() override {
  16540. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16541. SERVER_PRIVATE_KEY_FILE);
  16542. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16543. std::string msg;
  16544. ws::ReadResult ret;
  16545. while ((ret = ws.read(msg))) {
  16546. if (ret == ws::Binary) {
  16547. ws.send(msg.data(), msg.size());
  16548. } else {
  16549. ws.send(msg);
  16550. }
  16551. }
  16552. });
  16553. port_ = server_->bind_to_any_port(HOST);
  16554. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16555. server_->wait_until_ready();
  16556. }
  16557. void TearDown() override {
  16558. server_->stop();
  16559. if (server_thread_.joinable()) { server_thread_.join(); }
  16560. }
  16561. std::unique_ptr<SSLServer> server_;
  16562. std::thread server_thread_;
  16563. int port_ = 0;
  16564. };
  16565. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16566. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16567. "/ws-echo");
  16568. client.enable_server_certificate_verification(false);
  16569. ASSERT_TRUE(client.connect());
  16570. ASSERT_TRUE(client.is_open());
  16571. ASSERT_TRUE(client.send("Hello WSS"));
  16572. std::string msg;
  16573. EXPECT_EQ(ws::Text, client.read(msg));
  16574. EXPECT_EQ("Hello WSS", msg);
  16575. client.close();
  16576. }
  16577. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16578. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16579. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16580. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16581. // client (without calling close() first) is the only path that runs
  16582. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16583. // bug exactly.
  16584. //
  16585. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16586. // when linked against an instrumented libssl; run under Valgrind to catch it
  16587. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16588. // suite (the freed session otherwise stalls on the close handshake) — this test
  16589. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16590. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16591. {
  16592. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16593. "/ws-echo");
  16594. client.enable_server_certificate_verification(false);
  16595. client.set_read_timeout(2, 0);
  16596. client.set_write_timeout(2, 0);
  16597. ASSERT_TRUE(client.connect());
  16598. ASSERT_TRUE(client.is_open());
  16599. ASSERT_TRUE(client.send("still open"));
  16600. // Intentionally do NOT call client.close(): leaving scope runs
  16601. // shutdown_and_close() with the WebSocket still open, which must send the
  16602. // close frame while the TLS session is still alive.
  16603. }
  16604. }
  16605. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16606. // shutdown_and_close() at the start of connect(), reproducing the same
  16607. // use-after-free within the test body rather than at scope exit. The second
  16608. // connect must succeed and echo, proving the close handshake ran over a live
  16609. // session. See the note above about memory-tool requirements.
  16610. TEST_F(WebSocketSSLIntegrationTest,
  16611. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16612. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16613. "/ws-echo");
  16614. client.enable_server_certificate_verification(false);
  16615. client.set_read_timeout(2, 0);
  16616. client.set_write_timeout(2, 0);
  16617. ASSERT_TRUE(client.connect());
  16618. ASSERT_TRUE(client.is_open());
  16619. ASSERT_TRUE(client.send("still open"));
  16620. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16621. // the still-open connection, which must not touch a freed TLS session.
  16622. ASSERT_TRUE(client.connect());
  16623. ASSERT_TRUE(client.is_open());
  16624. ASSERT_TRUE(client.send("after reconnect"));
  16625. std::string msg;
  16626. EXPECT_EQ(ws::Text, client.read(msg));
  16627. EXPECT_EQ("after reconnect", msg);
  16628. client.close();
  16629. }
  16630. #endif
  16631. #ifdef CPPHTTPLIB_SSL_ENABLED
  16632. class WebSocketSSLCATest : public ::testing::Test {
  16633. protected:
  16634. void SetUp() override {
  16635. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16636. SERVER_PRIVATE_KEY_FILE);
  16637. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16638. std::string msg;
  16639. while (ws.read(msg)) {
  16640. ws.send(msg);
  16641. }
  16642. });
  16643. port_ = server_->bind_to_any_port("127.0.0.1");
  16644. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16645. server_->wait_until_ready();
  16646. }
  16647. void TearDown() override {
  16648. server_->stop();
  16649. if (server_thread_.joinable()) { server_thread_.join(); }
  16650. }
  16651. std::string url() const {
  16652. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16653. }
  16654. std::unique_ptr<SSLServer> server_;
  16655. std::thread server_thread_;
  16656. int port_ = 0;
  16657. };
  16658. // A custom CA loaded as PEM verifies the server with full certificate
  16659. // verification enabled
  16660. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16661. ws::WebSocketClient client(url());
  16662. std::string cert;
  16663. read_file(SERVER_CERT2_FILE, cert);
  16664. client.load_ca_cert_store(cert.c_str(), cert.size());
  16665. ASSERT_TRUE(client.connect());
  16666. ASSERT_TRUE(client.send("hello"));
  16667. std::string msg;
  16668. EXPECT_EQ(ws::Text, client.read(msg));
  16669. EXPECT_EQ("hello", msg);
  16670. client.close();
  16671. }
  16672. // A custom CA that does not cover the server must fail verification (the
  16673. // custom CA is exclusive; system certs are not loaded alongside it)
  16674. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16675. ws::WebSocketClient client(url());
  16676. std::string cert;
  16677. read_file(CLIENT_CA_CERT_FILE, cert);
  16678. client.load_ca_cert_store(cert.c_str(), cert.size());
  16679. ASSERT_FALSE(client.connect());
  16680. }
  16681. // Regression test: reconnecting with a native custom CA store used to reuse
  16682. // a store handle the previous TLS context had already freed (use-after-free
  16683. // under the OpenSSL backend). The context now lives as long as the client.
  16684. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16685. ws::WebSocketClient client(url());
  16686. std::string cert;
  16687. read_file(SERVER_CERT2_FILE, cert);
  16688. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16689. ASSERT_TRUE(client.connect());
  16690. client.close();
  16691. ASSERT_TRUE(client.connect());
  16692. ASSERT_TRUE(client.send("again"));
  16693. std::string msg;
  16694. EXPECT_EQ(ws::Text, client.read(msg));
  16695. EXPECT_EQ("again", msg);
  16696. client.close();
  16697. }
  16698. // Regression test: a certificate with a trusted chain but no identity match
  16699. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16700. // verification entirely for IP hosts, so this connection succeeded there.
  16701. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16702. // chain verification while the identity check must still fail.
  16703. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16704. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16705. ASSERT_TRUE(svr.is_valid());
  16706. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16707. std::string msg;
  16708. while (ws.read(msg)) {
  16709. ws.send(msg);
  16710. }
  16711. });
  16712. auto port = svr.bind_to_any_port("127.0.0.1");
  16713. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16714. auto se = detail::scope_exit([&] {
  16715. svr.stop();
  16716. t.join();
  16717. });
  16718. svr.wait_until_ready();
  16719. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16720. "/echo");
  16721. std::string cert;
  16722. read_file(SERVER_CERT_FILE, cert);
  16723. client.load_ca_cert_store(cert.c_str(), cert.size());
  16724. ASSERT_FALSE(client.connect());
  16725. }
  16726. #endif
  16727. #if !defined(_WIN32)
  16728. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16729. auto secret_dir = std::string("./symlink_test_secret");
  16730. auto served_dir = std::string("./symlink_test_served");
  16731. auto secret_file = secret_dir + "/secret.txt";
  16732. auto symlink_path = served_dir + "/escape";
  16733. // Setup: create directories and files
  16734. mkdir(secret_dir.c_str(), 0755);
  16735. mkdir(served_dir.c_str(), 0755);
  16736. {
  16737. std::ofstream ofs(secret_file);
  16738. ofs << "SECRET_DATA";
  16739. }
  16740. // Create symlink using absolute path so it resolves correctly
  16741. #ifdef PATH_MAX
  16742. char abs_secret[PATH_MAX];
  16743. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16744. #else
  16745. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16746. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16747. ASSERT_NE(nullptr, abs_secret);
  16748. #endif
  16749. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16750. auto se = detail::scope_exit([&] {
  16751. unlink(symlink_path.c_str());
  16752. unlink(secret_file.c_str());
  16753. rmdir(served_dir.c_str());
  16754. rmdir(secret_dir.c_str());
  16755. });
  16756. Server svr;
  16757. svr.set_mount_point("/", served_dir);
  16758. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16759. auto se2 = detail::scope_exit([&] {
  16760. svr.stop();
  16761. listen_thread.join();
  16762. });
  16763. svr.wait_until_ready();
  16764. Client cli("localhost", PORT);
  16765. // Symlink pointing outside base dir should be blocked
  16766. auto res = cli.Get("/escape/secret.txt");
  16767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16768. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16769. }
  16770. #endif
  16771. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16772. // A GET request with Content-Length to a static file handler must have its
  16773. // body drained before the keep-alive connection is reused. Otherwise the
  16774. // unread body bytes are interpreted as the next HTTP request.
  16775. //
  16776. // The body is sent AFTER receiving the first response (as in the original
  16777. // PoC) so that the stream_line_reader cannot buffer it together with the
  16778. // headers of the first request.
  16779. Server svr;
  16780. svr.set_mount_point("/", "./www");
  16781. std::atomic<int> smuggled_count(0);
  16782. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16783. smuggled_count++;
  16784. res.set_content("oops", "text/plain");
  16785. });
  16786. auto port = svr.bind_to_any_port("localhost");
  16787. thread t = thread([&] { svr.listen_after_bind(); });
  16788. auto se = detail::scope_exit([&] {
  16789. svr.stop();
  16790. t.join();
  16791. });
  16792. svr.wait_until_ready();
  16793. auto error = Error::Success;
  16794. auto sock = detail::create_client_socket(
  16795. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16796. /*connection_timeout_sec=*/2, 0,
  16797. /*read_timeout_sec=*/2, 0,
  16798. /*write_timeout_sec=*/2, 0, std::string(), error);
  16799. ASSERT_NE(INVALID_SOCKET, sock);
  16800. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16801. // The "smuggled" request will be sent as the body of the outer GET
  16802. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16803. "Host: localhost\r\n"
  16804. "Connection: close\r\n"
  16805. "\r\n";
  16806. // Step 1: Send only the outer request headers (no body yet)
  16807. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16808. "Host: localhost\r\n"
  16809. "Content-Length: " +
  16810. std::to_string(smuggled.size()) +
  16811. "\r\n"
  16812. "\r\n";
  16813. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16814. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16815. // Step 2: Read the first response (server serves file without reading body)
  16816. std::string first_response;
  16817. char buf[4096];
  16818. for (;;) {
  16819. auto n = recv(sock, buf, sizeof(buf), 0);
  16820. if (n <= 0) break;
  16821. first_response.append(buf, static_cast<size_t>(n));
  16822. // Stop once we have a complete response (headers + body)
  16823. auto hdr_end = first_response.find("\r\n\r\n");
  16824. if (hdr_end != std::string::npos) {
  16825. // Check for Content-Length to know when the body is complete
  16826. auto cl_pos = first_response.find("Content-Length:");
  16827. if (cl_pos != std::string::npos) {
  16828. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16829. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16830. auto cl = std::stoul(
  16831. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16832. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16833. } else {
  16834. break; // No Content-Length, assume headers-only response
  16835. }
  16836. }
  16837. }
  16838. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16839. // Step 3: Now send the body, which looks like a new HTTP request.
  16840. // On a vulnerable server the keep-alive loop reads this as a second request.
  16841. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16842. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16843. // Step 4: Try to read a second response (should NOT exist after fix)
  16844. std::string second_response;
  16845. for (;;) {
  16846. auto n = recv(sock, buf, sizeof(buf), 0);
  16847. if (n <= 0) break;
  16848. second_response.append(buf, static_cast<size_t>(n));
  16849. }
  16850. // The smuggled request must NOT have been processed
  16851. EXPECT_EQ(0, smuggled_count.load());
  16852. }
  16853. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16854. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16855. // must be rejected with 400 Bad Request.
  16856. Server svr;
  16857. svr.Post("/test", [&](const Request &, Response &res) {
  16858. res.set_content("ok", "text/plain");
  16859. });
  16860. thread t = thread([&] { svr.listen(HOST, PORT); });
  16861. auto se = detail::scope_exit([&] {
  16862. svr.stop();
  16863. t.join();
  16864. ASSERT_FALSE(svr.is_running());
  16865. });
  16866. svr.wait_until_ready();
  16867. // Exact "chunked"
  16868. {
  16869. auto req = "POST /test HTTP/1.1\r\n"
  16870. "Host: localhost\r\n"
  16871. "Content-Length: 5\r\n"
  16872. "Transfer-Encoding: chunked\r\n"
  16873. "Connection: close\r\n"
  16874. "\r\n"
  16875. "hello";
  16876. std::string response;
  16877. ASSERT_TRUE(send_request(1, req, &response));
  16878. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16879. response.substr(0, response.find("\r\n")));
  16880. }
  16881. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16882. {
  16883. auto req = "POST /test HTTP/1.1\r\n"
  16884. "Host: localhost\r\n"
  16885. "Content-Length: 5\r\n"
  16886. "Transfer-Encoding: gzip, chunked\r\n"
  16887. "Connection: close\r\n"
  16888. "\r\n"
  16889. "hello";
  16890. std::string response;
  16891. ASSERT_TRUE(send_request(1, req, &response));
  16892. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16893. response.substr(0, response.find("\r\n")));
  16894. }
  16895. }
  16896. // Regression for issue #2450: a DELETE without Content-Length on a
  16897. // keep-alive connection must not let the post-response drain consume the
  16898. // next request's bytes.
  16899. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16900. Server svr;
  16901. std::atomic<int> delete_count(0);
  16902. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16903. delete_count++;
  16904. res.status = StatusCode::NoContent_204;
  16905. });
  16906. auto port = svr.bind_to_any_port(HOST);
  16907. thread t = thread([&] { svr.listen_after_bind(); });
  16908. auto se = detail::scope_exit([&] {
  16909. svr.stop();
  16910. t.join();
  16911. });
  16912. svr.wait_until_ready();
  16913. auto error = Error::Success;
  16914. auto sock = detail::create_client_socket(
  16915. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16916. /*connection_timeout_sec=*/2, 0,
  16917. /*read_timeout_sec=*/2, 0,
  16918. /*write_timeout_sec=*/2, 0, std::string(), error);
  16919. ASSERT_NE(INVALID_SOCKET, sock);
  16920. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16921. auto send_request_and_read_response = [&](const std::string &req,
  16922. std::string &out) -> bool {
  16923. auto sent = send(sock, req.data(), req.size(), 0);
  16924. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16925. char buf[4096];
  16926. for (;;) {
  16927. auto n = recv(sock, buf, sizeof(buf), 0);
  16928. if (n <= 0) { return !out.empty(); }
  16929. out.append(buf, static_cast<size_t>(n));
  16930. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16931. }
  16932. };
  16933. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16934. "Host: localhost\r\n"
  16935. "\r\n";
  16936. std::string resp1;
  16937. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16938. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16939. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16940. "Host: localhost\r\n"
  16941. "Connection: close\r\n"
  16942. "\r\n";
  16943. std::string resp2;
  16944. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16945. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16946. EXPECT_EQ(2, delete_count.load());
  16947. }
  16948. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  16949. Server svr;
  16950. svr.Post("/ingest", [&](const Request &, Response &res,
  16951. const ContentReader &content_reader) {
  16952. auto consumed = content_reader([](const char *, size_t) { return false; });
  16953. EXPECT_FALSE(consumed);
  16954. res.status = StatusCode::Conflict_409;
  16955. res.set_header("Connection", "close");
  16956. });
  16957. auto port = svr.bind_to_any_port(HOST);
  16958. thread t = thread([&] { svr.listen_after_bind(); });
  16959. auto se = detail::scope_exit([&] {
  16960. svr.stop();
  16961. t.join();
  16962. });
  16963. svr.wait_until_ready();
  16964. auto error = Error::Success;
  16965. auto sock = detail::create_client_socket(
  16966. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16967. /*connection_timeout_sec=*/2, 0,
  16968. /*read_timeout_sec=*/1, 0,
  16969. /*write_timeout_sec=*/2, 0, std::string(), error);
  16970. ASSERT_NE(INVALID_SOCKET, sock);
  16971. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16972. std::string request = "POST /ingest HTTP/1.1\r\n"
  16973. "Host: localhost\r\n"
  16974. "Transfer-Encoding: chunked\r\n"
  16975. "\r\n"
  16976. "4\r\n"
  16977. "data\r\n";
  16978. auto sent = send(sock, request.data(), request.size(), 0);
  16979. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  16980. std::string response;
  16981. ssize_t received = 0;
  16982. do {
  16983. char buf[4096];
  16984. received = recv(sock, buf, sizeof(buf), 0);
  16985. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  16986. } while (received > 0);
  16987. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  16988. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  16989. EXPECT_EQ(0, received);
  16990. }
  16991. namespace no_proxy_test {
  16992. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16993. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16994. // calling listen().
  16995. class ScopedServer {
  16996. public:
  16997. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16998. ~ScopedServer() {
  16999. svr_.stop();
  17000. if (th_.joinable()) { th_.join(); }
  17001. }
  17002. Server &svr() { return svr_; }
  17003. int port() const { return port_; }
  17004. void listen() {
  17005. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17006. svr_.wait_until_ready();
  17007. }
  17008. private:
  17009. Server svr_;
  17010. std::thread th_;
  17011. int port_ = 0;
  17012. };
  17013. class ProxyAndTargetServers {
  17014. public:
  17015. ProxyAndTargetServers() {
  17016. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17017. proxy_hits_++;
  17018. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17019. res.set_content("via-proxy", "text/plain");
  17020. });
  17021. target_.Get(".*", [this](const Request &req, Response &res) {
  17022. target_hits_++;
  17023. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17024. res.set_content("direct", "text/plain");
  17025. });
  17026. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17027. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17028. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17029. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17030. proxy_mock_.wait_until_ready();
  17031. target_.wait_until_ready();
  17032. }
  17033. ~ProxyAndTargetServers() {
  17034. proxy_mock_.stop();
  17035. target_.stop();
  17036. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17037. if (target_thread_.joinable()) { target_thread_.join(); }
  17038. }
  17039. Server &proxy_mock() { return proxy_mock_; }
  17040. Server &target() { return target_; }
  17041. int proxy_port() const { return proxy_port_; }
  17042. int target_port() const { return target_port_; }
  17043. int proxy_hits() const { return proxy_hits_.load(); }
  17044. int target_hits() const { return target_hits_.load(); }
  17045. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17046. void reset_counters() {
  17047. proxy_hits_ = 0;
  17048. target_hits_ = 0;
  17049. last_had_proxy_authz_ = false;
  17050. }
  17051. private:
  17052. Server proxy_mock_;
  17053. Server target_;
  17054. std::thread proxy_thread_;
  17055. std::thread target_thread_;
  17056. int proxy_port_ = 0;
  17057. int target_port_ = 0;
  17058. std::atomic<int> proxy_hits_{0};
  17059. std::atomic<int> target_hits_{0};
  17060. std::atomic<bool> last_had_proxy_authz_{false};
  17061. };
  17062. inline std::unique_ptr<Client> make_client(const std::string &host,
  17063. ProxyAndTargetServers &s) {
  17064. auto cli = detail::make_unique<Client>(host, s.target_port());
  17065. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17066. cli->set_proxy("127.0.0.1", s.proxy_port());
  17067. return cli;
  17068. }
  17069. } // namespace no_proxy_test
  17070. using no_proxy_test::make_client;
  17071. using no_proxy_test::ProxyAndTargetServers;
  17072. TEST(NoProxyTest, ExactHostnameBypasses) {
  17073. ProxyAndTargetServers s;
  17074. auto cli = make_client("example.com", s);
  17075. cli->set_no_proxy({"example.com"});
  17076. auto res = cli->Get("/");
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. EXPECT_EQ(0, s.proxy_hits());
  17079. EXPECT_EQ(1, s.target_hits());
  17080. }
  17081. TEST(NoProxyTest, SubdomainBypasses) {
  17082. ProxyAndTargetServers s;
  17083. auto cli = make_client("foo.example.com", s);
  17084. cli->set_no_proxy({"example.com"});
  17085. auto res = cli->Get("/");
  17086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17087. EXPECT_EQ(0, s.proxy_hits());
  17088. EXPECT_EQ(1, s.target_hits());
  17089. }
  17090. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17091. // Regression guard: "evilexample.com" must not be considered a subdomain
  17092. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17093. // check would let traffic bypass the proxy and leak credentials direct
  17094. // to the attacker host.
  17095. ProxyAndTargetServers s;
  17096. auto cli = make_client("evilexample.com", s);
  17097. cli->set_no_proxy({"example.com"});
  17098. auto res = cli->Get("/");
  17099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17100. EXPECT_GE(s.proxy_hits(), 1);
  17101. EXPECT_EQ(0, s.target_hits());
  17102. }
  17103. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17104. ProxyAndTargetServers s;
  17105. auto cli = make_client("example.com.evil.com", s);
  17106. cli->set_no_proxy({"example.com"});
  17107. auto res = cli->Get("/");
  17108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17109. EXPECT_GE(s.proxy_hits(), 1);
  17110. EXPECT_EQ(0, s.target_hits());
  17111. }
  17112. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17113. ProxyAndTargetServers s;
  17114. auto cli = make_client("example.com", s);
  17115. cli->set_no_proxy({".example.com"});
  17116. auto res = cli->Get("/");
  17117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17118. EXPECT_EQ(0, s.proxy_hits());
  17119. EXPECT_EQ(1, s.target_hits());
  17120. }
  17121. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17122. ProxyAndTargetServers s;
  17123. auto cli = make_client("Example.COM", s);
  17124. cli->set_no_proxy({"EXAMPLE.com"});
  17125. auto res = cli->Get("/");
  17126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17127. EXPECT_EQ(0, s.proxy_hits());
  17128. EXPECT_EQ(1, s.target_hits());
  17129. }
  17130. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17131. ProxyAndTargetServers s;
  17132. auto cli = make_client("example.com.", s);
  17133. cli->set_no_proxy({"example.com"});
  17134. auto res = cli->Get("/");
  17135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17136. EXPECT_EQ(0, s.proxy_hits());
  17137. EXPECT_EQ(1, s.target_hits());
  17138. }
  17139. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17140. // Trailing dots must be normalized on BOTH sides — host and entry.
  17141. // An implementation that only strips the host-side trailing dot would
  17142. // fail to match host "example.com" against entry "example.com." because
  17143. // a literal substring search would compare 11 chars against 12.
  17144. ProxyAndTargetServers s;
  17145. auto cli = make_client("example.com", s);
  17146. cli->set_no_proxy({"example.com."});
  17147. auto res = cli->Get("/");
  17148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17149. EXPECT_EQ(0, s.proxy_hits());
  17150. EXPECT_EQ(1, s.target_hits());
  17151. }
  17152. TEST(NoProxyTest, WildcardBypassesEverything) {
  17153. ProxyAndTargetServers s;
  17154. auto cli = make_client("anything.invalid.test", s);
  17155. cli->set_no_proxy({"*"});
  17156. auto res = cli->Get("/");
  17157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17158. EXPECT_EQ(0, s.proxy_hits());
  17159. EXPECT_EQ(1, s.target_hits());
  17160. }
  17161. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17162. ProxyAndTargetServers s;
  17163. Client cli("127.0.0.1", s.target_port());
  17164. cli.set_proxy("127.0.0.1", s.proxy_port());
  17165. cli.set_no_proxy({"127.0.0.1"});
  17166. auto res = cli.Get("/");
  17167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17168. EXPECT_EQ(0, s.proxy_hits());
  17169. EXPECT_EQ(1, s.target_hits());
  17170. }
  17171. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17172. ProxyAndTargetServers s;
  17173. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17174. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17175. cli.set_proxy("127.0.0.1", s.proxy_port());
  17176. cli.set_no_proxy({"::1"});
  17177. auto res = cli.Get("/");
  17178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17179. EXPECT_EQ(0, s.proxy_hits());
  17180. EXPECT_EQ(1, s.target_hits());
  17181. }
  17182. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17183. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17184. // must still be recognized as IPv6 for CIDR matching. Implementations
  17185. // that detect IPv6 only when the host begins with '[' would parse the
  17186. // host as a hostname and miss the match.
  17187. ProxyAndTargetServers s;
  17188. Client cli("fe80::1", s.target_port());
  17189. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17190. cli.set_proxy("127.0.0.1", s.proxy_port());
  17191. cli.set_no_proxy({"fe80::/10"});
  17192. auto res = cli.Get("/");
  17193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17194. EXPECT_EQ(0, s.proxy_hits());
  17195. EXPECT_EQ(1, s.target_hits());
  17196. }
  17197. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17198. ProxyAndTargetServers s;
  17199. Client cli("::1", s.target_port());
  17200. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17201. cli.set_proxy("127.0.0.1", s.proxy_port());
  17202. cli.set_no_proxy({"[::1]"});
  17203. auto res = cli.Get("/");
  17204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17205. EXPECT_EQ(0, s.proxy_hits());
  17206. EXPECT_EQ(1, s.target_hits());
  17207. }
  17208. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17209. ProxyAndTargetServers s;
  17210. Client cli("fe80::1", s.target_port());
  17211. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17212. cli.set_proxy("127.0.0.1", s.proxy_port());
  17213. cli.set_no_proxy({"[fe80::]/10"});
  17214. auto res = cli.Get("/");
  17215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17216. EXPECT_EQ(0, s.proxy_hits());
  17217. EXPECT_EQ(1, s.target_hits());
  17218. }
  17219. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17220. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17221. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17222. // tricks via address-family conversion.
  17223. ProxyAndTargetServers s;
  17224. Client cli("::ffff:127.0.0.1", s.target_port());
  17225. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17226. cli.set_proxy("127.0.0.1", s.proxy_port());
  17227. cli.set_no_proxy({"127.0.0.1"});
  17228. auto res = cli.Get("/");
  17229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17230. EXPECT_GE(s.proxy_hits(), 1);
  17231. EXPECT_EQ(0, s.target_hits());
  17232. }
  17233. TEST(NoProxyTest, IPv4CidrMatch) {
  17234. ProxyAndTargetServers s;
  17235. Client cli("127.0.0.1", s.target_port());
  17236. cli.set_proxy("127.0.0.1", s.proxy_port());
  17237. cli.set_no_proxy({"127.0.0.0/8"});
  17238. auto res = cli.Get("/");
  17239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17240. EXPECT_EQ(0, s.proxy_hits());
  17241. EXPECT_EQ(1, s.target_hits());
  17242. }
  17243. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17244. ProxyAndTargetServers s;
  17245. Client cli("127.0.0.1", s.target_port());
  17246. cli.set_proxy("127.0.0.1", s.proxy_port());
  17247. cli.set_no_proxy({"10.0.0.0/8"});
  17248. auto res = cli.Get("/");
  17249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17250. EXPECT_GE(s.proxy_hits(), 1);
  17251. EXPECT_EQ(0, s.target_hits());
  17252. }
  17253. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17254. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17255. // IPv4 target matches.
  17256. ProxyAndTargetServers s;
  17257. Client cli("127.0.0.1", s.target_port());
  17258. cli.set_proxy("127.0.0.1", s.proxy_port());
  17259. cli.set_no_proxy({"0.0.0.0/0"});
  17260. auto res = cli.Get("/");
  17261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17262. EXPECT_EQ(0, s.proxy_hits());
  17263. EXPECT_EQ(1, s.target_hits());
  17264. }
  17265. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17266. ProxyAndTargetServers s;
  17267. Client cli("127.0.0.1", s.target_port());
  17268. cli.set_proxy("127.0.0.1", s.proxy_port());
  17269. cli.set_no_proxy({"127.0.0.1"});
  17270. auto res = cli.Get("/");
  17271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17272. EXPECT_EQ(0, s.proxy_hits());
  17273. EXPECT_EQ(1, s.target_hits());
  17274. }
  17275. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17276. ProxyAndTargetServers s;
  17277. Client cli("127.0.0.1", s.target_port());
  17278. cli.set_proxy("127.0.0.1", s.proxy_port());
  17279. cli.set_no_proxy({"127.0.0.0/33"});
  17280. auto res = cli.Get("/");
  17281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17282. EXPECT_GE(s.proxy_hits(), 1);
  17283. EXPECT_EQ(0, s.target_hits());
  17284. }
  17285. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17286. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17287. ProxyAndTargetServers s;
  17288. Client cli("127.0.0.1", s.target_port());
  17289. cli.set_proxy("127.0.0.1", s.proxy_port());
  17290. cli.set_no_proxy({"127.0.0.1/"});
  17291. auto res = cli.Get("/");
  17292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17293. EXPECT_GE(s.proxy_hits(), 1);
  17294. EXPECT_EQ(0, s.target_hits());
  17295. }
  17296. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17297. ProxyAndTargetServers s;
  17298. auto cli = make_client("internal.corp", s);
  17299. cli->set_proxy_basic_auth("u", "p");
  17300. cli->set_no_proxy({"internal.corp"});
  17301. auto res = cli->Get("/");
  17302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17303. EXPECT_EQ(1, s.target_hits());
  17304. EXPECT_EQ(0, s.proxy_hits());
  17305. EXPECT_FALSE(s.last_had_proxy_authz())
  17306. << "Proxy-Authorization must not be sent direct to the target";
  17307. }
  17308. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17309. ProxyAndTargetServers s;
  17310. auto cli = make_client("public.example", s);
  17311. cli->set_proxy_basic_auth("u", "p");
  17312. cli->set_no_proxy({"internal.corp"}); // does not match
  17313. auto res = cli->Get("/");
  17314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17315. EXPECT_GE(s.proxy_hits(), 1);
  17316. EXPECT_TRUE(s.last_had_proxy_authz());
  17317. }
  17318. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17319. ProxyAndTargetServers s;
  17320. auto cli = make_client("anything.test", s);
  17321. auto res = cli->Get("/");
  17322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17323. EXPECT_GE(s.proxy_hits(), 1);
  17324. EXPECT_EQ(0, s.target_hits());
  17325. }
  17326. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17327. ProxyAndTargetServers s;
  17328. auto cli = make_client("example.com", s);
  17329. cli->set_no_proxy({"example.com:8080"});
  17330. auto res = cli->Get("/");
  17331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17332. EXPECT_GE(s.proxy_hits(), 1);
  17333. EXPECT_EQ(0, s.target_hits());
  17334. }
  17335. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17336. ProxyAndTargetServers s;
  17337. auto cli = make_client("anything.test", s);
  17338. cli->set_no_proxy({"", " ", "\t"});
  17339. auto res = cli->Get("/");
  17340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17341. EXPECT_GE(s.proxy_hits(), 1);
  17342. EXPECT_EQ(0, s.target_hits());
  17343. }
  17344. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17345. // An entry with leading/trailing whitespace must still match — env-style
  17346. // values are commonly pasted with stray spaces and an implementation
  17347. // that feeds the raw token directly to inet_pton would fail to match
  17348. // valid CIDRs because of the spaces.
  17349. ProxyAndTargetServers s;
  17350. Client cli("127.0.0.1", s.target_port());
  17351. cli.set_proxy("127.0.0.1", s.proxy_port());
  17352. cli.set_no_proxy({" 127.0.0.0/8 "});
  17353. auto res = cli.Get("/");
  17354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17355. EXPECT_EQ(0, s.proxy_hits());
  17356. EXPECT_EQ(1, s.target_hits());
  17357. }
  17358. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17359. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17360. // go direct and must NOT carry Proxy-Authorization.
  17361. std::atomic<int> proxy_hits{0};
  17362. std::atomic<int> target_hits{0};
  17363. std::atomic<bool> target_saw_authz{false};
  17364. no_proxy_test::ScopedServer proxy_mock, target;
  17365. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17366. proxy_hits++;
  17367. res.status = 302;
  17368. res.set_header("Location", "http://127.0.0.1:" +
  17369. std::to_string(target.port()) + "/landed");
  17370. });
  17371. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17372. target_hits++;
  17373. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17374. res.set_content("direct", "text/plain");
  17375. });
  17376. proxy_mock.listen();
  17377. target.listen();
  17378. Client cli("public.example", target.port());
  17379. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17380. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17381. cli.set_proxy_basic_auth("u", "p");
  17382. cli.set_no_proxy({"127.0.0.1"});
  17383. cli.set_follow_location(true);
  17384. auto res = cli.Get("/redir");
  17385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17386. EXPECT_GE(proxy_hits.load(), 1);
  17387. EXPECT_GE(target_hits.load(), 1);
  17388. EXPECT_FALSE(target_saw_authz.load());
  17389. }
  17390. #ifdef CPPHTTPLIB_SSL_ENABLED
  17391. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17392. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17393. // proxy creds would be sent to the (possibly hostile) origin.
  17394. std::atomic<int> target_hits{0};
  17395. std::atomic<bool> target_saw_proxy_authz{false};
  17396. no_proxy_test::ScopedServer target;
  17397. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17398. target_hits++;
  17399. if (req.has_header("Proxy-Authorization")) {
  17400. target_saw_proxy_authz = true;
  17401. }
  17402. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17403. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17404. "nonce=\"abc\", algorithm=MD5");
  17405. });
  17406. target.listen();
  17407. // The proxy address is set to the target's port: the bypass MUST kick in;
  17408. // if it doesn't, the test still routes "via proxy" to the same server and
  17409. // the Proxy-Authorization assertion below catches the leak.
  17410. Client cli("evil.example", target.port());
  17411. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17412. cli.set_proxy("127.0.0.1", target.port());
  17413. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17414. cli.set_no_proxy({"evil.example"});
  17415. auto res = cli.Get("/x");
  17416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17417. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17418. EXPECT_EQ(1, target_hits.load());
  17419. EXPECT_FALSE(target_saw_proxy_authz.load());
  17420. }
  17421. #endif
  17422. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17423. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17424. std::atomic<int> proxy_hits{0};
  17425. std::atomic<int> bypass_hits{0};
  17426. std::atomic<bool> proxy_saw_c_url{false};
  17427. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17428. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17429. proxy_hits++;
  17430. if (req.path.find("/start") != std::string::npos) {
  17431. res.status = 302;
  17432. res.set_header("Location", "http://127.0.0.1:" +
  17433. std::to_string(bypass_server.port()) +
  17434. "/middle");
  17435. return;
  17436. }
  17437. if (req.path.find("/end") != std::string::npos) {
  17438. proxy_saw_c_url = true;
  17439. res.set_content("c-via-proxy", "text/plain");
  17440. return;
  17441. }
  17442. res.set_content("unexpected", "text/plain");
  17443. });
  17444. // public.example's "advertised" port is arbitrary (the request never lands
  17445. // there — it goes through the proxy), but use a dynamic value to stay
  17446. // friendly with sharded parallel runs.
  17447. int public_port = bypass_server.port();
  17448. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17449. bypass_hits++;
  17450. res.status = 302;
  17451. res.set_header("Location", "http://public.example:" +
  17452. std::to_string(public_port) + "/end");
  17453. });
  17454. proxy_mock.listen();
  17455. bypass_server.listen();
  17456. Client cli("public.example", public_port);
  17457. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17458. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17459. cli.set_no_proxy({"127.0.0.1"});
  17460. cli.set_follow_location(true);
  17461. auto res = cli.Get("/start");
  17462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17463. EXPECT_EQ(StatusCode::OK_200, res->status);
  17464. EXPECT_EQ("c-via-proxy", res->body);
  17465. EXPECT_GE(proxy_hits.load(), 2);
  17466. EXPECT_GE(bypass_hits.load(), 1);
  17467. EXPECT_TRUE(proxy_saw_c_url.load());
  17468. }
  17469. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17470. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17471. // request reconnects to the correct endpoint.
  17472. std::atomic<int> proxy_hits{0};
  17473. std::atomic<int> target_hits{0};
  17474. no_proxy_test::ScopedServer proxy_mock, target;
  17475. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17476. proxy_hits++;
  17477. res.set_content("via-proxy", "text/plain");
  17478. });
  17479. target.svr().Get(".*", [&](const Request &, Response &res) {
  17480. target_hits++;
  17481. res.set_content("direct", "text/plain");
  17482. });
  17483. proxy_mock.listen();
  17484. target.listen();
  17485. Client cli("public.example", target.port());
  17486. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17487. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17488. cli.set_keep_alive(true);
  17489. auto res1 = cli.Get("/a");
  17490. ASSERT_TRUE(res1);
  17491. EXPECT_EQ("via-proxy", res1->body);
  17492. EXPECT_EQ(1, proxy_hits.load());
  17493. EXPECT_EQ(0, target_hits.load());
  17494. cli.set_no_proxy({"public.example"});
  17495. auto res2 = cli.Get("/b");
  17496. ASSERT_TRUE(res2);
  17497. EXPECT_EQ("direct", res2->body);
  17498. EXPECT_EQ(1, proxy_hits.load());
  17499. EXPECT_EQ(1, target_hits.load());
  17500. }
  17501. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17502. namespace proxy_tunnel_test {
  17503. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17504. class ScopedSSLServer {
  17505. public:
  17506. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17507. port_ = svr_.bind_to_any_port("127.0.0.1");
  17508. }
  17509. ~ScopedSSLServer() {
  17510. svr_.stop();
  17511. if (th_.joinable()) { th_.join(); }
  17512. }
  17513. SSLServer &svr() { return svr_; }
  17514. int port() const { return port_; }
  17515. void listen() {
  17516. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17517. svr_.wait_until_ready();
  17518. }
  17519. private:
  17520. SSLServer svr_;
  17521. std::thread th_;
  17522. int port_ = 0;
  17523. };
  17524. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17525. class ScopedConnectProxy {
  17526. public:
  17527. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17528. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17529. if (listen_fd_ < 0) { return; }
  17530. int yes = 1;
  17531. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17532. sockaddr_in a{};
  17533. a.sin_family = AF_INET;
  17534. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17535. a.sin_port = 0;
  17536. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17537. return;
  17538. }
  17539. socklen_t alen = sizeof(a);
  17540. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17541. 0) {
  17542. return;
  17543. }
  17544. port_ = ntohs(a.sin_port);
  17545. if (::listen(listen_fd_, 1) != 0) { return; }
  17546. th_ = std::thread([this] { run(); });
  17547. }
  17548. ~ScopedConnectProxy() {
  17549. stop_ = true;
  17550. if (listen_fd_ >= 0) {
  17551. ::shutdown(listen_fd_, SHUT_RDWR);
  17552. ::close(listen_fd_);
  17553. }
  17554. if (th_.joinable()) { th_.join(); }
  17555. }
  17556. int port() const { return port_; }
  17557. int connect_hits() const { return connect_hits_.load(); }
  17558. private:
  17559. void run() {
  17560. while (!stop_.load()) {
  17561. fd_set rfds;
  17562. FD_ZERO(&rfds);
  17563. FD_SET(listen_fd_, &rfds);
  17564. timeval tv{0, 100 * 1000};
  17565. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17566. if (sel <= 0) { continue; }
  17567. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17568. if (client_fd < 0) { continue; }
  17569. std::string req;
  17570. char buf[2048];
  17571. while (req.find("\r\n\r\n") == std::string::npos) {
  17572. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17573. if (n <= 0) { break; }
  17574. req.append(buf, static_cast<size_t>(n));
  17575. }
  17576. if (req.compare(0, 7, "CONNECT") != 0) {
  17577. ::close(client_fd);
  17578. continue;
  17579. }
  17580. connect_hits_++;
  17581. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17582. ::send(client_fd, ok, std::strlen(ok), 0);
  17583. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17584. sockaddr_in o{};
  17585. o.sin_family = AF_INET;
  17586. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17587. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17588. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17589. 0) {
  17590. ::close(client_fd);
  17591. ::close(origin_fd);
  17592. continue;
  17593. }
  17594. auto forward = [](int from, int to) {
  17595. char b[8192];
  17596. for (;;) {
  17597. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17598. if (n <= 0) { break; }
  17599. ssize_t off = 0;
  17600. while (off < n) {
  17601. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17602. if (s <= 0) {
  17603. off = n;
  17604. break;
  17605. }
  17606. off += s;
  17607. }
  17608. }
  17609. ::shutdown(to, SHUT_WR);
  17610. };
  17611. std::thread t1([&] { forward(client_fd, origin_fd); });
  17612. std::thread t2([&] { forward(origin_fd, client_fd); });
  17613. t1.join();
  17614. t2.join();
  17615. ::close(client_fd);
  17616. ::close(origin_fd);
  17617. }
  17618. }
  17619. int forward_port_ = -1;
  17620. int listen_fd_ = -1;
  17621. int port_ = 0;
  17622. std::thread th_;
  17623. std::atomic<bool> stop_{false};
  17624. std::atomic<int> connect_hits_{0};
  17625. };
  17626. } // namespace proxy_tunnel_test
  17627. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17628. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17629. // retry; otherwise proxy creds would be sent to the origin.
  17630. std::atomic<int> origin_hits{0};
  17631. std::atomic<bool> origin_saw_proxy_authz{false};
  17632. proxy_tunnel_test::ScopedSSLServer origin;
  17633. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17634. origin_hits++;
  17635. if (req.has_header("Proxy-Authorization")) {
  17636. origin_saw_proxy_authz = true;
  17637. }
  17638. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17639. res.set_header("Proxy-Authenticate",
  17640. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17641. "algorithm=MD5");
  17642. });
  17643. origin.listen();
  17644. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17645. ASSERT_NE(0, proxy.port());
  17646. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  17647. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  17648. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  17649. // and answer with its own status, making this test flaky.
  17650. SSLClient cli("127.0.0.1", origin.port());
  17651. cli.enable_server_certificate_verification(false);
  17652. cli.set_proxy("127.0.0.1", proxy.port());
  17653. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17654. auto res = cli.Get("/x");
  17655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17656. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17657. EXPECT_EQ(1, origin_hits.load());
  17658. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17659. EXPECT_EQ(1, proxy.connect_hits());
  17660. }
  17661. #endif