test.cc 641 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692
  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. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  47. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  48. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  49. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  50. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  51. #ifdef CPPHTTPLIB_SSL_ENABLED
  52. namespace httplib {
  53. namespace tls {
  54. // Declared here for the split build, where the TLS abstraction declarations
  55. // live below the split border; the definition is linked from httplib.cc.
  56. ca_store_t create_ca_store(const char *pem, size_t len);
  57. } // namespace tls
  58. } // namespace httplib
  59. #endif
  60. using namespace std;
  61. using namespace httplib;
  62. const char *HOST = "localhost";
  63. static int get_base_port() {
  64. const char *shard = getenv("GTEST_SHARD_INDEX");
  65. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  66. }
  67. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  68. // New standalone tests MUST use svr.bind_to_any_port() instead.
  69. const int PORT = get_base_port();
  70. const string LONG_QUERY_VALUE = string(25000, '@');
  71. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  72. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  73. const string TOO_LONG_QUERY_URL =
  74. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  75. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  76. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  77. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  78. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  79. return file.name == key;
  80. });
  81. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  82. return *it;
  83. #else
  84. if (it != items.end()) { return *it; }
  85. throw std::runtime_error("invalid multipart form data name error");
  86. #endif
  87. }
  88. static void read_file(const std::string &path, std::string &out) {
  89. std::ifstream fs(path, std::ios_base::binary);
  90. if (!fs) {
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return;
  93. #else
  94. throw std::runtime_error("File not found: " + path);
  95. #endif
  96. }
  97. fs.seekg(0, std::ios_base::end);
  98. auto size = fs.tellg();
  99. fs.seekg(0);
  100. out.resize(static_cast<size_t>(size));
  101. fs.read(&out[0], static_cast<std::streamsize>(size));
  102. }
  103. class UnixSocketTest : public ::testing::Test {
  104. protected:
  105. void TearDown() override { std::remove(pathname_.c_str()); }
  106. void client_GET(const std::string &addr) {
  107. httplib::Client cli{addr};
  108. cli.set_address_family(AF_UNIX);
  109. ASSERT_TRUE(cli.is_valid());
  110. const auto &result = cli.Get(pattern_);
  111. ASSERT_TRUE(result) << "error: " << result.error();
  112. const auto &resp = result.value();
  113. EXPECT_EQ(resp.status, StatusCode::OK_200);
  114. EXPECT_EQ(resp.body, content_);
  115. }
  116. static std::string make_sock_path() {
  117. const char *shard = getenv("GTEST_SHARD_INDEX");
  118. return shard ? std::string("./httplib-server-") + shard + ".sock"
  119. : "./httplib-server.sock";
  120. }
  121. const std::string pathname_{make_sock_path()};
  122. const std::string pattern_{"/hi"};
  123. const std::string content_{"Hello World!"};
  124. };
  125. TEST_F(UnixSocketTest, pathname) {
  126. httplib::Server svr;
  127. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  128. res.set_content(content_, "text/plain");
  129. });
  130. std::thread t{[&] {
  131. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  132. }};
  133. auto se = detail::scope_exit([&] {
  134. svr.stop();
  135. t.join();
  136. ASSERT_FALSE(svr.is_running());
  137. });
  138. svr.wait_until_ready();
  139. ASSERT_TRUE(svr.is_running());
  140. client_GET(pathname_);
  141. }
  142. #if defined(__linux__) || \
  143. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  144. TEST_F(UnixSocketTest, PeerPid) {
  145. httplib::Server svr;
  146. std::string remote_port_val;
  147. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  148. res.set_content(content_, "text/plain");
  149. remote_port_val = std::to_string(req.remote_port);
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  163. }
  164. #endif
  165. #ifdef __linux__
  166. TEST_F(UnixSocketTest, abstract) {
  167. constexpr char svr_path[]{"\x00httplib-server.sock"};
  168. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  169. httplib::Server svr;
  170. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  171. res.set_content(content_, "text/plain");
  172. });
  173. std::thread t{[&] {
  174. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  175. }};
  176. auto se = detail::scope_exit([&] {
  177. svr.stop();
  178. t.join();
  179. ASSERT_FALSE(svr.is_running());
  180. });
  181. svr.wait_until_ready();
  182. ASSERT_TRUE(svr.is_running());
  183. client_GET(abstract_addr);
  184. }
  185. #endif
  186. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  187. httplib::Server svr;
  188. std::string received_host_header;
  189. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  190. // Capture the Host header sent by the client
  191. auto host_iter = req.headers.find("Host");
  192. if (host_iter != req.headers.end()) {
  193. received_host_header = host_iter->second;
  194. }
  195. res.set_content(content_, "text/plain");
  196. });
  197. std::thread t{[&] {
  198. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  199. }};
  200. auto se = detail::scope_exit([&] {
  201. svr.stop();
  202. t.join();
  203. ASSERT_FALSE(svr.is_running());
  204. });
  205. svr.wait_until_ready();
  206. ASSERT_TRUE(svr.is_running());
  207. // Test that Host header is automatically set to "localhost" for Unix socket
  208. // connections
  209. httplib::Client cli{pathname_};
  210. cli.set_address_family(AF_UNIX);
  211. ASSERT_TRUE(cli.is_valid());
  212. const auto &result = cli.Get(pattern_);
  213. ASSERT_TRUE(result) << "error: " << result.error();
  214. const auto &resp = result.value();
  215. EXPECT_EQ(resp.status, StatusCode::OK_200);
  216. EXPECT_EQ(resp.body, content_);
  217. // Verify that Host header was automatically set to "localhost"
  218. EXPECT_EQ(received_host_header, "localhost");
  219. }
  220. #ifndef _WIN32
  221. TEST(SocketStream, wait_writable_UNIX) {
  222. int fds[2];
  223. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  224. const auto asSocketStream = [&](socket_t fd,
  225. std::function<bool(Stream &)> func) {
  226. return detail::process_client_socket(
  227. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  228. };
  229. asSocketStream(fds[0], [&](Stream &s0) {
  230. EXPECT_EQ(s0.socket(), fds[0]);
  231. EXPECT_TRUE(s0.wait_writable());
  232. EXPECT_TRUE(s0.is_peer_alive());
  233. EXPECT_EQ(0, close(fds[1]));
  234. EXPECT_FALSE(s0.is_peer_alive());
  235. return true;
  236. });
  237. EXPECT_EQ(0, close(fds[0]));
  238. }
  239. TEST(SocketStream, wait_writable_INET) {
  240. sockaddr_in addr;
  241. memset(&addr, 0, sizeof(addr));
  242. addr.sin_family = AF_INET;
  243. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  244. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  245. int disconnected_svr_sock = -1;
  246. std::thread svr{[&] {
  247. const int s = socket(AF_INET, SOCK_STREAM, 0);
  248. ASSERT_LE(0, s);
  249. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  250. ASSERT_EQ(0, listen(s, 1));
  251. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  252. ASSERT_EQ(0, close(s));
  253. }};
  254. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  255. std::thread cli{[&] {
  256. const int s = socket(AF_INET, SOCK_STREAM, 0);
  257. ASSERT_LE(0, s);
  258. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  259. ASSERT_EQ(0, close(s));
  260. }};
  261. cli.join();
  262. svr.join();
  263. ASSERT_NE(disconnected_svr_sock, -1);
  264. const auto asSocketStream = [&](socket_t fd,
  265. std::function<bool(Stream &)> func) {
  266. return detail::process_client_socket(
  267. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  268. };
  269. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  270. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  271. // wait_writable() returns true because select_write() only checks if the
  272. // send buffer has space. Peer disconnection is detected later by send().
  273. EXPECT_TRUE(ss.wait_writable());
  274. return true;
  275. });
  276. ASSERT_EQ(0, close(disconnected_svr_sock));
  277. }
  278. #endif // #ifndef _WIN32
  279. TEST(SetSocketOptTest, TcpNoDelay) {
  280. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  281. ASSERT_NE(sock, INVALID_SOCKET);
  282. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  283. int val = 0;
  284. socklen_t len = sizeof(val);
  285. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  286. reinterpret_cast<char *>(&val), &len));
  287. EXPECT_NE(val, 0);
  288. detail::close_socket(sock);
  289. }
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. U8("descrip=Gastos áéíóúñÑ 6"));
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(DecodePathTest, UnicodeEncoding) {
  319. // %u0041 = 'A' (1-byte UTF-8)
  320. EXPECT_EQ("A", decode_path_component("%u0041"));
  321. // %u00E9 = 'é' (2-byte UTF-8)
  322. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  323. // %u3042 = 'あ' (3-byte UTF-8)
  324. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  325. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  326. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  327. // %uD800 = surrogate (invalid, silently dropped)
  328. EXPECT_EQ("", decode_path_component("%uD800"));
  329. }
  330. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  331. // A sign or whitespace inside the two-character escape window must not be
  332. // accepted as a valid percent-encoding; the sequence is passed through
  333. // literally, matching decode_uri_component / decode_path_component.
  334. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  335. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  336. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  337. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  338. // Well-formed escapes still decode.
  339. EXPECT_EQ("-", decode_query_component("%2D", false));
  340. EXPECT_EQ("A", decode_query_component("%41", false));
  341. }
  342. TEST(SanitizeFilenameTest, VariousPatterns) {
  343. // Path traversal
  344. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  345. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  346. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  347. // Normal and edge cases
  348. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  349. EXPECT_EQ("filename.txt",
  350. httplib::sanitize_filename("/path/to/filename.txt"));
  351. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  352. EXPECT_EQ("", httplib::sanitize_filename(".."));
  353. EXPECT_EQ("", httplib::sanitize_filename(""));
  354. // Null bytes stripped
  355. EXPECT_EQ("safe.txt",
  356. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  357. // Whitespace-only rejected
  358. EXPECT_EQ("", httplib::sanitize_filename(" "));
  359. }
  360. // Forward declaration (see the base64_encode note below): split builds move the
  361. // definition into httplib.cc, so re-declaring it here lets the test link.
  362. namespace httplib {
  363. namespace detail {
  364. bool is_chunked_transfer_encoding(const Headers &headers);
  365. } // namespace detail
  366. } // namespace httplib
  367. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  368. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  369. auto make = [](std::initializer_list<const char *> lines) {
  370. Headers h;
  371. for (auto te : lines) {
  372. if (te) { h.emplace("Transfer-Encoding", te); }
  373. }
  374. return h;
  375. };
  376. // Sole coding, matched case-insensitively.
  377. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  378. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  379. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  380. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  381. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  382. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  383. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  384. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  385. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  386. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  387. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  388. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  389. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  390. // portable, so any line naming chunked is treated as chunked (fail safe).
  391. // The result must not depend on the order the lines were added.
  392. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  393. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  395. }
  396. // Forward declaration: in split builds split.py strips `inline` and moves the
  397. // definition into httplib.cc, so detail::base64_encode is not visible from the
  398. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  399. // in both header-only and split builds.
  400. namespace httplib {
  401. namespace detail {
  402. std::string base64_encode(const std::string &in);
  403. } // namespace detail
  404. } // namespace httplib
  405. TEST(Base64EncodeTest, KnownAnswers) {
  406. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  407. // where the accumulator's top bit is already set before the next shift.
  408. EXPECT_EQ("", detail::base64_encode(""));
  409. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  410. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  411. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  412. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  413. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  414. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  415. // High bytes keep the top bit set across several rounds.
  416. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  417. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  418. }
  419. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  420. string unescapedCharacters = "-_.!~*'()";
  421. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  422. }
  423. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  424. string reservedCharacters = ";,/?:@&=+$";
  425. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  426. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  427. }
  428. TEST(ClientQueryOrder, PreserveOrder) {
  429. // This test reproduces Issue #2259: client may reorder query parameters
  430. // when sending a GET request. The expected behavior is that the client
  431. // preserves the original query string order when the caller supplied it
  432. // as part of the path.
  433. Server svr;
  434. svr.Get("/", [&](const Request &req, Response &res) {
  435. // Echo back the raw target so the test can assert ordering
  436. res.set_content(req.target, "text/plain");
  437. });
  438. std::thread t{[&] { svr.listen(HOST, PORT); }};
  439. auto se = detail::scope_exit([&] {
  440. svr.stop();
  441. t.join();
  442. ASSERT_FALSE(svr.is_running());
  443. });
  444. svr.wait_until_ready();
  445. Client cli(HOST, PORT);
  446. ASSERT_TRUE(cli.is_valid());
  447. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  448. auto res = cli.Get(original);
  449. ASSERT_TRUE(res);
  450. // Expect the echoed target to exactly match the original path (order
  451. // preserved)
  452. EXPECT_EQ(res->body, original);
  453. }
  454. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  455. string chineseCharacters = U8("中国語");
  456. string russianCharacters = U8("дом");
  457. string brazilianCharacters = U8("óculos");
  458. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  459. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  460. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  461. "%D0%B4%D0%BE%D0%BC");
  462. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  463. }
  464. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  465. string unescapedCharacters = "-_.!~*'()";
  466. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  467. }
  468. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  469. string reservedCharacters = ";,/?:@&=+$";
  470. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  471. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  472. }
  473. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  474. string chineseCharacters = U8("中国語");
  475. string russianCharacters = U8("дом");
  476. string brazilianCharacters = U8("óculos");
  477. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  478. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  479. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  480. "%D0%B4%D0%BE%D0%BC");
  481. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  482. }
  483. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  484. // Issue #2082 use case: encoding path component with ampersand
  485. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  486. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  487. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  488. }
  489. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  490. string unescapedCharacters = "-_.!~*'()";
  491. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  492. }
  493. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  494. string reservedCharacters = ";,/?:@&=+$#";
  495. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  496. }
  497. TEST(EncodeUriTest, TestUTF8Characters) {
  498. string chineseCharacters = U8("中国語");
  499. string russianCharacters = U8("дом");
  500. string brazilianCharacters = U8("óculos");
  501. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  502. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  503. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  504. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  505. }
  506. TEST(EncodeUriTest, TestCompleteUri) {
  507. string uri =
  508. "https://example.com/path/to/resource?query=value&param=test#fragment";
  509. EXPECT_EQ(
  510. httplib::encode_uri(uri),
  511. "https://example.com/path/to/resource?query=value&param=test#fragment");
  512. }
  513. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  514. string uri =
  515. "https://example.com/path with spaces/file name.html?q=hello world";
  516. EXPECT_EQ(httplib::encode_uri(uri),
  517. "https://example.com/path%20with%20spaces/"
  518. "file%20name.html?q=hello%20world");
  519. }
  520. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  521. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  522. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  523. }
  524. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  525. string unescapedCharacters = "-_.!~*'()";
  526. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  527. }
  528. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  529. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  530. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  531. string encodedBrazilian = "%C3%B3culos";
  532. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  533. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  534. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  535. }
  536. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  537. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  538. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  539. "Piri Tommy Villiers - on & on");
  540. }
  541. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  542. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  543. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  544. }
  545. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  546. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  547. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  548. }
  549. TEST(DecodeUriTest, TestUTF8Characters) {
  550. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  551. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  552. string encodedBrazilian = "%C3%B3culos";
  553. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  554. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  555. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  556. }
  557. TEST(DecodeUriTest, TestCompleteUri) {
  558. string encodedUri = "https://example.com/path%20with%20spaces/"
  559. "file%20name.html?q=hello%20world";
  560. EXPECT_EQ(
  561. httplib::decode_uri(encodedUri),
  562. "https://example.com/path with spaces/file name.html?q=hello world");
  563. }
  564. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  565. string original =
  566. "https://example.com/path with spaces/file name.html?q=hello world";
  567. string encoded = httplib::encode_uri(original);
  568. string decoded = httplib::decode_uri(encoded);
  569. EXPECT_EQ(decoded, original);
  570. }
  571. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  572. string original = "Piri Tommy Villiers - on & on";
  573. string encoded = httplib::encode_uri_component(original);
  574. string decoded = httplib::decode_uri_component(encoded);
  575. EXPECT_EQ(decoded, original);
  576. }
  577. TEST(TrimTests, TrimStringTests) {
  578. EXPECT_EQ("abc", detail::trim_copy("abc"));
  579. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  580. EXPECT_TRUE(detail::trim_copy("").empty());
  581. }
  582. TEST(AsciiTest, LocaleIndependentClassification) {
  583. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  584. // which consult the global C locale: std::isalnum(0xC5) can return true
  585. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  586. // helpers must classify every byte by the ASCII grammar alone.
  587. for (int i = 0; i < 256; i++) {
  588. auto c = static_cast<char>(i);
  589. auto is_digit = i >= '0' && i <= '9';
  590. auto is_upper = i >= 'A' && i <= 'Z';
  591. auto is_lower = i >= 'a' && i <= 'z';
  592. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  593. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  594. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  595. << "byte " << i;
  596. }
  597. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  598. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  599. // Non-ASCII bytes must be percent-encoded, never passed through as
  600. // alphanumeric.
  601. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  602. }
  603. TEST(FromCharsTest, Double) {
  604. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  605. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  606. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  607. auto parse = [](const std::string &s, double &v) {
  608. return detail::from_chars(s.data(), s.data() + s.size(), v);
  609. };
  610. double v = -1.0;
  611. // Representative quality values.
  612. EXPECT_EQ(parse("0", v).ec, std::errc{});
  613. EXPECT_DOUBLE_EQ(v, 0.0);
  614. EXPECT_EQ(parse("1", v).ec, std::errc{});
  615. EXPECT_DOUBLE_EQ(v, 1.0);
  616. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  617. EXPECT_DOUBLE_EQ(v, 0.8);
  618. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.001);
  620. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 1.0);
  622. // A missing integer or fractional part is tolerated.
  623. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  624. EXPECT_DOUBLE_EQ(v, 0.5);
  625. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  626. EXPECT_DOUBLE_EQ(v, 5.0);
  627. // Values outside [0, 1] still parse; the caller range-checks them.
  628. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  629. EXPECT_DOUBLE_EQ(v, 123.456);
  630. // Stops at the first byte that is not part of the number and reports where.
  631. std::string trailing = "0.9, text/html";
  632. auto r = parse(trailing, v);
  633. EXPECT_EQ(r.ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 0.9);
  635. EXPECT_EQ(*r.ptr, ',');
  636. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  637. // outright, and an 'e'/'E' simply ends the number.
  638. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  639. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  640. std::string exp_input = "1.5e3";
  641. r = parse(exp_input, v);
  642. EXPECT_EQ(r.ec, std::errc{});
  643. EXPECT_DOUBLE_EQ(v, 1.5);
  644. EXPECT_EQ(*r.ptr, 'e');
  645. // Invalid inputs.
  646. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  647. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  648. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  649. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  650. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  651. // Pathological but well-formed inputs must stay bounded (no overflow, no
  652. // out-of-bounds table access) and stay within [0, 1] for the caller.
  653. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  654. std::errc{});
  655. EXPECT_DOUBLE_EQ(v, 0.0);
  656. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  657. std::errc{});
  658. EXPECT_GE(v, 0.0);
  659. EXPECT_LE(v, 1.0);
  660. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  661. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  662. }
  663. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  664. // Simple case without quality values
  665. std::vector<std::string> result1;
  666. EXPECT_TRUE(detail::parse_accept_header(
  667. "text/html,application/json,text/plain", result1));
  668. EXPECT_EQ(result1.size(), 3U);
  669. EXPECT_EQ(result1[0], "text/html");
  670. EXPECT_EQ(result1[1], "application/json");
  671. EXPECT_EQ(result1[2], "text/plain");
  672. // With quality values
  673. std::vector<std::string> result2;
  674. EXPECT_TRUE(detail::parse_accept_header(
  675. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  676. EXPECT_EQ(result2.size(), 3U);
  677. EXPECT_EQ(result2[0], "application/json"); // highest q value
  678. EXPECT_EQ(result2[1], "text/html");
  679. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  680. }
  681. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  682. // Mixed with and without quality values
  683. std::vector<std::string> result;
  684. EXPECT_TRUE(detail::parse_accept_header(
  685. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  686. EXPECT_EQ(result.size(), 3U);
  687. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  688. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  689. EXPECT_EQ(result[2], "application/json"); // q=0.5
  690. }
  691. TEST(ParseAcceptHeaderTest, EdgeCases) {
  692. // Empty header
  693. std::vector<std::string> empty_result;
  694. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  695. EXPECT_TRUE(empty_result.empty());
  696. // Single type
  697. std::vector<std::string> single_result;
  698. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  699. EXPECT_EQ(single_result.size(), 1U);
  700. EXPECT_EQ(single_result[0], "application/json");
  701. // Wildcard types
  702. std::vector<std::string> wildcard_result;
  703. EXPECT_TRUE(detail::parse_accept_header(
  704. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  705. EXPECT_EQ(wildcard_result.size(), 3U);
  706. EXPECT_EQ(wildcard_result[0], "application/json");
  707. EXPECT_EQ(wildcard_result[1], "text/*");
  708. EXPECT_EQ(wildcard_result[2], "*/*");
  709. }
  710. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  711. // Common browser Accept header
  712. std::vector<std::string> browser_result;
  713. EXPECT_TRUE(
  714. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  715. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  716. browser_result));
  717. EXPECT_EQ(browser_result.size(), 6U);
  718. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  719. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  720. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  721. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  722. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  723. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  724. // API client header
  725. std::vector<std::string> api_result;
  726. EXPECT_TRUE(detail::parse_accept_header(
  727. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  728. api_result));
  729. EXPECT_EQ(api_result.size(), 3U);
  730. EXPECT_EQ(api_result[0], "application/json");
  731. EXPECT_EQ(api_result[1], "application/xml");
  732. EXPECT_EQ(api_result[2], "text/plain");
  733. }
  734. TEST(ParseAcceptHeaderTest, SpecialCases) {
  735. // Quality value with 3 decimal places
  736. std::vector<std::string> decimal_result;
  737. EXPECT_TRUE(detail::parse_accept_header(
  738. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  739. EXPECT_EQ(decimal_result.size(), 2U);
  740. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  741. EXPECT_EQ(decimal_result[1], "text/html");
  742. // Zero quality (should still be included but with lowest priority)
  743. std::vector<std::string> zero_q_result;
  744. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  745. zero_q_result));
  746. EXPECT_EQ(zero_q_result.size(), 2U);
  747. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  748. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  749. // No spaces around commas
  750. std::vector<std::string> no_space_result;
  751. EXPECT_TRUE(detail::parse_accept_header(
  752. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  753. no_space_result));
  754. EXPECT_EQ(no_space_result.size(), 3U);
  755. EXPECT_EQ(no_space_result[0], "text/html");
  756. EXPECT_EQ(no_space_result[1], "application/json");
  757. EXPECT_EQ(no_space_result[2], "text/plain");
  758. }
  759. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  760. // Quality values always use '.' as the decimal separator, so parsing must
  761. // not depend on the process locale. An embedding application may have
  762. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  763. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  764. std::string saved = cur ? cur : "C";
  765. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  766. "fr_FR.UTF-8"};
  767. bool switched = false;
  768. for (const auto loc : comma_locales) {
  769. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  770. std::localeconv()->decimal_point[0] == ',') {
  771. switched = true;
  772. break;
  773. }
  774. }
  775. if (!switched) {
  776. std::setlocale(LC_NUMERIC, saved.c_str());
  777. GTEST_SKIP() << "no comma-decimal locale available on this host";
  778. }
  779. // The higher-weighted type appears later in the list, so a correct parse
  780. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  781. // sensitive parse reads both weights as 0 and leaves the original order.
  782. std::vector<std::string> result;
  783. EXPECT_TRUE(detail::parse_accept_header(
  784. "application/json;q=0.1,text/html;q=0.9", result));
  785. ASSERT_EQ(result.size(), 2U);
  786. EXPECT_EQ(result[0], "text/html");
  787. EXPECT_EQ(result[1], "application/json");
  788. std::setlocale(LC_NUMERIC, saved.c_str());
  789. }
  790. TEST(ParseAcceptHeaderTest, InvalidCases) {
  791. std::vector<std::string> result;
  792. // Invalid quality value (> 1.0)
  793. EXPECT_FALSE(
  794. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  795. // Invalid quality value (< 0.0)
  796. EXPECT_FALSE(
  797. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  798. // Invalid quality value (not a number)
  799. EXPECT_FALSE(detail::parse_accept_header(
  800. "text/html;q=invalid,application/json", result));
  801. // Empty quality value
  802. EXPECT_FALSE(
  803. detail::parse_accept_header("text/html;q=,application/json", result));
  804. // Invalid media type format (no slash and not wildcard)
  805. EXPECT_FALSE(
  806. detail::parse_accept_header("invalidtype,application/json", result));
  807. // Empty media type
  808. result.clear();
  809. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  810. // Only commas
  811. result.clear();
  812. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  813. // Valid cases should still work
  814. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  815. EXPECT_EQ(result.size(), 1U);
  816. EXPECT_EQ(result[0], "*/*");
  817. EXPECT_TRUE(detail::parse_accept_header("*", result));
  818. EXPECT_EQ(result.size(), 1U);
  819. EXPECT_EQ(result[0], "*");
  820. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  821. EXPECT_EQ(result.size(), 1U);
  822. EXPECT_EQ(result[0], "text/*");
  823. }
  824. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  825. Server svr;
  826. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  827. EXPECT_EQ(req.accept_content_types.size(), 3U);
  828. EXPECT_EQ(req.accept_content_types[0], "application/json");
  829. EXPECT_EQ(req.accept_content_types[1], "text/html");
  830. EXPECT_EQ(req.accept_content_types[2], "*/*");
  831. res.set_content("ok", "text/plain");
  832. });
  833. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  834. EXPECT_TRUE(false);
  835. res.set_content("bad request", "text/plain");
  836. });
  837. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  838. auto se = detail::scope_exit([&] {
  839. svr.stop();
  840. listen_thread.join();
  841. ASSERT_FALSE(svr.is_running());
  842. });
  843. svr.wait_until_ready();
  844. Client cli("localhost", PORT);
  845. {
  846. auto res = cli.Get(
  847. "/accept_ok",
  848. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  849. ASSERT_TRUE(res);
  850. EXPECT_EQ(StatusCode::OK_200, res->status);
  851. }
  852. {
  853. auto res = cli.Get("/accept_bad_request",
  854. Headers{{"Accept", "text/html;q=abc,application/json"}});
  855. ASSERT_TRUE(res);
  856. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  857. }
  858. }
  859. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  860. Server svr;
  861. svr.Get("/", [](const Request & /*req*/, Response &res) {
  862. res.set_content("ok", "text/plain");
  863. });
  864. std::atomic<int> start_count{0};
  865. std::atomic<bool> running_when_called{false};
  866. svr.set_start_handler([&]() {
  867. running_when_called = svr.is_running();
  868. start_count++;
  869. });
  870. auto port = svr.bind_to_any_port(HOST);
  871. std::thread t([&]() { svr.listen_after_bind(); });
  872. auto se = detail::scope_exit([&] {
  873. svr.stop();
  874. t.join();
  875. ASSERT_FALSE(svr.is_running());
  876. });
  877. svr.wait_until_ready();
  878. // A successful request proves the accept loop is running, which the start
  879. // handler precedes; so by now the handler must have run exactly once.
  880. Client cli(HOST, port);
  881. cli.set_connection_timeout(std::chrono::seconds(5));
  882. auto res = cli.Get("/");
  883. ASSERT_TRUE(res);
  884. EXPECT_EQ(StatusCode::OK_200, res->status);
  885. EXPECT_EQ(1, start_count.load());
  886. EXPECT_TRUE(running_when_called.load());
  887. }
  888. TEST(DivideTest, DivideStringTests) {
  889. auto divide = [](const std::string &str, char d) {
  890. std::string lhs;
  891. std::string rhs;
  892. detail::divide(str, d,
  893. [&](const char *lhs_data, std::size_t lhs_size,
  894. const char *rhs_data, std::size_t rhs_size) {
  895. lhs.assign(lhs_data, lhs_size);
  896. rhs.assign(rhs_data, rhs_size);
  897. });
  898. return std::make_pair(std::move(lhs), std::move(rhs));
  899. };
  900. {
  901. const auto res = divide("", '=');
  902. EXPECT_EQ(res.first, "");
  903. EXPECT_EQ(res.second, "");
  904. }
  905. {
  906. const auto res = divide("=", '=');
  907. EXPECT_EQ(res.first, "");
  908. EXPECT_EQ(res.second, "");
  909. }
  910. {
  911. const auto res = divide(" ", '=');
  912. EXPECT_EQ(res.first, " ");
  913. EXPECT_EQ(res.second, "");
  914. }
  915. {
  916. const auto res = divide("a", '=');
  917. EXPECT_EQ(res.first, "a");
  918. EXPECT_EQ(res.second, "");
  919. }
  920. {
  921. const auto res = divide("a=", '=');
  922. EXPECT_EQ(res.first, "a");
  923. EXPECT_EQ(res.second, "");
  924. }
  925. {
  926. const auto res = divide("=b", '=');
  927. EXPECT_EQ(res.first, "");
  928. EXPECT_EQ(res.second, "b");
  929. }
  930. {
  931. const auto res = divide("a=b", '=');
  932. EXPECT_EQ(res.first, "a");
  933. EXPECT_EQ(res.second, "b");
  934. }
  935. {
  936. const auto res = divide("a=b=", '=');
  937. EXPECT_EQ(res.first, "a");
  938. EXPECT_EQ(res.second, "b=");
  939. }
  940. {
  941. const auto res = divide("a=b=c", '=');
  942. EXPECT_EQ(res.first, "a");
  943. EXPECT_EQ(res.second, "b=c");
  944. }
  945. }
  946. TEST(SplitTest, ParseQueryString) {
  947. string s = "key1=val1&key2=val2&key3=val3";
  948. Params dic;
  949. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  950. [&](const char *b, const char *e) {
  951. string key, val;
  952. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  953. if (key.empty()) {
  954. key.assign(b2, e2);
  955. } else {
  956. val.assign(b2, e2);
  957. }
  958. });
  959. dic.emplace(key, val);
  960. });
  961. EXPECT_EQ("val1", dic.find("key1")->second);
  962. EXPECT_EQ("val2", dic.find("key2")->second);
  963. EXPECT_EQ("val3", dic.find("key3")->second);
  964. }
  965. TEST(SplitTest, ParseInvalidQueryTests) {
  966. {
  967. string s = " ";
  968. Params dict;
  969. detail::parse_query_text(s, dict);
  970. EXPECT_TRUE(dict.empty());
  971. }
  972. {
  973. string s = " = =";
  974. Params dict;
  975. detail::parse_query_text(s, dict);
  976. EXPECT_TRUE(dict.empty());
  977. }
  978. }
  979. TEST(ParseQueryTest, ParseQueryString) {
  980. {
  981. std::string s = "key1=val1&key2=val2&key3=val3";
  982. Params dic;
  983. detail::parse_query_text(s, dic);
  984. EXPECT_EQ("val1", dic.find("key1")->second);
  985. EXPECT_EQ("val2", dic.find("key2")->second);
  986. EXPECT_EQ("val3", dic.find("key3")->second);
  987. }
  988. {
  989. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  990. Params dic;
  991. detail::parse_query_text(s, dic);
  992. EXPECT_EQ("", dic.find("key1")->second);
  993. EXPECT_EQ("val1", dic.find("key2")->second);
  994. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  995. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  996. }
  997. }
  998. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  999. Params dic;
  1000. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1001. dic.emplace("key1", "val1");
  1002. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1003. dic.emplace("key2", "val2");
  1004. dic.emplace("key3", "val3");
  1005. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1006. }
  1007. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1008. string content_type = "multipart/form-data; boundary=something";
  1009. string boundary;
  1010. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1011. EXPECT_TRUE(ret);
  1012. EXPECT_EQ(boundary, "something");
  1013. }
  1014. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1015. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1016. string boundary;
  1017. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1018. EXPECT_TRUE(ret);
  1019. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1020. }
  1021. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1022. string content_type =
  1023. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1024. string boundary;
  1025. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1026. EXPECT_TRUE(ret);
  1027. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1028. }
  1029. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1030. string content_type =
  1031. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1032. string boundary;
  1033. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1034. EXPECT_TRUE(ret);
  1035. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1036. }
  1037. TEST(GetHeaderValueTest, DefaultValue) {
  1038. Headers headers = {{"Dummy", "Dummy"}};
  1039. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1040. EXPECT_STREQ("text/plain", val);
  1041. }
  1042. TEST(GetHeaderValueTest, DefaultValueInt) {
  1043. Headers headers = {{"Dummy", "Dummy"}};
  1044. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1045. EXPECT_EQ(100ull, val);
  1046. }
  1047. TEST(GetHeaderValueTest, RegularValue) {
  1048. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1049. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1050. EXPECT_STREQ("text/html", val);
  1051. }
  1052. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1053. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1054. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1055. EXPECT_STREQ("text/html", val);
  1056. }
  1057. TEST(GetHeaderValueTest, SetContent) {
  1058. Response res;
  1059. res.set_content("html", "text/html");
  1060. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1061. res.set_content("text", "text/plain");
  1062. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1063. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1064. }
  1065. TEST(GetHeaderValueTest, RegularValueInt) {
  1066. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1067. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1068. EXPECT_EQ(100ull, val);
  1069. }
  1070. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1071. Headers headers = {{"Content-Length", "x"}};
  1072. auto is_invalid_value = false;
  1073. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1074. is_invalid_value);
  1075. EXPECT_EQ(0ull, val);
  1076. EXPECT_TRUE(is_invalid_value);
  1077. }
  1078. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1079. // An all-digit value that overflows size_t must be reported as invalid, not
  1080. // silently saturated/truncated: strtoull would otherwise return ULLONG_MAX
  1081. // (or, on 32-bit builds, the cast would wrap a large length to a small one),
  1082. // leaving the framing length wrong while is_invalid_value stayed false.
  1083. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1084. auto is_invalid_value = false;
  1085. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1086. is_invalid_value);
  1087. EXPECT_TRUE(is_invalid_value);
  1088. // A well-formed length is unaffected.
  1089. Headers ok = {{"Content-Length", "1234"}};
  1090. is_invalid_value = false;
  1091. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1092. is_invalid_value);
  1093. EXPECT_EQ(1234ull, val);
  1094. EXPECT_FALSE(is_invalid_value);
  1095. }
  1096. TEST(GetHeaderValueTest, Range) {
  1097. {
  1098. Headers headers = {make_range_header({{1, -1}})};
  1099. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1100. EXPECT_STREQ("bytes=1-", val);
  1101. }
  1102. {
  1103. Headers headers = {make_range_header({{-1, 1}})};
  1104. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1105. EXPECT_STREQ("bytes=-1", val);
  1106. }
  1107. {
  1108. Headers headers = {make_range_header({{1, 10}})};
  1109. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1110. EXPECT_STREQ("bytes=1-10", val);
  1111. }
  1112. {
  1113. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1114. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1115. EXPECT_STREQ("bytes=1-10, 100-", val);
  1116. }
  1117. {
  1118. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1119. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1120. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1121. }
  1122. {
  1123. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1124. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1125. EXPECT_STREQ("bytes=0-0, -1", val);
  1126. }
  1127. }
  1128. TEST(ParseHeaderValueTest, Range) {
  1129. {
  1130. Ranges ranges;
  1131. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1132. EXPECT_TRUE(ret);
  1133. EXPECT_EQ(1u, ranges.size());
  1134. EXPECT_EQ(1u, ranges[0].first);
  1135. EXPECT_EQ(-1, ranges[0].second);
  1136. }
  1137. {
  1138. Ranges ranges;
  1139. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1140. EXPECT_TRUE(ret);
  1141. EXPECT_EQ(1u, ranges.size());
  1142. EXPECT_EQ(-1, ranges[0].first);
  1143. EXPECT_EQ(1u, ranges[0].second);
  1144. }
  1145. {
  1146. Ranges ranges;
  1147. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1148. EXPECT_TRUE(ret);
  1149. EXPECT_EQ(1u, ranges.size());
  1150. EXPECT_EQ(1u, ranges[0].first);
  1151. EXPECT_EQ(10u, ranges[0].second);
  1152. }
  1153. {
  1154. Ranges ranges;
  1155. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1156. EXPECT_FALSE(ret);
  1157. }
  1158. {
  1159. Ranges ranges;
  1160. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1161. EXPECT_TRUE(ret);
  1162. EXPECT_EQ(2u, ranges.size());
  1163. EXPECT_EQ(1u, ranges[0].first);
  1164. EXPECT_EQ(10u, ranges[0].second);
  1165. EXPECT_EQ(100u, ranges[1].first);
  1166. EXPECT_EQ(-1, ranges[1].second);
  1167. }
  1168. {
  1169. Ranges ranges;
  1170. auto ret =
  1171. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1172. EXPECT_TRUE(ret);
  1173. EXPECT_EQ(3u, ranges.size());
  1174. EXPECT_EQ(1u, ranges[0].first);
  1175. EXPECT_EQ(10u, ranges[0].second);
  1176. EXPECT_EQ(100u, ranges[1].first);
  1177. EXPECT_EQ(200u, ranges[1].second);
  1178. EXPECT_EQ(300u, ranges[2].first);
  1179. EXPECT_EQ(400u, ranges[2].second);
  1180. }
  1181. {
  1182. Ranges ranges;
  1183. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1184. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1185. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1186. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1187. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1188. EXPECT_FALSE(detail::parse_range_header("bytes=,", 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=a-b", ranges));
  1192. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1193. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1194. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1195. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1196. EXPECT_TRUE(ranges.empty());
  1197. }
  1198. }
  1199. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1200. Request req;
  1201. req.set_header("Accept-Encoding", "gzip");
  1202. Response res;
  1203. res.set_header("Content-Type", "text/plain");
  1204. auto ret = detail::encoding_type(req, res);
  1205. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1206. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1207. #else
  1208. EXPECT_TRUE(ret == detail::EncodingType::None);
  1209. #endif
  1210. }
  1211. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1212. Request req;
  1213. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1214. Response res;
  1215. res.set_header("Content-Type", "text/plain");
  1216. auto ret = detail::encoding_type(req, res);
  1217. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1218. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1219. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1220. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1221. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1222. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1223. #else
  1224. EXPECT_TRUE(ret == detail::EncodingType::None);
  1225. #endif
  1226. }
  1227. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1228. Request req;
  1229. req.set_header("Accept-Encoding",
  1230. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1231. Response res;
  1232. res.set_header("Content-Type", "text/plain");
  1233. auto ret = detail::encoding_type(req, res);
  1234. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1235. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1236. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1237. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1238. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1239. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1240. #else
  1241. EXPECT_TRUE(ret == detail::EncodingType::None);
  1242. #endif
  1243. }
  1244. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1245. // All supported encodings rejected with q=0 should return None
  1246. Request req;
  1247. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1248. Response res;
  1249. res.set_header("Content-Type", "text/plain");
  1250. auto ret = detail::encoding_type(req, res);
  1251. EXPECT_TRUE(ret == detail::EncodingType::None);
  1252. }
  1253. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1254. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1255. Request req;
  1256. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1257. Response res;
  1258. res.set_header("Content-Type", "text/plain");
  1259. auto ret = detail::encoding_type(req, res);
  1260. EXPECT_TRUE(ret == detail::EncodingType::None);
  1261. }
  1262. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1263. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1264. Request req;
  1265. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1266. Response res;
  1267. res.set_header("Content-Type", "text/plain");
  1268. auto ret = detail::encoding_type(req, res);
  1269. EXPECT_TRUE(ret == detail::EncodingType::None);
  1270. }
  1271. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1272. // RFC 7231: Accept-Encoding values are case-insensitive
  1273. Request req;
  1274. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1275. Response res;
  1276. res.set_header("Content-Type", "text/plain");
  1277. auto ret = detail::encoding_type(req, res);
  1278. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1279. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1280. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1281. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1282. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1283. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1284. #else
  1285. EXPECT_TRUE(ret == detail::EncodingType::None);
  1286. #endif
  1287. }
  1288. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1289. // q value should determine priority, not hardcoded order
  1290. Request req;
  1291. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1292. Response res;
  1293. res.set_header("Content-Type", "text/plain");
  1294. auto ret = detail::encoding_type(req, res);
  1295. // gzip has highest q=1.0, so it should be selected even though
  1296. // br and zstd are also supported
  1297. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1298. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1299. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1300. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1301. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1302. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1303. #else
  1304. EXPECT_TRUE(ret == detail::EncodingType::None);
  1305. #endif
  1306. }
  1307. TEST(BufferStreamTest, read) {
  1308. detail::BufferStream strm1;
  1309. Stream &strm = strm1;
  1310. EXPECT_EQ(5, strm.write("hello"));
  1311. char buf[512];
  1312. EXPECT_EQ(2, strm.read(buf, 2));
  1313. EXPECT_EQ('h', buf[0]);
  1314. EXPECT_EQ('e', buf[1]);
  1315. EXPECT_EQ(2, strm.read(buf, 2));
  1316. EXPECT_EQ('l', buf[0]);
  1317. EXPECT_EQ('l', buf[1]);
  1318. EXPECT_EQ(1, strm.read(buf, 1));
  1319. EXPECT_EQ('o', buf[0]);
  1320. EXPECT_EQ(0, strm.read(buf, 1));
  1321. }
  1322. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1323. auto host = "www.httpwatch.com";
  1324. auto ip = hosted_at(host);
  1325. EXPECT_EQ("23.96.13.243", ip);
  1326. std::vector<std::string> addrs;
  1327. hosted_at(host, addrs);
  1328. EXPECT_EQ(1u, addrs.size());
  1329. }
  1330. #if 0 // It depends on each test environment...
  1331. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1332. auto host = "www.youtube.com";
  1333. std::vector<std::string> addrs;
  1334. hosted_at(host, addrs);
  1335. EXPECT_EQ(20u, addrs.size());
  1336. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1337. EXPECT_TRUE(it != addrs.end());
  1338. }
  1339. #endif
  1340. class ChunkedEncodingTest : public ::testing::Test {
  1341. protected:
  1342. ChunkedEncodingTest()
  1343. : cli_(HOST, PORT)
  1344. #ifdef CPPHTTPLIB_SSL_ENABLED
  1345. ,
  1346. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1347. #endif
  1348. {
  1349. cli_.set_connection_timeout(2);
  1350. #ifdef CPPHTTPLIB_SSL_ENABLED
  1351. cli_.enable_server_certificate_verification(false);
  1352. #endif
  1353. }
  1354. virtual void SetUp() {
  1355. read_file("./image.jpg", image_data_);
  1356. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1357. res.set_content("Hello World!", "text/plain");
  1358. });
  1359. svr_.Get(
  1360. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1361. res.set_chunked_content_provider(
  1362. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1363. size_t remaining = image_data_.size() - offset;
  1364. if (remaining == 0) {
  1365. sink.done();
  1366. } else {
  1367. constexpr size_t CHUNK_SIZE = 1024;
  1368. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1369. sink.write(&image_data_[offset], send_size);
  1370. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1371. }
  1372. return true;
  1373. });
  1374. });
  1375. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1376. svr_.wait_until_ready();
  1377. }
  1378. virtual void TearDown() {
  1379. svr_.stop();
  1380. if (!request_threads_.empty()) {
  1381. std::this_thread::sleep_for(std::chrono::seconds(1));
  1382. for (auto &t : request_threads_) {
  1383. t.join();
  1384. }
  1385. }
  1386. t_.join();
  1387. }
  1388. #ifdef CPPHTTPLIB_SSL_ENABLED
  1389. SSLClient cli_;
  1390. SSLServer svr_;
  1391. #else
  1392. Client cli_;
  1393. Server svr_;
  1394. #endif
  1395. thread t_;
  1396. std::vector<thread> request_threads_;
  1397. std::string image_data_;
  1398. };
  1399. TEST_F(ChunkedEncodingTest, NormalGet) {
  1400. auto res = cli_.Get("/chunked");
  1401. ASSERT_TRUE(res);
  1402. std::string out;
  1403. read_file("./image.jpg", out);
  1404. EXPECT_EQ(StatusCode::OK_200, res->status);
  1405. EXPECT_EQ(out, res->body);
  1406. }
  1407. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1408. std::string body;
  1409. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1410. body.append(data, data_length);
  1411. return true;
  1412. });
  1413. ASSERT_TRUE(res);
  1414. std::string out;
  1415. read_file("./image.jpg", out);
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. EXPECT_EQ(out, body);
  1418. }
  1419. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1420. std::string body;
  1421. auto res = cli_.Get(
  1422. "/chunked",
  1423. [&](const Response &response) {
  1424. EXPECT_EQ(StatusCode::OK_200, response.status);
  1425. return true;
  1426. },
  1427. [&](const char *data, size_t data_length) {
  1428. body.append(data, data_length);
  1429. return true;
  1430. });
  1431. ASSERT_TRUE(res);
  1432. std::string out;
  1433. read_file("./image.jpg", out);
  1434. EXPECT_EQ(StatusCode::OK_200, res->status);
  1435. EXPECT_EQ(out, body);
  1436. }
  1437. TEST(RangeTest, FromHTTPBin_Online) {
  1438. auto host = "httpbingo.org";
  1439. auto path = std::string{"/range/32"};
  1440. #ifdef CPPHTTPLIB_SSL_ENABLED
  1441. auto port = 443;
  1442. SSLClient cli(host, port);
  1443. #else
  1444. auto port = 80;
  1445. Client cli(host, port);
  1446. #endif
  1447. cli.set_connection_timeout(5);
  1448. {
  1449. auto res = cli.Get(path);
  1450. ASSERT_TRUE(res);
  1451. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1452. EXPECT_EQ(StatusCode::OK_200, res->status);
  1453. }
  1454. {
  1455. Headers headers = {make_range_header({{1, -1}})};
  1456. auto res = cli.Get(path, headers);
  1457. ASSERT_TRUE(res);
  1458. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1459. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1460. }
  1461. {
  1462. Headers headers = {make_range_header({{1, 10}})};
  1463. auto res = cli.Get(path, headers);
  1464. ASSERT_TRUE(res);
  1465. EXPECT_EQ("bcdefghijk", res->body);
  1466. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1467. }
  1468. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1469. // entire resource, while the original httpbin returned 200. Both are
  1470. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1471. {
  1472. Headers headers = {make_range_header({{0, 31}})};
  1473. auto res = cli.Get(path, headers);
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1476. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1477. res->status == StatusCode::PartialContent_206);
  1478. }
  1479. {
  1480. Headers headers = {make_range_header({{0, -1}})};
  1481. auto res = cli.Get(path, headers);
  1482. ASSERT_TRUE(res);
  1483. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1484. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1485. res->status == StatusCode::PartialContent_206);
  1486. }
  1487. // go-httpbin returns 206 with clamped range for over-range requests,
  1488. // while the original httpbin returned 416. Both behaviors are observed
  1489. // in real servers, so we only verify the request succeeds.
  1490. {
  1491. Headers headers = {make_range_header({{0, 32}})};
  1492. auto res = cli.Get(path, headers);
  1493. ASSERT_TRUE(res);
  1494. }
  1495. }
  1496. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1497. auto host = "unresolvableaddress.local";
  1498. auto path = std::string{"/"};
  1499. #ifdef CPPHTTPLIB_SSL_ENABLED
  1500. auto port = 443;
  1501. SSLClient cli(host, port);
  1502. #else
  1503. auto port = 80;
  1504. Client cli(host, port);
  1505. #endif
  1506. cli.set_connection_timeout(1);
  1507. {
  1508. auto res = cli.Get(path);
  1509. ASSERT_FALSE(res);
  1510. }
  1511. std::this_thread::sleep_for(std::chrono::seconds(8));
  1512. }
  1513. #if defined(__linux__) && defined(__GLIBC__) && \
  1514. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1515. // Forward declaration: in split builds split.py strips `inline` and moves the
  1516. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1517. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1518. // against the symbol in both header-only and split builds.
  1519. namespace httplib {
  1520. namespace detail {
  1521. int getaddrinfo_with_timeout(const char *node, const char *service,
  1522. const struct addrinfo *hints,
  1523. struct addrinfo **res, time_t timeout_sec);
  1524. } // namespace detail
  1525. } // namespace httplib
  1526. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1527. //
  1528. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1529. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1530. // gai_suspend() call hits the connection timeout the function calls
  1531. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1532. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1533. // still alive and still references the now-destroyed stack frame.
  1534. //
  1535. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1536. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1537. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1538. // and runs them in a container.
  1539. namespace {
  1540. bool should_run_issue_2431_tests() {
  1541. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1542. return v && *v && std::string(v) != "0";
  1543. }
  1544. std::string unique_unresolvable_host(int n) {
  1545. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1546. // glibc still asks the configured nameserver — which is exactly the path
  1547. // we want to exercise. A unique label per call avoids the resolver cache.
  1548. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1549. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1550. std::to_string(n) + ".invalid";
  1551. }
  1552. } // namespace
  1553. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1554. if (!should_run_issue_2431_tests()) {
  1555. GTEST_SKIP()
  1556. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1557. }
  1558. for (int i = 0; i < 8; ++i) {
  1559. struct addrinfo hints;
  1560. memset(&hints, 0, sizeof(hints));
  1561. hints.ai_family = AF_UNSPEC;
  1562. hints.ai_socktype = SOCK_STREAM;
  1563. auto host = unique_unresolvable_host(i);
  1564. struct addrinfo *result = nullptr;
  1565. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1566. &result, /*timeout_sec=*/1);
  1567. if (rc == 0 && result) { freeaddrinfo(result); }
  1568. }
  1569. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1570. // stack region they still believe holds their gaicb.
  1571. std::this_thread::sleep_for(std::chrono::seconds(3));
  1572. }
  1573. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1574. if (!should_run_issue_2431_tests()) {
  1575. GTEST_SKIP()
  1576. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1577. }
  1578. std::atomic<bool> stop{false};
  1579. std::vector<std::thread> threads;
  1580. for (int t = 0; t < 8; ++t) {
  1581. threads.emplace_back([t, &stop] {
  1582. int i = 0;
  1583. while (!stop.load(std::memory_order_relaxed)) {
  1584. struct addrinfo hints;
  1585. memset(&hints, 0, sizeof(hints));
  1586. hints.ai_family = AF_UNSPEC;
  1587. hints.ai_socktype = SOCK_STREAM;
  1588. auto host = unique_unresolvable_host(t * 100000 + i++);
  1589. struct addrinfo *result = nullptr;
  1590. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1591. &result, /*timeout_sec=*/1);
  1592. if (rc == 0 && result) { freeaddrinfo(result); }
  1593. }
  1594. });
  1595. }
  1596. std::this_thread::sleep_for(std::chrono::seconds(8));
  1597. stop.store(true, std::memory_order_relaxed);
  1598. for (auto &th : threads) {
  1599. th.join();
  1600. }
  1601. std::this_thread::sleep_for(std::chrono::seconds(3));
  1602. }
  1603. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1604. if (!should_run_issue_2431_tests()) {
  1605. GTEST_SKIP()
  1606. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1607. }
  1608. std::atomic<bool> stop{false};
  1609. std::vector<std::thread> threads;
  1610. for (int t = 0; t < 8; ++t) {
  1611. threads.emplace_back([t, &stop] {
  1612. int i = 0;
  1613. while (!stop.load(std::memory_order_relaxed)) {
  1614. auto host = unique_unresolvable_host(t * 100000 + i++);
  1615. Client cli(host, 80);
  1616. cli.set_connection_timeout(1, 0);
  1617. cli.set_read_timeout(1, 0);
  1618. cli.set_write_timeout(1, 0);
  1619. (void)cli.Get("/");
  1620. }
  1621. });
  1622. }
  1623. std::this_thread::sleep_for(std::chrono::seconds(8));
  1624. stop.store(true, std::memory_order_relaxed);
  1625. for (auto &th : threads) {
  1626. th.join();
  1627. }
  1628. std::this_thread::sleep_for(std::chrono::seconds(3));
  1629. }
  1630. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1631. TEST(ConnectionErrorTest, InvalidHost) {
  1632. auto host = "-abcde.com";
  1633. #ifdef CPPHTTPLIB_SSL_ENABLED
  1634. auto port = 443;
  1635. SSLClient cli(host, port);
  1636. #else
  1637. auto port = 80;
  1638. Client cli(host, port);
  1639. #endif
  1640. cli.set_connection_timeout(std::chrono::seconds(2));
  1641. auto res = cli.Get("/");
  1642. ASSERT_TRUE(!res);
  1643. EXPECT_EQ(Error::Connection, res.error());
  1644. }
  1645. TEST(ConnectionErrorTest, InvalidHost2) {
  1646. auto host = "httpcan.org/";
  1647. #ifdef CPPHTTPLIB_SSL_ENABLED
  1648. SSLClient cli(host);
  1649. #else
  1650. Client cli(host);
  1651. #endif
  1652. cli.set_connection_timeout(std::chrono::seconds(2));
  1653. auto res = cli.Get("/");
  1654. ASSERT_TRUE(!res);
  1655. EXPECT_EQ(Error::Connection, res.error());
  1656. }
  1657. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1658. auto host = "httpcan.org/";
  1659. #ifdef CPPHTTPLIB_SSL_ENABLED
  1660. SSLClient cli(host);
  1661. #else
  1662. Client cli(host);
  1663. #endif
  1664. cli.set_connection_timeout(std::chrono::seconds(2));
  1665. auto res = cli.Get("/");
  1666. ASSERT_TRUE(!res);
  1667. stringstream s;
  1668. s << "error code: " << res.error();
  1669. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1670. }
  1671. TEST(ConnectionErrorTest, InvalidPort) {
  1672. auto host = "localhost";
  1673. auto port = 44380;
  1674. #ifdef CPPHTTPLIB_SSL_ENABLED
  1675. SSLClient cli(host, port);
  1676. #else
  1677. Client cli(host, port);
  1678. #endif
  1679. cli.set_connection_timeout(std::chrono::seconds(2));
  1680. auto res = cli.Get("/");
  1681. ASSERT_TRUE(!res);
  1682. EXPECT_TRUE(Error::Connection == res.error() ||
  1683. Error::ConnectionTimeout == res.error());
  1684. }
  1685. TEST(ConnectionErrorTest, Timeout_Online) {
  1686. auto host = "google.com";
  1687. #ifdef CPPHTTPLIB_SSL_ENABLED
  1688. auto port = 44380;
  1689. SSLClient cli(host, port);
  1690. #else
  1691. auto port = 8080;
  1692. Client cli(host, port);
  1693. #endif
  1694. cli.set_connection_timeout(std::chrono::seconds(2));
  1695. // only probe one address type so that the error reason
  1696. // correlates to the timed-out IPv4, not the unsupported
  1697. // IPv6 connection attempt
  1698. cli.set_address_family(AF_INET);
  1699. auto res = cli.Get("/");
  1700. ASSERT_TRUE(!res);
  1701. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1702. }
  1703. TEST(CancelTest, NoCancel_Online) {
  1704. auto host = "httpbingo.org";
  1705. auto path = std::string{"/range/32"};
  1706. #ifdef CPPHTTPLIB_SSL_ENABLED
  1707. auto port = 443;
  1708. SSLClient cli(host, port);
  1709. #else
  1710. auto port = 80;
  1711. Client cli(host, port);
  1712. #endif
  1713. cli.set_connection_timeout(std::chrono::seconds(5));
  1714. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1715. ASSERT_TRUE(res);
  1716. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1717. EXPECT_EQ(StatusCode::OK_200, res->status);
  1718. }
  1719. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1720. // Use /bytes with a large payload so that the DownloadProgress callback
  1721. // (which only fires for Content-Length responses) is invoked before the
  1722. // entire body is received, giving cancellation a chance to fire.
  1723. auto host = "httpbingo.org";
  1724. auto path = std::string{"/bytes/524288"};
  1725. #ifdef CPPHTTPLIB_SSL_ENABLED
  1726. auto port = 443;
  1727. SSLClient cli(host, port);
  1728. #else
  1729. auto port = 80;
  1730. Client cli(host, port);
  1731. #endif
  1732. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1733. cli.set_connection_timeout(std::chrono::seconds(5));
  1734. ASSERT_TRUE(!res);
  1735. EXPECT_EQ(Error::Canceled, res.error());
  1736. }
  1737. TEST(CancelTest, WithCancelLargePayload_Online) {
  1738. auto host = "httpbingo.org";
  1739. auto path = std::string{"/bytes/524288"};
  1740. #ifdef CPPHTTPLIB_SSL_ENABLED
  1741. auto port = 443;
  1742. SSLClient cli(host, port);
  1743. #else
  1744. auto port = 80;
  1745. Client cli(host, port);
  1746. #endif
  1747. cli.set_connection_timeout(std::chrono::seconds(5));
  1748. uint32_t count = 0;
  1749. auto res =
  1750. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1751. ASSERT_TRUE(!res);
  1752. EXPECT_EQ(Error::Canceled, res.error());
  1753. }
  1754. TEST(CancelTest, NoCancelPost) {
  1755. Server svr;
  1756. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1757. res.set_content("Hello World!", "text/plain");
  1758. });
  1759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1760. auto se = detail::scope_exit([&] {
  1761. svr.stop();
  1762. thread.join();
  1763. ASSERT_FALSE(svr.is_running());
  1764. });
  1765. svr.wait_until_ready();
  1766. Client cli(HOST, PORT);
  1767. cli.set_connection_timeout(std::chrono::seconds(5));
  1768. auto res =
  1769. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1770. "application/json", [](uint64_t, uint64_t) { return true; });
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ("Hello World!", res->body);
  1773. EXPECT_EQ(StatusCode::OK_200, res->status);
  1774. }
  1775. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1776. Server svr;
  1777. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1778. res.set_content("Hello World!", "text/plain");
  1779. });
  1780. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1781. auto se = detail::scope_exit([&] {
  1782. svr.stop();
  1783. thread.join();
  1784. ASSERT_FALSE(svr.is_running());
  1785. });
  1786. svr.wait_until_ready();
  1787. Client cli(HOST, PORT);
  1788. cli.set_connection_timeout(std::chrono::seconds(5));
  1789. auto res =
  1790. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1791. "application/json", [](uint64_t, uint64_t) { return false; });
  1792. ASSERT_TRUE(!res);
  1793. EXPECT_EQ(Error::Canceled, res.error());
  1794. }
  1795. TEST(CancelTest, WithCancelLargePayloadPost) {
  1796. Server svr;
  1797. svr.set_payload_max_length(200 * 1024 * 1024);
  1798. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1799. res.set_content(LARGE_DATA, "text/plain");
  1800. });
  1801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1802. auto se = detail::scope_exit([&] {
  1803. svr.stop();
  1804. thread.join();
  1805. ASSERT_FALSE(svr.is_running());
  1806. });
  1807. svr.wait_until_ready();
  1808. Client cli(HOST, PORT);
  1809. cli.set_payload_max_length(200 * 1024 * 1024);
  1810. cli.set_connection_timeout(std::chrono::seconds(5));
  1811. auto res =
  1812. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1813. "application/json", [](uint64_t, uint64_t) { return false; });
  1814. ASSERT_TRUE(!res);
  1815. EXPECT_EQ(Error::Canceled, res.error());
  1816. }
  1817. TEST(CancelTest, NoCancelPut) {
  1818. Server svr;
  1819. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1820. res.set_content("Hello World!", "text/plain");
  1821. });
  1822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1823. auto se = detail::scope_exit([&] {
  1824. svr.stop();
  1825. thread.join();
  1826. ASSERT_FALSE(svr.is_running());
  1827. });
  1828. svr.wait_until_ready();
  1829. Client cli(HOST, PORT);
  1830. cli.set_connection_timeout(std::chrono::seconds(5));
  1831. auto res =
  1832. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1833. "application/json", [](uint64_t, uint64_t) { return true; });
  1834. ASSERT_TRUE(res);
  1835. EXPECT_EQ("Hello World!", res->body);
  1836. EXPECT_EQ(StatusCode::OK_200, res->status);
  1837. }
  1838. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1839. Server svr;
  1840. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1841. res.set_content("Hello World!", "text/plain");
  1842. });
  1843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1844. auto se = detail::scope_exit([&] {
  1845. svr.stop();
  1846. thread.join();
  1847. ASSERT_FALSE(svr.is_running());
  1848. });
  1849. svr.wait_until_ready();
  1850. Client cli(HOST, PORT);
  1851. cli.set_connection_timeout(std::chrono::seconds(5));
  1852. auto res =
  1853. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1854. "application/json", [](uint64_t, uint64_t) { return false; });
  1855. ASSERT_TRUE(!res);
  1856. EXPECT_EQ(Error::Canceled, res.error());
  1857. }
  1858. TEST(CancelTest, WithCancelLargePayloadPut) {
  1859. Server svr;
  1860. svr.set_payload_max_length(200 * 1024 * 1024);
  1861. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1862. res.set_content(LARGE_DATA, "text/plain");
  1863. });
  1864. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1865. auto se = detail::scope_exit([&] {
  1866. svr.stop();
  1867. thread.join();
  1868. ASSERT_FALSE(svr.is_running());
  1869. });
  1870. svr.wait_until_ready();
  1871. Client cli(HOST, PORT);
  1872. cli.set_payload_max_length(200 * 1024 * 1024);
  1873. cli.set_connection_timeout(std::chrono::seconds(5));
  1874. auto res =
  1875. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1876. "application/json", [](uint64_t, uint64_t) { return false; });
  1877. ASSERT_TRUE(!res);
  1878. EXPECT_EQ(Error::Canceled, res.error());
  1879. }
  1880. TEST(CancelTest, NoCancelPatch) {
  1881. Server svr;
  1882. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1883. res.set_content("Hello World!", "text/plain");
  1884. });
  1885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1886. auto se = detail::scope_exit([&] {
  1887. svr.stop();
  1888. thread.join();
  1889. ASSERT_FALSE(svr.is_running());
  1890. });
  1891. svr.wait_until_ready();
  1892. Client cli(HOST, PORT);
  1893. cli.set_connection_timeout(std::chrono::seconds(5));
  1894. auto res =
  1895. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1896. "application/json", [](uint64_t, uint64_t) { return true; });
  1897. ASSERT_TRUE(res);
  1898. EXPECT_EQ("Hello World!", res->body);
  1899. EXPECT_EQ(StatusCode::OK_200, res->status);
  1900. }
  1901. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1902. Server svr;
  1903. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1904. res.set_content("Hello World!", "text/plain");
  1905. });
  1906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1907. auto se = detail::scope_exit([&] {
  1908. svr.stop();
  1909. thread.join();
  1910. ASSERT_FALSE(svr.is_running());
  1911. });
  1912. svr.wait_until_ready();
  1913. Client cli(HOST, PORT);
  1914. cli.set_connection_timeout(std::chrono::seconds(5));
  1915. auto res =
  1916. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1917. "application/json", [](uint64_t, uint64_t) { return false; });
  1918. ASSERT_TRUE(!res);
  1919. EXPECT_EQ(Error::Canceled, res.error());
  1920. }
  1921. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1922. Server svr;
  1923. svr.set_payload_max_length(200 * 1024 * 1024);
  1924. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1925. res.set_content(LARGE_DATA, "text/plain");
  1926. });
  1927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1928. auto se = detail::scope_exit([&] {
  1929. svr.stop();
  1930. thread.join();
  1931. ASSERT_FALSE(svr.is_running());
  1932. });
  1933. svr.wait_until_ready();
  1934. Client cli(HOST, PORT);
  1935. cli.set_payload_max_length(200 * 1024 * 1024);
  1936. cli.set_connection_timeout(std::chrono::seconds(5));
  1937. auto res =
  1938. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1939. "application/json", [](uint64_t, uint64_t) { return false; });
  1940. ASSERT_TRUE(!res);
  1941. EXPECT_EQ(Error::Canceled, res.error());
  1942. }
  1943. TEST(CancelTest, NoCancelDelete) {
  1944. Server svr;
  1945. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1946. res.set_content("Hello World!", "text/plain");
  1947. });
  1948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1949. auto se = detail::scope_exit([&] {
  1950. svr.stop();
  1951. thread.join();
  1952. ASSERT_FALSE(svr.is_running());
  1953. });
  1954. svr.wait_until_ready();
  1955. Client cli(HOST, PORT);
  1956. cli.set_connection_timeout(std::chrono::seconds(5));
  1957. auto res =
  1958. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1959. "application/json", [](uint64_t, uint64_t) { return true; });
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ("Hello World!", res->body);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. }
  1964. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1965. Server svr;
  1966. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1967. res.set_content("Hello World!", "text/plain");
  1968. });
  1969. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1970. auto se = detail::scope_exit([&] {
  1971. svr.stop();
  1972. thread.join();
  1973. ASSERT_FALSE(svr.is_running());
  1974. });
  1975. svr.wait_until_ready();
  1976. Client cli(HOST, PORT);
  1977. cli.set_connection_timeout(std::chrono::seconds(5));
  1978. auto res =
  1979. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1980. "application/json", [](uint64_t, uint64_t) { return false; });
  1981. ASSERT_TRUE(!res);
  1982. EXPECT_EQ(Error::Canceled, res.error());
  1983. }
  1984. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1985. Server svr;
  1986. svr.set_payload_max_length(200 * 1024 * 1024);
  1987. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1988. res.set_content(LARGE_DATA, "text/plain");
  1989. });
  1990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. Client cli(HOST, PORT);
  1998. cli.set_payload_max_length(200 * 1024 * 1024);
  1999. cli.set_connection_timeout(std::chrono::seconds(5));
  2000. auto res =
  2001. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2002. "application/json", [](uint64_t, uint64_t) { return false; });
  2003. ASSERT_TRUE(!res);
  2004. EXPECT_EQ(Error::Canceled, res.error());
  2005. }
  2006. static std::string remove_whitespace(const std::string &input) {
  2007. std::string output;
  2008. output.reserve(input.size());
  2009. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2010. [](unsigned char c) { return !std::isspace(c); });
  2011. return output;
  2012. }
  2013. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2014. auto host = "httpbingo.org";
  2015. auto path = std::string{"/basic-auth/hello/world"};
  2016. #ifdef CPPHTTPLIB_SSL_ENABLED
  2017. auto port = 443;
  2018. SSLClient cli(host, port);
  2019. #else
  2020. auto port = 80;
  2021. Client cli(host, port);
  2022. #endif
  2023. {
  2024. auto res = cli.Get(path);
  2025. ASSERT_TRUE(res);
  2026. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2027. }
  2028. {
  2029. auto res = cli.Get(
  2030. path, Headers{make_basic_authentication_header("hello", "world")});
  2031. ASSERT_TRUE(res);
  2032. auto body = remove_whitespace(res->body);
  2033. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2034. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2035. EXPECT_EQ(StatusCode::OK_200, res->status);
  2036. }
  2037. {
  2038. cli.set_basic_auth("hello", "world");
  2039. auto res = cli.Get(path);
  2040. ASSERT_TRUE(res);
  2041. auto body = remove_whitespace(res->body);
  2042. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2043. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2044. EXPECT_EQ(StatusCode::OK_200, res->status);
  2045. }
  2046. {
  2047. cli.set_basic_auth("hello", "bad");
  2048. auto res = cli.Get(path);
  2049. ASSERT_TRUE(res);
  2050. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2051. }
  2052. {
  2053. cli.set_basic_auth("bad", "world");
  2054. auto res = cli.Get(path);
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2057. }
  2058. }
  2059. #ifdef CPPHTTPLIB_SSL_ENABLED
  2060. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2061. auto host = "httpbingo.org";
  2062. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2063. auto paths = std::vector<std::string>{
  2064. "/digest-auth/auth/hello/world/MD5",
  2065. "/digest-auth/auth/hello/world/SHA-256",
  2066. };
  2067. auto port = 443;
  2068. SSLClient cli(host, port);
  2069. {
  2070. auto res = cli.Get(unauth_path);
  2071. ASSERT_TRUE(res);
  2072. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2073. }
  2074. {
  2075. cli.set_digest_auth("hello", "world");
  2076. for (const auto &path : paths) {
  2077. auto res = cli.Get(path.c_str());
  2078. ASSERT_TRUE(res);
  2079. auto body = remove_whitespace(res->body);
  2080. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2081. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2082. EXPECT_EQ(StatusCode::OK_200, res->status);
  2083. }
  2084. cli.set_digest_auth("hello", "bad");
  2085. for (const auto &path : paths) {
  2086. auto res = cli.Get(path.c_str());
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2089. }
  2090. }
  2091. }
  2092. #endif
  2093. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2094. auto host = "google.com";
  2095. auto another_host = "example.com";
  2096. auto wrong_ip = "0.0.0.0";
  2097. #ifdef CPPHTTPLIB_SSL_ENABLED
  2098. SSLClient cli(host);
  2099. #else
  2100. Client cli(host);
  2101. #endif
  2102. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2103. auto res = cli.Get("/");
  2104. ASSERT_TRUE(res);
  2105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2106. }
  2107. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2108. auto host = "google.com";
  2109. auto wrong_ip = "0.0.0.0";
  2110. #ifdef CPPHTTPLIB_SSL_ENABLED
  2111. SSLClient cli(host);
  2112. #else
  2113. Client cli(host);
  2114. #endif
  2115. cli.set_hostname_addr_map({{host, wrong_ip}});
  2116. auto res = cli.Get("/");
  2117. ASSERT_TRUE(!res);
  2118. EXPECT_EQ(Error::Connection, res.error());
  2119. }
  2120. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2121. auto host = "httpbingo.org";
  2122. auto path = std::string{"/absolute-redirect/3"};
  2123. #ifdef CPPHTTPLIB_SSL_ENABLED
  2124. SSLClient cli(host);
  2125. #else
  2126. Client cli(host);
  2127. #endif
  2128. cli.set_follow_location(true);
  2129. auto res = cli.Get(path);
  2130. ASSERT_TRUE(res);
  2131. EXPECT_EQ(StatusCode::OK_200, res->status);
  2132. }
  2133. TEST(RedirectTest, Redirect_Online) {
  2134. auto host = "httpbingo.org";
  2135. auto path = std::string{"/redirect/3"};
  2136. #ifdef CPPHTTPLIB_SSL_ENABLED
  2137. SSLClient cli(host);
  2138. #else
  2139. Client cli(host);
  2140. #endif
  2141. cli.set_follow_location(true);
  2142. auto res = cli.Get(path);
  2143. ASSERT_TRUE(res);
  2144. EXPECT_EQ(StatusCode::OK_200, res->status);
  2145. }
  2146. TEST(RelativeRedirectTest, Redirect_Online) {
  2147. auto host = "httpbingo.org";
  2148. auto path = std::string{"/relative-redirect/3"};
  2149. #ifdef CPPHTTPLIB_SSL_ENABLED
  2150. SSLClient cli(host);
  2151. #else
  2152. Client cli(host);
  2153. #endif
  2154. cli.set_follow_location(true);
  2155. auto res = cli.Get(path);
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(StatusCode::OK_200, res->status);
  2158. }
  2159. TEST(TooManyRedirectTest, Redirect_Online) {
  2160. auto host = "httpbingo.org";
  2161. auto path = std::string{"/redirect/21"};
  2162. #ifdef CPPHTTPLIB_SSL_ENABLED
  2163. SSLClient cli(host);
  2164. #else
  2165. Client cli(host);
  2166. #endif
  2167. cli.set_follow_location(true);
  2168. auto res = cli.Get(path);
  2169. ASSERT_TRUE(!res);
  2170. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2171. }
  2172. #ifdef CPPHTTPLIB_SSL_ENABLED
  2173. TEST(YahooRedirectTest, Redirect_Online) {
  2174. Client cli("yahoo.com");
  2175. auto res = cli.Get("/");
  2176. ASSERT_TRUE(res);
  2177. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2178. cli.set_follow_location(true);
  2179. res = cli.Get("/");
  2180. ASSERT_TRUE(res);
  2181. EXPECT_EQ(StatusCode::OK_200, res->status);
  2182. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2183. }
  2184. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2185. #define REDIR_HOST "httpbingo.org"
  2186. #define REDIR_PATH "/redirect-to"
  2187. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2188. SSLClient cli(REDIR_HOST);
  2189. cli.set_follow_location(true);
  2190. auto res =
  2191. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2192. ASSERT_TRUE(res);
  2193. EXPECT_EQ(StatusCode::OK_200, res->status);
  2194. }
  2195. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2196. SSLClient cli(REDIR_HOST);
  2197. cli.set_follow_location(true);
  2198. Params params;
  2199. params.emplace("url", "http://example.com");
  2200. params.emplace("status_code", "302");
  2201. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2202. ASSERT_TRUE(res);
  2203. EXPECT_EQ(StatusCode::OK_200, res->status);
  2204. }
  2205. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2206. SSLClient cli(REDIR_HOST);
  2207. cli.set_follow_location(true);
  2208. Params params;
  2209. params.emplace("url", "http://example.com");
  2210. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2211. ASSERT_TRUE(res);
  2212. EXPECT_EQ(StatusCode::OK_200, res->status);
  2213. }
  2214. TEST(UrlWithSpace, Redirect_Online) {
  2215. SSLClient cli("edge.forgecdn.net");
  2216. cli.set_follow_location(true);
  2217. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2218. ASSERT_TRUE(res);
  2219. EXPECT_EQ(StatusCode::OK_200, res->status);
  2220. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2221. }
  2222. #endif
  2223. #if !defined(_WIN32) && !defined(_WIN64)
  2224. TEST(ReceiveSignals, Signal) {
  2225. auto setupSignalHandlers = []() {
  2226. struct sigaction act;
  2227. sigemptyset(&act.sa_mask);
  2228. act.sa_flags = SA_SIGINFO;
  2229. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2230. switch (sig) {
  2231. case SIGINT:
  2232. default: break;
  2233. }
  2234. };
  2235. ::sigaction(SIGINT, &act, nullptr);
  2236. };
  2237. Server svr;
  2238. int port = 0;
  2239. auto thread = std::thread([&]() {
  2240. setupSignalHandlers();
  2241. port = svr.bind_to_any_port(HOST);
  2242. svr.listen_after_bind();
  2243. });
  2244. auto se = detail::scope_exit([&] {
  2245. svr.stop();
  2246. thread.join();
  2247. ASSERT_FALSE(svr.is_running());
  2248. });
  2249. svr.wait_until_ready();
  2250. ASSERT_TRUE(svr.is_running());
  2251. pthread_kill(thread.native_handle(), SIGINT);
  2252. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2253. ASSERT_TRUE(svr.is_running());
  2254. }
  2255. #endif
  2256. TEST(RedirectToDifferentPort, Redirect) {
  2257. Server svr1;
  2258. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2259. res.set_content("Hello World!", "text/plain");
  2260. });
  2261. int svr1_port = 0;
  2262. auto thread1 = std::thread([&]() {
  2263. svr1_port = svr1.bind_to_any_port(HOST);
  2264. svr1.listen_after_bind();
  2265. });
  2266. Server svr2;
  2267. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2268. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2269. });
  2270. int svr2_port = 0;
  2271. auto thread2 = std::thread([&]() {
  2272. svr2_port = svr2.bind_to_any_port(HOST);
  2273. svr2.listen_after_bind();
  2274. });
  2275. auto se = detail::scope_exit([&] {
  2276. svr2.stop();
  2277. thread2.join();
  2278. svr1.stop();
  2279. thread1.join();
  2280. ASSERT_FALSE(svr2.is_running());
  2281. ASSERT_FALSE(svr1.is_running());
  2282. });
  2283. svr1.wait_until_ready();
  2284. svr2.wait_until_ready();
  2285. Client cli("localhost", svr2_port);
  2286. cli.set_follow_location(true);
  2287. auto res = cli.Get("/2");
  2288. ASSERT_TRUE(res);
  2289. EXPECT_EQ(StatusCode::OK_200, res->status);
  2290. EXPECT_EQ("Hello World!", res->body);
  2291. }
  2292. static void
  2293. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2294. Server svr1;
  2295. std::string captured_authorization;
  2296. svr1.Get("/target", [&](const Request &req, Response &res) {
  2297. captured_authorization = req.get_header_value("Authorization");
  2298. res.set_content("OK", "text/plain");
  2299. });
  2300. int svr1_port = 0;
  2301. auto thread1 = std::thread([&]() {
  2302. svr1_port = svr1.bind_to_any_port(HOST);
  2303. svr1.listen_after_bind();
  2304. });
  2305. Server svr2;
  2306. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2307. res.set_redirect(
  2308. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2309. });
  2310. int svr2_port = 0;
  2311. auto thread2 = std::thread([&]() {
  2312. svr2_port = svr2.bind_to_any_port(HOST);
  2313. svr2.listen_after_bind();
  2314. });
  2315. auto se = detail::scope_exit([&] {
  2316. svr2.stop();
  2317. thread2.join();
  2318. svr1.stop();
  2319. thread1.join();
  2320. ASSERT_FALSE(svr2.is_running());
  2321. ASSERT_FALSE(svr1.is_running());
  2322. });
  2323. svr1.wait_until_ready();
  2324. svr2.wait_until_ready();
  2325. Client cli("localhost", svr2_port);
  2326. cli.set_follow_location(true);
  2327. set_auth(cli);
  2328. auto res = cli.Get("/redir");
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(StatusCode::OK_200, res->status);
  2331. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2332. EXPECT_TRUE(captured_authorization.empty());
  2333. }
  2334. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2335. TestDoNotForwardCredentialsOnRedirect(
  2336. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2337. }
  2338. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2339. TestDoNotForwardCredentialsOnRedirect(
  2340. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2341. }
  2342. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2343. Server svr1;
  2344. std::string captured_cookie;
  2345. bool target_hit = false;
  2346. svr1.Get("/target", [&](const Request &req, Response &res) {
  2347. captured_cookie = req.get_header_value("Cookie");
  2348. target_hit = true;
  2349. res.set_content("OK", "text/plain");
  2350. });
  2351. int svr1_port = 0;
  2352. auto thread1 = std::thread([&]() {
  2353. svr1_port = svr1.bind_to_any_port(HOST);
  2354. svr1.listen_after_bind();
  2355. });
  2356. Server svr2;
  2357. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2358. res.set_redirect(
  2359. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2360. });
  2361. int svr2_port = 0;
  2362. auto thread2 = std::thread([&]() {
  2363. svr2_port = svr2.bind_to_any_port(HOST);
  2364. svr2.listen_after_bind();
  2365. });
  2366. auto se = detail::scope_exit([&] {
  2367. svr2.stop();
  2368. thread2.join();
  2369. svr1.stop();
  2370. thread1.join();
  2371. ASSERT_FALSE(svr2.is_running());
  2372. ASSERT_FALSE(svr1.is_running());
  2373. });
  2374. svr1.wait_until_ready();
  2375. svr2.wait_until_ready();
  2376. Client cli("localhost", svr2_port);
  2377. cli.set_follow_location(true);
  2378. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2379. auto res = cli.Get("/redir", headers);
  2380. ASSERT_TRUE(res);
  2381. EXPECT_EQ(StatusCode::OK_200, res->status);
  2382. EXPECT_TRUE(target_hit);
  2383. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2384. EXPECT_TRUE(captured_cookie.empty());
  2385. }
  2386. TEST(RedirectToSamePort, ForwardCookie) {
  2387. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2388. // header so that ordinary session flows keep working.
  2389. Server svr;
  2390. std::string captured_cookie;
  2391. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2392. res.set_redirect("/target", 302);
  2393. });
  2394. svr.Get("/target", [&](const Request &req, Response &res) {
  2395. captured_cookie = req.get_header_value("Cookie");
  2396. res.set_content("OK", "text/plain");
  2397. });
  2398. auto port = svr.bind_to_any_port(HOST);
  2399. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2400. auto se = detail::scope_exit([&] {
  2401. svr.stop();
  2402. thread.join();
  2403. ASSERT_FALSE(svr.is_running());
  2404. });
  2405. svr.wait_until_ready();
  2406. Client cli(HOST, port);
  2407. cli.set_follow_location(true);
  2408. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2409. auto res = cli.Get("/redir", headers);
  2410. ASSERT_TRUE(res);
  2411. EXPECT_EQ(StatusCode::OK_200, res->status);
  2412. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2413. }
  2414. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2415. Server svr;
  2416. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2417. // Port number that overflows int — should not crash
  2418. res.set_redirect("http://localhost:99999999999999999999/target");
  2419. });
  2420. auto port = svr.bind_to_any_port(HOST);
  2421. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2422. auto se = detail::scope_exit([&] {
  2423. svr.stop();
  2424. thread.join();
  2425. ASSERT_FALSE(svr.is_running());
  2426. });
  2427. svr.wait_until_ready();
  2428. Client cli(HOST, port);
  2429. cli.set_follow_location(true);
  2430. auto res = cli.Get("/redir");
  2431. // Should fail gracefully, not crash (no valid response due to bad port)
  2432. EXPECT_FALSE(res);
  2433. }
  2434. TEST(RedirectFromPageWithContent, Redirect) {
  2435. Server svr;
  2436. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2437. res.set_content("___", "text/plain");
  2438. res.set_redirect("/2");
  2439. });
  2440. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2441. res.set_content("Hello World!", "text/plain");
  2442. });
  2443. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2444. auto se = detail::scope_exit([&] {
  2445. svr.stop();
  2446. th.join();
  2447. ASSERT_FALSE(svr.is_running());
  2448. });
  2449. svr.wait_until_ready();
  2450. {
  2451. Client cli("localhost", PORT);
  2452. cli.set_follow_location(true);
  2453. std::string body;
  2454. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2455. body.append(data, data_length);
  2456. return true;
  2457. });
  2458. ASSERT_TRUE(res);
  2459. EXPECT_EQ(StatusCode::OK_200, res->status);
  2460. EXPECT_EQ("Hello World!", body);
  2461. }
  2462. {
  2463. Client cli("localhost", PORT);
  2464. std::string body;
  2465. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2466. body.append(data, data_length);
  2467. return true;
  2468. });
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::Found_302, res->status);
  2471. EXPECT_EQ("___", body);
  2472. }
  2473. }
  2474. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2475. Server svr;
  2476. auto port_str = std::to_string(PORT);
  2477. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2478. auto expected_host = "[::1]:" + port_str;
  2479. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2480. res.set_content("___", "text/plain");
  2481. // res.set_redirect("/2");
  2482. res.set_redirect(redirect_url);
  2483. });
  2484. svr.Get("/2", [&](const Request &req, Response &res) {
  2485. auto host_header = req.headers.find("Host");
  2486. ASSERT_TRUE(host_header != req.headers.end());
  2487. EXPECT_EQ(expected_host, host_header->second);
  2488. res.set_content("Hello World!", "text/plain");
  2489. });
  2490. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2491. auto se = detail::scope_exit([&] {
  2492. svr.stop();
  2493. th.join();
  2494. ASSERT_FALSE(svr.is_running());
  2495. });
  2496. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2497. // actually starts anything, so the condition !svr.is_running() will
  2498. // always remain true, and the loop never stops.
  2499. // This basically counts how many milliseconds have passed since the
  2500. // call to svr.listen(), and if after 5 seconds nothing started yet
  2501. // aborts the test.
  2502. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2503. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2504. ASSERT_LT(milliseconds, 5000U);
  2505. }
  2506. {
  2507. Client cli("::1", PORT);
  2508. cli.set_follow_location(true);
  2509. std::string body;
  2510. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2511. body.append(data, data_length);
  2512. return true;
  2513. });
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(StatusCode::OK_200, res->status);
  2516. EXPECT_EQ("Hello World!", body);
  2517. }
  2518. {
  2519. Client cli("::1", PORT);
  2520. std::string body;
  2521. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2522. body.append(data, data_length);
  2523. return true;
  2524. });
  2525. ASSERT_TRUE(res);
  2526. EXPECT_EQ(StatusCode::Found_302, res->status);
  2527. EXPECT_EQ("___", body);
  2528. }
  2529. }
  2530. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2531. Server svr;
  2532. svr.Get("/foo", [](const Request &req, Response &res) {
  2533. auto a = req.params.find("a");
  2534. if (a != req.params.end()) {
  2535. res.set_content((*a).second, "text/plain");
  2536. res.status = StatusCode::OK_200;
  2537. } else {
  2538. res.status = StatusCode::BadRequest_400;
  2539. }
  2540. });
  2541. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2542. auto se = detail::scope_exit([&] {
  2543. svr.stop();
  2544. thread.join();
  2545. ASSERT_FALSE(svr.is_running());
  2546. });
  2547. svr.wait_until_ready();
  2548. {
  2549. Client cli(HOST, PORT);
  2550. cli.set_path_encode(false);
  2551. auto res = cli.Get("/foo?a=explicitly+encoded");
  2552. ASSERT_TRUE(res);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. // This expects it back with a space, as the `+` won't have been
  2555. // url-encoded, and server-side the params get decoded turning `+`
  2556. // into spaces.
  2557. EXPECT_EQ("explicitly encoded", res->body);
  2558. }
  2559. }
  2560. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2561. // When path encoding is disabled the client must transmit the supplied
  2562. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2563. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2564. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2565. // than a space (0x20). Assert on the raw wire target to catch this.
  2566. Server svr;
  2567. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2568. svr.Get("/foo", [&](const Request &req, Response &res) {
  2569. EXPECT_EQ(expected_target, req.target);
  2570. res.status = StatusCode::OK_200;
  2571. });
  2572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. svr.wait_until_ready();
  2579. {
  2580. Client cli(HOST, PORT);
  2581. cli.set_path_encode(false);
  2582. auto res = cli.Get(expected_target.c_str());
  2583. ASSERT_TRUE(res);
  2584. EXPECT_EQ(StatusCode::OK_200, res->status);
  2585. }
  2586. }
  2587. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2588. Server svr;
  2589. svr.Get("/", [](const Request &req, Response &) {
  2590. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2591. });
  2592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2593. auto se = detail::scope_exit([&] {
  2594. svr.stop();
  2595. thread.join();
  2596. ASSERT_FALSE(svr.is_running());
  2597. });
  2598. svr.wait_until_ready();
  2599. {
  2600. Client cli(HOST, PORT);
  2601. cli.set_path_encode(false);
  2602. auto res = cli.Get("/?something=%0A");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(StatusCode::OK_200, res->status);
  2605. }
  2606. }
  2607. TEST(BindServerTest, BindDualStack) {
  2608. Server svr;
  2609. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2610. res.set_content("Hello World!", "text/plain");
  2611. });
  2612. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2613. auto se = detail::scope_exit([&] {
  2614. svr.stop();
  2615. thread.join();
  2616. ASSERT_FALSE(svr.is_running());
  2617. });
  2618. svr.wait_until_ready();
  2619. {
  2620. Client cli("127.0.0.1", PORT);
  2621. auto res = cli.Get("/1");
  2622. ASSERT_TRUE(res);
  2623. EXPECT_EQ(StatusCode::OK_200, res->status);
  2624. EXPECT_EQ("Hello World!", res->body);
  2625. }
  2626. {
  2627. Client cli("::1", PORT);
  2628. auto res = cli.Get("/1");
  2629. ASSERT_TRUE(res);
  2630. EXPECT_EQ(StatusCode::OK_200, res->status);
  2631. EXPECT_EQ("Hello World!", res->body);
  2632. }
  2633. }
  2634. TEST(BindServerTest, BindAndListenSeparately) {
  2635. Server svr;
  2636. int port = svr.bind_to_any_port("0.0.0.0");
  2637. ASSERT_TRUE(svr.is_valid());
  2638. ASSERT_TRUE(port > 0);
  2639. svr.stop();
  2640. }
  2641. #ifdef CPPHTTPLIB_SSL_ENABLED
  2642. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2644. CLIENT_CA_CERT_DIR);
  2645. int port = svr.bind_to_any_port("0.0.0.0");
  2646. ASSERT_TRUE(svr.is_valid());
  2647. ASSERT_TRUE(port > 0);
  2648. svr.stop();
  2649. }
  2650. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2651. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2652. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2653. int port = svr.bind_to_any_port("0.0.0.0");
  2654. ASSERT_TRUE(svr.is_valid());
  2655. ASSERT_TRUE(port > 0);
  2656. svr.stop();
  2657. }
  2658. TEST(BindServerTest, UpdateCertsPem) {
  2659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2660. int port = svr.bind_to_any_port("0.0.0.0");
  2661. ASSERT_TRUE(svr.is_valid());
  2662. ASSERT_TRUE(port > 0);
  2663. // Read PEM files
  2664. std::string cert_pem, key_pem, ca_pem;
  2665. read_file(SERVER_CERT_FILE, cert_pem);
  2666. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2667. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2668. // Update server certificates using PEM API
  2669. ASSERT_TRUE(
  2670. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2671. ASSERT_TRUE(svr.is_valid());
  2672. svr.stop();
  2673. }
  2674. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2675. // Start server with client CA (enables client auth)
  2676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2677. ASSERT_TRUE(svr.is_valid());
  2678. bool handler_called = false;
  2679. svr.Get("/test", [&](const Request &req, Response &res) {
  2680. handler_called = true;
  2681. // Verify client certificate is present
  2682. auto cert = req.peer_cert();
  2683. EXPECT_TRUE(static_cast<bool>(cert));
  2684. res.set_content("ok", "text/plain");
  2685. });
  2686. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2687. auto se = detail::scope_exit([&] {
  2688. svr.stop();
  2689. t.join();
  2690. ASSERT_FALSE(svr.is_running());
  2691. });
  2692. svr.wait_until_ready();
  2693. // Read PEM files
  2694. std::string cert_pem, key_pem, ca_pem;
  2695. read_file(SERVER_CERT_FILE, cert_pem);
  2696. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2697. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2698. // Update server certificates and client CA using PEM API while server running
  2699. ASSERT_TRUE(
  2700. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2701. // Connect with client certificate
  2702. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2703. cli.enable_server_certificate_verification(false);
  2704. cli.set_connection_timeout(30);
  2705. auto res = cli.Get("/test");
  2706. ASSERT_TRUE(res);
  2707. ASSERT_EQ(StatusCode::OK_200, res->status);
  2708. ASSERT_TRUE(handler_called);
  2709. EXPECT_EQ("ok", res->body);
  2710. }
  2711. #endif
  2712. TEST(ErrorHandlerTest, ContentLength) {
  2713. Server svr;
  2714. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2715. res.status = StatusCode::OK_200;
  2716. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2717. "text/html"); // <= Content-Length still 13
  2718. });
  2719. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2720. res.set_content("Hello World!\n", "text/plain");
  2721. res.status = 524;
  2722. });
  2723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2724. auto se = detail::scope_exit([&] {
  2725. svr.stop();
  2726. thread.join();
  2727. ASSERT_FALSE(svr.is_running());
  2728. });
  2729. svr.wait_until_ready();
  2730. {
  2731. Client cli(HOST, PORT);
  2732. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2733. ASSERT_TRUE(res);
  2734. EXPECT_EQ(StatusCode::OK_200, res->status);
  2735. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2736. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2737. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2738. }
  2739. }
  2740. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2741. TEST(ExceptionTest, WithoutExceptionHandler) {
  2742. Server svr;
  2743. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2744. throw std::runtime_error("exception...");
  2745. });
  2746. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2747. throw std::runtime_error("exception\r\n...");
  2748. });
  2749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2750. auto se = detail::scope_exit([&] {
  2751. svr.stop();
  2752. listen_thread.join();
  2753. ASSERT_FALSE(svr.is_running());
  2754. });
  2755. svr.wait_until_ready();
  2756. Client cli("localhost", PORT);
  2757. {
  2758. auto res = cli.Get("/exception");
  2759. ASSERT_TRUE(res);
  2760. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2761. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2762. }
  2763. {
  2764. auto res = cli.Get("/unknown");
  2765. ASSERT_TRUE(res);
  2766. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2767. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2768. }
  2769. }
  2770. TEST(ExceptionTest, WithExceptionHandler) {
  2771. Server svr;
  2772. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2773. std::exception_ptr ep) {
  2774. EXPECT_FALSE(ep == nullptr);
  2775. try {
  2776. std::rethrow_exception(ep);
  2777. } catch (std::exception &e) {
  2778. EXPECT_EQ("abc", std::string(e.what()));
  2779. } catch (...) {}
  2780. res.status = StatusCode::InternalServerError_500;
  2781. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2782. "text/html"); // <= Content-Length still 13 at this point
  2783. });
  2784. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2785. res.set_content("Hello World!\n", "text/plain");
  2786. throw std::runtime_error("abc");
  2787. });
  2788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2789. auto se = detail::scope_exit([&] {
  2790. svr.stop();
  2791. thread.join();
  2792. ASSERT_FALSE(svr.is_running());
  2793. });
  2794. svr.wait_until_ready();
  2795. for (size_t i = 0; i < 10; i++) {
  2796. Client cli(HOST, PORT);
  2797. for (size_t j = 0; j < 100; j++) {
  2798. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2799. ASSERT_TRUE(res);
  2800. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2801. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2802. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2803. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2804. }
  2805. cli.set_keep_alive(true);
  2806. for (size_t j = 0; j < 100; j++) {
  2807. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2808. ASSERT_TRUE(res);
  2809. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2810. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2811. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2812. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2813. }
  2814. }
  2815. }
  2816. TEST(ExceptionTest, AndErrorHandler) {
  2817. Server svr;
  2818. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2819. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2820. });
  2821. svr.set_exception_handler(
  2822. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2823. EXPECT_FALSE(ep == nullptr);
  2824. try {
  2825. std::rethrow_exception(ep);
  2826. } catch (std::exception &e) {
  2827. res.set_content(e.what(), "text/html");
  2828. } catch (...) {}
  2829. res.status = StatusCode::InternalServerError_500;
  2830. });
  2831. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2832. throw std::runtime_error("EXCEPTION");
  2833. });
  2834. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2835. res.set_content("ERROR", "text/html");
  2836. res.status = StatusCode::InternalServerError_500;
  2837. });
  2838. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2839. auto se = detail::scope_exit([&] {
  2840. svr.stop();
  2841. thread.join();
  2842. ASSERT_FALSE(svr.is_running());
  2843. });
  2844. svr.wait_until_ready();
  2845. Client cli(HOST, PORT);
  2846. {
  2847. auto res = cli.Get("/exception");
  2848. ASSERT_TRUE(res);
  2849. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2850. EXPECT_EQ("EXCEPTION", res->body);
  2851. }
  2852. {
  2853. auto res = cli.Get("/error");
  2854. ASSERT_TRUE(res);
  2855. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2856. EXPECT_EQ("ERROR", res->body);
  2857. }
  2858. {
  2859. auto res = cli.Get("/invalid");
  2860. ASSERT_TRUE(res);
  2861. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2862. EXPECT_EQ("NOT_FOUND", res->body);
  2863. }
  2864. }
  2865. #endif
  2866. TEST(NoContentTest, ContentLength) {
  2867. Server svr;
  2868. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2869. res.status = StatusCode::NoContent_204;
  2870. });
  2871. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2872. auto se = detail::scope_exit([&] {
  2873. svr.stop();
  2874. thread.join();
  2875. ASSERT_FALSE(svr.is_running());
  2876. });
  2877. svr.wait_until_ready();
  2878. {
  2879. Client cli(HOST, PORT);
  2880. auto res = cli.Get("/hi");
  2881. ASSERT_TRUE(res);
  2882. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2883. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2884. }
  2885. }
  2886. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2887. #ifdef CPPHTTPLIB_SSL_ENABLED
  2888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2889. ASSERT_TRUE(svr.is_valid());
  2890. #else
  2891. Server svr;
  2892. #endif
  2893. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2894. if (req.path == "/routing_handler") {
  2895. res.set_header("PRE_ROUTING", "on");
  2896. res.set_content("Routing Handler", "text/plain");
  2897. return httplib::Server::HandlerResponse::Handled;
  2898. }
  2899. return httplib::Server::HandlerResponse::Unhandled;
  2900. });
  2901. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2902. res.set_content("Error", "text/html");
  2903. });
  2904. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2905. if (req.path == "/routing_handler") {
  2906. res.set_header("POST_ROUTING", "on");
  2907. }
  2908. });
  2909. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2910. res.set_content("Hello World!\n", "text/plain");
  2911. });
  2912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2913. auto se = detail::scope_exit([&] {
  2914. svr.stop();
  2915. thread.join();
  2916. ASSERT_FALSE(svr.is_running());
  2917. });
  2918. svr.wait_until_ready();
  2919. {
  2920. #ifdef CPPHTTPLIB_SSL_ENABLED
  2921. SSLClient cli(HOST, PORT);
  2922. cli.enable_server_certificate_verification(false);
  2923. #else
  2924. Client cli(HOST, PORT);
  2925. #endif
  2926. auto res = cli.Get("/routing_handler");
  2927. ASSERT_TRUE(res);
  2928. EXPECT_EQ(StatusCode::OK_200, res->status);
  2929. EXPECT_EQ("Routing Handler", res->body);
  2930. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2931. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2932. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2933. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2934. }
  2935. {
  2936. #ifdef CPPHTTPLIB_SSL_ENABLED
  2937. SSLClient cli(HOST, PORT);
  2938. cli.enable_server_certificate_verification(false);
  2939. #else
  2940. Client cli(HOST, PORT);
  2941. #endif
  2942. auto res = cli.Get("/hi");
  2943. ASSERT_TRUE(res);
  2944. EXPECT_EQ(StatusCode::OK_200, res->status);
  2945. EXPECT_EQ("Hello World!\n", res->body);
  2946. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2947. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2948. }
  2949. {
  2950. #ifdef CPPHTTPLIB_SSL_ENABLED
  2951. SSLClient cli(HOST, PORT);
  2952. cli.enable_server_certificate_verification(false);
  2953. #else
  2954. Client cli(HOST, PORT);
  2955. #endif
  2956. auto res = cli.Get("/aaa");
  2957. ASSERT_TRUE(res);
  2958. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2959. EXPECT_EQ("Error", res->body);
  2960. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2961. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2962. }
  2963. }
  2964. TEST(RequestHandlerTest, PreRequestHandler) {
  2965. auto route_path = "/user/:user";
  2966. Server svr;
  2967. svr.Get("/hi", [](const Request &, Response &res) {
  2968. res.set_content("hi", "text/plain");
  2969. });
  2970. svr.Get(route_path, [](const Request &req, Response &res) {
  2971. res.set_content(req.path_params.at("user"), "text/plain");
  2972. });
  2973. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2974. if (req.matched_route == route_path) {
  2975. auto user = req.path_params.at("user");
  2976. if (user != "john") {
  2977. res.status = StatusCode::Forbidden_403;
  2978. res.set_content("error", "text/html");
  2979. return Server::HandlerResponse::Handled;
  2980. }
  2981. }
  2982. return Server::HandlerResponse::Unhandled;
  2983. });
  2984. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2985. auto se = detail::scope_exit([&] {
  2986. svr.stop();
  2987. thread.join();
  2988. ASSERT_FALSE(svr.is_running());
  2989. });
  2990. svr.wait_until_ready();
  2991. Client cli(HOST, PORT);
  2992. {
  2993. auto res = cli.Get("/hi");
  2994. ASSERT_TRUE(res);
  2995. EXPECT_EQ(StatusCode::OK_200, res->status);
  2996. EXPECT_EQ("hi", res->body);
  2997. }
  2998. {
  2999. auto res = cli.Get("/user/john");
  3000. ASSERT_TRUE(res);
  3001. EXPECT_EQ(StatusCode::OK_200, res->status);
  3002. EXPECT_EQ("john", res->body);
  3003. }
  3004. {
  3005. auto res = cli.Get("/user/invalid-user");
  3006. ASSERT_TRUE(res);
  3007. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3008. EXPECT_EQ("error", res->body);
  3009. }
  3010. }
  3011. // The pre-request handler must run before the request body is read, so a
  3012. // rejected request never forces the server to buffer a (potentially large)
  3013. // body. Here the posted body is larger than the payload limit: if the body
  3014. // were read first the server would answer 413, but because the pre-request
  3015. // handler runs first it answers 403 and the body is never read.
  3016. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3017. Server svr;
  3018. svr.set_payload_max_length(8);
  3019. auto handler_ran = false;
  3020. svr.Post("/reject", [&](const Request &req, Response &res) {
  3021. handler_ran = true;
  3022. res.set_content(req.body, "text/plain");
  3023. });
  3024. svr.Post("/accept", [](const Request &req, Response &res) {
  3025. res.set_content(req.body, "text/plain");
  3026. });
  3027. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3028. if (req.matched_route == "/reject") {
  3029. res.status = StatusCode::Forbidden_403;
  3030. res.set_content("denied", "text/plain");
  3031. return Server::HandlerResponse::Handled;
  3032. }
  3033. return Server::HandlerResponse::Unhandled;
  3034. });
  3035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3036. auto se = detail::scope_exit([&] {
  3037. svr.stop();
  3038. thread.join();
  3039. ASSERT_FALSE(svr.is_running());
  3040. });
  3041. svr.wait_until_ready();
  3042. Client cli(HOST, PORT);
  3043. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3044. // rejects with 403 before the body is read, so 413 is never reached.
  3045. {
  3046. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3047. ASSERT_TRUE(res);
  3048. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3049. EXPECT_EQ("denied", res->body);
  3050. EXPECT_FALSE(handler_ran);
  3051. }
  3052. // An approved route still reads the body and enforces the payload limit.
  3053. {
  3054. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3055. ASSERT_TRUE(res);
  3056. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3057. }
  3058. }
  3059. TEST(UserDataTest, BasicOperations) {
  3060. httplib::UserData ud;
  3061. // Initially empty
  3062. EXPECT_FALSE(ud.has("key"));
  3063. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3064. // set and get
  3065. ud.set("key", 42);
  3066. EXPECT_TRUE(ud.has("key"));
  3067. auto *p = ud.get<int>("key");
  3068. ASSERT_NE(nullptr, p);
  3069. EXPECT_EQ(42, *p);
  3070. // Type mismatch → nullptr
  3071. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3072. // Overwrite with different type
  3073. ud.set("key", std::string("hello"));
  3074. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3075. auto *s = ud.get<std::string>("key");
  3076. ASSERT_NE(nullptr, s);
  3077. EXPECT_EQ("hello", *s);
  3078. // erase
  3079. ud.erase("key");
  3080. EXPECT_FALSE(ud.has("key"));
  3081. // clear
  3082. ud.set("a", 1);
  3083. ud.set("b", 2);
  3084. ud.clear();
  3085. EXPECT_FALSE(ud.has("a"));
  3086. EXPECT_FALSE(ud.has("b"));
  3087. }
  3088. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3089. struct AuthCtx {
  3090. std::string user_id;
  3091. };
  3092. Server svr;
  3093. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3094. res.user_data.set("auth", AuthCtx{"alice"});
  3095. return Server::HandlerResponse::Unhandled;
  3096. });
  3097. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3098. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3099. ASSERT_NE(nullptr, ctx);
  3100. res.set_content("Hello " + ctx->user_id, "text/plain");
  3101. });
  3102. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3103. auto se = detail::scope_exit([&] {
  3104. svr.stop();
  3105. thread.join();
  3106. ASSERT_FALSE(svr.is_running());
  3107. });
  3108. svr.wait_until_ready();
  3109. Client cli(HOST, PORT);
  3110. auto res = cli.Get("/me");
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. EXPECT_EQ("Hello alice", res->body);
  3114. }
  3115. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3116. struct RoleCtx {
  3117. std::string role;
  3118. };
  3119. Server svr;
  3120. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3121. res.user_data.set("role", RoleCtx{"admin"});
  3122. return Server::HandlerResponse::Unhandled;
  3123. });
  3124. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3125. auto *ctx = res.user_data.get<RoleCtx>("role");
  3126. ASSERT_NE(nullptr, ctx);
  3127. res.set_content(ctx->role, "text/plain");
  3128. });
  3129. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3130. auto se = detail::scope_exit([&] {
  3131. svr.stop();
  3132. thread.join();
  3133. ASSERT_FALSE(svr.is_running());
  3134. });
  3135. svr.wait_until_ready();
  3136. Client cli(HOST, PORT);
  3137. auto res = cli.Get("/role");
  3138. ASSERT_TRUE(res);
  3139. EXPECT_EQ(StatusCode::OK_200, res->status);
  3140. EXPECT_EQ("admin", res->body);
  3141. }
  3142. TEST(InvalidFormatTest, StatusCode) {
  3143. Server svr;
  3144. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3145. res.set_content("Hello World!\n", "text/plain");
  3146. res.status = 9999; // Status should be a three-digit code...
  3147. });
  3148. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3149. auto se = detail::scope_exit([&] {
  3150. svr.stop();
  3151. thread.join();
  3152. ASSERT_FALSE(svr.is_running());
  3153. });
  3154. svr.wait_until_ready();
  3155. {
  3156. Client cli(HOST, PORT);
  3157. auto res = cli.Get("/hi");
  3158. ASSERT_FALSE(res);
  3159. }
  3160. }
  3161. TEST(URLFragmentTest, WithFragment) {
  3162. Server svr;
  3163. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3164. EXPECT_TRUE(req.target == "/hi");
  3165. });
  3166. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3167. auto se = detail::scope_exit([&] {
  3168. svr.stop();
  3169. thread.join();
  3170. ASSERT_FALSE(svr.is_running());
  3171. });
  3172. svr.wait_until_ready();
  3173. {
  3174. Client cli(HOST, PORT);
  3175. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3176. EXPECT_TRUE(res);
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. res = cli.Get("/hi%23key1=val1=key2=val2");
  3179. EXPECT_TRUE(res);
  3180. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3181. }
  3182. }
  3183. TEST(HeaderWriter, SetHeaderWriter) {
  3184. Server svr;
  3185. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3186. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3187. return detail::write_headers(strm, hdrs);
  3188. });
  3189. svr.Get("/hi", [](const Request &req, Response &res) {
  3190. auto it = req.headers.find("CustomClientHeader");
  3191. EXPECT_TRUE(it != req.headers.end());
  3192. EXPECT_EQ(it->second, "CustomClientValue");
  3193. res.set_content("Hello World!\n", "text/plain");
  3194. });
  3195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3196. auto se = detail::scope_exit([&] {
  3197. svr.stop();
  3198. thread.join();
  3199. ASSERT_FALSE(svr.is_running());
  3200. });
  3201. svr.wait_until_ready();
  3202. {
  3203. Client cli(HOST, PORT);
  3204. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3205. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3206. return detail::write_headers(strm, hdrs);
  3207. });
  3208. auto res = cli.Get("/hi");
  3209. EXPECT_TRUE(res);
  3210. EXPECT_EQ(StatusCode::OK_200, res->status);
  3211. auto it = res->headers.find("CustomServerHeader");
  3212. EXPECT_TRUE(it != res->headers.end());
  3213. EXPECT_EQ(it->second, "CustomServerValue");
  3214. }
  3215. }
  3216. class ServerTest : public ::testing::Test {
  3217. protected:
  3218. ServerTest()
  3219. : cli_(HOST, PORT)
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. ,
  3222. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3223. #endif
  3224. {
  3225. #ifdef CPPHTTPLIB_SSL_ENABLED
  3226. cli_.enable_server_certificate_verification(false);
  3227. #endif
  3228. // Allow LARGE_DATA (100MB) responses
  3229. cli_.set_payload_max_length(200 * 1024 * 1024);
  3230. }
  3231. virtual void SetUp() {
  3232. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3233. svr_.set_payload_max_length(200 * 1024 * 1024);
  3234. svr_.set_mount_point("/", "./www");
  3235. svr_.set_mount_point("/mount", "./www2");
  3236. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3237. svr_.Get("/hi",
  3238. [&](const Request & /*req*/, Response &res) {
  3239. res.set_content("Hello World!", "text/plain");
  3240. })
  3241. .Get("/file_content",
  3242. [&](const Request & /*req*/, Response &res) {
  3243. res.set_file_content("./www/dir/test.html");
  3244. })
  3245. .Get("/file_content_with_content_type",
  3246. [&](const Request & /*req*/, Response &res) {
  3247. res.set_file_content("./www/file", "text/plain");
  3248. })
  3249. .Get("/invalid_file_content",
  3250. [&](const Request & /*req*/, Response &res) {
  3251. res.set_file_content("./www/dir/invalid_file_path");
  3252. })
  3253. .Get("/http_response_splitting",
  3254. [&](const Request & /*req*/, Response &res) {
  3255. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3256. EXPECT_EQ(0U, res.headers.size());
  3257. EXPECT_FALSE(res.has_header("a"));
  3258. res.set_header("a", "1\nSet-Cookie: a=1");
  3259. EXPECT_EQ(0U, res.headers.size());
  3260. EXPECT_FALSE(res.has_header("a"));
  3261. res.set_header("a", "1\rSet-Cookie: a=1");
  3262. EXPECT_EQ(0U, res.headers.size());
  3263. EXPECT_FALSE(res.has_header("a"));
  3264. res.set_header("a\r\nb", "0");
  3265. EXPECT_EQ(0U, res.headers.size());
  3266. EXPECT_FALSE(res.has_header("a"));
  3267. res.set_header("a\rb", "0");
  3268. EXPECT_EQ(0U, res.headers.size());
  3269. EXPECT_FALSE(res.has_header("a"));
  3270. res.set_header("a\nb", "0");
  3271. EXPECT_EQ(0U, res.headers.size());
  3272. EXPECT_FALSE(res.has_header("a"));
  3273. res.set_redirect("1\r\nSet-Cookie: a=1");
  3274. EXPECT_EQ(0U, res.headers.size());
  3275. EXPECT_FALSE(res.has_header("Location"));
  3276. })
  3277. .Get("/slow",
  3278. [&](const Request & /*req*/, Response &res) {
  3279. std::this_thread::sleep_for(std::chrono::seconds(4));
  3280. res.set_content("slow", "text/plain");
  3281. })
  3282. #if 0
  3283. .Post("/slowpost",
  3284. [&](const Request & /*req*/, Response &res) {
  3285. std::this_thread::sleep_for(std::chrono::seconds(2));
  3286. res.set_content("slow", "text/plain");
  3287. })
  3288. #endif
  3289. .Get("/remote_addr",
  3290. [&](const Request &req, Response &res) {
  3291. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3292. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3293. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3294. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3295. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3296. #endif
  3297. res.set_content(req.remote_addr, "text/plain");
  3298. })
  3299. .Get("/local_addr",
  3300. [&](const Request &req, Response &res) {
  3301. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3302. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3303. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3304. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3305. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3306. #endif
  3307. auto local_addr = req.local_addr;
  3308. auto local_port = std::to_string(req.local_port);
  3309. res.set_content(local_addr.append(":").append(local_port),
  3310. "text/plain");
  3311. })
  3312. .Get("/endwith%",
  3313. [&](const Request & /*req*/, Response &res) {
  3314. res.set_content("Hello World!", "text/plain");
  3315. })
  3316. .Get("/a\\+\\+b",
  3317. [&](const Request &req, Response &res) {
  3318. ASSERT_TRUE(req.has_param("a +b"));
  3319. auto val = req.get_param_value("a +b");
  3320. res.set_content(val, "text/plain");
  3321. })
  3322. .Get("/", [&](const Request & /*req*/,
  3323. Response &res) { res.set_redirect("/hi"); })
  3324. .Post("/1",
  3325. [](const Request & /*req*/, Response &res) {
  3326. res.set_redirect("/2", StatusCode::SeeOther_303);
  3327. })
  3328. .Get("/2",
  3329. [](const Request & /*req*/, Response &res) {
  3330. res.set_content("redirected.", "text/plain");
  3331. res.status = StatusCode::OK_200;
  3332. })
  3333. .Post("/person",
  3334. [&](const Request &req, Response &res) {
  3335. if (req.has_param("name") && req.has_param("note")) {
  3336. persons_[req.get_param_value("name")] =
  3337. req.get_param_value("note");
  3338. } else {
  3339. res.status = StatusCode::BadRequest_400;
  3340. }
  3341. })
  3342. .Put("/person",
  3343. [&](const Request &req, Response &res) {
  3344. if (req.has_param("name") && req.has_param("note")) {
  3345. persons_[req.get_param_value("name")] =
  3346. req.get_param_value("note");
  3347. } else {
  3348. res.status = StatusCode::BadRequest_400;
  3349. }
  3350. })
  3351. .Get("/person/(.*)",
  3352. [&](const Request &req, Response &res) {
  3353. string name = req.matches[1];
  3354. if (persons_.find(name) != persons_.end()) {
  3355. auto note = persons_[name];
  3356. res.set_content(note, "text/plain");
  3357. } else {
  3358. res.status = StatusCode::NotFound_404;
  3359. }
  3360. })
  3361. .Delete("/person",
  3362. [&](const Request &req, Response &res) {
  3363. if (req.has_param("name")) {
  3364. string name = req.get_param_value("name");
  3365. if (persons_.find(name) != persons_.end()) {
  3366. persons_.erase(name);
  3367. res.set_content("DELETED", "text/plain");
  3368. } else {
  3369. res.status = StatusCode::NotFound_404;
  3370. }
  3371. } else {
  3372. res.status = StatusCode::BadRequest_400;
  3373. }
  3374. })
  3375. .Post("/x-www-form-urlencoded-json",
  3376. [&](const Request &req, Response &res) {
  3377. auto json = req.get_param_value("json");
  3378. ASSERT_EQ(JSON_DATA, json);
  3379. res.set_content(json, "appliation/json");
  3380. res.status = StatusCode::OK_200;
  3381. })
  3382. .Get("/streamed-chunked",
  3383. [&](const Request & /*req*/, Response &res) {
  3384. res.set_chunked_content_provider(
  3385. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3386. sink.os << "123";
  3387. sink.os << "456";
  3388. sink.os << "789";
  3389. sink.done();
  3390. return true;
  3391. });
  3392. })
  3393. .Get("/streamed-chunked-with-prohibited-trailer",
  3394. [&](const Request & /*req*/, Response &res) {
  3395. auto i = new int(0);
  3396. // Declare both a prohibited trailer (Content-Length) and an
  3397. // allowed one
  3398. res.set_header("Trailer", "Content-Length, X-Allowed");
  3399. res.set_chunked_content_provider(
  3400. "text/plain",
  3401. [i](size_t /*offset*/, DataSink &sink) {
  3402. switch (*i) {
  3403. case 0: sink.os << "123"; break;
  3404. case 1: sink.os << "456"; break;
  3405. case 2: sink.os << "789"; break;
  3406. case 3: {
  3407. sink.done_with_trailer(
  3408. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3409. } break;
  3410. }
  3411. (*i)++;
  3412. return true;
  3413. },
  3414. [i](bool success) {
  3415. EXPECT_TRUE(success);
  3416. delete i;
  3417. });
  3418. })
  3419. .Get("/streamed-chunked2",
  3420. [&](const Request & /*req*/, Response &res) {
  3421. auto i = new int(0);
  3422. res.set_chunked_content_provider(
  3423. "text/plain",
  3424. [i](size_t /*offset*/, DataSink &sink) {
  3425. switch (*i) {
  3426. case 0: sink.os << "123"; break;
  3427. case 1: sink.os << "456"; break;
  3428. case 2: sink.os << "789"; break;
  3429. case 3: sink.done(); break;
  3430. }
  3431. (*i)++;
  3432. return true;
  3433. },
  3434. [i](bool success) {
  3435. EXPECT_TRUE(success);
  3436. delete i;
  3437. });
  3438. })
  3439. .Get("/streamed-chunked-with-trailer",
  3440. [&](const Request & /*req*/, Response &res) {
  3441. auto i = new int(0);
  3442. res.set_header("Trailer", "Dummy1, Dummy2");
  3443. res.set_chunked_content_provider(
  3444. "text/plain",
  3445. [i](size_t /*offset*/, DataSink &sink) {
  3446. switch (*i) {
  3447. case 0: sink.os << "123"; break;
  3448. case 1: sink.os << "456"; break;
  3449. case 2: sink.os << "789"; break;
  3450. case 3: {
  3451. sink.done_with_trailer(
  3452. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3453. } break;
  3454. }
  3455. (*i)++;
  3456. return true;
  3457. },
  3458. [i](bool success) {
  3459. EXPECT_TRUE(success);
  3460. delete i;
  3461. });
  3462. })
  3463. .Get("/streamed",
  3464. [&](const Request & /*req*/, Response &res) {
  3465. res.set_content_provider(
  3466. 6, "text/plain",
  3467. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3468. sink.os << (offset < 3 ? "a" : "b");
  3469. return true;
  3470. });
  3471. })
  3472. .Get("/streamed-without-length",
  3473. [&](const Request & /*req*/, Response &res) {
  3474. auto data = new std::string("abcdefg");
  3475. res.set_content_provider(
  3476. "text/plain",
  3477. [data](size_t offset, DataSink &sink) {
  3478. if (offset < data->size()) {
  3479. sink.os << data->substr(offset);
  3480. }
  3481. sink.done();
  3482. return true;
  3483. },
  3484. [data](bool success) {
  3485. EXPECT_TRUE(success);
  3486. delete data;
  3487. });
  3488. })
  3489. .Get("/streamed-with-range",
  3490. [&](const Request &req, Response &res) {
  3491. auto data = new std::string("abcdefg");
  3492. res.set_content_provider(
  3493. data->size(), "text/plain",
  3494. [data](size_t offset, size_t length, DataSink &sink) {
  3495. size_t DATA_CHUNK_SIZE = 4;
  3496. const auto &d = *data;
  3497. auto out_len =
  3498. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3499. auto ret =
  3500. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3501. EXPECT_TRUE(ret);
  3502. return true;
  3503. },
  3504. [data, &req](bool success) {
  3505. EXPECT_EQ(success, !req.has_param("error"));
  3506. delete data;
  3507. });
  3508. })
  3509. .Get("/streamed-cancel",
  3510. [&](const Request & /*req*/, Response &res) {
  3511. res.set_content_provider(
  3512. size_t(-1), "text/plain",
  3513. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3514. sink.os << "data_chunk";
  3515. return true;
  3516. });
  3517. })
  3518. .Get("/regex-with-delimiter",
  3519. [&](const Request &req, Response & /*res*/) {
  3520. ASSERT_TRUE(req.has_param("key"));
  3521. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3522. })
  3523. .Get("/with-range",
  3524. [&](const Request & /*req*/, Response &res) {
  3525. res.set_content("abcdefg", "text/plain");
  3526. })
  3527. .Get("/test-start-time",
  3528. [&](const Request &req, Response & /*res*/) {
  3529. EXPECT_NE(req.start_time_,
  3530. std::chrono::steady_clock::time_point::min());
  3531. })
  3532. .Get("/with-range-customized-response",
  3533. [&](const Request & /*req*/, Response &res) {
  3534. res.status = StatusCode::BadRequest_400;
  3535. res.set_content(JSON_DATA, "application/json");
  3536. })
  3537. .Post("/chunked",
  3538. [&](const Request &req, Response & /*res*/) {
  3539. EXPECT_EQ(req.body, "dechunked post body");
  3540. })
  3541. .Post("/large-chunked",
  3542. [&](const Request &req, Response & /*res*/) {
  3543. std::string expected(6 * 30 * 1024u, 'a');
  3544. EXPECT_EQ(req.body, expected);
  3545. })
  3546. .Post("/multipart",
  3547. [&](const Request &req, Response & /*res*/) {
  3548. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3549. req.form.get_field_count("text2") +
  3550. req.form.get_field_count("file3") +
  3551. req.form.get_field_count("file4"));
  3552. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3553. req.form.get_file_count("file2"));
  3554. ASSERT_TRUE(!req.form.has_file("???"));
  3555. ASSERT_TRUE(!req.form.has_field("???"));
  3556. ASSERT_TRUE(req.body.empty());
  3557. {
  3558. const auto &text = req.form.get_field("text1");
  3559. EXPECT_EQ("text default", text);
  3560. }
  3561. {
  3562. const auto &text = req.form.get_field("text2");
  3563. EXPECT_EQ("aωb", text);
  3564. }
  3565. {
  3566. const auto &file = req.form.get_file("file1");
  3567. EXPECT_EQ("hello.txt", file.filename);
  3568. EXPECT_EQ("text/plain", file.content_type);
  3569. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3570. }
  3571. {
  3572. const auto &file = req.form.get_file("file2");
  3573. EXPECT_EQ("world.json", file.filename);
  3574. EXPECT_EQ("application/json", file.content_type);
  3575. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3576. }
  3577. {
  3578. const auto &text = req.form.get_field("file3");
  3579. EXPECT_EQ(0u, text.size());
  3580. }
  3581. {
  3582. const auto &text = req.form.get_field("file4");
  3583. EXPECT_EQ(0u, text.size());
  3584. }
  3585. })
  3586. .Post("/multipart/multi_file_values",
  3587. [&](const Request &req, Response & /*res*/) {
  3588. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3589. req.form.get_field_count("multi_text1"));
  3590. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3591. ASSERT_TRUE(!req.form.has_file("???"));
  3592. ASSERT_TRUE(!req.form.has_field("???"));
  3593. ASSERT_TRUE(req.body.empty());
  3594. {
  3595. const auto &text = req.form.get_field("text");
  3596. EXPECT_EQ("default text", text);
  3597. }
  3598. {
  3599. const auto &text1_values = req.form.get_fields("multi_text1");
  3600. EXPECT_EQ(2u, text1_values.size());
  3601. EXPECT_EQ("aaaaa", text1_values[0]);
  3602. EXPECT_EQ("bbbbb", text1_values[1]);
  3603. }
  3604. {
  3605. const auto &file1_values = req.form.get_files("multi_file1");
  3606. EXPECT_EQ(2u, file1_values.size());
  3607. auto file1 = file1_values[0];
  3608. EXPECT_EQ(file1.filename, "hello.txt");
  3609. EXPECT_EQ(file1.content_type, "text/plain");
  3610. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3611. auto file2 = file1_values[1];
  3612. EXPECT_EQ(file2.filename, "world.json");
  3613. EXPECT_EQ(file2.content_type, "application/json");
  3614. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3615. }
  3616. })
  3617. .Post("/empty",
  3618. [&](const Request &req, Response &res) {
  3619. EXPECT_EQ(req.body, "");
  3620. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3621. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3622. res.set_content("empty", "text/plain");
  3623. })
  3624. .Post("/empty-no-content-type",
  3625. [&](const Request &req, Response &res) {
  3626. EXPECT_EQ(req.body, "");
  3627. EXPECT_FALSE(req.has_header("Content-Type"));
  3628. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3629. res.set_content("empty-no-content-type", "text/plain");
  3630. })
  3631. .Post("/path-only",
  3632. [&](const Request &req, Response &res) {
  3633. EXPECT_EQ(req.body, "");
  3634. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3635. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3636. res.set_content("path-only", "text/plain");
  3637. })
  3638. .Post("/path-headers-only",
  3639. [&](const Request &req, Response &res) {
  3640. EXPECT_EQ(req.body, "");
  3641. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3642. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3643. EXPECT_EQ("world", req.get_header_value("hello"));
  3644. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3645. res.set_content("path-headers-only", "text/plain");
  3646. })
  3647. .Post("/post-large",
  3648. [&](const Request &req, Response &res) {
  3649. EXPECT_EQ(req.body, LARGE_DATA);
  3650. res.set_content(req.body, "text/plain");
  3651. })
  3652. .Post("/post-loopback",
  3653. [&](const Request &, Response &res,
  3654. ContentReader const &content_reader) {
  3655. std::string body;
  3656. content_reader([&](const char *data, size_t data_length) {
  3657. body.append(data, data_length);
  3658. return true;
  3659. });
  3660. res.set_content(body, "text/plain");
  3661. })
  3662. .Put("/put-loopback",
  3663. [&](const Request &, Response &res,
  3664. ContentReader const &content_reader) {
  3665. std::string body;
  3666. content_reader([&](const char *data, size_t data_length) {
  3667. body.append(data, data_length);
  3668. return true;
  3669. });
  3670. res.set_content(body, "text/plain");
  3671. })
  3672. .Patch("/patch-loopback",
  3673. [&](const Request &, Response &res,
  3674. ContentReader const &content_reader) {
  3675. std::string body;
  3676. content_reader([&](const char *data, size_t data_length) {
  3677. body.append(data, data_length);
  3678. return true;
  3679. });
  3680. res.set_content(body, "text/plain");
  3681. })
  3682. .Put("/empty-no-content-type",
  3683. [&](const Request &req, Response &res) {
  3684. EXPECT_EQ(req.body, "");
  3685. EXPECT_FALSE(req.has_header("Content-Type"));
  3686. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3687. res.set_content("empty-no-content-type", "text/plain");
  3688. })
  3689. .Put("/put",
  3690. [&](const Request &req, Response &res) {
  3691. EXPECT_EQ(req.body, "PUT");
  3692. res.set_content(req.body, "text/plain");
  3693. })
  3694. .Put("/put-large",
  3695. [&](const Request &req, Response &res) {
  3696. EXPECT_EQ(req.body, LARGE_DATA);
  3697. res.set_content(req.body, "text/plain");
  3698. })
  3699. .Patch("/patch",
  3700. [&](const Request &req, Response &res) {
  3701. EXPECT_EQ(req.body, "PATCH");
  3702. res.set_content(req.body, "text/plain");
  3703. })
  3704. .Delete("/delete",
  3705. [&](const Request & /*req*/, Response &res) {
  3706. res.set_content("DELETE", "text/plain");
  3707. })
  3708. .Delete("/delete-body",
  3709. [&](const Request &req, Response &res) {
  3710. EXPECT_EQ(req.body, "content");
  3711. res.set_content(req.body, "text/plain");
  3712. })
  3713. .Options(R"(\*)",
  3714. [&](const Request & /*req*/, Response &res) {
  3715. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3716. })
  3717. .Get("/request-target",
  3718. [&](const Request &req, Response & /*res*/) {
  3719. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3720. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3721. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3722. })
  3723. .Get("/long-query-value",
  3724. [&](const Request &req, Response & /*res*/) {
  3725. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3726. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3727. })
  3728. .Get("/too-long-query-value",
  3729. [&](const Request &req, Response & /*res*/) {
  3730. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3731. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3732. })
  3733. .Get("/array-param",
  3734. [&](const Request &req, Response & /*res*/) {
  3735. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3736. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3737. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3738. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3739. })
  3740. .Get("/array-param-values",
  3741. [&](const Request &req, Response & /*res*/) {
  3742. auto values = req.get_param_values("array");
  3743. EXPECT_EQ(3u, values.size());
  3744. EXPECT_EQ("value1", values[0]);
  3745. EXPECT_EQ("value2", values[1]);
  3746. EXPECT_EQ("value3", values[2]);
  3747. auto empty = req.get_param_values("nonexistent");
  3748. EXPECT_TRUE(empty.empty());
  3749. })
  3750. .Post("/validate-no-multiple-headers",
  3751. [&](const Request &req, Response & /*res*/) {
  3752. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3753. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3754. })
  3755. .Post("/content_receiver",
  3756. [&](const Request &req, Response &res,
  3757. const ContentReader &content_reader) {
  3758. if (req.is_multipart_form_data()) {
  3759. std::vector<FormData> items;
  3760. content_reader(
  3761. [&](const FormData &file) {
  3762. items.push_back(file);
  3763. return true;
  3764. },
  3765. [&](const char *data, size_t data_length) {
  3766. items.back().content.append(data, data_length);
  3767. return true;
  3768. });
  3769. EXPECT_EQ(5u, items.size());
  3770. {
  3771. const auto &file = get_file_value(items, "text1");
  3772. EXPECT_TRUE(file.filename.empty());
  3773. EXPECT_EQ("text default", file.content);
  3774. }
  3775. {
  3776. const auto &file = get_file_value(items, "text2");
  3777. EXPECT_TRUE(file.filename.empty());
  3778. EXPECT_EQ("aωb", file.content);
  3779. }
  3780. {
  3781. const auto &file = get_file_value(items, "file1");
  3782. EXPECT_EQ("hello.txt", file.filename);
  3783. EXPECT_EQ("text/plain", file.content_type);
  3784. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3785. }
  3786. {
  3787. const auto &file = get_file_value(items, "file2");
  3788. EXPECT_EQ("world.json", file.filename);
  3789. EXPECT_EQ("application/json", file.content_type);
  3790. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3791. }
  3792. {
  3793. const auto &file = get_file_value(items, "file3");
  3794. EXPECT_TRUE(file.filename.empty());
  3795. EXPECT_EQ("application/octet-stream", file.content_type);
  3796. EXPECT_EQ(0u, file.content.size());
  3797. }
  3798. } else {
  3799. std::string body;
  3800. content_reader([&](const char *data, size_t data_length) {
  3801. EXPECT_EQ(7U, data_length);
  3802. body.append(data, data_length);
  3803. return true;
  3804. });
  3805. EXPECT_EQ(body, "content");
  3806. res.set_content(body, "text/plain");
  3807. }
  3808. })
  3809. .Put("/content_receiver",
  3810. [&](const Request & /*req*/, Response &res,
  3811. const ContentReader &content_reader) {
  3812. std::string body;
  3813. content_reader([&](const char *data, size_t data_length) {
  3814. body.append(data, data_length);
  3815. return true;
  3816. });
  3817. EXPECT_EQ(body, "content");
  3818. res.set_content(body, "text/plain");
  3819. })
  3820. .Patch("/content_receiver",
  3821. [&](const Request & /*req*/, Response &res,
  3822. const ContentReader &content_reader) {
  3823. std::string body;
  3824. content_reader([&](const char *data, size_t data_length) {
  3825. body.append(data, data_length);
  3826. return true;
  3827. });
  3828. EXPECT_EQ(body, "content");
  3829. res.set_content(body, "text/plain");
  3830. })
  3831. .Post("/query-string-and-body",
  3832. [&](const Request &req, Response & /*res*/) {
  3833. ASSERT_TRUE(req.has_param("key"));
  3834. EXPECT_EQ(req.get_param_value("key"), "value");
  3835. EXPECT_EQ(req.body, "content");
  3836. })
  3837. .Get("/last-request",
  3838. [&](const Request &req, Response & /*res*/) {
  3839. EXPECT_EQ("close", req.get_header_value("Connection"));
  3840. })
  3841. .Get(R"(/redirect/(\d+))",
  3842. [&](const Request &req, Response &res) {
  3843. auto num = std::stoi(req.matches[1]) + 1;
  3844. std::string url = "/redirect/" + std::to_string(num);
  3845. res.set_redirect(url);
  3846. })
  3847. .Post("/binary",
  3848. [&](const Request &req, Response &res) {
  3849. EXPECT_EQ(4U, req.body.size());
  3850. EXPECT_EQ("application/octet-stream",
  3851. req.get_header_value("Content-Type"));
  3852. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3853. res.set_content(req.body, "application/octet-stream");
  3854. })
  3855. .Put("/binary",
  3856. [&](const Request &req, Response &res) {
  3857. EXPECT_EQ(4U, req.body.size());
  3858. EXPECT_EQ("application/octet-stream",
  3859. req.get_header_value("Content-Type"));
  3860. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3861. res.set_content(req.body, "application/octet-stream");
  3862. })
  3863. .Patch("/binary",
  3864. [&](const Request &req, Response &res) {
  3865. EXPECT_EQ(4U, req.body.size());
  3866. EXPECT_EQ("application/octet-stream",
  3867. req.get_header_value("Content-Type"));
  3868. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3869. res.set_content(req.body, "application/octet-stream");
  3870. })
  3871. .Delete("/binary",
  3872. [&](const Request &req, Response &res) {
  3873. EXPECT_EQ(4U, req.body.size());
  3874. EXPECT_EQ("application/octet-stream",
  3875. req.get_header_value("Content-Type"));
  3876. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3877. res.set_content(req.body, "application/octet-stream");
  3878. })
  3879. .Get("/issue1772",
  3880. [&](const Request & /*req*/, Response &res) {
  3881. res.status = 401;
  3882. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3883. })
  3884. .Delete("/issue609",
  3885. [](const httplib::Request &, httplib::Response &res,
  3886. const httplib::ContentReader &) {
  3887. res.set_content("ok", "text/plain");
  3888. })
  3889. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3890. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3891. .Get("/compress",
  3892. [&](const Request & /*req*/, Response &res) {
  3893. res.set_content(
  3894. "12345678901234567890123456789012345678901234567890123456789"
  3895. "01234567890123456789012345678901234567890",
  3896. "text/plain");
  3897. })
  3898. .Get("/compress-with-charset",
  3899. [&](const Request & /*req*/, Response &res) {
  3900. res.set_content(
  3901. "12345678901234567890123456789012345678901234567890123456789"
  3902. "01234567890123456789012345678901234567890",
  3903. "application/json; charset=utf-8");
  3904. })
  3905. .Get("/nocompress",
  3906. [&](const Request & /*req*/, Response &res) {
  3907. res.set_content(
  3908. "12345678901234567890123456789012345678901234567890123456789"
  3909. "01234567890123456789012345678901234567890",
  3910. "application/octet-stream");
  3911. })
  3912. .Post("/compress-multipart",
  3913. [&](const Request &req, Response & /*res*/) {
  3914. EXPECT_EQ(2u, req.form.fields.size());
  3915. ASSERT_TRUE(!req.form.has_field("???"));
  3916. {
  3917. const auto &text = req.form.get_field("key1");
  3918. EXPECT_EQ("test", text);
  3919. }
  3920. {
  3921. const auto &text = req.form.get_field("key2");
  3922. EXPECT_EQ("--abcdefg123", text);
  3923. }
  3924. })
  3925. #endif
  3926. ;
  3927. persons_["john"] = "programmer";
  3928. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3929. svr_.wait_until_ready();
  3930. }
  3931. virtual void TearDown() {
  3932. svr_.stop();
  3933. if (!request_threads_.empty()) {
  3934. std::this_thread::sleep_for(std::chrono::seconds(1));
  3935. for (auto &t : request_threads_) {
  3936. t.join();
  3937. }
  3938. }
  3939. t_.join();
  3940. }
  3941. map<string, string> persons_;
  3942. #ifdef CPPHTTPLIB_SSL_ENABLED
  3943. SSLClient cli_;
  3944. SSLServer svr_;
  3945. #else
  3946. Client cli_;
  3947. Server svr_;
  3948. #endif
  3949. thread t_;
  3950. std::vector<thread> request_threads_;
  3951. };
  3952. TEST_F(ServerTest, GetMethod200) {
  3953. auto res = cli_.Get("/hi");
  3954. ASSERT_TRUE(res);
  3955. EXPECT_EQ("HTTP/1.1", res->version);
  3956. EXPECT_EQ(StatusCode::OK_200, res->status);
  3957. EXPECT_EQ("OK", res->reason);
  3958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3959. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3960. EXPECT_EQ("Hello World!", res->body);
  3961. }
  3962. TEST_F(ServerTest, GetEmptyFile) {
  3963. auto res = cli_.Get("/empty_file");
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3967. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3968. EXPECT_EQ("", res->body);
  3969. }
  3970. TEST_F(ServerTest, GetFileContent) {
  3971. auto res = cli_.Get("/file_content");
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ(StatusCode::OK_200, res->status);
  3974. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3975. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3976. EXPECT_EQ("test.html", res->body);
  3977. }
  3978. TEST_F(ServerTest, GetFileContentWithRange) {
  3979. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3980. ASSERT_TRUE(res);
  3981. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3982. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3983. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3984. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3985. EXPECT_EQ("est", res->body);
  3986. }
  3987. TEST_F(ServerTest, GetFileContentWithContentType) {
  3988. auto res = cli_.Get("/file_content_with_content_type");
  3989. ASSERT_TRUE(res);
  3990. EXPECT_EQ(StatusCode::OK_200, res->status);
  3991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3992. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3993. EXPECT_EQ("file\n", res->body);
  3994. }
  3995. TEST_F(ServerTest, GetInvalidFileContent) {
  3996. auto res = cli_.Get("/invalid_file_content");
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3999. }
  4000. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4001. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4002. ASSERT_TRUE(res);
  4003. EXPECT_EQ("HTTP/1.1", res->version);
  4004. EXPECT_EQ(StatusCode::OK_200, res->status);
  4005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4006. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4007. EXPECT_EQ("Hello World!", res->body);
  4008. }
  4009. TEST_F(ServerTest, GetMethod302) {
  4010. auto res = cli_.Get("/");
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::Found_302, res->status);
  4013. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4014. }
  4015. TEST_F(ServerTest, GetMethod302Redirect) {
  4016. cli_.set_follow_location(true);
  4017. auto res = cli_.Get("/");
  4018. ASSERT_TRUE(res);
  4019. EXPECT_EQ(StatusCode::OK_200, res->status);
  4020. EXPECT_EQ("Hello World!", res->body);
  4021. EXPECT_EQ("/hi", res->location);
  4022. }
  4023. TEST_F(ServerTest, GetMethod404) {
  4024. auto res = cli_.Get("/invalid");
  4025. ASSERT_TRUE(res);
  4026. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4027. }
  4028. TEST_F(ServerTest, HeadMethod200) {
  4029. auto res = cli_.Head("/hi");
  4030. ASSERT_TRUE(res);
  4031. EXPECT_EQ(StatusCode::OK_200, res->status);
  4032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4033. EXPECT_TRUE(res->body.empty());
  4034. }
  4035. TEST_F(ServerTest, HeadMethod200Static) {
  4036. auto res = cli_.Head("/mount/dir/index.html");
  4037. ASSERT_TRUE(res);
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4040. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4041. EXPECT_TRUE(res->body.empty());
  4042. }
  4043. TEST_F(ServerTest, HeadMethod404) {
  4044. auto res = cli_.Head("/invalid");
  4045. ASSERT_TRUE(res);
  4046. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4047. EXPECT_TRUE(res->body.empty());
  4048. }
  4049. TEST_F(ServerTest, GetMethodPersonJohn) {
  4050. auto res = cli_.Get("/person/john");
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4054. EXPECT_EQ("programmer", res->body);
  4055. }
  4056. TEST_F(ServerTest, PostMethod1) {
  4057. auto res = cli_.Get("/person/john1");
  4058. ASSERT_TRUE(res);
  4059. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4060. res = cli_.Post("/person", "name=john1&note=coder",
  4061. "application/x-www-form-urlencoded");
  4062. ASSERT_TRUE(res);
  4063. ASSERT_EQ(StatusCode::OK_200, res->status);
  4064. res = cli_.Get("/person/john1");
  4065. ASSERT_TRUE(res);
  4066. ASSERT_EQ(StatusCode::OK_200, res->status);
  4067. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4068. ASSERT_EQ("coder", res->body);
  4069. }
  4070. TEST_F(ServerTest, PostMethod2) {
  4071. auto res = cli_.Get("/person/john2");
  4072. ASSERT_TRUE(res);
  4073. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4074. Params params;
  4075. params.emplace("name", "john2");
  4076. params.emplace("note", "coder");
  4077. res = cli_.Post("/person", params);
  4078. ASSERT_TRUE(res);
  4079. ASSERT_EQ(StatusCode::OK_200, res->status);
  4080. res = cli_.Get("/person/john2");
  4081. ASSERT_TRUE(res);
  4082. ASSERT_EQ(StatusCode::OK_200, res->status);
  4083. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4084. ASSERT_EQ("coder", res->body);
  4085. }
  4086. TEST_F(ServerTest, PutMethod3) {
  4087. auto res = cli_.Get("/person/john3");
  4088. ASSERT_TRUE(res);
  4089. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4090. Params params;
  4091. params.emplace("name", "john3");
  4092. params.emplace("note", "coder");
  4093. res = cli_.Put("/person", params);
  4094. ASSERT_TRUE(res);
  4095. ASSERT_EQ(StatusCode::OK_200, res->status);
  4096. res = cli_.Get("/person/john3");
  4097. ASSERT_TRUE(res);
  4098. ASSERT_EQ(StatusCode::OK_200, res->status);
  4099. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4100. ASSERT_EQ("coder", res->body);
  4101. }
  4102. TEST_F(ServerTest, DeleteMethod1) {
  4103. auto res = cli_.Get("/person/john4");
  4104. ASSERT_TRUE(res);
  4105. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4106. Params params;
  4107. params.emplace("name", "john4");
  4108. params.emplace("note", "coder");
  4109. res = cli_.Post("/person", params);
  4110. ASSERT_TRUE(res);
  4111. ASSERT_EQ(StatusCode::OK_200, res->status);
  4112. res = cli_.Get("/person/john4");
  4113. ASSERT_TRUE(res);
  4114. ASSERT_EQ(StatusCode::OK_200, res->status);
  4115. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4116. ASSERT_EQ("coder", res->body);
  4117. Params delete_params;
  4118. delete_params.emplace("name", "john4");
  4119. res = cli_.Delete("/person", delete_params);
  4120. ASSERT_TRUE(res);
  4121. ASSERT_EQ(StatusCode::OK_200, res->status);
  4122. ASSERT_EQ("DELETED", res->body);
  4123. res = cli_.Get("/person/john4");
  4124. ASSERT_TRUE(res);
  4125. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4126. }
  4127. TEST_F(ServerTest, DeleteMethod2) {
  4128. auto res = cli_.Get("/person/john5");
  4129. ASSERT_TRUE(res);
  4130. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4131. Params params;
  4132. params.emplace("name", "john5");
  4133. params.emplace("note", "developer");
  4134. res = cli_.Post("/person", params);
  4135. ASSERT_TRUE(res);
  4136. ASSERT_EQ(StatusCode::OK_200, res->status);
  4137. res = cli_.Get("/person/john5");
  4138. ASSERT_TRUE(res);
  4139. ASSERT_EQ(StatusCode::OK_200, res->status);
  4140. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4141. ASSERT_EQ("developer", res->body);
  4142. Params delete_params;
  4143. delete_params.emplace("name", "john5");
  4144. Headers headers;
  4145. headers.emplace("Custom-Header", "test-value");
  4146. res = cli_.Delete("/person", headers, delete_params);
  4147. ASSERT_TRUE(res);
  4148. ASSERT_EQ(StatusCode::OK_200, res->status);
  4149. ASSERT_EQ("DELETED", res->body);
  4150. res = cli_.Get("/person/john5");
  4151. ASSERT_TRUE(res);
  4152. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4153. }
  4154. TEST_F(ServerTest, DeleteMethod3) {
  4155. auto res = cli_.Get("/person/john6");
  4156. ASSERT_TRUE(res);
  4157. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4158. Params params;
  4159. params.emplace("name", "john6");
  4160. params.emplace("note", "tester");
  4161. res = cli_.Post("/person", params);
  4162. ASSERT_TRUE(res);
  4163. ASSERT_EQ(StatusCode::OK_200, res->status);
  4164. res = cli_.Get("/person/john6");
  4165. ASSERT_TRUE(res);
  4166. ASSERT_EQ(StatusCode::OK_200, res->status);
  4167. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4168. ASSERT_EQ("tester", res->body);
  4169. Params delete_params;
  4170. delete_params.emplace("name", "john6");
  4171. Headers headers;
  4172. headers.emplace("Custom-Header", "test-value");
  4173. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4174. ASSERT_TRUE(res);
  4175. ASSERT_EQ(StatusCode::OK_200, res->status);
  4176. ASSERT_EQ("DELETED", res->body);
  4177. res = cli_.Get("/person/john6");
  4178. ASSERT_TRUE(res);
  4179. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4180. }
  4181. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4182. Params params;
  4183. params.emplace("json", JSON_DATA);
  4184. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4185. ASSERT_TRUE(res);
  4186. ASSERT_EQ(StatusCode::OK_200, res->status);
  4187. ASSERT_EQ(JSON_DATA, res->body);
  4188. }
  4189. TEST_F(ServerTest, PostEmptyContent) {
  4190. auto res = cli_.Post("/empty", "", "text/plain");
  4191. ASSERT_TRUE(res);
  4192. ASSERT_EQ(StatusCode::OK_200, res->status);
  4193. ASSERT_EQ("empty", res->body);
  4194. }
  4195. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4196. auto res = cli_.Post("/empty-no-content-type");
  4197. ASSERT_TRUE(res);
  4198. ASSERT_EQ(StatusCode::OK_200, res->status);
  4199. ASSERT_EQ("empty-no-content-type", res->body);
  4200. }
  4201. TEST_F(ServerTest, PostPathOnly) {
  4202. auto res = cli_.Post("/path-only");
  4203. ASSERT_TRUE(res);
  4204. ASSERT_EQ(StatusCode::OK_200, res->status);
  4205. ASSERT_EQ("path-only", res->body);
  4206. }
  4207. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4208. auto res = cli_.Post("/path-headers-only",
  4209. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4210. ASSERT_TRUE(res);
  4211. ASSERT_EQ(StatusCode::OK_200, res->status);
  4212. ASSERT_EQ("path-headers-only", res->body);
  4213. }
  4214. TEST_F(ServerTest, PostLarge) {
  4215. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4216. ASSERT_TRUE(res);
  4217. ASSERT_EQ(StatusCode::OK_200, res->status);
  4218. EXPECT_EQ(LARGE_DATA, res->body);
  4219. }
  4220. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4221. auto res = cli_.Put("/empty-no-content-type");
  4222. ASSERT_TRUE(res);
  4223. ASSERT_EQ(StatusCode::OK_200, res->status);
  4224. ASSERT_EQ("empty-no-content-type", res->body);
  4225. }
  4226. TEST_F(ServerTest, GetMethodDir) {
  4227. auto res = cli_.Get("/dir/");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4231. auto body = R"(<html>
  4232. <head>
  4233. </head>
  4234. <body>
  4235. <a href="/dir/test.html">Test</a>
  4236. <a href="/hi">hi</a>
  4237. </body>
  4238. </html>
  4239. )";
  4240. EXPECT_EQ(body, res->body);
  4241. }
  4242. TEST_F(ServerTest, GetMethodDirTest) {
  4243. auto res = cli_.Get("/dir/test.html");
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::OK_200, res->status);
  4246. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4247. EXPECT_EQ("test.html", res->body);
  4248. }
  4249. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4250. auto res = cli_.Get("/dir/../dir/test.html");
  4251. ASSERT_TRUE(res);
  4252. EXPECT_EQ(StatusCode::OK_200, res->status);
  4253. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4254. EXPECT_EQ("test.html", res->body);
  4255. }
  4256. TEST_F(ServerTest, GetMethodInvalidPath) {
  4257. auto res = cli_.Get("/dir/../test.html");
  4258. ASSERT_TRUE(res);
  4259. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4260. }
  4261. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4262. auto res = cli_.Get("/../www/dir/test.html");
  4263. ASSERT_TRUE(res);
  4264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4265. }
  4266. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4267. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4270. }
  4271. TEST_F(ServerTest, GetMethodDirMountTest) {
  4272. auto res = cli_.Get("/mount/dir/test.html");
  4273. ASSERT_TRUE(res);
  4274. EXPECT_EQ(StatusCode::OK_200, res->status);
  4275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4276. EXPECT_EQ("test.html", res->body);
  4277. }
  4278. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4279. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(StatusCode::OK_200, res->status);
  4282. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4283. EXPECT_EQ("test.html", res->body);
  4284. }
  4285. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4286. auto res = cli_.Get("/mount/dir/../test.html");
  4287. ASSERT_TRUE(res);
  4288. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4289. }
  4290. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4291. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4292. ASSERT_TRUE(res);
  4293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4294. }
  4295. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4296. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4297. ASSERT_TRUE(res);
  4298. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4299. }
  4300. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4301. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4304. }
  4305. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4306. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4307. ASSERT_TRUE(res);
  4308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4309. }
  4310. TEST_F(ServerTest, PostMethod303) {
  4311. auto res = cli_.Post("/1", "body", "text/plain");
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4314. EXPECT_EQ("/2", res->get_header_value("Location"));
  4315. }
  4316. TEST_F(ServerTest, PostMethod303Redirect) {
  4317. cli_.set_follow_location(true);
  4318. auto res = cli_.Post("/1", "body", "text/plain");
  4319. ASSERT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. EXPECT_EQ("redirected.", res->body);
  4322. EXPECT_EQ("/2", res->location);
  4323. }
  4324. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4325. auto res = cli_.Get("/dir/test.abcde");
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::OK_200, res->status);
  4328. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4329. EXPECT_EQ("abcde", res->body);
  4330. }
  4331. TEST_F(ServerTest, StaticFileRange) {
  4332. auto res =
  4333. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4334. ASSERT_TRUE(res);
  4335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4336. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4337. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4338. EXPECT_EQ(true, res->has_header("Content-Range"));
  4339. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4340. EXPECT_EQ(std::string("cd"), res->body);
  4341. }
  4342. TEST_F(ServerTest, StaticFileRanges) {
  4343. auto res = cli_.Get("/dir/test.abcde",
  4344. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4345. ASSERT_TRUE(res);
  4346. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4347. EXPECT_TRUE(
  4348. res->get_header_value("Content-Type")
  4349. .find(
  4350. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4351. 0);
  4352. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4353. }
  4354. TEST_F(ServerTest, StaticFileRangeHead) {
  4355. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4356. ASSERT_TRUE(res);
  4357. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4358. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4359. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4360. EXPECT_EQ(true, res->has_header("Content-Range"));
  4361. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4362. }
  4363. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4364. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4365. ASSERT_TRUE(res);
  4366. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4368. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4369. EXPECT_EQ(true, res->has_header("Content-Range"));
  4370. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4371. res->get_header_value("Content-Range"));
  4372. EXPECT_EQ("LAST\n", res->body);
  4373. }
  4374. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4375. auto res =
  4376. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4377. ASSERT_TRUE(res);
  4378. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4379. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4380. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4381. EXPECT_EQ(true, res->has_header("Content-Range"));
  4382. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4383. }
  4384. TEST_F(ServerTest, StaticFileBigFile) {
  4385. auto res = cli_.Get("/dir/1MB.txt");
  4386. ASSERT_TRUE(res);
  4387. EXPECT_EQ(StatusCode::OK_200, res->status);
  4388. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4389. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4390. }
  4391. TEST_F(ServerTest, InvalidBaseDirMount) {
  4392. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4393. }
  4394. TEST_F(ServerTest, Binary) {
  4395. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4396. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4397. "application/octet-stream");
  4398. ASSERT_TRUE(res);
  4399. ASSERT_EQ(StatusCode::OK_200, res->status);
  4400. ASSERT_EQ(4U, res->body.size());
  4401. res = cli_.Put("/binary", binary.data(), binary.size(),
  4402. "application/octet-stream");
  4403. ASSERT_TRUE(res);
  4404. ASSERT_EQ(StatusCode::OK_200, res->status);
  4405. ASSERT_EQ(4U, res->body.size());
  4406. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4407. "application/octet-stream");
  4408. ASSERT_TRUE(res);
  4409. ASSERT_EQ(StatusCode::OK_200, res->status);
  4410. ASSERT_EQ(4U, res->body.size());
  4411. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4412. "application/octet-stream");
  4413. ASSERT_TRUE(res);
  4414. ASSERT_EQ(StatusCode::OK_200, res->status);
  4415. ASSERT_EQ(4U, res->body.size());
  4416. }
  4417. TEST_F(ServerTest, BinaryString) {
  4418. auto binary = std::string("\x00\x01\x02\x03", 4);
  4419. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4420. ASSERT_TRUE(res);
  4421. ASSERT_EQ(StatusCode::OK_200, res->status);
  4422. ASSERT_EQ(4U, res->body.size());
  4423. res = cli_.Put("/binary", binary, "application/octet-stream");
  4424. ASSERT_TRUE(res);
  4425. ASSERT_EQ(StatusCode::OK_200, res->status);
  4426. ASSERT_EQ(4U, res->body.size());
  4427. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4428. ASSERT_TRUE(res);
  4429. ASSERT_EQ(StatusCode::OK_200, res->status);
  4430. ASSERT_EQ(4U, res->body.size());
  4431. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4432. ASSERT_TRUE(res);
  4433. ASSERT_EQ(StatusCode::OK_200, res->status);
  4434. ASSERT_EQ(4U, res->body.size());
  4435. }
  4436. TEST_F(ServerTest, EmptyRequest) {
  4437. auto res = cli_.Get("");
  4438. ASSERT_TRUE(!res);
  4439. EXPECT_EQ(Error::Connection, res.error());
  4440. }
  4441. TEST_F(ServerTest, LongRequest) {
  4442. std::string request;
  4443. for (size_t i = 0; i < 545; i++) {
  4444. request += "/TooLongRequest";
  4445. }
  4446. request += "OK";
  4447. auto res = cli_.Get(request.c_str());
  4448. ASSERT_TRUE(res);
  4449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4450. }
  4451. TEST_F(ServerTest, TooLongRequest) {
  4452. std::string request;
  4453. for (size_t i = 0; i < 546; i++) {
  4454. request += "/TooLongRequest";
  4455. }
  4456. request += "_NG";
  4457. auto start = std::chrono::high_resolution_clock::now();
  4458. cli_.set_keep_alive(true);
  4459. auto res = cli_.Get(request.c_str());
  4460. auto end = std::chrono::high_resolution_clock::now();
  4461. auto elapsed =
  4462. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4463. .count();
  4464. ASSERT_TRUE(res);
  4465. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4466. EXPECT_LE(elapsed, 1000);
  4467. EXPECT_EQ("close", res->get_header_value("Connection"));
  4468. EXPECT_FALSE(cli_.is_socket_open());
  4469. }
  4470. TEST_F(ServerTest, AlmostTooLongRequest) {
  4471. // test for #2046 - URI length check shouldn't include other content on req
  4472. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4473. // leading /, space, HTTP/1.1)
  4474. std::string request =
  4475. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4476. auto res = cli_.Get(request.c_str());
  4477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4478. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4479. }
  4480. TEST_F(ServerTest, LongHeader) {
  4481. Request req;
  4482. req.method = "GET";
  4483. req.path = "/hi";
  4484. std::string host_and_port;
  4485. host_and_port += HOST;
  4486. host_and_port += ":";
  4487. host_and_port += std::to_string(PORT);
  4488. req.headers.emplace("Host", host_and_port.c_str());
  4489. req.headers.emplace("Accept", "*/*");
  4490. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4491. req.headers.emplace(
  4492. "Header-Name",
  4493. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4494. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4495. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4496. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4497. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4498. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4521. "@@@@@@@@@@@@@@@@");
  4522. auto res = std::make_shared<Response>();
  4523. auto error = Error::Success;
  4524. auto ret = cli_.send(req, *res, error);
  4525. ASSERT_TRUE(ret);
  4526. EXPECT_EQ(StatusCode::OK_200, res->status);
  4527. }
  4528. TEST_F(ServerTest, LongQueryValue) {
  4529. auto start = std::chrono::high_resolution_clock::now();
  4530. cli_.set_keep_alive(true);
  4531. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4532. auto end = std::chrono::high_resolution_clock::now();
  4533. auto elapsed =
  4534. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4535. .count();
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4538. EXPECT_LE(elapsed, 1000);
  4539. EXPECT_EQ("close", res->get_header_value("Connection"));
  4540. EXPECT_FALSE(cli_.is_socket_open());
  4541. }
  4542. TEST_F(ServerTest, TooLongQueryValue) {
  4543. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4544. ASSERT_FALSE(res);
  4545. EXPECT_EQ(Error::Read, res.error());
  4546. }
  4547. TEST_F(ServerTest, TooLongHeader) {
  4548. Request req;
  4549. req.method = "GET";
  4550. req.path = "/hi";
  4551. std::string host_and_port;
  4552. host_and_port += HOST;
  4553. host_and_port += ":";
  4554. host_and_port += std::to_string(PORT);
  4555. req.headers.emplace("Host", host_and_port.c_str());
  4556. req.headers.emplace("Accept", "*/*");
  4557. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4558. req.headers.emplace(
  4559. "Header-Name",
  4560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4588. "@@@@@@@@@@@@@@@@@");
  4589. auto res = std::make_shared<Response>();
  4590. auto error = Error::Success;
  4591. auto ret = cli_.send(req, *res, error);
  4592. ASSERT_TRUE(ret);
  4593. EXPECT_EQ(StatusCode::OK_200, res->status);
  4594. }
  4595. TEST_F(ServerTest, HeaderCountAtLimit) {
  4596. // Test with headers just under the 100 limit
  4597. httplib::Headers headers;
  4598. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4599. // This should keep us just under the 100 header limit
  4600. for (int i = 0; i < 95; i++) {
  4601. std::string name = "X-Test-Header-" + std::to_string(i);
  4602. std::string value = "value" + std::to_string(i);
  4603. headers.emplace(name, value);
  4604. }
  4605. // This should work fine as we're under the limit
  4606. auto res = cli_.Get("/hi", headers);
  4607. EXPECT_TRUE(res);
  4608. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4609. }
  4610. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4611. // Test with many headers to exceed the 100 limit
  4612. httplib::Headers headers;
  4613. // Add 150 headers to definitely exceed the 100 limit
  4614. for (int i = 0; i < 150; i++) {
  4615. std::string name = "X-Test-Header-" + std::to_string(i);
  4616. std::string value = "value" + std::to_string(i);
  4617. headers.emplace(name, value);
  4618. }
  4619. // This should fail due to exceeding header count limit
  4620. cli_.set_keep_alive(true);
  4621. auto res = cli_.Get("/hi", headers);
  4622. // The server should respond with 400 Bad Request
  4623. ASSERT_TRUE(res);
  4624. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4625. EXPECT_EQ("close", res->get_header_value("Connection"));
  4626. EXPECT_FALSE(cli_.is_socket_open());
  4627. }
  4628. TEST_F(ServerTest, PercentEncoding) {
  4629. auto res = cli_.Get("/e%6edwith%");
  4630. ASSERT_TRUE(res);
  4631. EXPECT_EQ(StatusCode::OK_200, res->status);
  4632. }
  4633. TEST_F(ServerTest, PercentEncodingUnicode) {
  4634. auto res = cli_.Get("/e%u006edwith%");
  4635. ASSERT_TRUE(res);
  4636. EXPECT_EQ(StatusCode::OK_200, res->status);
  4637. }
  4638. TEST_F(ServerTest, InvalidPercentEncoding) {
  4639. auto res = cli_.Get("/%endwith%");
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4642. }
  4643. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4644. auto res = cli_.Get("/%uendwith%");
  4645. ASSERT_TRUE(res);
  4646. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4647. }
  4648. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4649. auto res = cli_.Get("/hello?aaa=bbb%");
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4652. }
  4653. TEST_F(ServerTest, PlusSignEncoding) {
  4654. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. EXPECT_EQ("a +b", res->body);
  4658. }
  4659. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4660. // This test simulates a potential DoS attack using many headers
  4661. // to verify our security fix prevents memory exhaustion
  4662. httplib::Headers attack_headers;
  4663. // Attempt to add many headers like an attacker would (200 headers to far
  4664. // exceed limit)
  4665. for (int i = 0; i < 200; i++) {
  4666. std::string name = "X-Attack-Header-" + std::to_string(i);
  4667. std::string value = "attack_payload_" + std::to_string(i);
  4668. attack_headers.emplace(name, value);
  4669. }
  4670. // Try to POST with excessive headers
  4671. cli_.set_keep_alive(true);
  4672. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4673. // Should either fail or return 400 Bad Request due to security limit
  4674. if (res) {
  4675. // If we get a response, it should be 400 Bad Request
  4676. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4677. EXPECT_EQ("close", res->get_header_value("Connection"));
  4678. }
  4679. EXPECT_FALSE(cli_.is_socket_open());
  4680. }
  4681. TEST_F(ServerTest, MultipartFormData) {
  4682. UploadFormDataItems items = {
  4683. {"text1", "text default", "", ""},
  4684. {"text2", "aωb", "", ""},
  4685. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4686. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4687. {"file3", "", "", "application/octet-stream"},
  4688. {"file4", "", "", " application/json tmp-string "}};
  4689. auto res = cli_.Post("/multipart", items);
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::OK_200, res->status);
  4692. }
  4693. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4694. UploadFormDataItems items = {
  4695. {"text", "default text", "", ""},
  4696. {"multi_text1", "aaaaa", "", ""},
  4697. {"multi_text1", "bbbbb", "", ""},
  4698. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4699. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4700. "application/json"},
  4701. };
  4702. auto res = cli_.Post("/multipart/multi_file_values", items);
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. }
  4706. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4707. auto res = cli_.Get("/hi");
  4708. ASSERT_TRUE(res);
  4709. EXPECT_EQ(StatusCode::OK_200, res->status);
  4710. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4711. EXPECT_EQ("Hello World!", res->body);
  4712. }
  4713. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4714. Request req;
  4715. req.method = "POST";
  4716. req.path = "/chunked";
  4717. std::string host_and_port;
  4718. host_and_port += HOST;
  4719. host_and_port += ":";
  4720. host_and_port += std::to_string(PORT);
  4721. req.headers.emplace("Host", host_and_port.c_str());
  4722. req.headers.emplace("Accept", "*/*");
  4723. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4724. req.headers.emplace("Content-Type", "text/plain");
  4725. req.headers.emplace("Content-Length", "0");
  4726. req.headers.emplace(
  4727. "Transfer-Encoding",
  4728. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4729. // Client does not chunk, so make a chunked body manually.
  4730. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4731. auto res = std::make_shared<Response>();
  4732. auto error = Error::Success;
  4733. auto ret = cli_.send(req, *res, error);
  4734. ASSERT_TRUE(ret);
  4735. EXPECT_EQ(StatusCode::OK_200, res->status);
  4736. }
  4737. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4738. // rather than treat them as valid lengths.
  4739. template <typename ClientT>
  4740. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4741. Request req;
  4742. req.method = "POST";
  4743. req.path = "/chunked";
  4744. std::string host_and_port;
  4745. host_and_port += HOST;
  4746. host_and_port += ":";
  4747. host_and_port += std::to_string(PORT);
  4748. req.headers.emplace("Host", host_and_port.c_str());
  4749. req.headers.emplace("Content-Length", "0");
  4750. req.headers.emplace("Transfer-Encoding", "chunked");
  4751. req.body = body;
  4752. auto res = std::make_shared<Response>();
  4753. auto error = Error::Success;
  4754. ASSERT_TRUE(cli.send(req, *res, error));
  4755. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4756. }
  4757. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4758. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4759. }
  4760. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4761. expect_chunked_body_rejected(
  4762. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4763. }
  4764. TEST_F(ServerTest, GetStreamed2) {
  4765. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4766. ASSERT_TRUE(res);
  4767. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4768. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4769. EXPECT_EQ(true, res->has_header("Content-Range"));
  4770. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4771. EXPECT_EQ(std::string("ab"), res->body);
  4772. }
  4773. TEST_F(ServerTest, GetStreamed) {
  4774. auto res = cli_.Get("/streamed");
  4775. ASSERT_TRUE(res);
  4776. EXPECT_EQ(StatusCode::OK_200, res->status);
  4777. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4778. EXPECT_EQ(std::string("aaabbb"), res->body);
  4779. }
  4780. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4781. auto res = cli_.Get("/streamed-without-length",
  4782. Headers{make_range_header({{0, -1}})});
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ(false, res->has_header("Content-Length"));
  4786. EXPECT_EQ(false, res->has_header("Content-Range"));
  4787. EXPECT_EQ(std::string("abcdefg"), res->body);
  4788. }
  4789. TEST_F(ServerTest, GetStreamedWithRange1) {
  4790. auto res =
  4791. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4792. ASSERT_TRUE(res);
  4793. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4794. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4795. EXPECT_EQ(true, res->has_header("Content-Range"));
  4796. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4797. EXPECT_EQ(std::string("def"), res->body);
  4798. }
  4799. TEST_F(ServerTest, GetStreamedWithRange2) {
  4800. auto res =
  4801. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4802. ASSERT_TRUE(res);
  4803. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4804. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4805. EXPECT_EQ(true, res->has_header("Content-Range"));
  4806. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4807. EXPECT_EQ(std::string("bcdefg"), res->body);
  4808. }
  4809. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4810. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4811. ASSERT_TRUE(res);
  4812. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4813. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4814. EXPECT_EQ(true, res->has_header("Content-Range"));
  4815. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4816. EXPECT_EQ(std::string("efg"), res->body);
  4817. }
  4818. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4819. auto res =
  4820. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4823. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4824. EXPECT_EQ(false, res->has_header("Content-Range"));
  4825. EXPECT_EQ(0U, res->body.size());
  4826. }
  4827. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4828. auto res =
  4829. cli_.Get("/streamed-with-range",
  4830. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4831. "92233720368547758079223372036854775807"}});
  4832. ASSERT_TRUE(res);
  4833. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4834. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4835. EXPECT_EQ(false, res->has_header("Content-Range"));
  4836. EXPECT_EQ(0U, res->body.size());
  4837. }
  4838. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4839. auto res = cli_.Get(
  4840. "/with-range",
  4841. Headers{{"Range",
  4842. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4843. {"Accept-Encoding", ""}});
  4844. ASSERT_TRUE(res);
  4845. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4846. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4847. EXPECT_EQ(true, res->has_header("Content-Range"));
  4848. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4849. EXPECT_EQ(std::string("abcdefg"), res->body);
  4850. }
  4851. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4852. auto res = cli_.Get("/with-range", Headers{
  4853. {"Range", "bytes=0-"},
  4854. {"Accept-Encoding", ""},
  4855. });
  4856. ASSERT_TRUE(res);
  4857. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4858. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4859. EXPECT_EQ(true, res->has_header("Content-Range"));
  4860. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4861. EXPECT_EQ(std::string("abcdefg"), res->body);
  4862. }
  4863. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4864. auto res = cli_.Get("/streamed-with-range",
  4865. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4866. ASSERT_TRUE(res);
  4867. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4868. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4869. EXPECT_EQ(false, res->has_header("Content-Range"));
  4870. EXPECT_EQ(267U, res->body.size());
  4871. // Check that both range contents are present
  4872. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4873. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4874. // Check that Content-Range headers are present for both ranges
  4875. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4876. std::string::npos);
  4877. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4878. std::string::npos);
  4879. }
  4880. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4881. Ranges ranges;
  4882. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4883. ranges.emplace_back(0, -1);
  4884. }
  4885. auto res = cli_.Get("/streamed-with-range?error",
  4886. Headers{{make_range_header(ranges)}});
  4887. ASSERT_TRUE(res);
  4888. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4889. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4890. EXPECT_EQ(false, res->has_header("Content-Range"));
  4891. EXPECT_EQ(0U, res->body.size());
  4892. }
  4893. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4894. auto res = cli_.Get("/streamed-with-range",
  4895. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4896. ASSERT_TRUE(res);
  4897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4898. EXPECT_EQ(5U, res->body.size());
  4899. // Check that overlapping ranges are coalesced into a single range
  4900. EXPECT_EQ("bcdef", res->body);
  4901. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4902. // Should be single range, not multipart
  4903. EXPECT_TRUE(res->has_header("Content-Range"));
  4904. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4905. }
  4906. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4907. auto res = cli_.Get("/streamed-with-range",
  4908. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4909. ASSERT_TRUE(res);
  4910. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4911. EXPECT_EQ(268U, res->body.size());
  4912. // Check that both range contents are present
  4913. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4914. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4915. // Check that Content-Range headers are present for both ranges
  4916. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4917. std::string::npos);
  4918. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4919. std::string::npos);
  4920. }
  4921. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4922. auto res = cli_.Get("/streamed-with-range",
  4923. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4924. ASSERT_TRUE(res);
  4925. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4926. EXPECT_EQ(269U, res->body.size());
  4927. // Check that both duplicate range contents are present
  4928. size_t first_abc = res->body.find("abc\r\n");
  4929. EXPECT_TRUE(first_abc != std::string::npos);
  4930. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4931. EXPECT_TRUE(second_abc != std::string::npos);
  4932. // Check that Content-Range headers are present for both ranges
  4933. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4934. EXPECT_TRUE(first_range != std::string::npos);
  4935. size_t second_range =
  4936. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4937. EXPECT_TRUE(second_range != std::string::npos);
  4938. }
  4939. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4940. auto res =
  4941. cli_.Get("/streamed-with-range?error",
  4942. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4945. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4946. EXPECT_EQ(false, res->has_header("Content-Range"));
  4947. EXPECT_EQ(0U, res->body.size());
  4948. }
  4949. TEST_F(ServerTest, GetStreamedEndless) {
  4950. uint64_t offset = 0;
  4951. auto res = cli_.Get("/streamed-cancel",
  4952. [&](const char * /*data*/, uint64_t data_length) {
  4953. if (offset < 100) {
  4954. offset += data_length;
  4955. return true;
  4956. }
  4957. return false;
  4958. });
  4959. ASSERT_TRUE(!res);
  4960. EXPECT_EQ(Error::Canceled, res.error());
  4961. }
  4962. TEST_F(ServerTest, ClientStop) {
  4963. std::atomic_size_t count{4};
  4964. std::vector<std::thread> threads;
  4965. for (auto i = count.load(); i != 0; --i) {
  4966. threads.emplace_back([&]() {
  4967. auto res = cli_.Get("/streamed-cancel",
  4968. [&](const char *, uint64_t) { return true; });
  4969. --count;
  4970. ASSERT_TRUE(!res);
  4971. EXPECT_TRUE(res.error() == Error::Canceled ||
  4972. res.error() == Error::Read || res.error() == Error::Write);
  4973. });
  4974. }
  4975. std::this_thread::sleep_for(std::chrono::seconds(2));
  4976. while (count != 0) {
  4977. cli_.stop();
  4978. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4979. }
  4980. for (auto &t : threads) {
  4981. t.join();
  4982. }
  4983. }
  4984. TEST_F(ServerTest, GetWithRange1) {
  4985. auto res = cli_.Get("/with-range", Headers{
  4986. make_range_header({{3, 5}}),
  4987. {"Accept-Encoding", ""},
  4988. });
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4991. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4992. EXPECT_EQ(true, res->has_header("Content-Range"));
  4993. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4994. EXPECT_EQ(std::string("def"), res->body);
  4995. }
  4996. TEST_F(ServerTest, GetWithRange2) {
  4997. auto res = cli_.Get("/with-range", Headers{
  4998. make_range_header({{1, -1}}),
  4999. {"Accept-Encoding", ""},
  5000. });
  5001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5003. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5004. EXPECT_EQ(true, res->has_header("Content-Range"));
  5005. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5006. EXPECT_EQ(std::string("bcdefg"), res->body);
  5007. }
  5008. TEST_F(ServerTest, GetWithRange3) {
  5009. auto res = cli_.Get("/with-range", Headers{
  5010. make_range_header({{0, 0}}),
  5011. {"Accept-Encoding", ""},
  5012. });
  5013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5014. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5015. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5016. EXPECT_EQ(true, res->has_header("Content-Range"));
  5017. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5018. EXPECT_EQ(std::string("a"), res->body);
  5019. }
  5020. TEST_F(ServerTest, GetWithRange4) {
  5021. auto res = cli_.Get("/with-range", Headers{
  5022. make_range_header({{-1, 2}}),
  5023. {"Accept-Encoding", ""},
  5024. });
  5025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5027. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5028. EXPECT_EQ(true, res->has_header("Content-Range"));
  5029. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5030. EXPECT_EQ(std::string("fg"), res->body);
  5031. }
  5032. TEST_F(ServerTest, GetWithRange5) {
  5033. auto res = cli_.Get("/with-range", Headers{
  5034. make_range_header({{0, 5}}),
  5035. {"Accept-Encoding", ""},
  5036. });
  5037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5039. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5040. EXPECT_EQ(true, res->has_header("Content-Range"));
  5041. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5042. EXPECT_EQ(std::string("abcdef"), res->body);
  5043. }
  5044. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5045. auto res =
  5046. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5047. ASSERT_TRUE(res);
  5048. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5049. }
  5050. TEST_F(ServerTest, GetWithRangeMultipart) {
  5051. auto res =
  5052. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5053. ASSERT_TRUE(res);
  5054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5055. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5056. EXPECT_EQ(false, res->has_header("Content-Range"));
  5057. EXPECT_EQ(267U, res->body.size());
  5058. }
  5059. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5060. auto res = cli_.Get("/with-range",
  5061. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5062. ASSERT_TRUE(res);
  5063. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5064. }
  5065. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5066. auto res = cli_.Get("/with-range-customized-response",
  5067. Headers{{make_range_header({{1, 2}})}});
  5068. ASSERT_TRUE(res);
  5069. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5070. EXPECT_EQ(true, res->has_header("Content-Length"));
  5071. EXPECT_EQ(false, res->has_header("Content-Range"));
  5072. EXPECT_EQ(JSON_DATA, res->body);
  5073. }
  5074. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5075. auto res = cli_.Get("/with-range-customized-response",
  5076. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5077. ASSERT_TRUE(res);
  5078. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5079. EXPECT_EQ(true, res->has_header("Content-Length"));
  5080. EXPECT_EQ(false, res->has_header("Content-Range"));
  5081. EXPECT_EQ(JSON_DATA, res->body);
  5082. }
  5083. TEST_F(ServerTest, Issue1772) {
  5084. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5085. ASSERT_TRUE(res);
  5086. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5087. }
  5088. TEST_F(ServerTest, Issue609) {
  5089. auto res = cli_.Delete("/issue609");
  5090. ASSERT_TRUE(res);
  5091. EXPECT_EQ(StatusCode::OK_200, res->status);
  5092. EXPECT_EQ(std::string("ok"), res->body);
  5093. }
  5094. TEST_F(ServerTest, GetStreamedChunked) {
  5095. auto res = cli_.Get("/streamed-chunked");
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ(std::string("123456789"), res->body);
  5099. }
  5100. TEST_F(ServerTest, GetStreamedChunked2) {
  5101. auto res = cli_.Get("/streamed-chunked2");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ(std::string("123456789"), res->body);
  5105. }
  5106. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5107. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5108. ASSERT_TRUE(res);
  5109. EXPECT_EQ(StatusCode::OK_200, res->status);
  5110. EXPECT_EQ(std::string("123456789"), res->body);
  5111. EXPECT_TRUE(res->has_header("Trailer"));
  5112. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5113. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5114. // Trailers are now stored separately from headers (security fix)
  5115. EXPECT_EQ(2U, res->trailers.size());
  5116. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5117. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5118. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5119. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5120. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5121. // Verify trailers are NOT in headers (security verification)
  5122. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5123. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5124. }
  5125. TEST_F(ServerTest, LargeChunkedPost) {
  5126. Request req;
  5127. req.method = "POST";
  5128. req.path = "/large-chunked";
  5129. std::string host_and_port;
  5130. host_and_port += HOST;
  5131. host_and_port += ":";
  5132. host_and_port += std::to_string(PORT);
  5133. req.headers.emplace("Host", host_and_port.c_str());
  5134. req.headers.emplace("Accept", "*/*");
  5135. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5136. req.headers.emplace("Content-Type", "text/plain");
  5137. req.headers.emplace("Content-Length", "0");
  5138. req.headers.emplace("Transfer-Encoding", "chunked");
  5139. std::string long_string(30 * 1024u, 'a');
  5140. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5141. // Attempt to make a large enough post to exceed OS buffers, to test that
  5142. // the server handles short reads if the full chunk data isn't available.
  5143. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5144. auto res = std::make_shared<Response>();
  5145. auto error = Error::Success;
  5146. auto ret = cli_.send(req, *res, error);
  5147. ASSERT_TRUE(ret);
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. }
  5150. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5151. auto res = cli_.Get("/remote_addr");
  5152. ASSERT_TRUE(res);
  5153. EXPECT_EQ(StatusCode::OK_200, res->status);
  5154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5155. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5156. }
  5157. TEST_F(ServerTest, GetMethodLocalAddr) {
  5158. auto res = cli_.Get("/local_addr");
  5159. ASSERT_TRUE(res);
  5160. EXPECT_EQ(StatusCode::OK_200, res->status);
  5161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5162. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5163. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5164. }
  5165. TEST_F(ServerTest, HTTPResponseSplitting) {
  5166. auto res = cli_.Get("/http_response_splitting");
  5167. ASSERT_TRUE(res);
  5168. EXPECT_EQ(StatusCode::OK_200, res->status);
  5169. }
  5170. TEST_F(ServerTest, SlowRequest) {
  5171. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5172. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5173. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5174. }
  5175. #if 0
  5176. TEST_F(ServerTest, SlowPost) {
  5177. char buffer[64 * 1024];
  5178. memset(buffer, 0x42, sizeof(buffer));
  5179. auto res = cli_.Post(
  5180. "/slowpost", 64 * 1024 * 1024,
  5181. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5182. auto ret = sink.write(buffer, sizeof(buffer));
  5183. EXPECT_TRUE(ret);
  5184. return true;
  5185. },
  5186. "text/plain");
  5187. ASSERT_TRUE(res);
  5188. EXPECT_EQ(StatusCode::OK_200, res->status);
  5189. }
  5190. TEST_F(ServerTest, SlowPostFail) {
  5191. char buffer[64 * 1024];
  5192. memset(buffer, 0x42, sizeof(buffer));
  5193. cli_.set_write_timeout(std::chrono::seconds(0));
  5194. auto res = cli_.Post(
  5195. "/slowpost", 64 * 1024 * 1024,
  5196. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5197. sink.write(buffer, sizeof(buffer));
  5198. return true;
  5199. },
  5200. "text/plain");
  5201. ASSERT_TRUE(!res);
  5202. EXPECT_EQ(Error::Write, res.error());
  5203. }
  5204. #endif
  5205. TEST_F(ServerTest, Put) {
  5206. auto res = cli_.Put("/put", "PUT", "text/plain");
  5207. ASSERT_TRUE(res);
  5208. EXPECT_EQ(StatusCode::OK_200, res->status);
  5209. EXPECT_EQ("PUT", res->body);
  5210. }
  5211. TEST_F(ServerTest, PutWithContentProvider) {
  5212. auto res = cli_.Put(
  5213. "/put", 3,
  5214. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5215. sink.os << "PUT";
  5216. return true;
  5217. },
  5218. "text/plain");
  5219. ASSERT_TRUE(res);
  5220. EXPECT_EQ(StatusCode::OK_200, res->status);
  5221. EXPECT_EQ("PUT", res->body);
  5222. }
  5223. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5224. auto res = cli_.Post(
  5225. "/post", 42,
  5226. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5227. return false;
  5228. },
  5229. "text/plain");
  5230. ASSERT_TRUE(!res);
  5231. EXPECT_EQ(Error::Canceled, res.error());
  5232. }
  5233. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5234. auto res = cli_.Put(
  5235. "/put",
  5236. [](size_t /*offset*/, DataSink &sink) {
  5237. sink.os << "PUT";
  5238. sink.done();
  5239. return true;
  5240. },
  5241. "text/plain");
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. EXPECT_EQ("PUT", res->body);
  5245. }
  5246. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5247. auto res = cli_.Post(
  5248. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5249. "text/plain");
  5250. ASSERT_TRUE(!res);
  5251. EXPECT_EQ(Error::Canceled, res.error());
  5252. }
  5253. TEST_F(ServerTest, PostLoopBack) {
  5254. std::string body;
  5255. auto res = cli_.Post(
  5256. "/post-loopback", 9,
  5257. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5258. EXPECT_EQ(9u, length);
  5259. sink.write("123", 3);
  5260. sink.write("456", 3);
  5261. sink.write("789", 3);
  5262. return true;
  5263. },
  5264. "text/plain",
  5265. [&body](const char *data, size_t data_length) {
  5266. body.append(data, data_length);
  5267. return true;
  5268. });
  5269. ASSERT_TRUE(res);
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("123456789", body);
  5272. }
  5273. TEST_F(ServerTest, PutLoopBack) {
  5274. std::string body;
  5275. auto res = cli_.Put(
  5276. "/put-loopback", 9,
  5277. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5278. EXPECT_EQ(9u, length);
  5279. sink.write("123", 3);
  5280. sink.write("456", 3);
  5281. sink.write("789", 3);
  5282. return true;
  5283. },
  5284. "text/plain",
  5285. [&body](const char *data, size_t data_length) {
  5286. body.append(data, data_length);
  5287. return true;
  5288. });
  5289. ASSERT_TRUE(res);
  5290. EXPECT_EQ(StatusCode::OK_200, res->status);
  5291. EXPECT_EQ("123456789", body);
  5292. }
  5293. TEST_F(ServerTest, PatchLoopBack) {
  5294. std::string body;
  5295. auto res = cli_.Patch(
  5296. "/patch-loopback", 9,
  5297. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5298. EXPECT_EQ(9u, length);
  5299. sink.write("123", 3);
  5300. sink.write("456", 3);
  5301. sink.write("789", 3);
  5302. return true;
  5303. },
  5304. "text/plain",
  5305. [&body](const char *data, size_t data_length) {
  5306. body.append(data, data_length);
  5307. return true;
  5308. });
  5309. ASSERT_TRUE(res);
  5310. EXPECT_EQ(StatusCode::OK_200, res->status);
  5311. EXPECT_EQ("123456789", body);
  5312. }
  5313. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5314. std::string body;
  5315. auto res = cli_.Post(
  5316. "/post-loopback",
  5317. [](size_t /*offset*/, DataSink &sink) {
  5318. sink.write("123", 3);
  5319. sink.write("456", 3);
  5320. sink.write("789", 3);
  5321. sink.done();
  5322. return true;
  5323. },
  5324. "text/plain",
  5325. [&body](const char *data, size_t data_length) {
  5326. body.append(data, data_length);
  5327. return true;
  5328. });
  5329. ASSERT_TRUE(res);
  5330. EXPECT_EQ(StatusCode::OK_200, res->status);
  5331. EXPECT_EQ("123456789", body);
  5332. }
  5333. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5334. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5335. cli_.set_compress(true);
  5336. auto res = cli_.Put(
  5337. "/put", 3,
  5338. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5339. sink.os << "PUT";
  5340. return true;
  5341. },
  5342. "text/plain");
  5343. ASSERT_TRUE(res);
  5344. EXPECT_EQ(StatusCode::OK_200, res->status);
  5345. EXPECT_EQ("PUT", res->body);
  5346. }
  5347. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5348. cli_.set_compress(true);
  5349. auto res = cli_.Post(
  5350. "/post", 42,
  5351. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5352. return false;
  5353. },
  5354. "text/plain");
  5355. ASSERT_TRUE(!res);
  5356. EXPECT_EQ(Error::Canceled, res.error());
  5357. }
  5358. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5359. cli_.set_compress(true);
  5360. auto res = cli_.Put(
  5361. "/put",
  5362. [](size_t /*offset*/, DataSink &sink) {
  5363. sink.os << "PUT";
  5364. sink.done();
  5365. return true;
  5366. },
  5367. "text/plain");
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. EXPECT_EQ("PUT", res->body);
  5371. }
  5372. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5373. cli_.set_compress(true);
  5374. auto res = cli_.Post(
  5375. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5376. "text/plain");
  5377. ASSERT_TRUE(!res);
  5378. EXPECT_EQ(Error::Canceled, res.error());
  5379. }
  5380. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5381. cli_.set_compress(true);
  5382. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5383. ASSERT_TRUE(res);
  5384. EXPECT_EQ(StatusCode::OK_200, res->status);
  5385. EXPECT_EQ(LARGE_DATA, res->body);
  5386. }
  5387. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5388. #ifdef CPPHTTPLIB_SSL_ENABLED
  5389. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5390. Client cli(s.c_str());
  5391. cli.enable_server_certificate_verification(false);
  5392. #else
  5393. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5394. Client cli(s.c_str());
  5395. #endif
  5396. cli.set_compress(true);
  5397. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5398. ASSERT_TRUE(res);
  5399. EXPECT_EQ(StatusCode::OK_200, res->status);
  5400. EXPECT_EQ(LARGE_DATA, res->body);
  5401. // The compressed size should be less than a 10th of the original. May vary
  5402. // depending on the zlib library.
  5403. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5404. static_cast<uint64_t>(10 * 1024 * 1024));
  5405. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5406. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5407. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5408. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5409. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5410. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5411. #endif
  5412. }
  5413. TEST_F(ServerTest, PutContentWithDeflate) {
  5414. cli_.set_compress(false);
  5415. Headers headers;
  5416. headers.emplace("Content-Encoding", "deflate");
  5417. // PUT in deflate format:
  5418. auto res = cli_.Put("/put", headers,
  5419. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5420. ASSERT_TRUE(res);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. EXPECT_EQ("PUT", res->body);
  5423. }
  5424. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5425. Headers headers;
  5426. headers.emplace("Accept-Encoding", "gzip, deflate");
  5427. auto res = cli_.Get("/streamed-chunked", headers);
  5428. ASSERT_TRUE(res);
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ(std::string("123456789"), res->body);
  5431. }
  5432. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5433. Headers headers;
  5434. headers.emplace("Accept-Encoding", "gzip, deflate");
  5435. auto res = cli_.Get("/streamed-chunked2", headers);
  5436. ASSERT_TRUE(res);
  5437. EXPECT_EQ(StatusCode::OK_200, res->status);
  5438. EXPECT_EQ(std::string("123456789"), res->body);
  5439. }
  5440. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5441. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5442. ASSERT_TRUE(res);
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. }
  5445. TEST(GzipDecompressor, ChunkedDecompression) {
  5446. std::string data;
  5447. for (size_t i = 0; i < 32 * 1024; ++i) {
  5448. data.push_back(static_cast<char>('a' + i % 26));
  5449. }
  5450. std::string compressed_data;
  5451. {
  5452. httplib::detail::gzip_compressor compressor;
  5453. bool result = compressor.compress(
  5454. data.data(), data.size(),
  5455. /*last=*/true,
  5456. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5457. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5458. compressed_data_size);
  5459. return true;
  5460. });
  5461. ASSERT_TRUE(result);
  5462. }
  5463. std::string decompressed_data;
  5464. {
  5465. httplib::detail::gzip_decompressor decompressor;
  5466. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5467. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5468. size_t chunk_size = 130;
  5469. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5470. chunk_begin += chunk_size) {
  5471. size_t current_chunk_size =
  5472. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5473. bool result = decompressor.decompress(
  5474. compressed_data.data() + chunk_begin, current_chunk_size,
  5475. [&](const char *decompressed_data_chunk,
  5476. size_t decompressed_data_chunk_size) {
  5477. decompressed_data.insert(decompressed_data.size(),
  5478. decompressed_data_chunk,
  5479. decompressed_data_chunk_size);
  5480. return true;
  5481. });
  5482. ASSERT_TRUE(result);
  5483. }
  5484. }
  5485. ASSERT_EQ(data, decompressed_data);
  5486. }
  5487. TEST(GzipDecompressor, DeflateDecompression) {
  5488. std::string original_text = "Raw deflate without gzip";
  5489. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5490. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5491. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5492. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5493. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5494. std::string decompressed_data;
  5495. {
  5496. httplib::detail::gzip_decompressor decompressor;
  5497. bool result = decompressor.decompress(
  5498. compressed_data.data(), compressed_data.size(),
  5499. [&](const char *decompressed_data_chunk,
  5500. size_t decompressed_data_chunk_size) {
  5501. decompressed_data.insert(decompressed_data.size(),
  5502. decompressed_data_chunk,
  5503. decompressed_data_chunk_size);
  5504. return true;
  5505. });
  5506. ASSERT_TRUE(result);
  5507. }
  5508. ASSERT_EQ(original_text, decompressed_data);
  5509. }
  5510. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5511. std::string original_text = "Raw deflate without gzip";
  5512. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5513. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5514. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5515. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5516. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5517. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5518. std::string decompressed_data;
  5519. {
  5520. httplib::detail::gzip_decompressor decompressor;
  5521. bool result = decompressor.decompress(
  5522. compressed_data.data(), compressed_data.size(),
  5523. [&](const char *decompressed_data_chunk,
  5524. size_t decompressed_data_chunk_size) {
  5525. decompressed_data.insert(decompressed_data.size(),
  5526. decompressed_data_chunk,
  5527. decompressed_data_chunk_size);
  5528. return true;
  5529. });
  5530. ASSERT_TRUE(result);
  5531. }
  5532. ASSERT_EQ(original_text, decompressed_data);
  5533. }
  5534. #endif
  5535. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5536. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5537. Headers headers;
  5538. headers.emplace("Accept-Encoding", "br");
  5539. auto res = cli_.Get("/streamed-chunked", headers);
  5540. ASSERT_TRUE(res);
  5541. EXPECT_EQ(StatusCode::OK_200, res->status);
  5542. EXPECT_EQ(std::string("123456789"), res->body);
  5543. }
  5544. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5545. Headers headers;
  5546. headers.emplace("Accept-Encoding", "br");
  5547. auto res = cli_.Get("/streamed-chunked2", headers);
  5548. ASSERT_TRUE(res);
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ(std::string("123456789"), res->body);
  5551. }
  5552. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5553. cli_.set_compress(true);
  5554. auto res = cli_.Put(
  5555. "/put", 3,
  5556. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5557. sink.os << "PUT";
  5558. return true;
  5559. },
  5560. "text/plain");
  5561. ASSERT_TRUE(res);
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. EXPECT_EQ("PUT", res->body);
  5564. }
  5565. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5566. cli_.set_compress(true);
  5567. auto res = cli_.Put(
  5568. "/put",
  5569. [](size_t /*offset*/, DataSink &sink) {
  5570. sink.os << "PUT";
  5571. sink.done();
  5572. return true;
  5573. },
  5574. "text/plain");
  5575. ASSERT_TRUE(res);
  5576. EXPECT_EQ(StatusCode::OK_200, res->status);
  5577. EXPECT_EQ("PUT", res->body);
  5578. }
  5579. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5580. cli_.set_compress(true);
  5581. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5582. ASSERT_TRUE(res);
  5583. EXPECT_EQ(StatusCode::OK_200, res->status);
  5584. EXPECT_EQ(LARGE_DATA, res->body);
  5585. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5586. }
  5587. #endif
  5588. TEST_F(ServerTest, Patch) {
  5589. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5590. ASSERT_TRUE(res);
  5591. EXPECT_EQ(StatusCode::OK_200, res->status);
  5592. EXPECT_EQ("PATCH", res->body);
  5593. }
  5594. TEST_F(ServerTest, Delete) {
  5595. auto res = cli_.Delete("/delete");
  5596. ASSERT_TRUE(res);
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. EXPECT_EQ("DELETE", res->body);
  5599. }
  5600. TEST_F(ServerTest, DeleteContentReceiver) {
  5601. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5602. ASSERT_TRUE(res);
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. EXPECT_EQ("content", res->body);
  5605. }
  5606. TEST_F(ServerTest, Options) {
  5607. auto res = cli_.Options("*");
  5608. ASSERT_TRUE(res);
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5611. EXPECT_TRUE(res->body.empty());
  5612. }
  5613. TEST_F(ServerTest, URL) {
  5614. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5615. ASSERT_TRUE(res);
  5616. EXPECT_EQ(StatusCode::OK_200, res->status);
  5617. }
  5618. TEST_F(ServerTest, ArrayParam) {
  5619. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5620. ASSERT_TRUE(res);
  5621. EXPECT_EQ(StatusCode::OK_200, res->status);
  5622. }
  5623. TEST_F(ServerTest, ArrayParamValues) {
  5624. auto res =
  5625. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5626. ASSERT_TRUE(res);
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. TEST_F(ServerTest, NoMultipleHeaders) {
  5630. Headers headers = {{"Content-Length", "5"}};
  5631. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5632. "text/plain");
  5633. ASSERT_TRUE(res);
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. }
  5636. TEST_F(ServerTest, PostContentReceiver) {
  5637. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5638. ASSERT_TRUE(res);
  5639. ASSERT_EQ(StatusCode::OK_200, res->status);
  5640. ASSERT_EQ("content", res->body);
  5641. }
  5642. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5643. UploadFormDataItems items = {
  5644. {"text1", "text default", "", ""},
  5645. {"text2", "aωb", "", ""},
  5646. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5647. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5648. {"file3", "", "", "application/octet-stream"},
  5649. };
  5650. auto res = cli_.Post("/content_receiver", items);
  5651. ASSERT_TRUE(res);
  5652. EXPECT_EQ(StatusCode::OK_200, res->status);
  5653. }
  5654. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5655. UploadFormDataItems items = {
  5656. {"text1", "text default", "", ""},
  5657. {"text2", "aωb", "", ""},
  5658. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5659. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5660. {"file3", "", "", "application/octet-stream"},
  5661. };
  5662. auto boundary = std::string("+++++");
  5663. std::string body;
  5664. for (const auto &item : items) {
  5665. body += "--" + boundary + "\r\n";
  5666. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5667. if (!item.filename.empty()) {
  5668. body += "; filename=\"" + item.filename + "\"";
  5669. }
  5670. body += "\r\n";
  5671. if (!item.content_type.empty()) {
  5672. body += "Content-Type: " + item.content_type + "\r\n";
  5673. }
  5674. body += "\r\n";
  5675. body += item.content + "\r\n";
  5676. }
  5677. body += "--" + boundary + "--\r\n";
  5678. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5679. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5680. ASSERT_TRUE(res);
  5681. EXPECT_EQ(StatusCode::OK_200, res->status);
  5682. }
  5683. TEST(MultipartFormDataTest, FieldEscaping) {
  5684. Server svr;
  5685. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5686. const ContentReader &content_reader) {
  5687. ASSERT_TRUE(req.is_multipart_form_data());
  5688. std::vector<FormData> received;
  5689. content_reader(
  5690. [&](const FormData &file) {
  5691. received.push_back(file);
  5692. return true;
  5693. },
  5694. [&](const char *data, size_t data_length) {
  5695. received.back().content.append(data, data_length);
  5696. return true;
  5697. });
  5698. // '"', CR and LF in names and filenames are escaped following the
  5699. // WHATWG HTML standard, so each part still parses as a single part
  5700. // with no injected headers. Content types get CR/LF escaped too,
  5701. // while '"' (legal there, e.g. quoted charset) is preserved.
  5702. ASSERT_EQ(4U, received.size());
  5703. EXPECT_EQ("na%22me", received[0].name);
  5704. EXPECT_EQ("quoted name", received[0].content);
  5705. EXPECT_EQ("file", received[1].name);
  5706. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5707. received[1].filename);
  5708. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5709. EXPECT_EQ("injected", received[1].content);
  5710. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5711. EXPECT_EQ("my%22file.txt", received[2].filename);
  5712. EXPECT_EQ("cr lf name", received[2].content);
  5713. EXPECT_EQ("typed", received[3].name);
  5714. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5715. received[3].content_type);
  5716. EXPECT_EQ("typed content", received[3].content);
  5717. });
  5718. auto port = svr.bind_to_any_port("localhost");
  5719. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5720. auto se = detail::scope_exit([&] {
  5721. svr.stop();
  5722. t.join();
  5723. ASSERT_FALSE(svr.is_running());
  5724. });
  5725. svr.wait_until_ready();
  5726. Client cli("localhost", port);
  5727. UploadFormDataItems items = {
  5728. {"na\"me", "quoted name", "", ""},
  5729. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5730. "application/octet-stream"},
  5731. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5732. {"typed", "typed content", "",
  5733. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5734. };
  5735. auto res = cli.Post("/post", items);
  5736. ASSERT_TRUE(res);
  5737. EXPECT_EQ(StatusCode::OK_200, res->status);
  5738. }
  5739. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5740. const UploadFormDataItems items = {
  5741. {"name1", "Content 1", "", ""},
  5742. {"name2", "Content 2", "file2.txt", "text/plain"},
  5743. };
  5744. Server svr;
  5745. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5746. const ContentReader &content_reader) {
  5747. ASSERT_TRUE(req.is_multipart_form_data());
  5748. std::vector<FormData> received;
  5749. content_reader(
  5750. [&](const FormData &file) {
  5751. received.push_back(file);
  5752. return true;
  5753. },
  5754. [&](const char *data, size_t data_length) {
  5755. received.back().content.append(data, data_length);
  5756. return true;
  5757. });
  5758. ASSERT_EQ(2U, received.size());
  5759. EXPECT_EQ("name1", received[0].name);
  5760. EXPECT_EQ("Content 1", received[0].content);
  5761. EXPECT_EQ("name2", received[1].name);
  5762. EXPECT_EQ("Content 2", received[1].content);
  5763. EXPECT_EQ("file2.txt", received[1].filename);
  5764. EXPECT_EQ("text/plain", received[1].content_type);
  5765. });
  5766. auto port = svr.bind_to_any_port("localhost");
  5767. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5768. auto se = detail::scope_exit([&] {
  5769. svr.stop();
  5770. t.join();
  5771. ASSERT_FALSE(svr.is_running());
  5772. });
  5773. svr.wait_until_ready();
  5774. Client cli("localhost", port);
  5775. // Whole-body serialization with a generated boundary
  5776. {
  5777. MultipartFormDataWriter writer;
  5778. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5779. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5780. writer.content_type());
  5781. auto body = writer.serialize(items);
  5782. EXPECT_EQ(body.size(), writer.content_length(items));
  5783. auto res = cli.Post("/post", body, writer.content_type());
  5784. ASSERT_TRUE(res);
  5785. EXPECT_EQ(StatusCode::OK_200, res->status);
  5786. }
  5787. // Per-part framing with a custom boundary via a content provider
  5788. {
  5789. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5790. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5791. MultipartFormDataWriter writer("custom-boundary_123");
  5792. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5793. std::string body;
  5794. for (const auto &item : items) {
  5795. body += writer.item_begin(item);
  5796. body += item.content;
  5797. body += MultipartFormDataWriter::item_end();
  5798. }
  5799. body += writer.finish();
  5800. EXPECT_EQ(body.size(), writer.content_length(items));
  5801. auto res = cli.Post(
  5802. "/post", body.size(),
  5803. [&](size_t offset, size_t length, DataSink &sink) {
  5804. sink.write(body.data() + offset, length);
  5805. return true;
  5806. },
  5807. writer.content_type());
  5808. ASSERT_TRUE(res);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. }
  5811. }
  5812. TEST_F(ServerTest, PostContentReceiverGzip) {
  5813. cli_.set_compress(true);
  5814. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5815. ASSERT_TRUE(res);
  5816. ASSERT_EQ(StatusCode::OK_200, res->status);
  5817. ASSERT_EQ("content", res->body);
  5818. }
  5819. TEST_F(ServerTest, PutContentReceiver) {
  5820. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5821. ASSERT_TRUE(res);
  5822. ASSERT_EQ(StatusCode::OK_200, res->status);
  5823. ASSERT_EQ("content", res->body);
  5824. }
  5825. TEST_F(ServerTest, PatchContentReceiver) {
  5826. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5827. ASSERT_TRUE(res);
  5828. ASSERT_EQ(StatusCode::OK_200, res->status);
  5829. ASSERT_EQ("content", res->body);
  5830. }
  5831. template <typename ClientType>
  5832. void TestWithHeadersAndContentReceiver(
  5833. ClientType &cli,
  5834. std::function<Result(ClientType &, const std::string &, const Headers &,
  5835. const std::string &, const std::string &,
  5836. ContentReceiver, DownloadProgress)>
  5837. request_func) {
  5838. Headers headers;
  5839. headers.emplace("X-Custom-Header", "test-value");
  5840. std::string received_body;
  5841. auto res = request_func(
  5842. cli, "/content_receiver", headers, "content", "application/json",
  5843. [&](const char *data, size_t data_length) {
  5844. received_body.append(data, data_length);
  5845. return true;
  5846. },
  5847. nullptr);
  5848. ASSERT_TRUE(res);
  5849. EXPECT_EQ(StatusCode::OK_200, res->status);
  5850. EXPECT_EQ("content", received_body);
  5851. }
  5852. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5853. #ifdef CPPHTTPLIB_SSL_ENABLED
  5854. using ClientT = SSLClient;
  5855. #else
  5856. using ClientT = Client;
  5857. #endif
  5858. TestWithHeadersAndContentReceiver<ClientT>(
  5859. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5860. const std::string &body, const std::string &content_type,
  5861. ContentReceiver receiver, DownloadProgress progress) {
  5862. return cli.Post(path, headers, body, content_type, receiver, progress);
  5863. });
  5864. }
  5865. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5866. #ifdef CPPHTTPLIB_SSL_ENABLED
  5867. using ClientT = SSLClient;
  5868. #else
  5869. using ClientT = Client;
  5870. #endif
  5871. TestWithHeadersAndContentReceiver<ClientT>(
  5872. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5873. const std::string &body, const std::string &content_type,
  5874. ContentReceiver receiver, DownloadProgress progress) {
  5875. return cli.Put(path, headers, body, content_type, receiver, progress);
  5876. });
  5877. }
  5878. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5879. #ifdef CPPHTTPLIB_SSL_ENABLED
  5880. using ClientT = SSLClient;
  5881. #else
  5882. using ClientT = Client;
  5883. #endif
  5884. TestWithHeadersAndContentReceiver<ClientT>(
  5885. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5886. const std::string &body, const std::string &content_type,
  5887. ContentReceiver receiver, DownloadProgress progress) {
  5888. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5889. });
  5890. }
  5891. template <typename ClientType>
  5892. void TestWithHeadersAndContentReceiverWithProgress(
  5893. ClientType &cli,
  5894. std::function<Result(ClientType &, const std::string &, const Headers &,
  5895. const std::string &, const std::string &,
  5896. ContentReceiver, DownloadProgress)>
  5897. request_func) {
  5898. Headers headers;
  5899. headers.emplace("X-Test-Header", "progress-test");
  5900. std::string received_body;
  5901. auto progress_called = false;
  5902. auto res = request_func(
  5903. cli, "/content_receiver", headers, "content", "text/plain",
  5904. [&](const char *data, size_t data_length) {
  5905. received_body.append(data, data_length);
  5906. return true;
  5907. },
  5908. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5909. progress_called = true;
  5910. return true;
  5911. });
  5912. ASSERT_TRUE(res);
  5913. EXPECT_EQ(StatusCode::OK_200, res->status);
  5914. EXPECT_EQ("content", received_body);
  5915. EXPECT_TRUE(progress_called);
  5916. }
  5917. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5918. #ifdef CPPHTTPLIB_SSL_ENABLED
  5919. using ClientT = SSLClient;
  5920. #else
  5921. using ClientT = Client;
  5922. #endif
  5923. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5924. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5925. const std::string &body, const std::string &content_type,
  5926. ContentReceiver receiver, DownloadProgress progress) {
  5927. return cli.Post(path, headers, body, content_type, receiver, progress);
  5928. });
  5929. }
  5930. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5931. #ifdef CPPHTTPLIB_SSL_ENABLED
  5932. using ClientT = SSLClient;
  5933. #else
  5934. using ClientT = Client;
  5935. #endif
  5936. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5937. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5938. const std::string &body, const std::string &content_type,
  5939. ContentReceiver receiver, DownloadProgress progress) {
  5940. return cli.Put(path, headers, body, content_type, receiver, progress);
  5941. });
  5942. }
  5943. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5944. #ifdef CPPHTTPLIB_SSL_ENABLED
  5945. using ClientT = SSLClient;
  5946. #else
  5947. using ClientT = Client;
  5948. #endif
  5949. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5950. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5951. const std::string &body, const std::string &content_type,
  5952. ContentReceiver receiver, DownloadProgress progress) {
  5953. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5954. });
  5955. }
  5956. template <typename ClientType>
  5957. void TestWithHeadersAndContentReceiverError(
  5958. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5959. const Headers &, const std::string &,
  5960. const std::string &, ContentReceiver)>
  5961. request_func) {
  5962. Headers headers;
  5963. headers.emplace("X-Error-Test", "true");
  5964. std::string received_body;
  5965. auto receiver_failed = false;
  5966. auto res =
  5967. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5968. [&](const char *data, size_t data_length) {
  5969. received_body.append(data, data_length);
  5970. receiver_failed = true;
  5971. return false;
  5972. });
  5973. ASSERT_FALSE(res);
  5974. EXPECT_TRUE(receiver_failed);
  5975. }
  5976. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5977. #ifdef CPPHTTPLIB_SSL_ENABLED
  5978. using ClientT = SSLClient;
  5979. #else
  5980. using ClientT = Client;
  5981. #endif
  5982. TestWithHeadersAndContentReceiverError<ClientT>(
  5983. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5984. const std::string &body, const std::string &content_type,
  5985. ContentReceiver receiver) {
  5986. return cli.Post(path, headers, body, content_type, receiver);
  5987. });
  5988. }
  5989. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5990. #ifdef CPPHTTPLIB_SSL_ENABLED
  5991. using ClientT = SSLClient;
  5992. #else
  5993. using ClientT = Client;
  5994. #endif
  5995. TestWithHeadersAndContentReceiverError<ClientT>(
  5996. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5997. const std::string &body, const std::string &content_type,
  5998. ContentReceiver receiver) {
  5999. return cli.Put(path, headers, body, content_type, receiver);
  6000. });
  6001. }
  6002. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6003. #ifdef CPPHTTPLIB_SSL_ENABLED
  6004. using ClientT = SSLClient;
  6005. #else
  6006. using ClientT = Client;
  6007. #endif
  6008. TestWithHeadersAndContentReceiverError<ClientT>(
  6009. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6010. const std::string &body, const std::string &content_type,
  6011. ContentReceiver receiver) {
  6012. return cli.Patch(path, headers, body, content_type, receiver);
  6013. });
  6014. }
  6015. TEST_F(ServerTest, PostQueryStringAndBody) {
  6016. auto res =
  6017. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6018. ASSERT_TRUE(res);
  6019. ASSERT_EQ(StatusCode::OK_200, res->status);
  6020. }
  6021. TEST_F(ServerTest, HTTP2Magic) {
  6022. Request req;
  6023. req.method = "PRI";
  6024. req.path = "*";
  6025. req.body = "SM";
  6026. auto res = std::make_shared<Response>();
  6027. auto error = Error::Success;
  6028. auto ret = cli_.send(req, *res, error);
  6029. ASSERT_TRUE(ret);
  6030. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6031. }
  6032. TEST_F(ServerTest, KeepAlive) {
  6033. auto res = cli_.Get("/hi");
  6034. ASSERT_TRUE(res);
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6037. EXPECT_EQ("Hello World!", res->body);
  6038. res = cli_.Get("/hi");
  6039. ASSERT_TRUE(res);
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6042. EXPECT_EQ("Hello World!", res->body);
  6043. res = cli_.Get("/hi");
  6044. ASSERT_TRUE(res);
  6045. EXPECT_EQ(StatusCode::OK_200, res->status);
  6046. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6047. EXPECT_EQ("Hello World!", res->body);
  6048. res = cli_.Get("/not-exist");
  6049. ASSERT_TRUE(res);
  6050. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6051. res = cli_.Post("/empty", "", "text/plain");
  6052. ASSERT_TRUE(res);
  6053. EXPECT_EQ(StatusCode::OK_200, res->status);
  6054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6055. EXPECT_EQ("empty", res->body);
  6056. EXPECT_EQ("close", res->get_header_value("Connection"));
  6057. res = cli_.Post(
  6058. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6059. "text/plain");
  6060. ASSERT_TRUE(res);
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6063. EXPECT_EQ("empty", res->body);
  6064. cli_.set_keep_alive(false);
  6065. res = cli_.Get("/last-request");
  6066. ASSERT_TRUE(res);
  6067. EXPECT_EQ(StatusCode::OK_200, res->status);
  6068. EXPECT_EQ("close", res->get_header_value("Connection"));
  6069. }
  6070. TEST_F(ServerTest, TooManyRedirect) {
  6071. cli_.set_follow_location(true);
  6072. auto res = cli_.Get("/redirect/0");
  6073. ASSERT_TRUE(!res);
  6074. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6075. }
  6076. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6077. Request req;
  6078. req.method = "FOOBAR";
  6079. req.path = "/hi";
  6080. cli_.set_keep_alive(true);
  6081. auto res = cli_.send(req);
  6082. ASSERT_TRUE(res);
  6083. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6084. EXPECT_EQ("close", res->get_header_value("Connection"));
  6085. EXPECT_FALSE(cli_.is_socket_open());
  6086. }
  6087. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6088. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6089. TEST_F(ServerTest, Gzip) {
  6090. Headers headers;
  6091. headers.emplace("Accept-Encoding", "gzip, deflate");
  6092. auto res = cli_.Get("/compress", headers);
  6093. ASSERT_TRUE(res);
  6094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6095. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6096. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6097. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6098. "7890123456789012345678901234567890",
  6099. res->body);
  6100. EXPECT_EQ(StatusCode::OK_200, res->status);
  6101. }
  6102. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6103. Headers headers;
  6104. headers.emplace("Accept-Encoding", "gzip, deflate");
  6105. auto res = cli_.Get("/compress-with-charset", headers);
  6106. ASSERT_TRUE(res);
  6107. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6108. EXPECT_EQ("application/json; charset=utf-8",
  6109. res->get_header_value("Content-Type"));
  6110. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6111. "7890123456789012345678901234567890",
  6112. res->body);
  6113. EXPECT_EQ(StatusCode::OK_200, res->status);
  6114. }
  6115. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6116. Headers headers;
  6117. headers.emplace("Accept-Encoding", "");
  6118. auto res = cli_.Get("/compress", headers);
  6119. ASSERT_TRUE(res);
  6120. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6122. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6123. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6124. "7890123456789012345678901234567890",
  6125. res->body);
  6126. EXPECT_EQ(StatusCode::OK_200, res->status);
  6127. }
  6128. TEST_F(ServerTest, GzipWithContentReceiver) {
  6129. Headers headers;
  6130. headers.emplace("Accept-Encoding", "gzip, deflate");
  6131. std::string body;
  6132. auto res = cli_.Get("/compress", headers,
  6133. [&](const char *data, uint64_t data_length) {
  6134. EXPECT_EQ(100U, data_length);
  6135. body.append(data, data_length);
  6136. return true;
  6137. });
  6138. ASSERT_TRUE(res);
  6139. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6140. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6141. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6142. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6143. "7890123456789012345678901234567890",
  6144. body);
  6145. EXPECT_EQ(StatusCode::OK_200, res->status);
  6146. }
  6147. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6148. Headers headers;
  6149. headers.emplace("Accept-Encoding", "gzip, deflate");
  6150. cli_.set_decompress(false);
  6151. auto res = cli_.Get("/compress", headers);
  6152. ASSERT_TRUE(res);
  6153. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6155. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6156. EXPECT_EQ(33U, res->body.size());
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. }
  6159. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6160. Headers headers;
  6161. headers.emplace("Accept-Encoding", "");
  6162. std::string body;
  6163. auto res = cli_.Get("/compress", headers,
  6164. [&](const char *data, uint64_t data_length) {
  6165. EXPECT_EQ(100U, data_length);
  6166. body.append(data, data_length);
  6167. return true;
  6168. });
  6169. ASSERT_TRUE(res);
  6170. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6172. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6173. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6174. "7890123456789012345678901234567890",
  6175. body);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. }
  6178. TEST_F(ServerTest, NoGzip) {
  6179. Headers headers;
  6180. headers.emplace("Accept-Encoding", "gzip, deflate");
  6181. auto res = cli_.Get("/nocompress", headers);
  6182. ASSERT_TRUE(res);
  6183. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6184. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6185. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6186. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6187. "7890123456789012345678901234567890",
  6188. res->body);
  6189. EXPECT_EQ(StatusCode::OK_200, res->status);
  6190. }
  6191. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6192. Headers headers;
  6193. headers.emplace("Accept-Encoding", "gzip, deflate");
  6194. std::string body;
  6195. auto res = cli_.Get("/nocompress", headers,
  6196. [&](const char *data, uint64_t data_length) {
  6197. EXPECT_EQ(100U, data_length);
  6198. body.append(data, data_length);
  6199. return true;
  6200. });
  6201. ASSERT_TRUE(res);
  6202. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6203. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6204. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6205. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6206. "7890123456789012345678901234567890",
  6207. body);
  6208. EXPECT_EQ(StatusCode::OK_200, res->status);
  6209. }
  6210. TEST_F(ServerTest, MultipartFormDataGzip) {
  6211. UploadFormDataItems items = {
  6212. {"key1", "test", "", ""},
  6213. {"key2", "--abcdefg123", "", ""},
  6214. };
  6215. cli_.set_compress(true);
  6216. auto res = cli_.Post("/compress-multipart", items);
  6217. ASSERT_TRUE(res);
  6218. EXPECT_EQ(StatusCode::OK_200, res->status);
  6219. }
  6220. #endif
  6221. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6222. TEST_F(ServerTest, Brotli) {
  6223. Headers headers;
  6224. headers.emplace("Accept-Encoding", "br");
  6225. auto res = cli_.Get("/compress", headers);
  6226. ASSERT_TRUE(res);
  6227. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6229. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6230. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6231. "7890123456789012345678901234567890",
  6232. res->body);
  6233. EXPECT_EQ(StatusCode::OK_200, res->status);
  6234. }
  6235. #endif
  6236. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6237. TEST_F(ServerTest, Zstd) {
  6238. Headers headers;
  6239. headers.emplace("Accept-Encoding", "zstd");
  6240. auto res = cli_.Get("/compress", headers);
  6241. ASSERT_TRUE(res);
  6242. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6243. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6244. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6245. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6246. "7890123456789012345678901234567890",
  6247. res->body);
  6248. EXPECT_EQ(StatusCode::OK_200, res->status);
  6249. }
  6250. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6251. Headers headers;
  6252. headers.emplace("Accept-Encoding", "");
  6253. auto res = cli_.Get("/compress", headers);
  6254. ASSERT_TRUE(res);
  6255. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6256. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6257. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6258. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6259. "7890123456789012345678901234567890",
  6260. res->body);
  6261. EXPECT_EQ(StatusCode::OK_200, res->status);
  6262. }
  6263. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6264. Headers headers;
  6265. headers.emplace("Accept-Encoding", "zstd");
  6266. std::string body;
  6267. auto res = cli_.Get("/compress", headers,
  6268. [&](const char *data, uint64_t data_length) {
  6269. EXPECT_EQ(100U, data_length);
  6270. body.append(data, data_length);
  6271. return true;
  6272. });
  6273. ASSERT_TRUE(res);
  6274. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6276. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6277. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6278. "7890123456789012345678901234567890",
  6279. body);
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. }
  6282. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6283. Headers headers;
  6284. headers.emplace("Accept-Encoding", "zstd");
  6285. cli_.set_decompress(false);
  6286. auto res = cli_.Get("/compress", headers);
  6287. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6288. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6289. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6290. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6291. ASSERT_TRUE(res);
  6292. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6294. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6295. EXPECT_EQ(StatusCode::OK_200, res->status);
  6296. ASSERT_EQ(26U, res->body.size());
  6297. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6298. 0);
  6299. }
  6300. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6301. Headers headers;
  6302. headers.emplace("Accept-Encoding", "");
  6303. std::string body;
  6304. auto res = cli_.Get("/compress", headers,
  6305. [&](const char *data, uint64_t data_length) {
  6306. EXPECT_EQ(100U, data_length);
  6307. body.append(data, data_length);
  6308. return true;
  6309. });
  6310. ASSERT_TRUE(res);
  6311. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6313. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6314. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6315. "7890123456789012345678901234567890",
  6316. body);
  6317. EXPECT_EQ(StatusCode::OK_200, res->status);
  6318. }
  6319. TEST_F(ServerTest, NoZstd) {
  6320. Headers headers;
  6321. headers.emplace("Accept-Encoding", "zstd");
  6322. auto res = cli_.Get("/nocompress", headers);
  6323. ASSERT_TRUE(res);
  6324. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6325. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6326. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6327. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6328. "7890123456789012345678901234567890",
  6329. res->body);
  6330. EXPECT_EQ(StatusCode::OK_200, res->status);
  6331. }
  6332. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6333. Headers headers;
  6334. headers.emplace("Accept-Encoding", "zstd");
  6335. std::string body;
  6336. auto res = cli_.Get("/nocompress", headers,
  6337. [&](const char *data, uint64_t data_length) {
  6338. EXPECT_EQ(100U, data_length);
  6339. body.append(data, data_length);
  6340. return true;
  6341. });
  6342. ASSERT_TRUE(res);
  6343. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6344. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6345. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6346. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6347. "7890123456789012345678901234567890",
  6348. body);
  6349. EXPECT_EQ(StatusCode::OK_200, res->status);
  6350. }
  6351. // TODO: How to enable zstd ??
  6352. TEST_F(ServerTest, MultipartFormDataZstd) {
  6353. UploadFormDataItems items = {
  6354. {"key1", "test", "", ""},
  6355. {"key2", "--abcdefg123", "", ""},
  6356. };
  6357. Headers headers;
  6358. headers.emplace("Accept-Encoding", "zstd");
  6359. cli_.set_compress(true);
  6360. auto res = cli_.Post("/compress-multipart", headers, items);
  6361. ASSERT_TRUE(res);
  6362. EXPECT_EQ(StatusCode::OK_200, res->status);
  6363. }
  6364. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6365. Headers headers;
  6366. headers.emplace("Accept-Encoding", "zstd");
  6367. cli_.set_compress(true);
  6368. auto res = cli_.Put(
  6369. "/put", headers, 3,
  6370. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6371. sink.os << "PUT";
  6372. return true;
  6373. },
  6374. "text/plain");
  6375. ASSERT_TRUE(res);
  6376. EXPECT_EQ(StatusCode::OK_200, res->status);
  6377. EXPECT_EQ("PUT", res->body);
  6378. }
  6379. // Pre-compression logging tests
  6380. TEST_F(ServerTest, PreCompressionLogging) {
  6381. // Test data for compression (matches the actual /compress endpoint content)
  6382. const std::string test_content =
  6383. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6384. "3456789012345678901234567890";
  6385. // Variables to capture logging data
  6386. std::string pre_compression_body;
  6387. std::string pre_compression_content_type;
  6388. std::string pre_compression_content_encoding;
  6389. std::string post_compression_body;
  6390. std::string post_compression_content_type;
  6391. std::string post_compression_content_encoding;
  6392. // Set up pre-compression logger
  6393. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6394. const Response &res) {
  6395. pre_compression_body = res.body;
  6396. pre_compression_content_type = res.get_header_value("Content-Type");
  6397. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6398. });
  6399. // Set up post-compression logger
  6400. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6401. post_compression_body = res.body;
  6402. post_compression_content_type = res.get_header_value("Content-Type");
  6403. post_compression_content_encoding =
  6404. res.get_header_value("Content-Encoding");
  6405. });
  6406. // Test with gzip compression
  6407. Headers headers;
  6408. headers.emplace("Accept-Encoding", "gzip");
  6409. auto res = cli_.Get("/compress", headers);
  6410. // Verify response was compressed
  6411. ASSERT_TRUE(res);
  6412. EXPECT_EQ(StatusCode::OK_200, res->status);
  6413. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6414. // Verify pre-compression logger captured uncompressed content
  6415. EXPECT_EQ(test_content, pre_compression_body);
  6416. EXPECT_EQ("text/plain", pre_compression_content_type);
  6417. EXPECT_TRUE(pre_compression_content_encoding
  6418. .empty()); // No encoding header before compression
  6419. // Verify post-compression logger captured compressed content
  6420. EXPECT_NE(test_content,
  6421. post_compression_body); // Should be different after compression
  6422. EXPECT_EQ("text/plain", post_compression_content_type);
  6423. EXPECT_EQ("gzip", post_compression_content_encoding);
  6424. // Verify compressed content is smaller
  6425. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6426. }
  6427. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6428. const std::string test_content =
  6429. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6430. "3456789012345678901234567890";
  6431. std::string pre_compression_body;
  6432. std::string post_compression_body;
  6433. svr_.set_pre_compression_logger(
  6434. [&](const Request & /*req*/, const Response &res) {
  6435. pre_compression_body = res.body;
  6436. });
  6437. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6438. post_compression_body = res.body;
  6439. });
  6440. Headers headers;
  6441. headers.emplace("Accept-Encoding", "br");
  6442. auto res = cli_.Get("/compress", headers);
  6443. ASSERT_TRUE(res);
  6444. EXPECT_EQ(StatusCode::OK_200, res->status);
  6445. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6446. // Verify pre-compression content is uncompressed
  6447. EXPECT_EQ(test_content, pre_compression_body);
  6448. // Verify post-compression content is compressed
  6449. EXPECT_NE(test_content, post_compression_body);
  6450. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6451. }
  6452. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6453. const std::string test_content =
  6454. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6455. "3456789012345678901234567890";
  6456. std::string pre_compression_body;
  6457. std::string post_compression_body;
  6458. svr_.set_pre_compression_logger(
  6459. [&](const Request & /*req*/, const Response &res) {
  6460. pre_compression_body = res.body;
  6461. });
  6462. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6463. post_compression_body = res.body;
  6464. });
  6465. // Request without compression (use /nocompress endpoint)
  6466. Headers headers;
  6467. auto res = cli_.Get("/nocompress", headers);
  6468. ASSERT_TRUE(res);
  6469. EXPECT_EQ(StatusCode::OK_200, res->status);
  6470. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6471. // Pre-compression logger should not be called when no compression is applied
  6472. EXPECT_TRUE(
  6473. pre_compression_body.empty()); // Pre-compression logger not called
  6474. EXPECT_EQ(
  6475. test_content,
  6476. post_compression_body); // Post-compression logger captures final content
  6477. }
  6478. TEST_F(ServerTest, LoggerSeesContentLength) {
  6479. size_t logged_content_length = 0;
  6480. std::string logged_content_length_header;
  6481. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6482. logged_content_length = res.content_length_;
  6483. logged_content_length_header = res.get_header_value("Content-Length");
  6484. });
  6485. auto res = cli_.Get("/nocompress");
  6486. ASSERT_TRUE(res);
  6487. EXPECT_EQ(StatusCode::OK_200, res->status);
  6488. EXPECT_EQ(res->body.size(), logged_content_length);
  6489. EXPECT_EQ(std::to_string(logged_content_length),
  6490. logged_content_length_header);
  6491. }
  6492. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6493. const std::string test_content =
  6494. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6495. "3456789012345678901234567890";
  6496. std::string pre_compression_body;
  6497. bool pre_logger_called = false;
  6498. // Set only pre-compression logger
  6499. svr_.set_pre_compression_logger(
  6500. [&](const Request & /*req*/, const Response &res) {
  6501. pre_compression_body = res.body;
  6502. pre_logger_called = true;
  6503. });
  6504. Headers headers;
  6505. headers.emplace("Accept-Encoding", "gzip");
  6506. auto res = cli_.Get("/compress", headers);
  6507. ASSERT_TRUE(res);
  6508. EXPECT_EQ(StatusCode::OK_200, res->status);
  6509. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6510. // Verify pre-compression logger was called
  6511. EXPECT_TRUE(pre_logger_called);
  6512. EXPECT_EQ(test_content, pre_compression_body);
  6513. }
  6514. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6515. {
  6516. // Test with Expect: 100-continue header - success case
  6517. // Server returns 100 Continue, client sends body, server returns 200 OK
  6518. Request req;
  6519. req.method = "POST";
  6520. req.path = "/post-large";
  6521. req.set_header("Expect", "100-continue");
  6522. req.body = LARGE_DATA;
  6523. Response res;
  6524. auto error = Error::Success;
  6525. cli_.set_keep_alive(true);
  6526. auto ret = cli_.send(req, res, error);
  6527. EXPECT_TRUE(ret);
  6528. EXPECT_EQ(StatusCode::OK_200, res.status);
  6529. EXPECT_EQ(LARGE_DATA, res.body);
  6530. }
  6531. {
  6532. // Test with Expect: 100-continue header - error case
  6533. // Client should not send the body when server returns an error
  6534. Request req;
  6535. req.method = "POST";
  6536. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6537. req.set_header("Expect", "100-continue");
  6538. req.body = LARGE_DATA;
  6539. Response res;
  6540. auto error = Error::Success;
  6541. auto start = std::chrono::high_resolution_clock::now();
  6542. cli_.set_keep_alive(true);
  6543. auto ret = cli_.send(req, res, error);
  6544. auto end = std::chrono::high_resolution_clock::now();
  6545. auto elapsed =
  6546. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6547. .count();
  6548. // With Expect: 100-continue, request completes successfully but with error
  6549. EXPECT_TRUE(ret);
  6550. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6551. EXPECT_EQ("close", res.get_header_value("Connection"));
  6552. EXPECT_FALSE(cli_.is_socket_open());
  6553. EXPECT_LE(elapsed, 2000);
  6554. }
  6555. {
  6556. // Send an extra GET request to ensure error recovery without hanging
  6557. Request req;
  6558. req.method = "GET";
  6559. req.path = "/hi";
  6560. auto start = std::chrono::high_resolution_clock::now();
  6561. auto res = cli_.send(req);
  6562. auto end = std::chrono::high_resolution_clock::now();
  6563. auto elapsed =
  6564. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6565. .count();
  6566. ASSERT_TRUE(res);
  6567. EXPECT_EQ(StatusCode::OK_200, res->status);
  6568. EXPECT_EQ("Hello World!", res->body);
  6569. EXPECT_LE(elapsed, 500);
  6570. }
  6571. }
  6572. TEST(ZstdDecompressor, ChunkedDecompression) {
  6573. std::string data;
  6574. for (size_t i = 0; i < 32 * 1024; ++i) {
  6575. data.push_back(static_cast<char>('a' + i % 26));
  6576. }
  6577. std::string compressed_data;
  6578. {
  6579. httplib::detail::zstd_compressor compressor;
  6580. bool result = compressor.compress(
  6581. data.data(), data.size(),
  6582. /*last=*/true,
  6583. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6584. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6585. compressed_data_size);
  6586. return true;
  6587. });
  6588. ASSERT_TRUE(result);
  6589. }
  6590. std::string decompressed_data;
  6591. {
  6592. httplib::detail::zstd_decompressor decompressor;
  6593. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6594. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6595. size_t chunk_size = 130;
  6596. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6597. chunk_begin += chunk_size) {
  6598. size_t current_chunk_size =
  6599. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6600. bool result = decompressor.decompress(
  6601. compressed_data.data() + chunk_begin, current_chunk_size,
  6602. [&](const char *decompressed_data_chunk,
  6603. size_t decompressed_data_chunk_size) {
  6604. decompressed_data.insert(decompressed_data.size(),
  6605. decompressed_data_chunk,
  6606. decompressed_data_chunk_size);
  6607. return true;
  6608. });
  6609. ASSERT_TRUE(result);
  6610. }
  6611. }
  6612. ASSERT_EQ(data, decompressed_data);
  6613. }
  6614. TEST(ZstdDecompressor, Decompress) {
  6615. std::string original_text = "Compressed with ZSTD";
  6616. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6617. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6618. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6619. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6620. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6621. std::string decompressed_data;
  6622. {
  6623. httplib::detail::zstd_decompressor decompressor;
  6624. bool result = decompressor.decompress(
  6625. compressed_data.data(), compressed_data.size(),
  6626. [&](const char *decompressed_data_chunk,
  6627. size_t decompressed_data_chunk_size) {
  6628. decompressed_data.insert(decompressed_data.size(),
  6629. decompressed_data_chunk,
  6630. decompressed_data_chunk_size);
  6631. return true;
  6632. });
  6633. ASSERT_TRUE(result);
  6634. }
  6635. ASSERT_EQ(original_text, decompressed_data);
  6636. }
  6637. #endif
  6638. // Sends a raw request to a server listening at HOST:PORT.
  6639. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6640. std::string *resp = nullptr) {
  6641. auto error = Error::Success;
  6642. auto client_sock = detail::create_client_socket(
  6643. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6644. /*connection_timeout_sec=*/5, 0,
  6645. /*read_timeout_sec=*/5, 0,
  6646. /*write_timeout_sec=*/5, 0, std::string(), error);
  6647. if (client_sock == INVALID_SOCKET) { return false; }
  6648. auto ret = detail::process_client_socket(
  6649. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6650. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6651. if (req.size() !=
  6652. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6653. return false;
  6654. }
  6655. char buf[512];
  6656. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6657. while (line_reader.getline()) {
  6658. if (resp) { *resp += line_reader.ptr(); }
  6659. }
  6660. return true;
  6661. });
  6662. detail::close_socket(client_sock);
  6663. return ret;
  6664. }
  6665. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6666. Server svr;
  6667. std::string header_value;
  6668. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6669. header_value = req.get_header_value("foo");
  6670. res.set_content("ok", "text/plain");
  6671. });
  6672. thread t = thread([&] { svr.listen(HOST, PORT); });
  6673. auto se = detail::scope_exit([&] {
  6674. svr.stop();
  6675. t.join();
  6676. ASSERT_FALSE(svr.is_running());
  6677. });
  6678. svr.wait_until_ready();
  6679. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6680. // like characters are not treated the same - use vertical tab and escape.
  6681. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6682. "foo: \t \v bar \x1B\t \r\n"
  6683. "Connection: close\r\n"
  6684. "\r\n";
  6685. std::string res;
  6686. ASSERT_TRUE(send_request(5, req, &res));
  6687. EXPECT_EQ(header_value, "");
  6688. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6689. }
  6690. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6691. Server svr;
  6692. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6693. auto i = new int(0);
  6694. res.set_header("Trailer", "X-Safe, X-Reflected");
  6695. res.set_chunked_content_provider(
  6696. "text/plain",
  6697. [i](size_t /*offset*/, DataSink &sink) {
  6698. if (*i == 0) {
  6699. sink.os << "body";
  6700. } else {
  6701. Headers trailer;
  6702. // A valid trailer that must survive.
  6703. trailer.emplace("X-Safe", "safe");
  6704. // Attacker-controlled value carrying CR/LF (response splitting).
  6705. trailer.emplace("X-Reflected",
  6706. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6707. // Attacker-controlled name carrying CR/LF.
  6708. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6709. sink.done_with_trailer(trailer);
  6710. }
  6711. (*i)++;
  6712. return true;
  6713. },
  6714. [i](bool /*success*/) { delete i; });
  6715. });
  6716. thread t = thread([&] { svr.listen(HOST, PORT); });
  6717. auto se = detail::scope_exit([&] {
  6718. svr.stop();
  6719. t.join();
  6720. ASSERT_FALSE(svr.is_running());
  6721. });
  6722. svr.wait_until_ready();
  6723. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6724. "Host: " + HOST +
  6725. "\r\n"
  6726. "Connection: close\r\n"
  6727. "\r\n";
  6728. std::string res;
  6729. ASSERT_TRUE(send_request(5, req, &res));
  6730. // The injected fields must not appear anywhere in the raw response.
  6731. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6732. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6733. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6734. // Invalid trailers are dropped entirely, matching set_header().
  6735. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6736. // The valid trailer still passes through.
  6737. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6738. }
  6739. // Forward declaration: in split builds split.py strips `inline` and moves the
  6740. // definition into httplib.cc, so detail::write_request_line is not visible from
  6741. // the public httplib.h. Re-declaring it here lets the tests link against the
  6742. // symbol in both header-only and split builds.
  6743. namespace httplib {
  6744. namespace detail {
  6745. ssize_t write_request_line(Stream &strm, const std::string &method,
  6746. const std::string &path);
  6747. } // namespace detail
  6748. } // namespace httplib
  6749. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  6750. // A well-formed target is written verbatim.
  6751. {
  6752. detail::BufferStream strm;
  6753. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  6754. EXPECT_GT(n, 0);
  6755. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  6756. }
  6757. // A target carrying CR/LF must be rejected before anything reaches the wire,
  6758. // otherwise it splits the request line and injects a header or a whole
  6759. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  6760. // when path encoding is disabled.
  6761. const std::string evil_targets[] = {
  6762. "/a\r\nInjected: pwned",
  6763. "/a\rInjected",
  6764. "/a\nInjected",
  6765. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  6766. };
  6767. for (const auto &evil : evil_targets) {
  6768. detail::BufferStream strm;
  6769. auto n = detail::write_request_line(strm, "GET", evil);
  6770. EXPECT_LT(n, 0);
  6771. EXPECT_TRUE(strm.get_buffer().empty());
  6772. }
  6773. }
  6774. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  6775. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  6776. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  6777. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  6778. // client must fail cleanly with Error::Write instead of putting a
  6779. // request-line-less, header-injecting request on the wire.
  6780. Server svr;
  6781. svr.Get("/a", [](const Request &, Response &res) {
  6782. res.set_content("ok", "text/plain");
  6783. });
  6784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6785. auto se = detail::scope_exit([&] {
  6786. svr.stop();
  6787. thread.join();
  6788. ASSERT_FALSE(svr.is_running());
  6789. });
  6790. svr.wait_until_ready();
  6791. {
  6792. Client cli(HOST, PORT);
  6793. cli.set_path_encode(false);
  6794. // The request is rejected before anything is written, so the connection
  6795. // stays silent and the subsequent response read would otherwise block for
  6796. // the full default read timeout. Shorten it -- the assertion is on the
  6797. // error, not the timeout.
  6798. cli.set_read_timeout(1, 0);
  6799. auto res = cli.Get("/a\r\nInjected: pwned");
  6800. EXPECT_FALSE(res);
  6801. EXPECT_EQ(Error::Write, res.error());
  6802. }
  6803. }
  6804. // Sends a raw request and verifies that there isn't a crash or exception.
  6805. static void test_raw_request(const std::string &req,
  6806. std::string *out = nullptr) {
  6807. Server svr;
  6808. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6809. res.set_content("ok", "text/plain");
  6810. });
  6811. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6812. res.set_content("ok", "text/plain");
  6813. });
  6814. svr.Get("/header_field_value_check",
  6815. [&](const Request & /*req*/, Response &res) {
  6816. res.set_content("ok", "text/plain");
  6817. });
  6818. // Server read timeout must be longer than the client read timeout for the
  6819. // bug to reproduce, probably to force the server to process a request
  6820. // without a trailing blank line.
  6821. const time_t client_read_timeout_sec = 1;
  6822. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6823. bool listen_thread_ok = false;
  6824. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. t.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. EXPECT_TRUE(listen_thread_ok);
  6830. });
  6831. svr.wait_until_ready();
  6832. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6833. }
  6834. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6835. // A certain header line causes an exception if the header property is parsed
  6836. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6837. test_raw_request(
  6838. "GET /hi HTTP/1.1\r\n"
  6839. " : "
  6840. " "
  6841. " ");
  6842. }
  6843. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6844. // A certain header line causes an exception if the header property *name* is
  6845. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6846. // greedy matcher and requires backtracking when there are a lot of ":"
  6847. // characters.
  6848. // This occurs with libc++ but not libstdc++.
  6849. test_raw_request(
  6850. "GET /hi HTTP/1.1\r\n"
  6851. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6852. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6853. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6854. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6855. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6856. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6857. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6858. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6859. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6860. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6861. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6862. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6863. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6864. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6865. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6866. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6867. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6868. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6869. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6870. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6871. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6872. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6873. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6874. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6875. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6876. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6877. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6878. "&&&%%%");
  6879. }
  6880. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6881. // Make sure this doesn't crash the server.
  6882. // In a previous version of the header line regex, the "\r" rendered the line
  6883. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6884. // a new position where the leading white space ended and the field value
  6885. // began.
  6886. // The crash occurs with libc++ but not libstdc++.
  6887. test_raw_request("GET /hi HTTP/1.1\r\n"
  6888. "a:" +
  6889. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6890. "\r\n"
  6891. "\r\n");
  6892. }
  6893. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6894. std::string out;
  6895. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6896. "Content-Type: text/plain\r\n"
  6897. "Transfer-Encoding: chunked\r\n"
  6898. "\r\n"
  6899. "nothex\r\n",
  6900. &out);
  6901. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6902. }
  6903. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6904. std::string out;
  6905. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6906. "Content-Type: text/plain\r\n"
  6907. "Transfer-Encoding: chunked\r\n"
  6908. "\r\n"
  6909. "3\r\n"
  6910. "xyz\r\n"
  6911. "NaN\r\n",
  6912. &out);
  6913. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6914. }
  6915. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6916. std::string out;
  6917. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6918. "Content-Type: text/plain\r\n"
  6919. "Transfer-Encoding: chunked\r\n"
  6920. "\r\n"
  6921. // Length is too large for 64 bits.
  6922. "1ffffffffffffffff\r\n"
  6923. "xyz\r\n",
  6924. &out);
  6925. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6926. }
  6927. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6928. test_raw_request("GET /hi HTTP/1.1\r\n"
  6929. "Content-Type: text/plain\r\n\r");
  6930. }
  6931. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6932. std::string out;
  6933. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6934. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6935. }
  6936. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6937. Server svr;
  6938. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6939. EXPECT_TRUE(!req.remote_addr.empty());
  6940. });
  6941. thread t = thread([&] { svr.listen(HOST, PORT); });
  6942. auto se = detail::scope_exit([&] {
  6943. svr.stop();
  6944. t.join();
  6945. ASSERT_FALSE(svr.is_running());
  6946. });
  6947. svr.wait_until_ready();
  6948. // Send an invalid request line to trigger Bad Request
  6949. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6950. std::string out;
  6951. ASSERT_TRUE(send_request(5, bad_req, &out));
  6952. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6953. }
  6954. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6955. std::string out;
  6956. std::string request(
  6957. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6958. test_raw_request(request, &out);
  6959. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6960. }
  6961. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6962. std::string out;
  6963. std::string request(
  6964. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6965. test_raw_request(request, &out);
  6966. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6967. }
  6968. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6969. std::string out;
  6970. std::string request(
  6971. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6972. test_raw_request(request, &out);
  6973. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6974. }
  6975. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6976. std::string out;
  6977. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6978. "Test: \r\n\r\n",
  6979. &out);
  6980. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6981. }
  6982. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6983. Server svr;
  6984. std::string x_custom;
  6985. std::string cookie;
  6986. std::string xff;
  6987. std::string x_unicode;
  6988. std::string x_iis;
  6989. svr.Get("/check", [&](const Request &req, Response &res) {
  6990. x_custom = req.get_header_value("X-Custom");
  6991. cookie = req.get_header_value("Cookie");
  6992. xff = req.get_header_value("X-Forwarded-For");
  6993. x_unicode = req.get_header_value("X-Unicode");
  6994. x_iis = req.get_header_value("X-IIS");
  6995. res.set_content("ok", "text/plain");
  6996. });
  6997. thread t = thread([&] { svr.listen(HOST, PORT); });
  6998. auto se = detail::scope_exit([&] {
  6999. svr.stop();
  7000. t.join();
  7001. ASSERT_FALSE(svr.is_running());
  7002. });
  7003. svr.wait_until_ready();
  7004. const std::string req = "GET /check HTTP/1.1\r\n"
  7005. "Host: localhost\r\n"
  7006. "X-Custom: a%0D%0AInjected: b\r\n"
  7007. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7008. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7009. "X-Unicode: %E3%81%82\r\n"
  7010. "X-IIS: %u00E9\r\n"
  7011. "Connection: close\r\n"
  7012. "\r\n";
  7013. std::string res;
  7014. ASSERT_TRUE(send_request(5, req, &res));
  7015. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7016. // Every value must be returned verbatim (wire form), with no decoding.
  7017. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7018. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7019. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7020. EXPECT_EQ("%E3%81%82", x_unicode);
  7021. EXPECT_EQ("%u00E9", x_iis);
  7022. }
  7023. // Applications that previously relied on automatic percent-decoding can
  7024. // reproduce the old behavior by explicitly calling decode_path_component()
  7025. // or, for RFC 3986 conformance, decode_uri_component().
  7026. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7027. Server svr;
  7028. std::string decoded;
  7029. svr.Get("/check", [&](const Request &req, Response &res) {
  7030. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7031. res.set_content("ok", "text/plain");
  7032. });
  7033. thread t = thread([&] { svr.listen(HOST, PORT); });
  7034. auto se = detail::scope_exit([&] {
  7035. svr.stop();
  7036. t.join();
  7037. ASSERT_FALSE(svr.is_running());
  7038. });
  7039. svr.wait_until_ready();
  7040. const std::string req = "GET /check HTTP/1.1\r\n"
  7041. "Host: localhost\r\n"
  7042. "X-Custom: hello%20world\r\n"
  7043. "Connection: close\r\n"
  7044. "\r\n";
  7045. std::string res;
  7046. ASSERT_TRUE(send_request(5, req, &res));
  7047. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7048. EXPECT_EQ("hello world", decoded);
  7049. }
  7050. // Regression test for #2033. Browsers send Referer values that include
  7051. // percent-encoded characters such as %0A inside the URL. Decoding the
  7052. // header value would either trip the post-decode CR/LF/NUL guard (the
  7053. // original bug, returning 400) or, after that guard was relaxed, silently
  7054. // store a literal LF — both unacceptable. The wire form must round-trip.
  7055. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7056. Server svr;
  7057. std::string referer;
  7058. svr.Get("/check", [&](const Request &req, Response &res) {
  7059. referer = req.get_header_value("Referer");
  7060. res.set_content("ok", "text/plain");
  7061. });
  7062. thread t = thread([&] { svr.listen(HOST, PORT); });
  7063. auto se = detail::scope_exit([&] {
  7064. svr.stop();
  7065. t.join();
  7066. ASSERT_FALSE(svr.is_running());
  7067. });
  7068. svr.wait_until_ready();
  7069. const std::string req = "GET /check HTTP/1.1\r\n"
  7070. "Host: localhost\r\n"
  7071. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7072. "Connection: close\r\n"
  7073. "\r\n";
  7074. std::string res;
  7075. ASSERT_TRUE(send_request(5, req, &res));
  7076. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7077. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7078. }
  7079. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7080. Server svr;
  7081. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7082. res.set_header("Cache-Control", "no-cache");
  7083. res.set_chunked_content_provider(
  7084. "text/event-stream", [](size_t offset, DataSink &sink) {
  7085. std::string s = "data:";
  7086. s += std::to_string(offset);
  7087. s += "\n\n";
  7088. auto ret = sink.write(s.data(), s.size());
  7089. EXPECT_TRUE(ret);
  7090. std::this_thread::sleep_for(std::chrono::seconds(1));
  7091. return true;
  7092. });
  7093. });
  7094. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7095. svr.wait_until_ready();
  7096. Client client(HOST, PORT);
  7097. const Headers headers = {{"Accept", "text/event-stream"}};
  7098. auto get_thread = std::thread([&client, &headers]() {
  7099. auto res = client.Get(
  7100. "/events", headers,
  7101. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7102. });
  7103. auto se = detail::scope_exit([&] {
  7104. svr.stop();
  7105. get_thread.join();
  7106. listen_thread.join();
  7107. ASSERT_FALSE(svr.is_running());
  7108. });
  7109. // Give GET time to get a few messages.
  7110. std::this_thread::sleep_for(std::chrono::seconds(2));
  7111. }
  7112. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7113. httplib::Server svr;
  7114. svr.Post("/hi",
  7115. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7116. res.status = StatusCode::OK_200;
  7117. });
  7118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7119. svr.wait_until_ready();
  7120. Client cli(HOST, PORT);
  7121. auto res = cli.Post("/hi", "data", "text/plain");
  7122. ASSERT_TRUE(res);
  7123. EXPECT_EQ(StatusCode::OK_200, res->status);
  7124. svr.stop();
  7125. thread.join();
  7126. ASSERT_FALSE(svr.is_running());
  7127. res = cli.Post("/hi", "data", "text/plain");
  7128. ASSERT_FALSE(res);
  7129. }
  7130. TEST(ServerStopTest, ListenFailure) {
  7131. Server svr;
  7132. auto t = thread([&]() {
  7133. auto ret = svr.listen("????", PORT);
  7134. EXPECT_FALSE(ret);
  7135. });
  7136. svr.wait_until_ready();
  7137. svr.stop();
  7138. t.join();
  7139. }
  7140. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7141. TEST(ServerStopTest, Decommision) {
  7142. Server svr;
  7143. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7144. for (int i = 0; i < 4; i++) {
  7145. auto is_even = !(i % 2);
  7146. std::thread t{[&] {
  7147. try {
  7148. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7149. if (is_even) {
  7150. throw std::runtime_error("Some thing that happens to go wrong.");
  7151. }
  7152. svr.listen(HOST, PORT);
  7153. } catch (...) { svr.decommission(); }
  7154. }};
  7155. svr.wait_until_ready();
  7156. // Server is up
  7157. {
  7158. Client cli(HOST, PORT);
  7159. auto res = cli.Get("/hi");
  7160. if (is_even) {
  7161. EXPECT_FALSE(res);
  7162. } else {
  7163. EXPECT_TRUE(res);
  7164. EXPECT_EQ("hi...", res->body);
  7165. }
  7166. }
  7167. svr.stop();
  7168. t.join();
  7169. // Server is down...
  7170. {
  7171. Client cli(HOST, PORT);
  7172. auto res = cli.Get("/hi");
  7173. EXPECT_FALSE(res);
  7174. }
  7175. }
  7176. }
  7177. #endif
  7178. // Helper function for string body upload progress tests
  7179. template <typename SetupHandler, typename ClientCall>
  7180. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7181. ClientCall &&client_call,
  7182. const string &body) {
  7183. Server svr;
  7184. setup_handler(svr);
  7185. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7186. auto se = detail::scope_exit([&] {
  7187. svr.stop();
  7188. t.join();
  7189. });
  7190. svr.wait_until_ready();
  7191. Client cli(HOST, PORT);
  7192. vector<uint64_t> progress_values;
  7193. bool progress_called = false;
  7194. auto res =
  7195. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7196. progress_values.push_back(current);
  7197. progress_called = true;
  7198. return true;
  7199. });
  7200. ASSERT_TRUE(res);
  7201. EXPECT_EQ(200, res->status);
  7202. EXPECT_TRUE(progress_called);
  7203. }
  7204. TEST(UploadProgressTest, PostStringBodyBasic) {
  7205. TestStringBodyUploadProgress(
  7206. [](Server &svr) {
  7207. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7208. res.set_content("received", "text/plain");
  7209. });
  7210. },
  7211. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7212. return cli.Post("/test", body, "text/plain", progress_callback);
  7213. },
  7214. "test data for upload progress");
  7215. }
  7216. TEST(UploadProgressTest, PutStringBodyBasic) {
  7217. TestStringBodyUploadProgress(
  7218. [](Server &svr) {
  7219. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7220. res.set_content("put received", "text/plain");
  7221. });
  7222. },
  7223. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7224. return cli.Put("/test", body, "text/plain", progress_callback);
  7225. },
  7226. "put test data for upload progress");
  7227. }
  7228. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7229. TestStringBodyUploadProgress(
  7230. [](Server &svr) {
  7231. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7232. res.set_content("patch received", "text/plain");
  7233. });
  7234. },
  7235. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7236. return cli.Patch("/test", body, "text/plain", progress_callback);
  7237. },
  7238. "patch test data for upload progress");
  7239. }
  7240. // Helper function for content provider upload progress tests
  7241. template <typename SetupHandler, typename ClientCall>
  7242. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7243. ClientCall &&client_call) {
  7244. Server svr;
  7245. setup_handler(svr);
  7246. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7247. auto se = detail::scope_exit([&] {
  7248. svr.stop();
  7249. t.join();
  7250. });
  7251. svr.wait_until_ready();
  7252. Client cli(HOST, PORT);
  7253. vector<uint64_t> progress_values;
  7254. auto res =
  7255. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7256. progress_values.push_back(current);
  7257. return true;
  7258. });
  7259. ASSERT_TRUE(res);
  7260. EXPECT_EQ(200, res->status);
  7261. EXPECT_FALSE(progress_values.empty());
  7262. }
  7263. TEST(UploadProgressTest, PostContentProviderProgress) {
  7264. TestContentProviderUploadProgress(
  7265. [](Server &svr) {
  7266. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7267. res.set_content("provider received", "text/plain");
  7268. });
  7269. },
  7270. [](Client &cli, UploadProgress progress_callback) {
  7271. return cli.Post(
  7272. "/test", 10,
  7273. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7274. sink.os << "test data";
  7275. return true;
  7276. },
  7277. "text/plain", progress_callback);
  7278. });
  7279. }
  7280. // Helper function for multipart upload progress tests
  7281. template <typename SetupHandler, typename ClientCall>
  7282. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7283. ClientCall &&client_call,
  7284. const string &endpoint) {
  7285. Server svr;
  7286. setup_handler(svr);
  7287. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7288. auto se = detail::scope_exit([&] {
  7289. svr.stop();
  7290. t.join();
  7291. });
  7292. svr.wait_until_ready();
  7293. Client cli(HOST, PORT);
  7294. vector<uint64_t> progress_values;
  7295. UploadFormDataItems items = {
  7296. {"field1", "value1", "", ""},
  7297. {"field2", "longer value for progress tracking test", "", ""},
  7298. {"file1", "file content data for upload progress", "test.txt",
  7299. "text/plain"}};
  7300. auto res = client_call(cli, endpoint, items,
  7301. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7302. progress_values.push_back(current);
  7303. return true;
  7304. });
  7305. ASSERT_TRUE(res);
  7306. EXPECT_EQ(200, res->status);
  7307. EXPECT_FALSE(progress_values.empty());
  7308. }
  7309. TEST(UploadProgressTest, PostMultipartProgress) {
  7310. TestMultipartUploadProgress(
  7311. [](Server &svr) {
  7312. svr.Post("/multipart", [](const Request &req, Response &res) {
  7313. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7314. res.set_content("multipart received", "text/plain");
  7315. });
  7316. },
  7317. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7318. UploadProgress progress_callback) {
  7319. return cli.Post(endpoint, items, progress_callback);
  7320. },
  7321. "/multipart");
  7322. }
  7323. // Helper function for basic download progress tests
  7324. template <typename SetupHandler, typename ClientCall>
  7325. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7326. ClientCall &&client_call, const string &endpoint,
  7327. size_t expected_content_size) {
  7328. Server svr;
  7329. setup_handler(svr);
  7330. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7331. auto se = detail::scope_exit([&] {
  7332. svr.stop();
  7333. t.join();
  7334. });
  7335. svr.wait_until_ready();
  7336. Client cli(HOST, PORT);
  7337. vector<uint64_t> progress_values;
  7338. auto res = client_call(cli, endpoint,
  7339. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7340. progress_values.push_back(current);
  7341. return true;
  7342. });
  7343. ASSERT_TRUE(res);
  7344. EXPECT_EQ(200, res->status);
  7345. EXPECT_FALSE(progress_values.empty());
  7346. EXPECT_EQ(expected_content_size, res->body.size());
  7347. }
  7348. TEST(DownloadProgressTest, GetBasic) {
  7349. TestBasicDownloadProgress(
  7350. [](Server &svr) {
  7351. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7352. string content(1000, 'D');
  7353. res.set_content(content, "text/plain");
  7354. });
  7355. },
  7356. [](Client &cli, const string &endpoint,
  7357. DownloadProgress progress_callback) {
  7358. return cli.Get(endpoint, progress_callback);
  7359. },
  7360. "/download", 1000u);
  7361. }
  7362. // Helper function for content receiver download progress tests
  7363. template <typename SetupHandler, typename ClientCall>
  7364. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7365. ClientCall &&client_call,
  7366. const string &endpoint,
  7367. size_t expected_content_size) {
  7368. Server svr;
  7369. setup_handler(svr);
  7370. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7371. auto se = detail::scope_exit([&] {
  7372. svr.stop();
  7373. t.join();
  7374. });
  7375. svr.wait_until_ready();
  7376. Client cli(HOST, PORT);
  7377. vector<uint64_t> progress_values;
  7378. string received_body;
  7379. auto res = client_call(
  7380. cli, endpoint,
  7381. [&](const char *data, size_t data_length) -> bool {
  7382. received_body.append(data, data_length);
  7383. return true;
  7384. },
  7385. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7386. progress_values.push_back(current);
  7387. return true;
  7388. });
  7389. ASSERT_TRUE(res);
  7390. EXPECT_EQ(200, res->status);
  7391. EXPECT_FALSE(progress_values.empty());
  7392. EXPECT_EQ(expected_content_size, received_body.size());
  7393. EXPECT_TRUE(res->body.empty());
  7394. }
  7395. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7396. TestContentReceiverDownloadProgress(
  7397. [](Server &svr) {
  7398. svr.Get("/download-receiver",
  7399. [](const Request & /*req*/, Response &res) {
  7400. string content(2000, 'R');
  7401. res.set_content(content, "text/plain");
  7402. });
  7403. },
  7404. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7405. DownloadProgress progress_callback) {
  7406. return cli.Get(endpoint, content_receiver, progress_callback);
  7407. },
  7408. "/download-receiver", 2000u);
  7409. }
  7410. TEST(StreamingTest, NoContentLengthStreaming) {
  7411. Server svr;
  7412. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7413. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7414. if (offset < 6) {
  7415. sink.os << (offset < 3 ? "a" : "b");
  7416. } else {
  7417. sink.done();
  7418. }
  7419. return true;
  7420. });
  7421. });
  7422. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7423. auto listen_se = detail::scope_exit([&] {
  7424. svr.stop();
  7425. listen_thread.join();
  7426. ASSERT_FALSE(svr.is_running());
  7427. });
  7428. svr.wait_until_ready();
  7429. Client client(HOST, PORT);
  7430. auto get_thread = std::thread([&client]() {
  7431. std::string s;
  7432. auto res =
  7433. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7434. s += std::string(data, len);
  7435. return true;
  7436. });
  7437. ASSERT_TRUE(res);
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. EXPECT_EQ("aaabbb", s);
  7440. });
  7441. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7442. // Give GET time to get a few messages.
  7443. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7444. }
  7445. TEST(MountTest, Unmount) {
  7446. Server svr;
  7447. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7448. auto se = detail::scope_exit([&] {
  7449. svr.stop();
  7450. listen_thread.join();
  7451. ASSERT_FALSE(svr.is_running());
  7452. });
  7453. svr.wait_until_ready();
  7454. Client cli("localhost", PORT);
  7455. svr.set_mount_point("/mount2", "./www2");
  7456. auto res = cli.Get("/");
  7457. ASSERT_TRUE(res);
  7458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7459. res = cli.Get("/mount2/dir/test.html");
  7460. ASSERT_TRUE(res);
  7461. EXPECT_EQ(StatusCode::OK_200, res->status);
  7462. svr.set_mount_point("/", "./www");
  7463. res = cli.Get("/dir/");
  7464. ASSERT_TRUE(res);
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. svr.remove_mount_point("/");
  7467. res = cli.Get("/dir/");
  7468. ASSERT_TRUE(res);
  7469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7470. svr.remove_mount_point("/mount2");
  7471. res = cli.Get("/mount2/dir/test.html");
  7472. ASSERT_TRUE(res);
  7473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7474. }
  7475. TEST(MountTest, Redicect) {
  7476. Server svr;
  7477. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7478. auto se = detail::scope_exit([&] {
  7479. svr.stop();
  7480. listen_thread.join();
  7481. ASSERT_FALSE(svr.is_running());
  7482. });
  7483. svr.set_mount_point("/", "./www");
  7484. svr.wait_until_ready();
  7485. Client cli("localhost", PORT);
  7486. auto res = cli.Get("/dir/");
  7487. ASSERT_TRUE(res);
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. res = cli.Get("/dir");
  7490. ASSERT_TRUE(res);
  7491. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7492. res = cli.Get("/file");
  7493. ASSERT_TRUE(res);
  7494. EXPECT_EQ(StatusCode::OK_200, res->status);
  7495. res = cli.Get("/file/");
  7496. ASSERT_TRUE(res);
  7497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7498. cli.set_follow_location(true);
  7499. res = cli.Get("/dir");
  7500. ASSERT_TRUE(res);
  7501. EXPECT_EQ(StatusCode::OK_200, res->status);
  7502. }
  7503. TEST(MountTest, MultibytesPathName) {
  7504. Server svr;
  7505. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7506. auto se = detail::scope_exit([&] {
  7507. svr.stop();
  7508. listen_thread.join();
  7509. ASSERT_FALSE(svr.is_running());
  7510. });
  7511. svr.set_mount_point("/", "./www");
  7512. svr.wait_until_ready();
  7513. Client cli("localhost", PORT);
  7514. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7515. ASSERT_TRUE(res);
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7518. }
  7519. #ifdef _WIN32
  7520. // Issue #2435: mmap::open() must succeed even when another handle holds
  7521. // the file open for writing (e.g. an active log file).
  7522. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7523. const char *path = "mmap_concurrent_writer_test.txt";
  7524. const char *content = "hello";
  7525. {
  7526. std::ofstream f(path, std::ios::binary);
  7527. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7528. }
  7529. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7530. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7531. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7532. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7533. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7534. detail::mmap m(path);
  7535. ASSERT_TRUE(m.is_open());
  7536. EXPECT_EQ(strlen(content), m.size());
  7537. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7538. }
  7539. #endif
  7540. TEST(KeepAliveTest, ReadTimeout) {
  7541. Server svr;
  7542. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7543. std::this_thread::sleep_for(std::chrono::seconds(2));
  7544. res.set_content("a", "text/plain");
  7545. });
  7546. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7547. res.set_content("b", "text/plain");
  7548. });
  7549. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7550. auto se = detail::scope_exit([&] {
  7551. svr.stop();
  7552. listen_thread.join();
  7553. ASSERT_FALSE(svr.is_running());
  7554. });
  7555. svr.wait_until_ready();
  7556. Client cli("localhost", PORT);
  7557. cli.set_keep_alive(true);
  7558. cli.set_read_timeout(std::chrono::seconds(1));
  7559. auto resa = cli.Get("/a");
  7560. ASSERT_FALSE(resa);
  7561. EXPECT_EQ(Error::Read, resa.error());
  7562. auto resb = cli.Get("/b");
  7563. ASSERT_TRUE(resb);
  7564. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7565. EXPECT_EQ("b", resb->body);
  7566. }
  7567. TEST(KeepAliveTest, MaxCount) {
  7568. size_t keep_alive_max_count = 3;
  7569. Server svr;
  7570. svr.set_keep_alive_max_count(keep_alive_max_count);
  7571. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7572. res.set_content("Hello World!", "text/plain");
  7573. });
  7574. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7575. auto se = detail::scope_exit([&] {
  7576. svr.stop();
  7577. listen_thread.join();
  7578. ASSERT_FALSE(svr.is_running());
  7579. });
  7580. svr.wait_until_ready();
  7581. Client cli(HOST, PORT);
  7582. cli.set_keep_alive(true);
  7583. for (size_t i = 0; i < 5; i++) {
  7584. auto result = cli.Get("/hi");
  7585. ASSERT_TRUE(result);
  7586. EXPECT_EQ(StatusCode::OK_200, result->status);
  7587. if (i == keep_alive_max_count - 1) {
  7588. EXPECT_EQ("close", result->get_header_value("Connection"));
  7589. } else {
  7590. EXPECT_FALSE(result->has_header("Connection"));
  7591. }
  7592. }
  7593. }
  7594. TEST(KeepAliveTest, Issue1041) {
  7595. Server svr;
  7596. svr.set_keep_alive_timeout(3);
  7597. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7598. res.set_content("Hello World!", "text/plain");
  7599. });
  7600. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7601. auto se = detail::scope_exit([&] {
  7602. svr.stop();
  7603. listen_thread.join();
  7604. ASSERT_FALSE(svr.is_running());
  7605. });
  7606. svr.wait_until_ready();
  7607. Client cli(HOST, PORT);
  7608. cli.set_keep_alive(true);
  7609. auto result = cli.Get("/hi");
  7610. ASSERT_TRUE(result);
  7611. EXPECT_EQ(StatusCode::OK_200, result->status);
  7612. std::this_thread::sleep_for(std::chrono::seconds(5));
  7613. result = cli.Get("/hi");
  7614. ASSERT_TRUE(result);
  7615. EXPECT_EQ(StatusCode::OK_200, result->status);
  7616. }
  7617. TEST(KeepAliveTest, Issue1959) {
  7618. Server svr;
  7619. svr.set_keep_alive_timeout(5);
  7620. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7621. res.set_content("a", "text/plain");
  7622. });
  7623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7624. auto se = detail::scope_exit([&] {
  7625. if (!svr.is_running()) return;
  7626. svr.stop();
  7627. listen_thread.join();
  7628. ASSERT_FALSE(svr.is_running());
  7629. });
  7630. svr.wait_until_ready();
  7631. Client cli("localhost", PORT);
  7632. cli.set_keep_alive(true);
  7633. using namespace std::chrono;
  7634. auto start = steady_clock::now();
  7635. cli.Get("/a");
  7636. svr.stop();
  7637. listen_thread.join();
  7638. auto end = steady_clock::now();
  7639. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7640. EXPECT_LT(elapsed, 5000);
  7641. }
  7642. #ifdef CPPHTTPLIB_SSL_ENABLED
  7643. TEST(KeepAliveTest, SSLClientReconnection) {
  7644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7645. ASSERT_TRUE(svr.is_valid());
  7646. svr.set_keep_alive_timeout(1);
  7647. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7648. res.set_content("Hello World!", "text/plain");
  7649. });
  7650. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7651. auto se = detail::scope_exit([&] {
  7652. svr.stop();
  7653. listen_thread.join();
  7654. ASSERT_FALSE(svr.is_running());
  7655. });
  7656. svr.wait_until_ready();
  7657. SSLClient cli(HOST, PORT);
  7658. cli.enable_server_certificate_verification(false);
  7659. cli.set_keep_alive(true);
  7660. auto result = cli.Get("/hi");
  7661. ASSERT_TRUE(result);
  7662. EXPECT_EQ(StatusCode::OK_200, result->status);
  7663. result = cli.Get("/hi");
  7664. ASSERT_TRUE(result);
  7665. EXPECT_EQ(StatusCode::OK_200, result->status);
  7666. std::this_thread::sleep_for(std::chrono::seconds(2));
  7667. // Recoonect
  7668. result = cli.Get("/hi");
  7669. ASSERT_TRUE(result);
  7670. EXPECT_EQ(StatusCode::OK_200, result->status);
  7671. result = cli.Get("/hi");
  7672. ASSERT_TRUE(result);
  7673. EXPECT_EQ(StatusCode::OK_200, result->status);
  7674. }
  7675. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7677. ASSERT_TRUE(svr.is_valid());
  7678. svr.set_keep_alive_timeout(1);
  7679. std::string content = "reconnect";
  7680. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7681. res.set_content("Hello World!", "text/plain");
  7682. });
  7683. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7684. auto se = detail::scope_exit([&] {
  7685. svr.stop();
  7686. listen_thread.join();
  7687. ASSERT_FALSE(svr.is_running());
  7688. });
  7689. svr.wait_until_ready();
  7690. SSLClient cli(HOST, PORT);
  7691. cli.enable_server_certificate_verification(false);
  7692. cli.set_keep_alive(true);
  7693. auto result = cli.Post(
  7694. "/hi", content.size(),
  7695. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7696. sink.write(content.c_str(), content.size());
  7697. return true;
  7698. },
  7699. "text/plain");
  7700. ASSERT_TRUE(result);
  7701. EXPECT_EQ(200, result->status);
  7702. std::this_thread::sleep_for(std::chrono::seconds(2));
  7703. // Recoonect
  7704. result = cli.Post(
  7705. "/hi", content.size(),
  7706. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7707. sink.write(content.c_str(), content.size());
  7708. return true;
  7709. },
  7710. "text/plain");
  7711. ASSERT_TRUE(result);
  7712. EXPECT_EQ(200, result->status);
  7713. result = cli.Post(
  7714. "/hi", content.size(),
  7715. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7716. sink.write(content.c_str(), content.size());
  7717. return true;
  7718. },
  7719. "text/plain");
  7720. ASSERT_TRUE(result);
  7721. EXPECT_EQ(200, result->status);
  7722. }
  7723. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7724. using namespace httplib::tls;
  7725. {
  7726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7727. ASSERT_TRUE(svr.is_valid());
  7728. svr.Get("/sni", [&](const Request &req, Response &res) {
  7729. std::string expected = req.sni();
  7730. EXPECT_EQ(expected, req.get_param_value("expected"));
  7731. res.set_content("ok", "text/plain");
  7732. });
  7733. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7734. auto se = detail::scope_exit([&] {
  7735. svr.stop();
  7736. listen_thread.join();
  7737. ASSERT_FALSE(svr.is_running());
  7738. });
  7739. svr.wait_until_ready();
  7740. {
  7741. SSLClient cli("localhost", PORT);
  7742. cli.enable_server_certificate_verification(false);
  7743. auto res = cli.Get("/sni?expected=localhost");
  7744. ASSERT_TRUE(res);
  7745. }
  7746. {
  7747. SSLClient cli("::1", PORT);
  7748. cli.enable_server_certificate_verification(false);
  7749. auto res = cli.Get("/sni?expected=");
  7750. // NOTE: This may fail if the server is listening on IPv4 only
  7751. // (e.g., when localhost resolves to 127.0.0.1 only)
  7752. if (res) {
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. } else {
  7755. EXPECT_EQ(Error::Connection, res.error());
  7756. }
  7757. }
  7758. }
  7759. }
  7760. #endif
  7761. TEST(ClientProblemDetectionTest, ContentProvider) {
  7762. Server svr;
  7763. size_t content_length = 1024 * 1024;
  7764. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7765. res.set_content_provider(
  7766. content_length, "text/plain",
  7767. [&](size_t offset, size_t length, DataSink &sink) {
  7768. auto out_len = std::min(length, static_cast<size_t>(1024));
  7769. std::string out(out_len, '@');
  7770. sink.write(out.data(), out_len);
  7771. return offset < 4096;
  7772. },
  7773. [](bool success) { ASSERT_FALSE(success); });
  7774. });
  7775. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7776. res.set_content_provider(
  7777. 0, "text/plain",
  7778. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7779. EXPECT_TRUE(false);
  7780. return true;
  7781. },
  7782. [](bool success) { ASSERT_FALSE(success); });
  7783. });
  7784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7785. auto se = detail::scope_exit([&] {
  7786. svr.stop();
  7787. listen_thread.join();
  7788. ASSERT_FALSE(svr.is_running());
  7789. });
  7790. svr.wait_until_ready();
  7791. Client cli("localhost", PORT);
  7792. {
  7793. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7794. size_t /*data_length*/) { return false; });
  7795. ASSERT_FALSE(res);
  7796. }
  7797. {
  7798. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7799. size_t /*data_length*/) { return false; });
  7800. ASSERT_TRUE(res);
  7801. }
  7802. }
  7803. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7804. Server svr;
  7805. svr.set_error_handler([](Request const &, Response &res) -> void {
  7806. res.set_chunked_content_provider(
  7807. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7808. sink.os << "hello";
  7809. sink.os << "world";
  7810. sink.done();
  7811. return true;
  7812. });
  7813. });
  7814. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7815. auto se = detail::scope_exit([&] {
  7816. svr.stop();
  7817. listen_thread.join();
  7818. ASSERT_FALSE(svr.is_running());
  7819. });
  7820. svr.wait_until_ready();
  7821. Client cli("localhost", PORT);
  7822. auto res = cli.Get("/");
  7823. ASSERT_TRUE(res);
  7824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7825. EXPECT_EQ("helloworld", res->body);
  7826. }
  7827. TEST(LongPollingTest, ClientCloseDetection) {
  7828. Server svr;
  7829. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7830. res.set_chunked_content_provider(
  7831. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7832. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7833. sink.os << "hello";
  7834. auto count = 10;
  7835. while (count > 0 && sink.is_writable()) {
  7836. this_thread::sleep_for(chrono::milliseconds(10));
  7837. count--;
  7838. }
  7839. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7840. return true;
  7841. });
  7842. });
  7843. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7844. auto se = detail::scope_exit([&] {
  7845. svr.stop();
  7846. listen_thread.join();
  7847. ASSERT_FALSE(svr.is_running());
  7848. });
  7849. svr.wait_until_ready();
  7850. Client cli("localhost", PORT);
  7851. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7852. EXPECT_EQ("hello", string(data, data_length));
  7853. return false; // close the socket immediately.
  7854. });
  7855. ASSERT_FALSE(res);
  7856. }
  7857. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7858. Server svr;
  7859. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7860. res.set_chunked_content_provider(
  7861. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7862. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7863. sink.os << "hello";
  7864. EXPECT_TRUE(sink.os.good());
  7865. // Wait for the client to close the connection
  7866. auto count = 10;
  7867. while (count > 0 && sink.is_writable()) {
  7868. this_thread::sleep_for(chrono::milliseconds(10));
  7869. count--;
  7870. }
  7871. // After client disconnect, write repeatedly until the socket
  7872. // write actually fails (small writes may be absorbed by the
  7873. // kernel buffer)
  7874. std::string chunk(1024, 'x');
  7875. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7876. sink.os << chunk;
  7877. }
  7878. EXPECT_TRUE(sink.os.fail());
  7879. return true;
  7880. });
  7881. });
  7882. auto port = svr.bind_to_any_port("localhost");
  7883. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7884. auto se = detail::scope_exit([&] {
  7885. svr.stop();
  7886. listen_thread.join();
  7887. ASSERT_FALSE(svr.is_running());
  7888. });
  7889. svr.wait_until_ready();
  7890. Client cli("localhost", port);
  7891. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7892. EXPECT_EQ("hello", string(data, data_length));
  7893. return false; // close the socket immediately.
  7894. });
  7895. ASSERT_FALSE(res);
  7896. }
  7897. TEST(GetWithParametersTest, GetWithParameters) {
  7898. Server svr;
  7899. svr.Get("/", [&](const Request &req, Response &) {
  7900. EXPECT_EQ("world", req.get_param_value("hello"));
  7901. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7902. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7903. });
  7904. svr.Get("/params", [&](const Request &req, Response &) {
  7905. EXPECT_EQ("world", req.get_param_value("hello"));
  7906. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7907. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7908. });
  7909. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7910. EXPECT_EQ("resource-id", req.matches[1]);
  7911. EXPECT_EQ("foo", req.get_param_value("param1"));
  7912. EXPECT_EQ("bar", req.get_param_value("param2"));
  7913. });
  7914. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7915. EXPECT_EQ("user-id", req.path_params.at("id"));
  7916. EXPECT_EQ("foo", req.get_param_value("param1"));
  7917. EXPECT_EQ("bar", req.get_param_value("param2"));
  7918. });
  7919. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7920. auto se = detail::scope_exit([&] {
  7921. svr.stop();
  7922. listen_thread.join();
  7923. ASSERT_FALSE(svr.is_running());
  7924. });
  7925. svr.wait_until_ready();
  7926. {
  7927. Client cli(HOST, PORT);
  7928. Params params;
  7929. params.emplace("hello", "world");
  7930. params.emplace("hello2", "world2");
  7931. params.emplace("hello3", "world3");
  7932. auto res = cli.Get("/", params, Headers{});
  7933. ASSERT_TRUE(res);
  7934. EXPECT_EQ(StatusCode::OK_200, res->status);
  7935. }
  7936. {
  7937. Client cli(HOST, PORT);
  7938. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7939. ASSERT_TRUE(res);
  7940. EXPECT_EQ(StatusCode::OK_200, res->status);
  7941. }
  7942. {
  7943. Client cli(HOST, PORT);
  7944. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7945. ASSERT_TRUE(res);
  7946. EXPECT_EQ(StatusCode::OK_200, res->status);
  7947. }
  7948. {
  7949. Client cli(HOST, PORT);
  7950. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7951. ASSERT_TRUE(res);
  7952. EXPECT_EQ(StatusCode::OK_200, res->status);
  7953. }
  7954. }
  7955. TEST(GetWithParametersTest, GetWithParameters2) {
  7956. Server svr;
  7957. svr.Get("/", [&](const Request &req, Response &res) {
  7958. auto text = req.get_param_value("hello");
  7959. res.set_content(text, "text/plain");
  7960. });
  7961. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7962. auto se = detail::scope_exit([&] {
  7963. svr.stop();
  7964. listen_thread.join();
  7965. ASSERT_FALSE(svr.is_running());
  7966. });
  7967. svr.wait_until_ready();
  7968. Client cli("localhost", PORT);
  7969. Params params;
  7970. params.emplace("hello", "world");
  7971. std::string body;
  7972. auto res = cli.Get("/", params, Headers{},
  7973. [&](const char *data, size_t data_length) {
  7974. body.append(data, data_length);
  7975. return true;
  7976. });
  7977. ASSERT_TRUE(res);
  7978. EXPECT_EQ(StatusCode::OK_200, res->status);
  7979. EXPECT_EQ("world", body);
  7980. }
  7981. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  7982. Server svr;
  7983. svr.Get("/search", [&](const Request &req, Response &res) {
  7984. auto q = req.get_param_value("q");
  7985. res.set_content(q, "text/plain");
  7986. });
  7987. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7988. auto se = detail::scope_exit([&] {
  7989. svr.stop();
  7990. listen_thread.join();
  7991. ASSERT_FALSE(svr.is_running());
  7992. });
  7993. svr.wait_until_ready();
  7994. Client cli("localhost", PORT);
  7995. // Verify that Get(path, params) works without requiring Headers argument
  7996. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  7997. ASSERT_TRUE(res);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. EXPECT_EQ("cpp-httplib", res->body);
  8000. }
  8001. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8002. auto host = "httpbingo.org";
  8003. auto path = std::string{"/range/32"};
  8004. #ifdef CPPHTTPLIB_SSL_ENABLED
  8005. SSLClient cli(host);
  8006. #else
  8007. Client cli(host);
  8008. #endif
  8009. cli.set_default_headers({make_range_header({{1, 10}})});
  8010. cli.set_connection_timeout(5);
  8011. {
  8012. auto res = cli.Get(path);
  8013. ASSERT_TRUE(res);
  8014. EXPECT_EQ("bcdefghijk", res->body);
  8015. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8016. }
  8017. {
  8018. auto res = cli.Get(path);
  8019. ASSERT_TRUE(res);
  8020. EXPECT_EQ("bcdefghijk", res->body);
  8021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8022. }
  8023. }
  8024. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8025. Server svr;
  8026. svr.set_default_headers({{"Hello", "World"}});
  8027. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8028. res.set_content("ok", "text/plain");
  8029. });
  8030. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8031. auto se = detail::scope_exit([&] {
  8032. svr.stop();
  8033. listen_thread.join();
  8034. ASSERT_FALSE(svr.is_running());
  8035. });
  8036. svr.wait_until_ready();
  8037. Client cli("localhost", PORT);
  8038. auto res = cli.Get("/");
  8039. ASSERT_TRUE(res);
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. EXPECT_EQ("ok", res->body);
  8042. EXPECT_EQ("World", res->get_header_value("Hello"));
  8043. }
  8044. #ifdef CPPHTTPLIB_SSL_ENABLED
  8045. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8047. ASSERT_TRUE(svr.is_valid());
  8048. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8049. std::this_thread::sleep_for(std::chrono::seconds(2));
  8050. res.set_content("a", "text/plain");
  8051. });
  8052. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8053. res.set_content("b", "text/plain");
  8054. });
  8055. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8056. auto se = detail::scope_exit([&] {
  8057. svr.stop();
  8058. listen_thread.join();
  8059. ASSERT_FALSE(svr.is_running());
  8060. });
  8061. svr.wait_until_ready();
  8062. SSLClient cli("localhost", PORT);
  8063. cli.enable_server_certificate_verification(false);
  8064. cli.set_keep_alive(true);
  8065. cli.set_read_timeout(std::chrono::seconds(1));
  8066. auto resa = cli.Get("/a");
  8067. ASSERT_TRUE(!resa);
  8068. EXPECT_EQ(Error::Read, resa.error());
  8069. auto resb = cli.Get("/b");
  8070. ASSERT_TRUE(resb);
  8071. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8072. EXPECT_EQ("b", resb->body);
  8073. }
  8074. #endif
  8075. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8076. protected:
  8077. ServerTestWithAI_PASSIVE()
  8078. : cli_(HOST, PORT)
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. ,
  8081. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8082. #endif
  8083. {
  8084. #ifdef CPPHTTPLIB_SSL_ENABLED
  8085. cli_.enable_server_certificate_verification(false);
  8086. #endif
  8087. }
  8088. virtual void SetUp() {
  8089. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8090. res.set_content("Hello World!", "text/plain");
  8091. });
  8092. t_ = thread(
  8093. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8094. svr_.wait_until_ready();
  8095. }
  8096. virtual void TearDown() {
  8097. svr_.stop();
  8098. t_.join();
  8099. }
  8100. #ifdef CPPHTTPLIB_SSL_ENABLED
  8101. SSLClient cli_;
  8102. SSLServer svr_;
  8103. #else
  8104. Client cli_;
  8105. Server svr_;
  8106. #endif
  8107. thread t_;
  8108. };
  8109. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8110. auto res = cli_.Get("/hi");
  8111. ASSERT_TRUE(res);
  8112. EXPECT_EQ(StatusCode::OK_200, res->status);
  8113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8114. EXPECT_EQ("Hello World!", res->body);
  8115. }
  8116. class ServerUpDownTest : public ::testing::Test {
  8117. protected:
  8118. ServerUpDownTest() : cli_(HOST, PORT) {}
  8119. virtual void SetUp() {
  8120. t_ = thread([&]() {
  8121. svr_.bind_to_any_port(HOST);
  8122. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8123. ASSERT_TRUE(svr_.listen_after_bind());
  8124. });
  8125. svr_.wait_until_ready();
  8126. }
  8127. virtual void TearDown() {
  8128. svr_.stop();
  8129. t_.join();
  8130. }
  8131. Client cli_;
  8132. Server svr_;
  8133. thread t_;
  8134. };
  8135. TEST_F(ServerUpDownTest, QuickStartStop) {
  8136. // Should not crash, especially when run with
  8137. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8138. }
  8139. class PayloadMaxLengthTest : public ::testing::Test {
  8140. protected:
  8141. PayloadMaxLengthTest()
  8142. : cli_(HOST, PORT)
  8143. #ifdef CPPHTTPLIB_SSL_ENABLED
  8144. ,
  8145. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8146. #endif
  8147. {
  8148. #ifdef CPPHTTPLIB_SSL_ENABLED
  8149. cli_.enable_server_certificate_verification(false);
  8150. #endif
  8151. }
  8152. virtual void SetUp() {
  8153. svr_.set_payload_max_length(8);
  8154. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8155. res.set_content("test", "text/plain");
  8156. });
  8157. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8158. svr_.wait_until_ready();
  8159. }
  8160. virtual void TearDown() {
  8161. svr_.stop();
  8162. t_.join();
  8163. }
  8164. #ifdef CPPHTTPLIB_SSL_ENABLED
  8165. SSLClient cli_;
  8166. SSLServer svr_;
  8167. #else
  8168. Client cli_;
  8169. Server svr_;
  8170. #endif
  8171. thread t_;
  8172. };
  8173. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8174. auto res = cli_.Post("/test", "123456789", "text/plain");
  8175. ASSERT_TRUE(res);
  8176. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8177. res = cli_.Post("/test", "12345678", "text/plain");
  8178. ASSERT_TRUE(res);
  8179. EXPECT_EQ(StatusCode::OK_200, res->status);
  8180. }
  8181. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8182. // Test chunked encoding with payload exceeding the 8-byte limit
  8183. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8184. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8185. ASSERT_TRUE(res);
  8186. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8187. }
  8188. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8189. // Test chunked encoding with payload within the 8-byte limit
  8190. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8191. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8192. ASSERT_TRUE(res);
  8193. EXPECT_EQ(StatusCode::OK_200, res->status);
  8194. }
  8195. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8196. // Test using send_request to send chunked data exceeding payload limit
  8197. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8198. "Host: " +
  8199. std::string(HOST) + ":" + std::to_string(PORT) +
  8200. "\r\n"
  8201. "Transfer-Encoding: chunked\r\n"
  8202. "Connection: close\r\n"
  8203. "\r\n"
  8204. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8205. "0123456789\r\n"
  8206. "0\r\n" // End chunk
  8207. "\r\n";
  8208. std::string response;
  8209. bool result = send_request(1, chunked_request, &response);
  8210. if (!result) {
  8211. // If send_request fails, it might be because the server closed the
  8212. // connection due to payload limit enforcement, which is acceptable
  8213. SUCCEED()
  8214. << "Server rejected oversized chunked request (connection closed)";
  8215. } else {
  8216. // If we got a response, check if it's an error response or connection was
  8217. // closed early Short response length indicates connection was closed due to
  8218. // payload limit
  8219. if (response.length() <= 10) {
  8220. SUCCEED() << "Server closed connection for oversized chunked request";
  8221. } else {
  8222. // Check for error status codes
  8223. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8224. response.find("Payload Too Large") != std::string::npos ||
  8225. response.find("400") != std::string::npos);
  8226. }
  8227. }
  8228. }
  8229. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8230. // Test request without Content-Length header exceeding payload limit
  8231. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8232. "Host: " +
  8233. std::string(HOST) + ":" +
  8234. std::to_string(PORT) +
  8235. "\r\n"
  8236. "Connection: close\r\n"
  8237. "\r\n";
  8238. // Add payload exceeding the 8-byte limit
  8239. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8240. request_without_content_length += large_payload;
  8241. std::string response;
  8242. bool result = send_request(1, request_without_content_length, &response);
  8243. if (!result) {
  8244. // If send_request fails, server likely closed connection due to payload
  8245. // limit
  8246. SUCCEED() << "Server rejected oversized request without Content-Length "
  8247. "(connection closed)";
  8248. } else {
  8249. // Check if server responded with error or closed connection early
  8250. if (response.length() <= 10) {
  8251. SUCCEED() << "Server closed connection for oversized request without "
  8252. "Content-Length";
  8253. } else {
  8254. // Check for error status codes
  8255. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8256. response.find("Payload Too Large") != std::string::npos ||
  8257. response.find("400") != std::string::npos);
  8258. }
  8259. }
  8260. }
  8261. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8262. // Test request without Content-Length header within payload limit
  8263. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8264. "Host: " +
  8265. std::string(HOST) + ":" +
  8266. std::to_string(PORT) +
  8267. "\r\n"
  8268. "Connection: close\r\n"
  8269. "\r\n";
  8270. // Add payload within the 8-byte limit
  8271. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8272. request_without_content_length += small_payload;
  8273. std::string response;
  8274. bool result = send_request(1, request_without_content_length, &response);
  8275. // For requests without Content-Length, the server may have different behavior
  8276. // The key is that it should not reject due to payload limit for small
  8277. // payloads
  8278. if (result) {
  8279. // Check for any HTTP response (success or error, but not connection closed)
  8280. if (response.length() > 10) {
  8281. SUCCEED()
  8282. << "Server processed request without Content-Length within limit";
  8283. } else {
  8284. // Short response might indicate connection closed, which is acceptable
  8285. SUCCEED() << "Server closed connection for request without "
  8286. "Content-Length (acceptable behavior)";
  8287. }
  8288. } else {
  8289. // Connection failure might be due to protocol requirements
  8290. SUCCEED() << "Connection issue with request without Content-Length "
  8291. "(environment-specific)";
  8292. }
  8293. }
  8294. class LargePayloadMaxLengthTest : public ::testing::Test {
  8295. protected:
  8296. LargePayloadMaxLengthTest()
  8297. : cli_(HOST, PORT)
  8298. #ifdef CPPHTTPLIB_SSL_ENABLED
  8299. ,
  8300. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8301. #endif
  8302. {
  8303. #ifdef CPPHTTPLIB_SSL_ENABLED
  8304. cli_.enable_server_certificate_verification(false);
  8305. #endif
  8306. }
  8307. virtual void SetUp() {
  8308. // Set 10MB payload limit
  8309. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8310. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8311. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8312. res.set_content("Large payload test", "text/plain");
  8313. });
  8314. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8315. svr_.wait_until_ready();
  8316. }
  8317. virtual void TearDown() {
  8318. svr_.stop();
  8319. t_.join();
  8320. }
  8321. #ifdef CPPHTTPLIB_SSL_ENABLED
  8322. SSLClient cli_;
  8323. SSLServer svr_;
  8324. #else
  8325. Client cli_;
  8326. Server svr_;
  8327. #endif
  8328. thread t_;
  8329. };
  8330. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8331. // Test chunked encoding with payload within 10MB limit
  8332. std::string medium_payload(5 * 1024 * 1024,
  8333. 'A'); // 5MB payload, within 10MB limit
  8334. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8335. ASSERT_TRUE(res);
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. }
  8338. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8339. // Test chunked encoding with payload exceeding 10MB limit
  8340. std::string large_payload(12 * 1024 * 1024,
  8341. 'B'); // 12MB payload, exceeds 10MB limit
  8342. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8343. // Server may either return 413 or close the connection
  8344. if (res) {
  8345. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8346. } else {
  8347. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8348. }
  8349. }
  8350. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8351. // Test request without Content-Length header within 10MB limit
  8352. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8353. "Host: " +
  8354. std::string(HOST) + ":" +
  8355. std::to_string(PORT) +
  8356. "\r\n"
  8357. "Connection: close\r\n"
  8358. "\r\n";
  8359. // Add 1MB payload (within 10MB limit)
  8360. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8361. request_without_content_length += medium_payload;
  8362. std::string response;
  8363. bool result = send_request(5, request_without_content_length, &response);
  8364. if (result) {
  8365. // Should get a proper HTTP response for payloads within limit
  8366. if (response.length() > 10) {
  8367. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8368. "10MB limit";
  8369. } else {
  8370. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8371. "Content-Length)";
  8372. }
  8373. } else {
  8374. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8375. }
  8376. }
  8377. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8378. // Test request without Content-Length header exceeding 10MB limit
  8379. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8380. "Host: " +
  8381. std::string(HOST) + ":" +
  8382. std::to_string(PORT) +
  8383. "\r\n"
  8384. "Connection: close\r\n"
  8385. "\r\n";
  8386. // Add 12MB payload (exceeds 10MB limit)
  8387. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8388. request_without_content_length += large_payload;
  8389. std::string response;
  8390. bool result = send_request(10, request_without_content_length, &response);
  8391. if (!result) {
  8392. // Server should close connection due to payload limit
  8393. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8394. "(connection closed)";
  8395. } else {
  8396. // Check for error response
  8397. if (response.length() <= 10) {
  8398. SUCCEED()
  8399. << "Server closed connection for 12MB request exceeding 10MB limit";
  8400. } else {
  8401. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8402. response.find("Payload Too Large") != std::string::npos ||
  8403. response.find("400") != std::string::npos);
  8404. }
  8405. }
  8406. }
  8407. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8408. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8409. // path.
  8410. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8411. Server svr;
  8412. const size_t LIMIT = 64 * 1024; // 64KB
  8413. svr.set_payload_max_length(LIMIT);
  8414. size_t total = 0;
  8415. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8416. const ContentReader &content_reader) {
  8417. content_reader([&](const char * /*data*/, size_t len) {
  8418. total += len;
  8419. return true;
  8420. });
  8421. res.status = 200;
  8422. res.set_content("stream_ok", "text/plain");
  8423. });
  8424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8425. auto se = detail::scope_exit([&] {
  8426. svr.stop();
  8427. thread.join();
  8428. ASSERT_FALSE(svr.is_running());
  8429. });
  8430. svr.wait_until_ready();
  8431. // Prepare 256KB raw data and gzip-compress it
  8432. std::string raw(256 * 1024, 'A');
  8433. std::string gz;
  8434. {
  8435. z_stream zs{};
  8436. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8437. Z_DEFAULT_STRATEGY);
  8438. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8439. zs.avail_in = static_cast<uInt>(raw.size());
  8440. char outbuf[4096];
  8441. int ret;
  8442. do {
  8443. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8444. zs.avail_out = sizeof(outbuf);
  8445. ret = deflate(&zs, Z_FINISH);
  8446. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8447. } while (ret != Z_STREAM_END);
  8448. deflateEnd(&zs);
  8449. }
  8450. Client cli(HOST, PORT);
  8451. cli.set_connection_timeout(std::chrono::seconds(5));
  8452. Headers headers = {{"Content-Encoding", "gzip"}};
  8453. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8454. "application/octet-stream");
  8455. ASSERT_TRUE(res);
  8456. // Server must reject oversized decompressed payloads with 413.
  8457. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8458. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8459. EXPECT_LE(total, LIMIT);
  8460. }
  8461. #endif
  8462. // Regression test for DoS vulnerability: a malicious server sending a response
  8463. // without Content-Length header must not cause unbounded memory consumption on
  8464. // the client side. The client should stop reading after a reasonable limit,
  8465. // similar to the server-side set_payload_max_length protection.
  8466. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8467. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8468. #ifndef _WIN32
  8469. signal(SIGPIPE, SIG_IGN);
  8470. #endif
  8471. auto server_thread = std::thread([] {
  8472. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8473. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8474. default_socket_options(srv);
  8475. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8476. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8477. sockaddr_in addr{};
  8478. addr.sin_family = AF_INET;
  8479. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8480. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8481. int opt = 1;
  8482. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8483. #ifdef _WIN32
  8484. reinterpret_cast<const char *>(&opt),
  8485. #else
  8486. &opt,
  8487. #endif
  8488. sizeof(opt));
  8489. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8490. ::listen(srv, 1);
  8491. sockaddr_in cli_addr{};
  8492. socklen_t cli_len = sizeof(cli_addr);
  8493. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8494. if (cli != INVALID_SOCKET) {
  8495. char buf[4096];
  8496. ::recv(cli, buf, sizeof(buf), 0);
  8497. // Malicious response: no Content-Length, no chunked encoding
  8498. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8499. "Connection: close\r\n"
  8500. "\r\n";
  8501. ::send(cli,
  8502. #ifdef _WIN32
  8503. static_cast<const char *>(response_header.c_str()),
  8504. static_cast<int>(response_header.size()),
  8505. #else
  8506. response_header.c_str(), response_header.size(),
  8507. #endif
  8508. 0);
  8509. // Send 10MB of data
  8510. std::string chunk(64 * 1024, 'A');
  8511. size_t total_sent = 0;
  8512. while (total_sent < MALICIOUS_DATA_SIZE) {
  8513. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8514. auto sent = ::send(cli,
  8515. #ifdef _WIN32
  8516. static_cast<const char *>(chunk.c_str()),
  8517. static_cast<int>(to_send),
  8518. #else
  8519. chunk.c_str(), to_send,
  8520. #endif
  8521. 0);
  8522. if (sent <= 0) break;
  8523. total_sent += static_cast<size_t>(sent);
  8524. }
  8525. detail::close_socket(cli);
  8526. }
  8527. detail::close_socket(srv);
  8528. });
  8529. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8530. size_t total_read = 0;
  8531. {
  8532. Client cli("127.0.0.1", PORT + 2);
  8533. cli.set_read_timeout(5, 0);
  8534. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8535. auto stream = cli.open_stream("GET", "/malicious");
  8536. ASSERT_TRUE(stream.is_valid());
  8537. char buffer[64 * 1024];
  8538. ssize_t n;
  8539. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8540. total_read += static_cast<size_t>(n);
  8541. }
  8542. } // StreamHandle and Client destroyed here, closing the socket
  8543. server_thread.join();
  8544. // With set_payload_max_length, the client must stop reading before consuming
  8545. // all 10MB. The read loop should be cut off at or near the configured limit.
  8546. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8547. << "Client read " << total_read << " bytes, exceeding the configured "
  8548. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8549. }
  8550. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8551. // the entire response body without truncation.
  8552. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8553. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8554. #ifndef _WIN32
  8555. signal(SIGPIPE, SIG_IGN);
  8556. #endif
  8557. auto server_thread = std::thread([] {
  8558. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8559. default_socket_options(srv);
  8560. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8561. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8562. sockaddr_in addr{};
  8563. addr.sin_family = AF_INET;
  8564. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8565. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8566. int opt = 1;
  8567. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8568. #ifdef _WIN32
  8569. reinterpret_cast<const char *>(&opt),
  8570. #else
  8571. &opt,
  8572. #endif
  8573. sizeof(opt));
  8574. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8575. ::listen(srv, 1);
  8576. sockaddr_in cli_addr{};
  8577. socklen_t cli_len = sizeof(cli_addr);
  8578. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8579. if (cli != INVALID_SOCKET) {
  8580. char buf[4096];
  8581. ::recv(cli, buf, sizeof(buf), 0);
  8582. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8583. "Connection: close\r\n"
  8584. "\r\n";
  8585. ::send(cli,
  8586. #ifdef _WIN32
  8587. static_cast<const char *>(response_header.c_str()),
  8588. static_cast<int>(response_header.size()),
  8589. #else
  8590. response_header.c_str(), response_header.size(),
  8591. #endif
  8592. 0);
  8593. std::string chunk(64 * 1024, 'A');
  8594. size_t total_sent = 0;
  8595. while (total_sent < DATA_SIZE) {
  8596. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8597. auto sent = ::send(cli,
  8598. #ifdef _WIN32
  8599. static_cast<const char *>(chunk.c_str()),
  8600. static_cast<int>(to_send),
  8601. #else
  8602. chunk.c_str(), to_send,
  8603. #endif
  8604. 0);
  8605. if (sent <= 0) break;
  8606. total_sent += static_cast<size_t>(sent);
  8607. }
  8608. #ifdef _WIN32
  8609. ::shutdown(cli, SD_SEND);
  8610. #else
  8611. ::shutdown(cli, SHUT_WR);
  8612. #endif
  8613. // Drain until the client closes its end, ensuring all data is delivered
  8614. char drain[1024];
  8615. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8616. detail::close_socket(cli);
  8617. }
  8618. detail::close_socket(srv);
  8619. });
  8620. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8621. size_t total_read = 0;
  8622. {
  8623. Client cli("127.0.0.1", PORT + 2);
  8624. cli.set_read_timeout(5, 0);
  8625. cli.set_payload_max_length(0); // 0 means no limit
  8626. auto stream = cli.open_stream("GET", "/data");
  8627. ASSERT_TRUE(stream.is_valid());
  8628. char buffer[64 * 1024];
  8629. ssize_t n;
  8630. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8631. total_read += static_cast<size_t>(n);
  8632. }
  8633. }
  8634. server_thread.join();
  8635. EXPECT_EQ(total_read, DATA_SIZE)
  8636. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8637. << " bytes without truncation, but only read " << total_read << " bytes.";
  8638. }
  8639. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8640. // enormous Content-Length must not cause the client to pre-allocate a huge
  8641. // response body buffer. The reservation is capped at payload_max_length_, and
  8642. // the read itself fails when the body exceeds the limit.
  8643. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8644. #ifndef _WIN32
  8645. signal(SIGPIPE, SIG_IGN);
  8646. #endif
  8647. auto server_thread = std::thread([] {
  8648. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8649. default_socket_options(srv);
  8650. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8651. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8652. sockaddr_in addr{};
  8653. addr.sin_family = AF_INET;
  8654. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8655. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8656. int opt = 1;
  8657. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8658. #ifdef _WIN32
  8659. reinterpret_cast<const char *>(&opt),
  8660. #else
  8661. &opt,
  8662. #endif
  8663. sizeof(opt));
  8664. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8665. ::listen(srv, 1);
  8666. sockaddr_in cli_addr{};
  8667. socklen_t cli_len = sizeof(cli_addr);
  8668. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8669. if (cli != INVALID_SOCKET) {
  8670. char buf[4096];
  8671. ::recv(cli, buf, sizeof(buf), 0);
  8672. // Malicious response: claim a 20GB body but send only a tiny payload.
  8673. std::string response = "HTTP/1.1 200 OK\r\n"
  8674. "Content-Length: 20000000000\r\n"
  8675. "\r\n"
  8676. "abc";
  8677. ::send(cli,
  8678. #ifdef _WIN32
  8679. static_cast<const char *>(response.c_str()),
  8680. static_cast<int>(response.size()),
  8681. #else
  8682. response.c_str(), response.size(),
  8683. #endif
  8684. 0);
  8685. detail::close_socket(cli);
  8686. }
  8687. detail::close_socket(srv);
  8688. });
  8689. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8690. {
  8691. Client cli("127.0.0.1", PORT + 2);
  8692. cli.set_read_timeout(5, 0);
  8693. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8694. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8695. // (server claims more bytes than payload_max_length permits), but it must
  8696. // not exhaust memory before getting there.
  8697. auto res = cli.Get("/malicious");
  8698. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8699. }
  8700. server_thread.join();
  8701. }
  8702. // Verify that content_receiver bypasses the default payload_max_length,
  8703. // allowing streaming downloads larger than 100MB without requiring an explicit
  8704. // set_payload_max_length call.
  8705. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8706. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8707. #ifndef _WIN32
  8708. signal(SIGPIPE, SIG_IGN);
  8709. #endif
  8710. auto server_thread = std::thread([] {
  8711. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8712. default_socket_options(srv);
  8713. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8714. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8715. sockaddr_in addr{};
  8716. addr.sin_family = AF_INET;
  8717. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8718. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8719. int opt = 1;
  8720. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8721. #ifdef _WIN32
  8722. reinterpret_cast<const char *>(&opt),
  8723. #else
  8724. &opt,
  8725. #endif
  8726. sizeof(opt));
  8727. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8728. ::listen(srv, 1);
  8729. sockaddr_in cli_addr{};
  8730. socklen_t cli_len = sizeof(cli_addr);
  8731. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8732. if (cli != INVALID_SOCKET) {
  8733. char buf[4096];
  8734. ::recv(cli, buf, sizeof(buf), 0);
  8735. // Response with Content-Length larger than default 100MB limit
  8736. auto content_length = std::to_string(DATA_SIZE);
  8737. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8738. "Content-Length: " +
  8739. content_length +
  8740. "\r\n"
  8741. "Connection: close\r\n"
  8742. "\r\n";
  8743. ::send(cli,
  8744. #ifdef _WIN32
  8745. static_cast<const char *>(response_header.c_str()),
  8746. static_cast<int>(response_header.size()),
  8747. #else
  8748. response_header.c_str(), response_header.size(),
  8749. #endif
  8750. 0);
  8751. std::string chunk(64 * 1024, 'A');
  8752. size_t total_sent = 0;
  8753. while (total_sent < DATA_SIZE) {
  8754. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8755. auto sent = ::send(cli,
  8756. #ifdef _WIN32
  8757. static_cast<const char *>(chunk.c_str()),
  8758. static_cast<int>(to_send),
  8759. #else
  8760. chunk.c_str(), to_send,
  8761. #endif
  8762. 0);
  8763. if (sent <= 0) break;
  8764. total_sent += static_cast<size_t>(sent);
  8765. }
  8766. detail::close_socket(cli);
  8767. }
  8768. detail::close_socket(srv);
  8769. });
  8770. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8771. size_t total_received = 0;
  8772. {
  8773. Client cli("127.0.0.1", PORT + 2);
  8774. cli.set_read_timeout(10, 0);
  8775. // Do NOT call set_payload_max_length — use the default 100MB limit
  8776. auto res =
  8777. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8778. total_received += data_length;
  8779. return true;
  8780. });
  8781. ASSERT_TRUE(res);
  8782. EXPECT_EQ(StatusCode::OK_200, res->status);
  8783. }
  8784. server_thread.join();
  8785. EXPECT_EQ(total_received, DATA_SIZE)
  8786. << "With content_receiver, the client should read all " << DATA_SIZE
  8787. << " bytes despite the default 100MB payload_max_length, but only read "
  8788. << total_received << " bytes.";
  8789. }
  8790. // Verify that an explicit set_payload_max_length smaller than the response is
  8791. // enforced even when a content_receiver is used.
  8792. TEST(ClientVulnerabilityTest,
  8793. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8794. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8795. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8796. #ifndef _WIN32
  8797. signal(SIGPIPE, SIG_IGN);
  8798. #endif
  8799. auto server_thread = std::thread([] {
  8800. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8801. default_socket_options(srv);
  8802. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8803. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8804. sockaddr_in addr{};
  8805. addr.sin_family = AF_INET;
  8806. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8807. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8808. int opt = 1;
  8809. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8810. #ifdef _WIN32
  8811. reinterpret_cast<const char *>(&opt),
  8812. #else
  8813. &opt,
  8814. #endif
  8815. sizeof(opt));
  8816. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8817. ::listen(srv, 1);
  8818. sockaddr_in cli_addr{};
  8819. socklen_t cli_len = sizeof(cli_addr);
  8820. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8821. if (cli != INVALID_SOCKET) {
  8822. char buf[4096];
  8823. ::recv(cli, buf, sizeof(buf), 0);
  8824. auto content_length = std::to_string(DATA_SIZE);
  8825. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8826. "Content-Length: " +
  8827. content_length +
  8828. "\r\n"
  8829. "Connection: close\r\n"
  8830. "\r\n";
  8831. ::send(cli,
  8832. #ifdef _WIN32
  8833. static_cast<const char *>(response_header.c_str()),
  8834. static_cast<int>(response_header.size()),
  8835. #else
  8836. response_header.c_str(), response_header.size(),
  8837. #endif
  8838. 0);
  8839. std::string chunk(64 * 1024, 'A');
  8840. size_t total_sent = 0;
  8841. while (total_sent < DATA_SIZE) {
  8842. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8843. auto sent = ::send(cli,
  8844. #ifdef _WIN32
  8845. static_cast<const char *>(chunk.c_str()),
  8846. static_cast<int>(to_send),
  8847. #else
  8848. chunk.c_str(), to_send,
  8849. #endif
  8850. 0);
  8851. if (sent <= 0) break;
  8852. total_sent += static_cast<size_t>(sent);
  8853. }
  8854. detail::close_socket(cli);
  8855. }
  8856. detail::close_socket(srv);
  8857. });
  8858. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8859. size_t total_received = 0;
  8860. {
  8861. Client cli("127.0.0.1", PORT + 2);
  8862. cli.set_read_timeout(10, 0);
  8863. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8864. auto res =
  8865. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8866. total_received += data_length;
  8867. return true;
  8868. });
  8869. // Should fail because 200MB exceeds the explicit 150MB limit
  8870. EXPECT_FALSE(res);
  8871. }
  8872. server_thread.join();
  8873. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8874. << "Client with content_receiver should respect the explicit "
  8875. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8876. << total_received << " bytes.";
  8877. }
  8878. // Verify that an explicit set_payload_max_length larger than the response
  8879. // allows the content_receiver to read all data successfully.
  8880. TEST(ClientVulnerabilityTest,
  8881. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8882. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8883. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8884. #ifndef _WIN32
  8885. signal(SIGPIPE, SIG_IGN);
  8886. #endif
  8887. auto server_thread = std::thread([] {
  8888. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8889. default_socket_options(srv);
  8890. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8891. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8892. sockaddr_in addr{};
  8893. addr.sin_family = AF_INET;
  8894. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8895. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8896. int opt = 1;
  8897. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8898. #ifdef _WIN32
  8899. reinterpret_cast<const char *>(&opt),
  8900. #else
  8901. &opt,
  8902. #endif
  8903. sizeof(opt));
  8904. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8905. ::listen(srv, 1);
  8906. sockaddr_in cli_addr{};
  8907. socklen_t cli_len = sizeof(cli_addr);
  8908. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8909. if (cli != INVALID_SOCKET) {
  8910. char buf[4096];
  8911. ::recv(cli, buf, sizeof(buf), 0);
  8912. auto content_length = std::to_string(DATA_SIZE);
  8913. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8914. "Content-Length: " +
  8915. content_length +
  8916. "\r\n"
  8917. "Connection: close\r\n"
  8918. "\r\n";
  8919. ::send(cli,
  8920. #ifdef _WIN32
  8921. static_cast<const char *>(response_header.c_str()),
  8922. static_cast<int>(response_header.size()),
  8923. #else
  8924. response_header.c_str(), response_header.size(),
  8925. #endif
  8926. 0);
  8927. std::string chunk(64 * 1024, 'A');
  8928. size_t total_sent = 0;
  8929. while (total_sent < DATA_SIZE) {
  8930. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8931. auto sent = ::send(cli,
  8932. #ifdef _WIN32
  8933. static_cast<const char *>(chunk.c_str()),
  8934. static_cast<int>(to_send),
  8935. #else
  8936. chunk.c_str(), to_send,
  8937. #endif
  8938. 0);
  8939. if (sent <= 0) break;
  8940. total_sent += static_cast<size_t>(sent);
  8941. }
  8942. #ifdef _WIN32
  8943. ::shutdown(cli, SD_SEND);
  8944. #else
  8945. ::shutdown(cli, SHUT_WR);
  8946. #endif
  8947. char drain[1024];
  8948. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8949. detail::close_socket(cli);
  8950. }
  8951. detail::close_socket(srv);
  8952. });
  8953. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8954. size_t total_received = 0;
  8955. {
  8956. Client cli("127.0.0.1", PORT + 2);
  8957. cli.set_read_timeout(10, 0);
  8958. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8959. auto res =
  8960. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8961. total_received += data_length;
  8962. return true;
  8963. });
  8964. ASSERT_TRUE(res);
  8965. EXPECT_EQ(StatusCode::OK_200, res->status);
  8966. }
  8967. server_thread.join();
  8968. EXPECT_EQ(total_received, DATA_SIZE)
  8969. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8970. << " bytes (larger than " << DATA_SIZE
  8971. << " bytes response), content_receiver should read all data, but only "
  8972. "read "
  8973. << total_received << " bytes.";
  8974. }
  8975. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8976. // Regression test for "zip bomb" attack on the client side: a malicious server
  8977. // sends a small gzip-compressed response that decompresses to a huge payload.
  8978. // The client must enforce payload_max_length on the decompressed size.
  8979. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8980. constexpr size_t DECOMPRESSED_SIZE =
  8981. 10 * 1024 * 1024; // 10MB after decompression
  8982. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8983. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8984. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8985. std::string compressed;
  8986. {
  8987. httplib::detail::gzip_compressor compressor;
  8988. bool ok =
  8989. compressor.compress(uncompressed.data(), uncompressed.size(),
  8990. /*last=*/true, [&](const char *buf, size_t len) {
  8991. compressed.append(buf, len);
  8992. return true;
  8993. });
  8994. ASSERT_TRUE(ok);
  8995. }
  8996. // Sanity: compressed data should be much smaller than the decompressed size
  8997. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8998. #ifndef _WIN32
  8999. signal(SIGPIPE, SIG_IGN);
  9000. #endif
  9001. // Set up the listening socket in the main thread so the server is guaranteed
  9002. // to be ready before the client connects (eliminates race condition).
  9003. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9004. default_socket_options(srv);
  9005. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9007. sockaddr_in addr{};
  9008. addr.sin_family = AF_INET;
  9009. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9010. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9011. int opt = 1;
  9012. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9013. #ifdef _WIN32
  9014. reinterpret_cast<const char *>(&opt),
  9015. #else
  9016. &opt,
  9017. #endif
  9018. sizeof(opt));
  9019. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9020. ASSERT_EQ(0, ::listen(srv, 1));
  9021. auto server_thread = std::thread([&compressed, srv] {
  9022. sockaddr_in cli_addr{};
  9023. socklen_t cli_len = sizeof(cli_addr);
  9024. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9025. if (cli != INVALID_SOCKET) {
  9026. // Read the full HTTP request (until \r\n\r\n)
  9027. char buf[4096];
  9028. size_t total = 0;
  9029. while (total < sizeof(buf)) {
  9030. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9031. if (n <= 0) break;
  9032. total += static_cast<size_t>(n);
  9033. // Check for end of headers
  9034. if (total >= 4) {
  9035. std::string req(buf, total);
  9036. if (req.find("\r\n\r\n") != std::string::npos) break;
  9037. }
  9038. }
  9039. // Malicious response: gzip-compressed body, no Content-Length
  9040. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9041. "Content-Encoding: gzip\r\n"
  9042. "Connection: close\r\n"
  9043. "\r\n";
  9044. ::send(cli,
  9045. #ifdef _WIN32
  9046. static_cast<const char *>(response_header.c_str()),
  9047. static_cast<int>(response_header.size()),
  9048. #else
  9049. response_header.c_str(), response_header.size(),
  9050. #endif
  9051. 0);
  9052. // Send the compressed payload (small on the wire, huge when decompressed)
  9053. size_t total_sent = 0;
  9054. while (total_sent < compressed.size()) {
  9055. auto to_send = std::min(compressed.size() - total_sent,
  9056. static_cast<size_t>(64 * 1024));
  9057. auto sent =
  9058. ::send(cli,
  9059. #ifdef _WIN32
  9060. static_cast<const char *>(compressed.c_str() + total_sent),
  9061. static_cast<int>(to_send),
  9062. #else
  9063. compressed.c_str() + total_sent, to_send,
  9064. #endif
  9065. 0);
  9066. if (sent <= 0) break;
  9067. total_sent += static_cast<size_t>(sent);
  9068. }
  9069. detail::close_socket(cli);
  9070. }
  9071. });
  9072. auto se = detail::scope_exit([&] {
  9073. detail::close_socket(srv);
  9074. server_thread.join();
  9075. });
  9076. size_t total_decompressed = 0;
  9077. {
  9078. Client cli("127.0.0.1", PORT + 3);
  9079. cli.set_read_timeout(5, 0);
  9080. cli.set_decompress(true);
  9081. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9082. auto stream = cli.open_stream("GET", "/zipbomb");
  9083. ASSERT_TRUE(stream.is_valid());
  9084. char buffer[64 * 1024];
  9085. ssize_t n;
  9086. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9087. total_decompressed += static_cast<size_t>(n);
  9088. }
  9089. }
  9090. // The decompressed size must be capped by payload_max_length. Without
  9091. // protection, the client would decompress the full 10MB from a tiny
  9092. // compressed payload, enabling a zip bomb DoS attack.
  9093. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9094. << "Client decompressed " << total_decompressed
  9095. << " bytes from a gzip response. The decompressed size should be "
  9096. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9097. }
  9098. #endif
  9099. TEST(HostAndPortPropertiesTest, NoSSL) {
  9100. httplib::Client cli("www.google.com", 1234);
  9101. ASSERT_EQ("www.google.com", cli.host());
  9102. ASSERT_EQ(1234, cli.port());
  9103. }
  9104. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9105. httplib::Client cli("www.google.com:1234");
  9106. ASSERT_EQ("www.google.com", cli.host());
  9107. ASSERT_EQ(1234, cli.port());
  9108. }
  9109. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9110. // Port number that overflows int — should not crash, client becomes invalid
  9111. httplib::Client cli("http://www.google.com:99999999999999999999");
  9112. ASSERT_FALSE(cli.is_valid());
  9113. }
  9114. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9115. // Port 99999 exceeds valid range (1-65535) — should not crash
  9116. httplib::Client cli("http://www.google.com:99999");
  9117. ASSERT_FALSE(cli.is_valid());
  9118. }
  9119. #ifdef CPPHTTPLIB_SSL_ENABLED
  9120. TEST(HostAndPortPropertiesTest, SSL) {
  9121. httplib::SSLClient cli("www.google.com");
  9122. ASSERT_EQ("www.google.com", cli.host());
  9123. ASSERT_EQ(443, cli.port());
  9124. }
  9125. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9126. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9127. std::string cert;
  9128. read_file(CA_CERT_FILE, cert);
  9129. httplib::SSLClient httplib_client("www.google.com");
  9130. // Load CA store first time
  9131. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9132. // Load CA store second time (update)
  9133. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9134. // Verify client is still valid and can make connections
  9135. httplib_client.enable_server_certificate_verification(true);
  9136. auto res = httplib_client.Get("/");
  9137. ASSERT_TRUE(res);
  9138. // Google may return 200 or 301 depending on various factors
  9139. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9140. res->status == StatusCode::MovedPermanently_301);
  9141. }
  9142. TEST(SSLClientTest, ServerNameIndication_Online) {
  9143. auto host = "httpbingo.org";
  9144. auto path = std::string{"/get"};
  9145. SSLClient cli(host, 443);
  9146. auto res = cli.Get(path);
  9147. ASSERT_TRUE(res);
  9148. ASSERT_EQ(StatusCode::OK_200, res->status);
  9149. }
  9150. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9151. // Use a site that will cause SSL verification failure due to self-signed cert
  9152. SSLClient cli("self-signed.badssl.com", 443);
  9153. cli.enable_server_certificate_verification(true);
  9154. auto res = cli.Get("/");
  9155. ASSERT_TRUE(!res);
  9156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9157. // Verify backend error is captured for SSLServerVerification
  9158. // This occurs when certificate verification fails
  9159. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9160. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9161. EXPECT_NE(0UL, res.ssl_backend_error());
  9162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9163. // For OpenSSL, ssl_error is 0 for verification errors
  9164. EXPECT_EQ(0, res.ssl_error());
  9165. #if !defined(_WIN32) || \
  9166. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9167. // On non-Windows or when Windows Schannel is disabled, the error comes
  9168. // from OpenSSL's verification
  9169. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9170. res.ssl_backend_error());
  9171. #endif
  9172. #endif
  9173. }
  9174. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9175. // Use a site where hostname doesn't match the certificate
  9176. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9177. SSLClient cli("wrong.host.badssl.com", 443);
  9178. cli.enable_server_certificate_verification(true);
  9179. cli.enable_server_hostname_verification(true);
  9180. auto res = cli.Get("/");
  9181. ASSERT_TRUE(!res);
  9182. // The error type depends on when hostname verification occurs:
  9183. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9184. // - Mbed TLS: SSLServerVerification (during handshake)
  9185. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9186. res.error() == Error::SSLServerVerification);
  9187. // Verify backend error is captured for hostname verification failure
  9188. EXPECT_NE(0UL, res.ssl_backend_error());
  9189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9190. // For OpenSSL, ssl_error is 0 for verification errors
  9191. EXPECT_EQ(0, res.ssl_error());
  9192. #if !defined(_WIN32) || \
  9193. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9194. // On non-Windows or when Windows Schannel is disabled, the error comes
  9195. // from OpenSSL's hostname verification
  9196. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9197. res.ssl_backend_error());
  9198. #endif
  9199. #endif
  9200. }
  9201. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9202. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9203. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9204. SSLClient cli("www.google.com", 443);
  9205. cli.enable_server_certificate_verification(true);
  9206. auto res = cli.Get("/");
  9207. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9208. }
  9209. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9210. SSLClient cli("www.google.com", 443);
  9211. cli.enable_server_certificate_verification(true);
  9212. cli.enable_windows_certificate_verification(false);
  9213. auto res = cli.Get("/");
  9214. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9215. }
  9216. #endif
  9217. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9218. Client cli("https://google.com");
  9219. auto res = cli.Get("/");
  9220. ASSERT_TRUE(res);
  9221. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9222. }
  9223. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9224. SSLClient cli("google.com");
  9225. cli.set_ca_cert_path(CA_CERT_FILE);
  9226. auto res = cli.Get("/");
  9227. ASSERT_TRUE(res);
  9228. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9229. }
  9230. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9231. SSLClient cli("google.com");
  9232. cli.enable_server_certificate_verification(true);
  9233. cli.set_ca_cert_path("hello");
  9234. auto res = cli.Get("/");
  9235. ASSERT_TRUE(!res);
  9236. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9237. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9238. // should be set
  9239. EXPECT_EQ(0, res.ssl_error());
  9240. // Verify backend error is captured for SSLLoadingCerts
  9241. // This error occurs when loading CA certificates fails
  9242. EXPECT_NE(0UL, res.ssl_backend_error());
  9243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9244. // OpenSSL specific error codes:
  9245. // > openssl errstr 0x80000002
  9246. // error:80000002:system library::No such file or directory
  9247. // > openssl errstr 0xA000126
  9248. // error:0A000126:SSL routines::unexpected eof while reading
  9249. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9250. res.ssl_backend_error() == 0xA000126);
  9251. #endif
  9252. }
  9253. TEST(SSLClientTest, ServerCertificateVerification4) {
  9254. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9255. ASSERT_TRUE(svr.is_valid());
  9256. svr.Get("/test", [&](const Request &, Response &res) {
  9257. res.set_content("test", "text/plain");
  9258. svr.stop();
  9259. ASSERT_TRUE(true);
  9260. });
  9261. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9262. auto se = detail::scope_exit([&] {
  9263. t.join();
  9264. ASSERT_FALSE(svr.is_running());
  9265. });
  9266. svr.wait_until_ready();
  9267. SSLClient cli("127.0.0.1", PORT);
  9268. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9269. cli.enable_server_certificate_verification(true);
  9270. cli.set_connection_timeout(30);
  9271. auto res = cli.Get("/test");
  9272. ASSERT_TRUE(res);
  9273. ASSERT_EQ(StatusCode::OK_200, res->status);
  9274. }
  9275. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9276. std::string cert;
  9277. read_file(CA_CERT_FILE, cert);
  9278. SSLClient cli("google.com");
  9279. cli.load_ca_cert_store(cert.data(), cert.size());
  9280. const auto res = cli.Get("/");
  9281. ASSERT_TRUE(res);
  9282. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9283. }
  9284. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9285. // clang-format off
  9286. static constexpr char cert[] =
  9287. "GlobalSign Root CA\n"
  9288. "==================\n"
  9289. "-----BEGIN CERTIFICATE-----\n"
  9290. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9291. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9292. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9293. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9294. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9295. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9296. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9297. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9298. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9299. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9300. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9301. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9302. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9303. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9304. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9305. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9306. "-----END CERTIFICATE-----\n";
  9307. // clang-format on
  9308. SSLClient cli("google.com");
  9309. cli.load_ca_cert_store(cert, sizeof(cert));
  9310. const auto res = cli.Get("/");
  9311. ASSERT_TRUE(res);
  9312. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9313. }
  9314. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9315. SSLClient cli("www.youtube.com");
  9316. cli.set_ca_cert_path(CA_CERT_FILE);
  9317. cli.enable_server_certificate_verification(true);
  9318. cli.set_follow_location(true);
  9319. auto res = cli.Get("/");
  9320. ASSERT_TRUE(res);
  9321. ASSERT_EQ(StatusCode::OK_200, res->status);
  9322. }
  9323. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9324. SSLClient cli("wWw.YouTube.Com");
  9325. cli.set_ca_cert_path(CA_CERT_FILE);
  9326. cli.enable_server_certificate_verification(true);
  9327. cli.enable_server_hostname_verification(true);
  9328. cli.set_follow_location(true);
  9329. auto res = cli.Get("/");
  9330. ASSERT_TRUE(res);
  9331. ASSERT_EQ(StatusCode::OK_200, res->status);
  9332. }
  9333. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9334. SSLClient cli("gOoGlE.COm");
  9335. cli.enable_server_certificate_verification(true);
  9336. cli.enable_server_hostname_verification(true);
  9337. cli.set_follow_location(true);
  9338. auto res = cli.Get("/");
  9339. ASSERT_TRUE(res);
  9340. ASSERT_EQ(StatusCode::OK_200, res->status);
  9341. }
  9342. TEST(SSLClientTest, Issue2004_Online) {
  9343. Client client("https://google.com");
  9344. client.set_follow_location(true);
  9345. auto res = client.Get("/");
  9346. ASSERT_TRUE(res);
  9347. ASSERT_EQ(StatusCode::OK_200, res->status);
  9348. auto body = res->body;
  9349. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9350. }
  9351. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9352. // Create SSLClient with invalid cert/key to make is_valid() return false
  9353. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9354. "nonexistent_key.pem");
  9355. // is_valid() should be false due to cert loading failure
  9356. ASSERT_FALSE(cli.is_valid());
  9357. auto res = cli.Get("/");
  9358. ASSERT_FALSE(res);
  9359. EXPECT_EQ(Error::SSLConnection, res.error());
  9360. }
  9361. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9362. // Test for Issue #2251: SSL error not properly reported when client cert
  9363. // and key paths are swapped or mismatched
  9364. // This simulates the scenario where user accidentally swaps the cert and key
  9365. // files
  9366. // Using client cert file as private key and vice versa (completely wrong)
  9367. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9368. // Should fail validation due to cert/key mismatch
  9369. ASSERT_FALSE(cli.is_valid());
  9370. // Attempt to make a request should fail with proper error
  9371. auto res = cli.Get("/");
  9372. ASSERT_FALSE(res);
  9373. EXPECT_EQ(Error::SSLConnection, res.error());
  9374. // SSL error should be recorded in the Result object (this is the key fix for
  9375. // Issue #2251)
  9376. auto backend_error = res.ssl_backend_error();
  9377. EXPECT_NE(0u, backend_error);
  9378. }
  9379. // Tests cert/key mismatch detection at the TLS context level
  9380. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9381. // Test that using mismatched cert/key causes connection failure.
  9382. // We verify this at the SSLClient level rather than through internal
  9383. // TLS API functions.
  9384. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9385. cli.enable_server_certificate_verification(false);
  9386. cli.set_connection_timeout(2);
  9387. // The mismatch should cause a connection or handshake error
  9388. auto res = cli.Get("/test");
  9389. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9390. // Either way, the request should fail
  9391. EXPECT_FALSE(res);
  9392. }
  9393. #endif
  9394. #if 0
  9395. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9396. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9397. ASSERT_TRUE(cli != nullptr);
  9398. cli->set_address_family(AF_INET6);
  9399. cli->set_interface("en0");
  9400. auto res = cli->Get("/get");
  9401. ASSERT_TRUE(res);
  9402. ASSERT_EQ(StatusCode::OK_200, res->status);
  9403. }
  9404. #endif
  9405. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9406. #ifdef CPPHTTPLIB_SSL_ENABLED
  9407. void ClientCertPresent(
  9408. const std::string &client_cert_file,
  9409. const std::string &client_private_key_file,
  9410. const std::string &client_encrypted_private_key_pass = std::string()) {
  9411. using namespace httplib::tls;
  9412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9413. CLIENT_CA_CERT_DIR);
  9414. ASSERT_TRUE(svr.is_valid());
  9415. svr.Get("/test", [&](const Request &req, Response &res) {
  9416. res.set_content("test", "text/plain");
  9417. auto cert = req.peer_cert();
  9418. ASSERT_TRUE(static_cast<bool>(cert));
  9419. std::string common_name = cert.subject_cn();
  9420. EXPECT_EQ("Common Name", common_name);
  9421. });
  9422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9423. auto se = detail::scope_exit([&] {
  9424. svr.stop();
  9425. t.join();
  9426. ASSERT_FALSE(svr.is_running());
  9427. });
  9428. svr.wait_until_ready();
  9429. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9430. client_encrypted_private_key_pass);
  9431. cli.enable_server_certificate_verification(false);
  9432. cli.set_connection_timeout(30);
  9433. auto res = cli.Get("/test");
  9434. ASSERT_TRUE(res);
  9435. ASSERT_EQ(StatusCode::OK_200, res->status);
  9436. }
  9437. TEST(SSLClientServerTest, ClientCertPresent) {
  9438. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9439. }
  9440. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9441. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9442. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9443. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9444. }
  9445. // PEM memory-based constructor tests (works with all TLS backends)
  9446. void PemMemoryClientCertPresent(
  9447. const std::string &client_cert_file,
  9448. const std::string &client_private_key_file,
  9449. const std::string &client_encrypted_private_key_pass = std::string()) {
  9450. // Read PEM files into memory
  9451. std::string server_cert_pem, server_key_pem;
  9452. std::string client_ca_pem;
  9453. std::string client_cert_pem, client_key_pem;
  9454. read_file(SERVER_CERT_FILE, server_cert_pem);
  9455. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9456. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9457. read_file(client_cert_file, client_cert_pem);
  9458. read_file(client_private_key_file, client_key_pem);
  9459. // Create server with PEM memory
  9460. SSLServer::PemMemory server_pem = {
  9461. server_cert_pem.c_str(),
  9462. server_cert_pem.size(),
  9463. server_key_pem.c_str(),
  9464. server_key_pem.size(),
  9465. client_ca_pem.c_str(),
  9466. client_ca_pem.size(),
  9467. nullptr // no password for server key
  9468. };
  9469. SSLServer svr(server_pem);
  9470. ASSERT_TRUE(svr.is_valid());
  9471. svr.Get("/test", [&](const Request &, Response &res) {
  9472. res.set_content("test", "text/plain");
  9473. });
  9474. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9475. auto se = detail::scope_exit([&] {
  9476. svr.stop();
  9477. t.join();
  9478. ASSERT_FALSE(svr.is_running());
  9479. });
  9480. svr.wait_until_ready();
  9481. // Create client with PEM memory
  9482. const char *password = client_encrypted_private_key_pass.empty()
  9483. ? nullptr
  9484. : client_encrypted_private_key_pass.c_str();
  9485. SSLClient::PemMemory client_pem = {
  9486. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9487. client_key_pem.size(), password};
  9488. SSLClient cli(HOST, PORT, client_pem);
  9489. cli.enable_server_certificate_verification(false);
  9490. cli.set_connection_timeout(30);
  9491. auto res = cli.Get("/test");
  9492. ASSERT_TRUE(res);
  9493. ASSERT_EQ(StatusCode::OK_200, res->status);
  9494. }
  9495. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9496. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9497. }
  9498. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9499. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9500. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9501. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9502. }
  9503. TEST(SSLClientServerTest, ClientCertMissing) {
  9504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9505. CLIENT_CA_CERT_DIR);
  9506. ASSERT_TRUE(svr.is_valid());
  9507. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9508. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9509. auto se = detail::scope_exit([&] {
  9510. svr.stop();
  9511. t.join();
  9512. ASSERT_FALSE(svr.is_running());
  9513. });
  9514. svr.wait_until_ready();
  9515. SSLClient cli(HOST, PORT);
  9516. cli.set_connection_timeout(30);
  9517. auto res = cli.Get("/test");
  9518. ASSERT_TRUE(!res);
  9519. // When client cert is missing and server requires it, connection fails
  9520. // Error type depends on backend implementation
  9521. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9522. res.error() == Error::SSLConnection);
  9523. // Verify backend error is captured
  9524. // Note: This test may have different error codes depending on the exact
  9525. // verification failure
  9526. EXPECT_NE(0UL, res.ssl_backend_error());
  9527. }
  9528. TEST(SSLClientServerTest, TrustDirOptional) {
  9529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9530. ASSERT_TRUE(svr.is_valid());
  9531. svr.Get("/test", [&](const Request &, Response &res) {
  9532. res.set_content("test", "text/plain");
  9533. });
  9534. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. t.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9542. cli.enable_server_certificate_verification(false);
  9543. cli.set_connection_timeout(30);
  9544. auto res = cli.Get("/test");
  9545. ASSERT_TRUE(res);
  9546. ASSERT_EQ(StatusCode::OK_200, res->status);
  9547. }
  9548. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9549. class NoListenSSLServer : public SSLServer {
  9550. public:
  9551. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9552. const char *client_ca_cert_file_path,
  9553. const char *client_ca_cert_dir_path = nullptr)
  9554. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9555. client_ca_cert_dir_path),
  9556. stop_(false) {}
  9557. std::atomic_bool stop_;
  9558. private:
  9559. bool process_and_close_socket(socket_t /*sock*/) override {
  9560. // Don't create SSL context
  9561. while (!stop_.load()) {
  9562. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9563. }
  9564. return true;
  9565. }
  9566. };
  9567. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9568. CLIENT_CA_CERT_FILE);
  9569. ASSERT_TRUE(svr.is_valid());
  9570. svr.Get("/test", [&](const Request &, Response &res) {
  9571. res.set_content("test", "text/plain");
  9572. });
  9573. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9574. auto se = detail::scope_exit([&] {
  9575. svr.stop_ = true;
  9576. svr.stop();
  9577. t.join();
  9578. ASSERT_FALSE(svr.is_running());
  9579. });
  9580. svr.wait_until_ready();
  9581. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9582. cli.enable_server_certificate_verification(false);
  9583. cli.set_connection_timeout(1);
  9584. auto res = cli.Get("/test");
  9585. ASSERT_TRUE(!res);
  9586. EXPECT_EQ(Error::SSLConnection, res.error());
  9587. // Timeout results in WantRead error code (maps to backend-specific value)
  9588. EXPECT_NE(0, res.ssl_error());
  9589. }
  9590. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9591. // Test SSLServer with client certificate verification using the standard
  9592. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9594. CLIENT_CA_CERT_DIR);
  9595. ASSERT_TRUE(svr.is_valid());
  9596. svr.Get("/test", [&](const Request &req, Response &res) {
  9597. res.set_content("test", "text/plain");
  9598. auto cert = req.peer_cert();
  9599. ASSERT_TRUE(static_cast<bool>(cert));
  9600. auto common_name = cert.subject_cn();
  9601. EXPECT_EQ("Common Name", common_name);
  9602. });
  9603. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9604. auto se = detail::scope_exit([&] {
  9605. svr.stop();
  9606. t.join();
  9607. ASSERT_FALSE(svr.is_running());
  9608. });
  9609. svr.wait_until_ready();
  9610. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9611. cli.enable_server_certificate_verification(false);
  9612. cli.set_connection_timeout(30);
  9613. auto res = cli.Get("/test");
  9614. ASSERT_TRUE(res);
  9615. ASSERT_EQ(StatusCode::OK_200, res->status);
  9616. }
  9617. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9618. // Verifies that wildcard matching and exact matching work consistently
  9619. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9620. using namespace httplib::tls;
  9621. // We need a running server to test against
  9622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9623. ASSERT_TRUE(svr.is_valid());
  9624. svr.Get("/test", [](const Request &, Response &res) {
  9625. res.set_content("ok", "text/plain");
  9626. });
  9627. thread t([&]() { svr.listen(HOST, PORT); });
  9628. auto se = detail::scope_exit([&] {
  9629. svr.stop();
  9630. t.join();
  9631. });
  9632. svr.wait_until_ready();
  9633. bool verify_callback_called = false;
  9634. bool verify_result_wrong = false;
  9635. SSLClient cli(HOST, PORT);
  9636. cli.enable_server_certificate_verification(true);
  9637. cli.set_ca_cert_path(CA_CERT_FILE);
  9638. cli.set_connection_timeout(5);
  9639. // Note: Test certificate has CN="Common Name", not "localhost"
  9640. bool verify_result_cn = false;
  9641. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9642. verify_callback_called = true;
  9643. if (!ctx.cert) return false;
  9644. // Test 1: "Common Name" should match (our test server cert CN)
  9645. verify_result_cn = ctx.check_hostname("Common Name");
  9646. // Test 2: wrong hostname should not match
  9647. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9648. return true; // Accept for the purpose of this test
  9649. });
  9650. auto res = cli.Get("/test");
  9651. // The request may succeed or fail depending on cert configuration
  9652. // but the callback should have been called
  9653. ASSERT_TRUE(verify_callback_called)
  9654. << "Verify callback should have been called";
  9655. // CN="Common Name" should match our test certificate
  9656. //
  9657. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9658. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9659. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9660. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9661. // <openssl/base.h>, which is included transitively when
  9662. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9663. #if defined(OPENSSL_IS_BORINGSSL)
  9664. EXPECT_FALSE(verify_result_cn)
  9665. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9666. #else
  9667. EXPECT_TRUE(verify_result_cn)
  9668. << "verify_hostname should match 'Common Name' (certificate CN)";
  9669. #endif
  9670. // Wrong hostname should not match
  9671. EXPECT_FALSE(verify_result_wrong)
  9672. << "verify_hostname should not match 'wronghost.example.com'";
  9673. }
  9674. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9675. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9676. // X509_check_ip behavior and must hold for every backend.
  9677. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9678. using namespace httplib::tls;
  9679. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9680. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9681. ASSERT_TRUE(svr.is_valid());
  9682. svr.Get("/test", [](const Request &, Response &res) {
  9683. res.set_content("ok", "text/plain");
  9684. });
  9685. thread t([&]() { svr.listen(HOST, PORT); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. });
  9690. svr.wait_until_ready();
  9691. bool verify_callback_called = false;
  9692. bool ip_matched_via_cn = true;
  9693. SSLClient cli(HOST, PORT);
  9694. cli.enable_server_certificate_verification(true);
  9695. cli.set_ca_cert_path(CA_CERT_FILE);
  9696. cli.set_connection_timeout(5);
  9697. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9698. verify_callback_called = true;
  9699. if (!ctx.cert) return false;
  9700. // The IP appears only in the CN, so it must NOT be accepted.
  9701. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9702. return true; // Accept for the purpose of this test
  9703. });
  9704. cli.Get("/test");
  9705. ASSERT_TRUE(verify_callback_called)
  9706. << "Verify callback should have been called";
  9707. EXPECT_FALSE(ip_matched_via_cn)
  9708. << "An IP host must not be authenticated via the certificate CN";
  9709. }
  9710. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9711. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9712. using namespace httplib::tls;
  9713. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9714. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9715. ASSERT_TRUE(svr.is_valid());
  9716. svr.Get("/test", [](const Request &, Response &res) {
  9717. res.set_content("ok", "text/plain");
  9718. });
  9719. thread t([&]() { svr.listen(HOST, PORT); });
  9720. auto se = detail::scope_exit([&] {
  9721. svr.stop();
  9722. t.join();
  9723. });
  9724. svr.wait_until_ready();
  9725. bool verify_callback_called = false;
  9726. bool san_matched = false;
  9727. bool wrong_ipv6_matched = true;
  9728. bool cn_ipv6_matched = true;
  9729. SSLClient cli(HOST, PORT);
  9730. cli.enable_server_certificate_verification(true);
  9731. cli.set_ca_cert_path(CA_CERT_FILE);
  9732. cli.set_connection_timeout(5);
  9733. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9734. verify_callback_called = true;
  9735. if (!ctx.cert) return false;
  9736. // Matches the IPv6 iPAddress SAN.
  9737. san_matched = ctx.check_hostname("2001:db8::1");
  9738. // A different IPv6 address must not match.
  9739. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9740. // "::1" lives only in the CN, so it must not be accepted.
  9741. cn_ipv6_matched = ctx.check_hostname("::1");
  9742. return true; // Accept for the purpose of this test
  9743. });
  9744. cli.Get("/test");
  9745. ASSERT_TRUE(verify_callback_called)
  9746. << "Verify callback should have been called";
  9747. EXPECT_TRUE(san_matched)
  9748. << "verify_hostname should match an IPv6 iPAddress SAN";
  9749. EXPECT_FALSE(wrong_ipv6_matched)
  9750. << "verify_hostname should not match a non-matching IPv6 address";
  9751. EXPECT_FALSE(cn_ipv6_matched)
  9752. << "An IPv6 host must not be authenticated via the certificate CN";
  9753. }
  9754. #endif
  9755. // mbedTLS-specific callback constructor test
  9756. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9757. #ifdef CPPHTTPLIB_SSL_ENABLED
  9758. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9759. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9760. ASSERT_TRUE(svr.is_valid());
  9761. // Set up a handler to verify client certificate is present
  9762. bool client_cert_verified = false;
  9763. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9764. // Verify that client certificate was provided
  9765. client_cert_verified = true;
  9766. res.set_content("success", "text/plain");
  9767. });
  9768. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. });
  9774. svr.wait_until_ready();
  9775. // Client with certificate
  9776. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9777. cli.enable_server_certificate_verification(false);
  9778. cli.set_connection_timeout(30);
  9779. auto res = cli.Get("/test");
  9780. ASSERT_TRUE(res);
  9781. ASSERT_EQ(StatusCode::OK_200, res->status);
  9782. ASSERT_TRUE(client_cert_verified);
  9783. EXPECT_EQ("success", res->body);
  9784. }
  9785. #endif
  9786. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9787. // backends
  9788. #ifdef CPPHTTPLIB_SSL_ENABLED
  9789. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9790. using namespace httplib::tls;
  9791. // Test that when client CA cert file is provided,
  9792. // the server properly requests and validates client certificates
  9793. // Create a server with client authentication
  9794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9795. ASSERT_TRUE(svr.is_valid());
  9796. bool handler_called = false;
  9797. svr.Get("/test", [&](const Request &req, Response &res) {
  9798. handler_called = true;
  9799. // Verify that a client certificate was provided
  9800. auto cert = req.peer_cert();
  9801. ASSERT_TRUE(static_cast<bool>(cert));
  9802. // Get the issuer name
  9803. std::string issuer_str = cert.issuer_name();
  9804. ASSERT_FALSE(issuer_str.empty());
  9805. // The client certificate should be issued by our test CA
  9806. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9807. res.set_content("authenticated", "text/plain");
  9808. });
  9809. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9810. auto se = detail::scope_exit([&] {
  9811. svr.stop();
  9812. t.join();
  9813. ASSERT_FALSE(svr.is_running());
  9814. });
  9815. svr.wait_until_ready();
  9816. // Connect with a client certificate issued by the CA
  9817. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9818. cli.enable_server_certificate_verification(false);
  9819. cli.set_connection_timeout(30);
  9820. auto res = cli.Get("/test");
  9821. ASSERT_TRUE(res);
  9822. ASSERT_EQ(StatusCode::OK_200, res->status);
  9823. ASSERT_TRUE(handler_called);
  9824. EXPECT_EQ("authenticated", res->body);
  9825. }
  9826. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9827. using namespace httplib::tls;
  9828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9829. ASSERT_TRUE(svr.is_valid());
  9830. svr.Get("/test", [](const Request &, Response &res) {
  9831. res.set_content("ok", "text/plain");
  9832. });
  9833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9834. auto se = detail::scope_exit([&] {
  9835. svr.stop();
  9836. t.join();
  9837. });
  9838. svr.wait_until_ready();
  9839. SSLClient cli(HOST, PORT);
  9840. cli.enable_server_certificate_verification(false);
  9841. cli.set_connection_timeout(30);
  9842. bool cert_checked = false;
  9843. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9844. if (ctx.cert) {
  9845. auto sans = ctx.sans();
  9846. // Test certificate may or may not have SANs - just verify the API
  9847. // works If SANs exist, verify the types are valid
  9848. for (const auto &san : sans) {
  9849. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9850. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9851. san.type == SanType::OTHER);
  9852. EXPECT_FALSE(san.value.empty());
  9853. }
  9854. cert_checked = true;
  9855. }
  9856. return true;
  9857. });
  9858. auto res = cli.Get("/test");
  9859. ASSERT_TRUE(res);
  9860. EXPECT_TRUE(cert_checked);
  9861. }
  9862. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9863. using namespace httplib::tls;
  9864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9865. ASSERT_TRUE(svr.is_valid());
  9866. svr.Get("/test", [](const Request &, Response &res) {
  9867. res.set_content("ok", "text/plain");
  9868. });
  9869. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9870. auto se = detail::scope_exit([&] {
  9871. svr.stop();
  9872. t.join();
  9873. });
  9874. svr.wait_until_ready();
  9875. SSLClient cli(HOST, PORT);
  9876. cli.enable_server_certificate_verification(false);
  9877. cli.set_connection_timeout(30);
  9878. bool validity_checked = false;
  9879. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9880. if (ctx.cert) {
  9881. time_t not_before = 0, not_after = 0;
  9882. bool result = ctx.validity(not_before, not_after);
  9883. EXPECT_TRUE(result);
  9884. // Verify that not_before < now < not_after for a valid cert
  9885. time_t now = time(nullptr);
  9886. EXPECT_LT(not_before, now);
  9887. EXPECT_GT(not_after, now);
  9888. validity_checked = true;
  9889. }
  9890. return true;
  9891. });
  9892. auto res = cli.Get("/test");
  9893. ASSERT_TRUE(res);
  9894. EXPECT_TRUE(validity_checked);
  9895. }
  9896. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9897. using namespace httplib::tls;
  9898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9899. ASSERT_TRUE(svr.is_valid());
  9900. svr.Get("/test", [](const Request &, Response &res) {
  9901. res.set_content("ok", "text/plain");
  9902. });
  9903. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9904. auto se = detail::scope_exit([&] {
  9905. svr.stop();
  9906. t.join();
  9907. });
  9908. svr.wait_until_ready();
  9909. SSLClient cli(HOST, PORT);
  9910. cli.enable_server_certificate_verification(false);
  9911. cli.set_connection_timeout(30);
  9912. bool serial_checked = false;
  9913. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9914. if (ctx.cert) {
  9915. std::string serial = ctx.serial();
  9916. EXPECT_FALSE(serial.empty());
  9917. // Serial should be a hex string
  9918. for (char c : serial) {
  9919. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9920. (c >= 'a' && c <= 'f'));
  9921. }
  9922. serial_checked = true;
  9923. }
  9924. return true;
  9925. });
  9926. auto res = cli.Get("/test");
  9927. ASSERT_TRUE(res);
  9928. EXPECT_TRUE(serial_checked);
  9929. }
  9930. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9931. // Test 1: Valid CA file - no error should be recorded
  9932. {
  9933. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9934. CLIENT_CA_CERT_FILE);
  9935. ASSERT_TRUE(svr.is_valid());
  9936. // With valid setup, last_ssl_error should be 0
  9937. EXPECT_EQ(0, svr.ssl_last_error());
  9938. }
  9939. // Test 2: Invalid CA file content
  9940. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9941. {
  9942. // Create a temporary file with completely invalid content
  9943. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9944. {
  9945. std::ofstream ofs(temp_invalid_ca);
  9946. ofs << "This is not a certificate file at all\n";
  9947. ofs << "Just plain text content\n";
  9948. }
  9949. // Create server with invalid CA file
  9950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9951. // Clean up temporary file
  9952. std::remove(temp_invalid_ca);
  9953. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9954. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9955. // Note: SSL_CTX_load_verify_locations typically fails first,
  9956. // but our error handling code path is still exercised
  9957. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9958. }
  9959. }
  9960. TEST(VerifyCallbackTest, VerifyContextFields) {
  9961. using namespace httplib::tls;
  9962. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9963. ASSERT_TRUE(svr.is_valid());
  9964. svr.Get("/test", [](const Request &, Response &res) {
  9965. res.set_content("ok", "text/plain");
  9966. });
  9967. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. t.join();
  9971. });
  9972. svr.wait_until_ready();
  9973. SSLClient cli(HOST, PORT);
  9974. cli.enable_server_certificate_verification(false);
  9975. cli.set_connection_timeout(30);
  9976. int callback_count = 0;
  9977. bool saw_leaf_cert = false;
  9978. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9979. if (ctx.cert) {
  9980. callback_count++;
  9981. // We should see at least one certificate (the leaf)
  9982. std::string cn = ctx.subject_cn();
  9983. if (!cn.empty()) { saw_leaf_cert = true; }
  9984. // Verify context fields are populated
  9985. EXPECT_NE(ctx.session, nullptr);
  9986. EXPECT_GE(ctx.depth, 0);
  9987. }
  9988. return true;
  9989. });
  9990. auto res = cli.Get("/test");
  9991. ASSERT_TRUE(res);
  9992. EXPECT_GT(callback_count, 0);
  9993. EXPECT_TRUE(saw_leaf_cert);
  9994. }
  9995. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9996. using httplib::tls::TlsError;
  9997. // Test that verify_error_to_string returns empty for success
  9998. std::string success_str = TlsError::verify_error_to_string(0);
  9999. EXPECT_TRUE(success_str.empty());
  10000. // Test that verify_error_to_string returns non-empty for error codes
  10001. // Using a common error code (certificate expired)
  10002. std::string error_str =
  10003. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10004. EXPECT_FALSE(error_str.empty());
  10005. }
  10006. TEST(SessionVerifierTest, CertificateAccepted) {
  10007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10008. ASSERT_TRUE(svr.is_valid());
  10009. svr.Get("/test", [](const Request &, Response &res) {
  10010. res.set_content("ok", "text/plain");
  10011. });
  10012. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10013. auto se = detail::scope_exit([&] {
  10014. svr.stop();
  10015. t.join();
  10016. });
  10017. svr.wait_until_ready();
  10018. SSLClient cli(HOST, PORT);
  10019. cli.enable_server_certificate_verification(false);
  10020. cli.set_connection_timeout(30);
  10021. bool callback_called = false;
  10022. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10023. EXPECT_NE(session, nullptr);
  10024. callback_called = true;
  10025. return SSLVerifierResponse::CertificateAccepted;
  10026. });
  10027. auto res = cli.Get("/test");
  10028. ASSERT_TRUE(res);
  10029. EXPECT_EQ(200, res->status);
  10030. EXPECT_TRUE(callback_called);
  10031. }
  10032. TEST(SessionVerifierTest, CertificateRejected) {
  10033. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10034. ASSERT_TRUE(svr.is_valid());
  10035. svr.Get("/test", [](const Request &, Response &res) {
  10036. res.set_content("ok", "text/plain");
  10037. });
  10038. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10039. auto se = detail::scope_exit([&] {
  10040. svr.stop();
  10041. t.join();
  10042. });
  10043. svr.wait_until_ready();
  10044. SSLClient cli(HOST, PORT);
  10045. cli.enable_server_certificate_verification(false);
  10046. cli.set_connection_timeout(30);
  10047. bool callback_called = false;
  10048. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10049. EXPECT_NE(session, nullptr);
  10050. callback_called = true;
  10051. return SSLVerifierResponse::CertificateRejected;
  10052. });
  10053. auto res = cli.Get("/test");
  10054. EXPECT_FALSE(res);
  10055. EXPECT_TRUE(callback_called);
  10056. }
  10057. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10058. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10059. ASSERT_TRUE(svr.is_valid());
  10060. svr.Get("/test", [](const Request &, Response &res) {
  10061. res.set_content("ok", "text/plain");
  10062. });
  10063. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10064. auto se = detail::scope_exit([&] {
  10065. svr.stop();
  10066. t.join();
  10067. });
  10068. svr.wait_until_ready();
  10069. // NoDecisionMade with verification disabled should succeed (no default check)
  10070. SSLClient cli(HOST, PORT);
  10071. cli.enable_server_certificate_verification(false);
  10072. cli.set_connection_timeout(30);
  10073. bool callback_called = false;
  10074. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10075. EXPECT_NE(session, nullptr);
  10076. callback_called = true;
  10077. return SSLVerifierResponse::NoDecisionMade;
  10078. });
  10079. auto res = cli.Get("/test");
  10080. ASSERT_TRUE(res);
  10081. EXPECT_EQ(200, res->status);
  10082. EXPECT_TRUE(callback_called);
  10083. }
  10084. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10085. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10086. ASSERT_TRUE(svr.is_valid());
  10087. svr.Get("/test", [](const Request &, Response &res) {
  10088. res.set_content("ok", "text/plain");
  10089. });
  10090. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10091. auto se = detail::scope_exit([&] {
  10092. svr.stop();
  10093. t.join();
  10094. });
  10095. svr.wait_until_ready();
  10096. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10097. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10098. // so we only check that the request fails, not whether the callback was
  10099. // called.
  10100. SSLClient cli(HOST, PORT);
  10101. cli.enable_server_certificate_verification(true);
  10102. cli.set_connection_timeout(30);
  10103. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10104. EXPECT_NE(session, nullptr);
  10105. return SSLVerifierResponse::NoDecisionMade;
  10106. });
  10107. auto res = cli.Get("/test");
  10108. EXPECT_FALSE(res);
  10109. }
  10110. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10111. // Test SSL server using PemMemory constructor with client CA certificates
  10112. // Read PEM files
  10113. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10114. read_file(SERVER_CERT_FILE, server_cert_pem);
  10115. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10116. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10117. // Create SSLServer with PemMemory constructor including client CA
  10118. SSLServer::PemMemory server_pem = {
  10119. server_cert_pem.c_str(),
  10120. server_cert_pem.size(),
  10121. server_key_pem.c_str(),
  10122. server_key_pem.size(),
  10123. client_ca_pem.c_str(),
  10124. client_ca_pem.size(),
  10125. nullptr // no password for server key
  10126. };
  10127. SSLServer svr(server_pem);
  10128. ASSERT_TRUE(svr.is_valid());
  10129. // No SSL error should be recorded for valid setup
  10130. EXPECT_EQ(0, svr.ssl_last_error());
  10131. // Set up server endpoints
  10132. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10133. res.set_content("ok", "text/plain");
  10134. });
  10135. // Start server in a thread
  10136. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10137. svr.wait_until_ready();
  10138. // Connect with client certificate (using constructor with paths)
  10139. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10140. cli.enable_server_certificate_verification(false);
  10141. auto res = cli.Get("/test-pem-ca");
  10142. ASSERT_TRUE(res);
  10143. EXPECT_EQ(200, res->status);
  10144. EXPECT_EQ("ok", res->body);
  10145. svr.stop();
  10146. server_thread.join();
  10147. }
  10148. #endif
  10149. #ifdef _WIN32
  10150. TEST(CleanupTest, WSACleanup) {
  10151. int ret = WSACleanup();
  10152. ASSERT_EQ(0, ret);
  10153. }
  10154. #endif
  10155. #ifndef CPPHTTPLIB_SSL_ENABLED
  10156. TEST(NoSSLSupport, SimpleInterface) {
  10157. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10158. }
  10159. #endif
  10160. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10161. TEST(InvalidScheme, SimpleInterface) {
  10162. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10163. }
  10164. #endif
  10165. TEST(NoScheme, SimpleInterface) {
  10166. Client cli("yahoo.com:80");
  10167. ASSERT_TRUE(cli.is_valid());
  10168. }
  10169. TEST(SendAPI, SimpleInterface_Online) {
  10170. Client cli("http://yahoo.com");
  10171. Request req;
  10172. req.method = "GET";
  10173. req.path = "/";
  10174. auto res = cli.send(req);
  10175. ASSERT_TRUE(res);
  10176. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10177. }
  10178. TEST(SendAPI, WithParamsInRequest) {
  10179. Server svr;
  10180. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10181. EXPECT_TRUE(req.has_param("test"));
  10182. EXPECT_EQ("test_value", req.get_param_value("test"));
  10183. });
  10184. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10185. auto se = detail::scope_exit([&] {
  10186. svr.stop();
  10187. t.join();
  10188. ASSERT_FALSE(svr.is_running());
  10189. });
  10190. svr.wait_until_ready();
  10191. Client cli(HOST, PORT);
  10192. {
  10193. Request req;
  10194. req.method = "GET";
  10195. req.path = "/";
  10196. req.params.emplace("test", "test_value");
  10197. auto res = cli.send(req);
  10198. ASSERT_TRUE(res);
  10199. }
  10200. {
  10201. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10202. ASSERT_TRUE(res);
  10203. }
  10204. }
  10205. TEST(ClientImplMethods, GetSocketTest) {
  10206. httplib::Server svr;
  10207. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10208. res.status = StatusCode::OK_200;
  10209. });
  10210. auto port = svr.bind_to_any_port("127.0.0.1");
  10211. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10212. auto se = detail::scope_exit([&] {
  10213. svr.stop();
  10214. thread.join();
  10215. ASSERT_FALSE(svr.is_running());
  10216. });
  10217. svr.wait_until_ready();
  10218. {
  10219. httplib::Client cli("127.0.0.1", port);
  10220. cli.set_keep_alive(true);
  10221. // Use the behavior of cpp-httplib of opening the connection
  10222. // only when the first request happens. If that changes,
  10223. // this test would be obsolete.
  10224. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10225. // This also implicitly tests the server. But other tests would fail much
  10226. // earlier than this one to be considered.
  10227. auto res = cli.Get("/");
  10228. ASSERT_TRUE(res);
  10229. EXPECT_EQ(StatusCode::OK_200, res->status);
  10230. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10231. }
  10232. }
  10233. #ifdef CPPHTTPLIB_SSL_ENABLED
  10234. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10235. Client cli("http://yahoo.com");
  10236. auto res = cli.Get("/");
  10237. ASSERT_TRUE(res);
  10238. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10239. cli.set_follow_location(true);
  10240. res = cli.Get("/");
  10241. ASSERT_TRUE(res);
  10242. EXPECT_EQ(StatusCode::OK_200, res->status);
  10243. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10244. }
  10245. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10246. Client cli("https://yahoo.com");
  10247. auto res = cli.Get("/");
  10248. ASSERT_TRUE(res);
  10249. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10250. cli.set_follow_location(true);
  10251. res = cli.Get("/");
  10252. ASSERT_TRUE(res);
  10253. EXPECT_EQ(StatusCode::OK_200, res->status);
  10254. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10255. }
  10256. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10257. Client cli("https://yahoo.com");
  10258. auto res = cli.Get("/");
  10259. ASSERT_TRUE(res);
  10260. ASSERT_FALSE(!res);
  10261. ASSERT_TRUE(res);
  10262. ASSERT_FALSE(res == nullptr);
  10263. ASSERT_TRUE(res != nullptr);
  10264. EXPECT_EQ(Error::Success, res.error());
  10265. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10266. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10267. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10268. cli.set_follow_location(true);
  10269. res = cli.Get("/");
  10270. ASSERT_TRUE(res);
  10271. EXPECT_EQ(Error::Success, res.error());
  10272. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10273. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10274. EXPECT_EQ(StatusCode::OK_200, res->status);
  10275. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10276. }
  10277. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10278. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10279. Client cli("https://cdnjs.cloudflare.com");
  10280. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10281. Headers{{"Accept-Encoding", "br"}});
  10282. ASSERT_TRUE(res);
  10283. EXPECT_EQ(StatusCode::OK_200, res->status);
  10284. EXPECT_EQ(287630U, res->body.size());
  10285. EXPECT_EQ("application/javascript; charset=utf-8",
  10286. res->get_header_value("Content-Type"));
  10287. }
  10288. #endif
  10289. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10290. #undef REDIR_HOST // Silence compiler warning
  10291. #define REDIR_HOST "https://httpbingo.org"
  10292. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10293. Client cli(REDIR_HOST);
  10294. cli.set_follow_location(true);
  10295. auto res =
  10296. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10297. ASSERT_TRUE(res);
  10298. EXPECT_EQ(StatusCode::OK_200, res->status);
  10299. }
  10300. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10301. Client cli(REDIR_HOST);
  10302. cli.set_follow_location(true);
  10303. Params params;
  10304. params.emplace("url", "http://example.com");
  10305. params.emplace("status_code", "302");
  10306. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10307. ASSERT_TRUE(res);
  10308. EXPECT_EQ(StatusCode::OK_200, res->status);
  10309. }
  10310. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10311. Client cli(REDIR_HOST);
  10312. cli.set_follow_location(true);
  10313. Params params;
  10314. params.emplace("url", "http://example.com");
  10315. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10316. ASSERT_TRUE(res);
  10317. EXPECT_EQ(StatusCode::OK_200, res->status);
  10318. }
  10319. TEST(HttpToHttpsRedirectTest, CertFile) {
  10320. auto ssl_port = PORT + 1;
  10321. Server svr;
  10322. ASSERT_TRUE(svr.is_valid());
  10323. svr.Get("/index", [&](const Request &, Response &res) {
  10324. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10325. "/index");
  10326. svr.stop();
  10327. });
  10328. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10329. ASSERT_TRUE(ssl_svr.is_valid());
  10330. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10331. res.set_content("test", "text/plain");
  10332. ssl_svr.stop();
  10333. });
  10334. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10335. thread t2 =
  10336. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10337. auto se = detail::scope_exit([&] {
  10338. t2.join();
  10339. t.join();
  10340. ASSERT_FALSE(svr.is_running());
  10341. });
  10342. svr.wait_until_ready();
  10343. ssl_svr.wait_until_ready();
  10344. Client cli("127.0.0.1", PORT);
  10345. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10346. cli.enable_server_certificate_verification(true);
  10347. cli.set_follow_location(true);
  10348. cli.set_connection_timeout(30);
  10349. auto res = cli.Get("/index");
  10350. ASSERT_TRUE(res);
  10351. ASSERT_EQ(StatusCode::OK_200, res->status);
  10352. }
  10353. TEST(SSLClientRedirectTest, CertFile) {
  10354. auto ssl_port = PORT + 1;
  10355. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10356. ASSERT_TRUE(ssl_svr1.is_valid());
  10357. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10358. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10359. "/index");
  10360. ssl_svr1.stop();
  10361. });
  10362. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10363. ASSERT_TRUE(ssl_svr2.is_valid());
  10364. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10365. res.set_content("test", "text/plain");
  10366. ssl_svr2.stop();
  10367. });
  10368. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10369. thread t2 =
  10370. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10371. auto se = detail::scope_exit([&] {
  10372. t2.join();
  10373. t.join();
  10374. ASSERT_FALSE(ssl_svr1.is_running());
  10375. });
  10376. ssl_svr1.wait_until_ready();
  10377. ssl_svr2.wait_until_ready();
  10378. SSLClient cli("127.0.0.1", PORT);
  10379. std::string cert;
  10380. read_file(SERVER_CERT2_FILE, cert);
  10381. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10382. cli.enable_server_certificate_verification(true);
  10383. cli.set_follow_location(true);
  10384. cli.set_connection_timeout(30);
  10385. auto res = cli.Get("/index");
  10386. ASSERT_TRUE(res);
  10387. ASSERT_EQ(StatusCode::OK_200, res->status);
  10388. }
  10389. #endif
  10390. #ifdef CPPHTTPLIB_SSL_ENABLED
  10391. // Test that set_ca_cert_store() skips system certs (consistent with
  10392. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10393. // should be trusted - system certs should NOT be loaded.
  10394. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10395. // Load a specific cert that is NOT a system CA cert
  10396. std::string cert;
  10397. read_file(SERVER_CERT2_FILE, cert);
  10398. SSLClient cli("google.com");
  10399. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10400. cli.enable_server_certificate_verification(true);
  10401. // This should FAIL because:
  10402. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10403. // 2. System certs should NOT be loaded when custom store is set
  10404. // If system certs WERE loaded, this would succeed
  10405. auto res = cli.Get("/");
  10406. ASSERT_FALSE(res);
  10407. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10408. }
  10409. // Same as above, but through the native store handle path. Regression test:
  10410. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10411. // merged system certs into the user-provided store.
  10412. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10413. std::string cert;
  10414. read_file(SERVER_CERT2_FILE, cert);
  10415. SSLClient cli("google.com");
  10416. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10417. cli.enable_server_certificate_verification(true);
  10418. auto res = cli.Get("/");
  10419. ASSERT_FALSE(res);
  10420. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10421. }
  10422. // A custom store set via the native handle must still verify a server whose
  10423. // cert it does contain.
  10424. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10425. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10426. ASSERT_TRUE(svr.is_valid());
  10427. svr.Get("/test", [&](const Request &, Response &res) {
  10428. res.set_content("test", "text/plain");
  10429. });
  10430. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10431. auto se = detail::scope_exit([&] {
  10432. svr.stop();
  10433. t.join();
  10434. ASSERT_FALSE(svr.is_running());
  10435. });
  10436. svr.wait_until_ready();
  10437. SSLClient cli("127.0.0.1", PORT);
  10438. std::string cert;
  10439. read_file(SERVER_CERT2_FILE, cert);
  10440. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10441. cli.enable_server_certificate_verification(true);
  10442. cli.set_connection_timeout(30);
  10443. auto res = cli.Get("/test");
  10444. ASSERT_TRUE(res);
  10445. ASSERT_EQ(StatusCode::OK_200, res->status);
  10446. }
  10447. // CA certs loaded through the universal Client must be transferred to the
  10448. // client created internally for following an HTTPS redirect. Regression test:
  10449. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10450. // the CA data for redirect transfer.
  10451. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10452. auto ssl_port = PORT + 1;
  10453. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10454. ASSERT_TRUE(ssl_svr1.is_valid());
  10455. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10456. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10457. "/index");
  10458. });
  10459. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10460. ASSERT_TRUE(ssl_svr2.is_valid());
  10461. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10462. res.set_content("test", "text/plain");
  10463. });
  10464. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10465. thread t2 =
  10466. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10467. auto se = detail::scope_exit([&] {
  10468. ssl_svr2.stop();
  10469. ssl_svr1.stop();
  10470. t2.join();
  10471. t.join();
  10472. ASSERT_FALSE(ssl_svr1.is_running());
  10473. });
  10474. ssl_svr1.wait_until_ready();
  10475. ssl_svr2.wait_until_ready();
  10476. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10477. std::string cert;
  10478. read_file(SERVER_CERT2_FILE, cert);
  10479. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10480. cli.enable_server_certificate_verification(true);
  10481. cli.set_follow_location(true);
  10482. cli.set_connection_timeout(30);
  10483. auto res = cli.Get("/index");
  10484. ASSERT_TRUE(res);
  10485. ASSERT_EQ(StatusCode::OK_200, res->status);
  10486. }
  10487. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10488. // so a host signed by a system CA verifies even though a custom CA is set
  10489. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10490. std::string cert;
  10491. read_file(SERVER_CERT2_FILE, cert);
  10492. SSLClient cli("google.com");
  10493. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10494. cli.enable_system_ca(true);
  10495. cli.enable_server_certificate_verification(true);
  10496. auto res = cli.Get("/");
  10497. ASSERT_TRUE(res);
  10498. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10499. }
  10500. // The custom CA remains effective when combined with the system CA
  10501. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10502. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10503. ASSERT_TRUE(svr.is_valid());
  10504. svr.Get("/test", [&](const Request &, Response &res) {
  10505. res.set_content("test", "text/plain");
  10506. });
  10507. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10508. auto se = detail::scope_exit([&] {
  10509. svr.stop();
  10510. t.join();
  10511. ASSERT_FALSE(svr.is_running());
  10512. });
  10513. svr.wait_until_ready();
  10514. SSLClient cli("127.0.0.1", PORT);
  10515. std::string cert;
  10516. read_file(SERVER_CERT2_FILE, cert);
  10517. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10518. cli.enable_system_ca(true);
  10519. cli.enable_server_certificate_verification(true);
  10520. cli.set_connection_timeout(30);
  10521. auto res = cli.Get("/test");
  10522. ASSERT_TRUE(res);
  10523. ASSERT_EQ(StatusCode::OK_200, res->status);
  10524. }
  10525. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10526. // skip chain verification entirely (only the certificate identity was
  10527. // checked), so a server presenting an untrusted certificate with a matching
  10528. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10529. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10530. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10531. ASSERT_TRUE(svr.is_valid());
  10532. svr.Get("/test", [&](const Request &, Response &res) {
  10533. res.set_content("test", "text/plain");
  10534. });
  10535. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10536. auto se = detail::scope_exit([&] {
  10537. svr.stop();
  10538. t.join();
  10539. ASSERT_FALSE(svr.is_running());
  10540. });
  10541. svr.wait_until_ready();
  10542. SSLClient cli("127.0.0.1", PORT);
  10543. std::string cert;
  10544. // A trusted CA that did not sign the server certificate. The server cert
  10545. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10546. // this connection.
  10547. read_file(CLIENT_CA_CERT_FILE, cert);
  10548. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10549. cli.enable_server_certificate_verification(true);
  10550. cli.set_connection_timeout(30);
  10551. auto res = cli.Get("/test");
  10552. ASSERT_FALSE(res);
  10553. }
  10554. // enable_system_ca(false) prevents system CA loading entirely
  10555. TEST(SSLClientTest, DisableSystemCa_Online) {
  10556. SSLClient cli("google.com");
  10557. cli.enable_system_ca(false);
  10558. cli.enable_server_certificate_verification(true);
  10559. auto res = cli.Get("/");
  10560. ASSERT_FALSE(res);
  10561. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10562. // itself when the CA chain is empty
  10563. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10564. res.error() == Error::SSLConnection);
  10565. }
  10566. // The universal Client forwards enable_system_ca()
  10567. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10568. std::string cert;
  10569. read_file(SERVER_CERT2_FILE, cert);
  10570. Client cli("https://google.com");
  10571. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10572. cli.enable_system_ca(true);
  10573. cli.enable_server_certificate_verification(true);
  10574. auto res = cli.Get("/");
  10575. ASSERT_TRUE(res);
  10576. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10577. }
  10578. // The system CA policy must carry over to the client created internally for
  10579. // following a cross-host HTTPS redirect
  10580. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10581. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10582. ASSERT_TRUE(svr.is_valid());
  10583. svr.Get("/index", [&](const Request &, Response &res) {
  10584. res.set_redirect("https://www.google.com/");
  10585. });
  10586. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10587. auto se = detail::scope_exit([&] {
  10588. svr.stop();
  10589. t.join();
  10590. ASSERT_FALSE(svr.is_running());
  10591. });
  10592. svr.wait_until_ready();
  10593. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10594. std::string cert;
  10595. read_file(SERVER_CERT2_FILE, cert);
  10596. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10597. cli.enable_system_ca(true);
  10598. cli.enable_server_certificate_verification(true);
  10599. cli.set_follow_location(true);
  10600. cli.set_connection_timeout(30);
  10601. // Receiving any response proves the redirect client completed the TLS
  10602. // handshake with a system-CA-signed host
  10603. auto res = cli.Get("/index");
  10604. ASSERT_TRUE(res);
  10605. }
  10606. TEST(MultipartFormDataTest, LargeData) {
  10607. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10608. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10609. const ContentReader &content_reader) {
  10610. if (req.is_multipart_form_data()) {
  10611. std::vector<FormData> items;
  10612. content_reader(
  10613. [&](const FormData &file) {
  10614. items.push_back(file);
  10615. return true;
  10616. },
  10617. [&](const char *data, size_t data_length) {
  10618. items.back().content.append(data, data_length);
  10619. return true;
  10620. });
  10621. EXPECT_TRUE(std::string(items[0].name) == "document");
  10622. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10623. EXPECT_TRUE(items[0].filename == "2MB_data");
  10624. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10625. EXPECT_TRUE(items[1].name == "hello");
  10626. EXPECT_TRUE(items[1].content == "world");
  10627. EXPECT_TRUE(items[1].filename == "");
  10628. EXPECT_TRUE(items[1].content_type == "");
  10629. } else {
  10630. std::string body;
  10631. content_reader([&](const char *data, size_t data_length) {
  10632. body.append(data, data_length);
  10633. return true;
  10634. });
  10635. }
  10636. });
  10637. auto port = svr.bind_to_any_port(HOST);
  10638. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10639. auto se = detail::scope_exit([&] {
  10640. svr.stop();
  10641. t.join();
  10642. ASSERT_FALSE(svr.is_running());
  10643. });
  10644. svr.wait_until_ready();
  10645. {
  10646. std::string data(1024 * 1024 * 2, '.');
  10647. std::stringstream buffer;
  10648. buffer << data;
  10649. SSLClient cli(HOST, port);
  10650. cli.enable_server_certificate_verification(false);
  10651. UploadFormDataItems items{
  10652. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10653. {"hello", "world", "", ""},
  10654. };
  10655. auto res = cli.Post("/post", items);
  10656. ASSERT_TRUE(res);
  10657. ASSERT_EQ(StatusCode::OK_200, res->status);
  10658. }
  10659. }
  10660. TEST(MultipartFormDataTest, DataProviderItems) {
  10661. std::random_device seed_gen;
  10662. std::mt19937 random(seed_gen());
  10663. std::string rand1;
  10664. rand1.resize(1000);
  10665. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10666. std::string rand2;
  10667. rand2.resize(3000);
  10668. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10670. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10671. const ContentReader &content_reader) {
  10672. ASSERT_FALSE(req.is_multipart_form_data());
  10673. std::string body;
  10674. content_reader([&](const char *data, size_t data_length) {
  10675. body.append(data, data_length);
  10676. return true;
  10677. });
  10678. EXPECT_EQ(body, "");
  10679. });
  10680. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10681. const ContentReader &content_reader) {
  10682. ASSERT_TRUE(req.is_multipart_form_data());
  10683. std::vector<FormData> items;
  10684. content_reader(
  10685. [&](const FormData &file) {
  10686. items.push_back(file);
  10687. return true;
  10688. },
  10689. [&](const char *data, size_t data_length) {
  10690. items.back().content.append(data, data_length);
  10691. return true;
  10692. });
  10693. ASSERT_TRUE(items.size() == 2);
  10694. EXPECT_EQ(std::string(items[0].name), "name1");
  10695. EXPECT_EQ(items[0].content, "Testing123");
  10696. EXPECT_EQ(items[0].filename, "filename1");
  10697. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10698. EXPECT_EQ(items[1].name, "name2");
  10699. EXPECT_EQ(items[1].content, "Testing456");
  10700. EXPECT_EQ(items[1].filename, "");
  10701. EXPECT_EQ(items[1].content_type, "");
  10702. });
  10703. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10704. const ContentReader &content_reader) {
  10705. ASSERT_TRUE(req.is_multipart_form_data());
  10706. std::vector<FormData> items;
  10707. content_reader(
  10708. [&](const FormData &file) {
  10709. items.push_back(file);
  10710. return true;
  10711. },
  10712. [&](const char *data, size_t data_length) {
  10713. items.back().content.append(data, data_length);
  10714. return true;
  10715. });
  10716. ASSERT_TRUE(items.size() == 2);
  10717. EXPECT_EQ(items[0].name, "name3");
  10718. EXPECT_EQ(items[0].content, rand1);
  10719. EXPECT_EQ(items[0].filename, "filename3");
  10720. EXPECT_EQ(items[0].content_type, "");
  10721. EXPECT_EQ(items[1].name, "name4");
  10722. EXPECT_EQ(items[1].content, rand2);
  10723. EXPECT_EQ(items[1].filename, "filename4");
  10724. EXPECT_EQ(items[1].content_type, "");
  10725. });
  10726. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10727. const ContentReader &content_reader) {
  10728. ASSERT_TRUE(req.is_multipart_form_data());
  10729. std::vector<FormData> items;
  10730. content_reader(
  10731. [&](const FormData &file) {
  10732. items.push_back(file);
  10733. return true;
  10734. },
  10735. [&](const char *data, size_t data_length) {
  10736. items.back().content.append(data, data_length);
  10737. return true;
  10738. });
  10739. ASSERT_TRUE(items.size() == 4);
  10740. EXPECT_EQ(std::string(items[0].name), "name1");
  10741. EXPECT_EQ(items[0].content, "Testing123");
  10742. EXPECT_EQ(items[0].filename, "filename1");
  10743. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10744. EXPECT_EQ(items[1].name, "name2");
  10745. EXPECT_EQ(items[1].content, "Testing456");
  10746. EXPECT_EQ(items[1].filename, "");
  10747. EXPECT_EQ(items[1].content_type, "");
  10748. EXPECT_EQ(items[2].name, "name3");
  10749. EXPECT_EQ(items[2].content, rand1);
  10750. EXPECT_EQ(items[2].filename, "filename3");
  10751. EXPECT_EQ(items[2].content_type, "");
  10752. EXPECT_EQ(items[3].name, "name4");
  10753. EXPECT_EQ(items[3].content, rand2);
  10754. EXPECT_EQ(items[3].filename, "filename4");
  10755. EXPECT_EQ(items[3].content_type, "");
  10756. });
  10757. auto port = svr.bind_to_any_port("localhost");
  10758. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10759. auto se = detail::scope_exit([&] {
  10760. svr.stop();
  10761. t.join();
  10762. ASSERT_FALSE(svr.is_running());
  10763. });
  10764. svr.wait_until_ready();
  10765. {
  10766. SSLClient cli("localhost", port);
  10767. cli.enable_server_certificate_verification(false);
  10768. UploadFormDataItems items{
  10769. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10770. {"name2", "Testing456", "", ""}, // not a file
  10771. };
  10772. {
  10773. auto res = cli.Post("/post-none", {}, {}, {});
  10774. ASSERT_TRUE(res);
  10775. ASSERT_EQ(StatusCode::OK_200, res->status);
  10776. }
  10777. FormDataProviderItems providers;
  10778. {
  10779. auto res =
  10780. cli.Post("/post-items", {}, items, providers); // empty providers
  10781. ASSERT_TRUE(res);
  10782. ASSERT_EQ(StatusCode::OK_200, res->status);
  10783. }
  10784. providers.push_back({"name3",
  10785. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10786. // test the offset is given correctly at each step
  10787. if (!offset)
  10788. sink.os.write(rand1.data(), 30);
  10789. else if (offset == 30)
  10790. sink.os.write(rand1.data() + 30, 300);
  10791. else if (offset == 330)
  10792. sink.os.write(rand1.data() + 330, 670);
  10793. else if (offset == rand1.size())
  10794. sink.done();
  10795. return true;
  10796. },
  10797. "filename3",
  10798. {}});
  10799. providers.push_back({"name4",
  10800. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10801. // test the offset is given correctly at each step
  10802. if (!offset)
  10803. sink.os.write(rand2.data(), 2000);
  10804. else if (offset == 2000)
  10805. sink.os.write(rand2.data() + 2000, 1);
  10806. else if (offset == 2001)
  10807. sink.os.write(rand2.data() + 2001, 999);
  10808. else if (offset == rand2.size())
  10809. sink.done();
  10810. return true;
  10811. },
  10812. "filename4",
  10813. {}});
  10814. {
  10815. auto res = cli.Post("/post-providers", {}, {}, providers);
  10816. ASSERT_TRUE(res);
  10817. ASSERT_EQ(StatusCode::OK_200, res->status);
  10818. }
  10819. {
  10820. auto res = cli.Post("/post-both", {}, items, providers);
  10821. ASSERT_TRUE(res);
  10822. ASSERT_EQ(StatusCode::OK_200, res->status);
  10823. }
  10824. }
  10825. }
  10826. TEST(MultipartFormDataTest, BadHeader) {
  10827. Server svr;
  10828. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10829. res.set_content("ok", "text/plain");
  10830. });
  10831. thread t = thread([&] { svr.listen(HOST, PORT); });
  10832. auto se = detail::scope_exit([&] {
  10833. svr.stop();
  10834. t.join();
  10835. ASSERT_FALSE(svr.is_running());
  10836. });
  10837. svr.wait_until_ready();
  10838. const std::string body =
  10839. "This is the preamble. It is to be ignored, though it\r\n"
  10840. "is a handy place for composition agents to include an\r\n"
  10841. "explanatory note to non-MIME conformant readers.\r\n"
  10842. "\r\n"
  10843. "\r\n"
  10844. "--simple boundary\r\n"
  10845. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10846. ": BAD...\r\n"
  10847. "\r\n"
  10848. "value1\r\n"
  10849. "--simple boundary\r\n"
  10850. "Content-Disposition: form-data; name=\"field2\"; "
  10851. "filename=\"example.txt\"\r\n"
  10852. "\r\n"
  10853. "value2\r\n"
  10854. "--simple boundary--\r\n"
  10855. "This is the epilogue. It is also to be ignored.\r\n";
  10856. std::string content_type =
  10857. R"(multipart/form-data; boundary="simple boundary")";
  10858. Client cli(HOST, PORT);
  10859. auto res = cli.Post("/post", body, content_type.c_str());
  10860. ASSERT_TRUE(res);
  10861. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10862. }
  10863. TEST(MultipartFormDataTest, WithPreamble) {
  10864. Server svr;
  10865. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10866. res.set_content("ok", "text/plain");
  10867. });
  10868. thread t = thread([&] { svr.listen(HOST, PORT); });
  10869. auto se = detail::scope_exit([&] {
  10870. svr.stop();
  10871. t.join();
  10872. ASSERT_FALSE(svr.is_running());
  10873. });
  10874. svr.wait_until_ready();
  10875. const std::string body =
  10876. "This is the preamble. It is to be ignored, though it\r\n"
  10877. "is a handy place for composition agents to include an\r\n"
  10878. "explanatory note to non-MIME conformant readers.\r\n"
  10879. "\r\n"
  10880. "\r\n"
  10881. "--simple boundary\r\n"
  10882. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10883. "\r\n"
  10884. "value1\r\n"
  10885. "--simple boundary\r\n"
  10886. "Content-Disposition: form-data; name=\"field2\"; "
  10887. "filename=\"example.txt\"\r\n"
  10888. "\r\n"
  10889. "value2\r\n"
  10890. "--simple boundary--\r\n"
  10891. "This is the epilogue. It is also to be ignored.\r\n";
  10892. std::string content_type =
  10893. R"(multipart/form-data; boundary="simple boundary")";
  10894. Client cli(HOST, PORT);
  10895. auto res = cli.Post("/post", body, content_type.c_str());
  10896. ASSERT_TRUE(res);
  10897. EXPECT_EQ(StatusCode::OK_200, res->status);
  10898. }
  10899. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10901. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10902. const ContentReader &content_reader) {
  10903. if (req.is_multipart_form_data()) {
  10904. std::vector<FormData> items;
  10905. content_reader(
  10906. [&](const FormData &file) {
  10907. items.push_back(file);
  10908. return true;
  10909. },
  10910. [&](const char *data, size_t data_length) {
  10911. items.back().content.append(data, data_length);
  10912. return true;
  10913. });
  10914. EXPECT_TRUE(std::string(items[0].name) == "document");
  10915. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10916. EXPECT_TRUE(items[0].filename == "2MB_data");
  10917. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10918. EXPECT_TRUE(items[1].name == "hello");
  10919. EXPECT_TRUE(items[1].content == "world");
  10920. EXPECT_TRUE(items[1].filename == "");
  10921. EXPECT_TRUE(items[1].content_type == "");
  10922. } else {
  10923. std::string body;
  10924. content_reader([&](const char *data, size_t data_length) {
  10925. body.append(data, data_length);
  10926. return true;
  10927. });
  10928. }
  10929. });
  10930. auto port = svr.bind_to_any_port("localhost");
  10931. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10932. auto se = detail::scope_exit([&] {
  10933. svr.stop();
  10934. t.join();
  10935. ASSERT_FALSE(svr.is_running());
  10936. });
  10937. svr.wait_until_ready();
  10938. {
  10939. std::string data(1024 * 1024 * 2, '.');
  10940. std::stringstream buffer;
  10941. buffer << data;
  10942. SSLClient cli("localhost", port);
  10943. cli.enable_server_certificate_verification(false);
  10944. UploadFormDataItems items{
  10945. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10946. {"hello", "world", "", ""},
  10947. };
  10948. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10949. ASSERT_TRUE(res);
  10950. ASSERT_EQ(StatusCode::OK_200, res->status);
  10951. }
  10952. }
  10953. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10954. std::string data(1024 * 1024 * 2, '&');
  10955. std::stringstream buffer;
  10956. buffer << data;
  10957. Client cli("https://localhost:8080");
  10958. UploadFormDataItems items{
  10959. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10960. {"hello", "world", "", ""},
  10961. };
  10962. for (const char &c : " \t\r\n") {
  10963. auto res =
  10964. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10965. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10966. ASSERT_FALSE(res);
  10967. }
  10968. }
  10969. TEST(MultipartFormDataTest, PutFormData) {
  10970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10971. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10972. const ContentReader &content_reader) {
  10973. if (req.is_multipart_form_data()) {
  10974. std::vector<FormData> items;
  10975. content_reader(
  10976. [&](const FormData &file) {
  10977. items.push_back(file);
  10978. return true;
  10979. },
  10980. [&](const char *data, size_t data_length) {
  10981. items.back().content.append(data, data_length);
  10982. return true;
  10983. });
  10984. EXPECT_TRUE(std::string(items[0].name) == "document");
  10985. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10986. EXPECT_TRUE(items[0].filename == "2MB_data");
  10987. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10988. EXPECT_TRUE(items[1].name == "hello");
  10989. EXPECT_TRUE(items[1].content == "world");
  10990. EXPECT_TRUE(items[1].filename == "");
  10991. EXPECT_TRUE(items[1].content_type == "");
  10992. } else {
  10993. std::string body;
  10994. content_reader([&](const char *data, size_t data_length) {
  10995. body.append(data, data_length);
  10996. return true;
  10997. });
  10998. }
  10999. });
  11000. auto port = svr.bind_to_any_port("localhost");
  11001. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11002. auto se = detail::scope_exit([&] {
  11003. svr.stop();
  11004. t.join();
  11005. ASSERT_FALSE(svr.is_running());
  11006. });
  11007. svr.wait_until_ready();
  11008. {
  11009. std::string data(1024 * 1024 * 2, '&');
  11010. std::stringstream buffer;
  11011. buffer << data;
  11012. SSLClient cli("localhost", port);
  11013. cli.enable_server_certificate_verification(false);
  11014. UploadFormDataItems items{
  11015. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11016. {"hello", "world", "", ""},
  11017. };
  11018. auto res = cli.Put("/put", items);
  11019. ASSERT_TRUE(res);
  11020. ASSERT_EQ(StatusCode::OK_200, res->status);
  11021. }
  11022. }
  11023. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11025. svr.Put("/put_customboundary",
  11026. [&](const Request &req, const Response & /*res*/,
  11027. const ContentReader &content_reader) {
  11028. if (req.is_multipart_form_data()) {
  11029. std::vector<FormData> items;
  11030. content_reader(
  11031. [&](const FormData &file) {
  11032. items.push_back(file);
  11033. return true;
  11034. },
  11035. [&](const char *data, size_t data_length) {
  11036. items.back().content.append(data, data_length);
  11037. return true;
  11038. });
  11039. EXPECT_TRUE(std::string(items[0].name) == "document");
  11040. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11041. EXPECT_TRUE(items[0].filename == "2MB_data");
  11042. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11043. EXPECT_TRUE(items[1].name == "hello");
  11044. EXPECT_TRUE(items[1].content == "world");
  11045. EXPECT_TRUE(items[1].filename == "");
  11046. EXPECT_TRUE(items[1].content_type == "");
  11047. } else {
  11048. std::string body;
  11049. content_reader([&](const char *data, size_t data_length) {
  11050. body.append(data, data_length);
  11051. return true;
  11052. });
  11053. }
  11054. });
  11055. auto port = svr.bind_to_any_port("localhost");
  11056. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11057. auto se = detail::scope_exit([&] {
  11058. svr.stop();
  11059. t.join();
  11060. ASSERT_FALSE(svr.is_running());
  11061. });
  11062. svr.wait_until_ready();
  11063. {
  11064. std::string data(1024 * 1024 * 2, '&');
  11065. std::stringstream buffer;
  11066. buffer << data;
  11067. SSLClient cli("localhost", port);
  11068. cli.enable_server_certificate_verification(false);
  11069. UploadFormDataItems items{
  11070. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11071. {"hello", "world", "", ""},
  11072. };
  11073. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11074. ASSERT_TRUE(res);
  11075. ASSERT_EQ(StatusCode::OK_200, res->status);
  11076. }
  11077. }
  11078. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11079. std::string data(1024 * 1024 * 2, '&');
  11080. std::stringstream buffer;
  11081. buffer << data;
  11082. Client cli("https://localhost:8080");
  11083. cli.enable_server_certificate_verification(false);
  11084. UploadFormDataItems items{
  11085. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11086. {"hello", "world", "", ""},
  11087. };
  11088. for (const char &c : " \t\r\n") {
  11089. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11090. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11091. ASSERT_FALSE(res);
  11092. }
  11093. }
  11094. TEST(MultipartFormDataTest, AlternateFilename) {
  11095. auto handled = false;
  11096. Server svr;
  11097. svr.Post("/test", [&](const Request &req, Response &res) {
  11098. ASSERT_EQ(2u, req.form.files.size());
  11099. ASSERT_EQ(1u, req.form.fields.size());
  11100. // Test files
  11101. const auto &file1 = req.form.get_file("file1");
  11102. ASSERT_EQ("file1", file1.name);
  11103. ASSERT_EQ("A.txt", file1.filename);
  11104. ASSERT_EQ("text/plain", file1.content_type);
  11105. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11106. const auto &file2 = req.form.get_file("file2");
  11107. ASSERT_EQ("file2", file2.name);
  11108. ASSERT_EQ("a.html", file2.filename);
  11109. ASSERT_EQ("text/html", file2.content_type);
  11110. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11111. file2.content);
  11112. // Test text field
  11113. const auto &text = req.form.get_field("text");
  11114. ASSERT_EQ("text default", text);
  11115. res.set_content("ok", "text/plain");
  11116. handled = true;
  11117. });
  11118. thread t = thread([&] { svr.listen(HOST, PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. ASSERT_TRUE(handled);
  11124. });
  11125. svr.wait_until_ready();
  11126. auto req = "POST /test HTTP/1.1\r\n"
  11127. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11128. "Content-Length: 399\r\n"
  11129. "\r\n"
  11130. "----------\r\n"
  11131. "Content-Disposition: form-data; name=\"text\"\r\n"
  11132. "\r\n"
  11133. "text default\r\n"
  11134. "----------\r\n"
  11135. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11136. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11137. "Content-Type: text/plain\r\n"
  11138. "\r\n"
  11139. "Content of a.txt.\r\n"
  11140. "\r\n"
  11141. "----------\r\n"
  11142. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11143. "\"a.html\"\r\n"
  11144. "Content-Type: text/html\r\n"
  11145. "\r\n"
  11146. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11147. "\r\n"
  11148. "------------\r\n";
  11149. ASSERT_TRUE(send_request(1, req));
  11150. }
  11151. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11152. auto handled = false;
  11153. Server svr;
  11154. svr.Post("/test", [&](const Request &req, Response &res) {
  11155. // Case-insensitive "utf-8''" prefix with a long value
  11156. const auto &file = req.form.get_file("file1");
  11157. ASSERT_EQ("file1", file.name);
  11158. // 8000 chars exercises both the Content-Disposition parser and the
  11159. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11160. // Prior to the fix, std::regex_match on this header would cause O(N)
  11161. // stack recursion in libstdc++, leading to SIGSEGV.
  11162. std::string expected_filename(8000, 'A');
  11163. ASSERT_EQ(expected_filename, file.filename);
  11164. res.set_content("ok", "text/plain");
  11165. handled = true;
  11166. });
  11167. thread t = thread([&] { svr.listen(HOST, PORT); });
  11168. auto se = detail::scope_exit([&] {
  11169. svr.stop();
  11170. t.join();
  11171. ASSERT_FALSE(svr.is_running());
  11172. ASSERT_TRUE(handled);
  11173. });
  11174. svr.wait_until_ready();
  11175. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11176. // Regression test for GHSA-qq6v-r583-3h69
  11177. std::string long_filename(8000, 'A');
  11178. std::string body = "----------\r\n"
  11179. "Content-Disposition: form-data; name=\"file1\"; "
  11180. "filename*=\"Utf-8''" +
  11181. long_filename +
  11182. "\"\r\n"
  11183. "\r\n"
  11184. "hello\r\n"
  11185. "------------\r\n";
  11186. auto req = "POST /test HTTP/1.1\r\n"
  11187. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11188. "Content-Length: " +
  11189. std::to_string(body.size()) + "\r\n\r\n" + body;
  11190. ASSERT_TRUE(send_request(1, req));
  11191. }
  11192. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11193. auto handled = false;
  11194. Server svr;
  11195. svr.Post("/test", [&](const Request &req, Response &) {
  11196. ASSERT_EQ(2u, req.form.fields.size());
  11197. const auto &text1 = req.form.get_field("text1");
  11198. ASSERT_EQ("text1", text1);
  11199. const auto &text2 = req.form.get_field("text2");
  11200. ASSERT_EQ("text2", text2);
  11201. handled = true;
  11202. });
  11203. thread t = thread([&] { svr.listen(HOST, PORT); });
  11204. auto se = detail::scope_exit([&] {
  11205. svr.stop();
  11206. t.join();
  11207. ASSERT_FALSE(svr.is_running());
  11208. ASSERT_TRUE(handled);
  11209. });
  11210. svr.wait_until_ready();
  11211. auto req = "POST /test HTTP/1.1\r\n"
  11212. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11213. "Content-Length: 146\r\n"
  11214. "\r\n----------\r\n"
  11215. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11216. "\r\n"
  11217. "text1"
  11218. "\r\n----------\r\n"
  11219. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11220. "\r\n"
  11221. "text2"
  11222. "\r\n------------";
  11223. std::string response;
  11224. ASSERT_TRUE(send_request(1, req, &response));
  11225. ASSERT_EQ("200", response.substr(9, 3));
  11226. }
  11227. TEST(MultipartFormDataTest, ContentLength) {
  11228. auto handled = false;
  11229. Server svr;
  11230. svr.Post("/test", [&](const Request &req, Response &) {
  11231. ASSERT_EQ(2u, req.form.fields.size());
  11232. const auto &text1 = req.form.get_field("text1");
  11233. ASSERT_EQ("text1", text1);
  11234. const auto &text2 = req.form.get_field("text2");
  11235. ASSERT_EQ("text2", text2);
  11236. handled = true;
  11237. });
  11238. thread t = thread([&] { svr.listen(HOST, PORT); });
  11239. auto se = detail::scope_exit([&] {
  11240. svr.stop();
  11241. t.join();
  11242. ASSERT_FALSE(svr.is_running());
  11243. ASSERT_TRUE(handled);
  11244. });
  11245. svr.wait_until_ready();
  11246. auto req = "POST /test HTTP/1.1\r\n"
  11247. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11248. "Content-Length: 167\r\n"
  11249. "\r\n----------\r\n"
  11250. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11251. "Content-Length: 5\r\n"
  11252. "\r\n"
  11253. "text1"
  11254. "\r\n----------\r\n"
  11255. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11256. "\r\n"
  11257. "text2"
  11258. "\r\n------------\r\n";
  11259. std::string response;
  11260. ASSERT_TRUE(send_request(1, req, &response));
  11261. ASSERT_EQ("200", response.substr(9, 3));
  11262. }
  11263. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11264. auto handled = false;
  11265. Server svr;
  11266. svr.Post("/test", [&](const Request &req, Response &) {
  11267. ASSERT_EQ(2u, req.form.fields.size());
  11268. const auto &text1 = req.form.get_field("text1");
  11269. ASSERT_EQ("text1", text1);
  11270. // TODO: Add header access for text fields if needed
  11271. const auto &text2 = req.form.get_field("text2");
  11272. ASSERT_EQ("text2", text2);
  11273. // TODO: Header access for text fields needs to be implemented
  11274. // auto &headers = it->second.headers;
  11275. // ASSERT_EQ(3U, headers.size());
  11276. // auto custom_header = headers.find("x-whatever");
  11277. // ASSERT_TRUE(custom_header != headers.end());
  11278. // ASSERT_NE("customvalue", custom_header->second);
  11279. // ASSERT_EQ("CustomValue", custom_header->second);
  11280. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11281. handled = true;
  11282. });
  11283. thread t = thread([&] { svr.listen(HOST, PORT); });
  11284. auto se = detail::scope_exit([&] {
  11285. svr.stop();
  11286. t.join();
  11287. ASSERT_FALSE(svr.is_running());
  11288. ASSERT_TRUE(handled);
  11289. });
  11290. svr.wait_until_ready();
  11291. auto req = "POST /test HTTP/1.1\r\n"
  11292. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11293. "Content-Length: 232\r\n"
  11294. "\r\n----------\r\n"
  11295. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11296. "Content-Length: 5\r\n"
  11297. "X-Test: 1\r\n"
  11298. "\r\n"
  11299. "text1"
  11300. "\r\n----------\r\n"
  11301. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11302. "Content-Type: text/plain\r\n"
  11303. "X-Whatever: CustomValue\r\n"
  11304. "\r\n"
  11305. "text2"
  11306. "\r\n------------\r\n"
  11307. "That should be disregarded. Not even read";
  11308. std::string response;
  11309. ASSERT_TRUE(send_request(1, req, &response));
  11310. ASSERT_EQ("200", response.substr(9, 3));
  11311. }
  11312. TEST(MultipartFormDataTest, LargeHeader) {
  11313. auto handled = false;
  11314. Server svr;
  11315. svr.Post("/test", [&](const Request &req, Response &) {
  11316. ASSERT_EQ(1u, req.form.fields.size());
  11317. const auto &text = req.form.get_field("name1");
  11318. ASSERT_EQ("text1", text);
  11319. handled = true;
  11320. });
  11321. thread t = thread([&] { svr.listen(HOST, PORT); });
  11322. auto se = detail::scope_exit([&] {
  11323. svr.stop();
  11324. t.join();
  11325. ASSERT_FALSE(svr.is_running());
  11326. ASSERT_TRUE(handled);
  11327. });
  11328. svr.wait_until_ready();
  11329. auto boundary = std::string("cpp-httplib-multipart-data");
  11330. std::string content = "--" + boundary +
  11331. "\r\n"
  11332. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11333. "\r\n"
  11334. "text1\r\n"
  11335. "--" +
  11336. boundary + "--\r\n";
  11337. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11338. "Content-Type: multipart/form-data;boundary=" +
  11339. boundary +
  11340. "\r\n"
  11341. "Content-Length: " +
  11342. std::to_string(content.size()) +
  11343. "\r\n"
  11344. "Dummy-Header: ";
  11345. std::string header_suffix = "\r\n"
  11346. "\r\n";
  11347. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11348. size_t header_dummy_size =
  11349. read_buff_size -
  11350. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11351. auto header_dummy = std::string(header_dummy_size, '@');
  11352. auto req = header_prefix + header_dummy + header_suffix + content;
  11353. std::string response;
  11354. ASSERT_TRUE(send_request(1, req, &response));
  11355. ASSERT_EQ("200", response.substr(9, 3));
  11356. }
  11357. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11358. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11359. // (not chunked Transfer-Encoding) after the streaming refactor.
  11360. auto handled = false;
  11361. Server svr;
  11362. svr.Post("/upload", [&](const Request &req, Response &res) {
  11363. auto cl_it = req.headers.find("Content-Length");
  11364. EXPECT_TRUE(cl_it != req.headers.end());
  11365. auto te_it = req.headers.find("Transfer-Encoding");
  11366. EXPECT_TRUE(te_it == req.headers.end());
  11367. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11368. res.set_content("ok", "text/plain");
  11369. handled = true;
  11370. });
  11371. auto port = svr.bind_to_any_port(HOST);
  11372. auto t = thread([&] { svr.listen_after_bind(); });
  11373. auto se = detail::scope_exit([&] {
  11374. svr.stop();
  11375. t.join();
  11376. ASSERT_FALSE(svr.is_running());
  11377. ASSERT_TRUE(handled);
  11378. });
  11379. svr.wait_until_ready();
  11380. UploadFormDataItems items = {
  11381. {"field1", "hello", "", "text/plain"},
  11382. {"file1", "world", "test.txt", "application/octet-stream"},
  11383. };
  11384. Client cli(HOST, port);
  11385. auto res = cli.Post("/upload", {}, items);
  11386. ASSERT_TRUE(res);
  11387. EXPECT_EQ(StatusCode::OK_200, res->status);
  11388. }
  11389. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11390. // Verify that make_multipart_content_provider coalesces many small segments
  11391. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11392. constexpr size_t kItemCount = 1000;
  11393. UploadFormDataItems items;
  11394. items.reserve(kItemCount);
  11395. for (size_t i = 0; i < kItemCount; i++) {
  11396. items.push_back(
  11397. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11398. }
  11399. const std::string boundary = "----test-boundary";
  11400. auto content_length = detail::get_multipart_content_length(items, boundary);
  11401. auto provider = detail::make_multipart_content_provider(items, boundary);
  11402. // Drive the provider the same way write_content_with_progress does
  11403. size_t write_count = 0;
  11404. size_t total_bytes = 0;
  11405. DataSink sink;
  11406. size_t offset = 0;
  11407. sink.write = [&](const char *d, size_t l) -> bool {
  11408. (void)d;
  11409. write_count++;
  11410. total_bytes += l;
  11411. offset += l;
  11412. return true;
  11413. };
  11414. sink.is_writable = []() -> bool { return true; };
  11415. while (offset < content_length) {
  11416. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11417. }
  11418. EXPECT_EQ(content_length, total_bytes);
  11419. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11420. // With buffering into 64KB blocks, write_count should be much smaller.
  11421. auto segment_count = 3 * kItemCount + 1;
  11422. EXPECT_LT(write_count, segment_count / 10);
  11423. }
  11424. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11425. // Integration test: send many UploadFormDataItems and verify the server
  11426. // receives all of them correctly (#2410).
  11427. constexpr size_t kItemCount = 500;
  11428. auto handled = false;
  11429. Server svr;
  11430. svr.Post("/upload", [&](const Request &req, Response &res) {
  11431. EXPECT_EQ(kItemCount, req.form.fields.size());
  11432. for (size_t i = 0; i < kItemCount; i++) {
  11433. auto key = "field" + std::to_string(i);
  11434. auto val = "value" + std::to_string(i);
  11435. auto it = req.form.fields.find(key);
  11436. if (it != req.form.fields.end()) {
  11437. EXPECT_EQ(val, it->second.content);
  11438. } else {
  11439. ADD_FAILURE() << "Missing field: " << key;
  11440. }
  11441. }
  11442. res.set_content("ok", "text/plain");
  11443. handled = true;
  11444. });
  11445. auto port = svr.bind_to_any_port(HOST);
  11446. auto t = thread([&] { svr.listen_after_bind(); });
  11447. auto se = detail::scope_exit([&] {
  11448. svr.stop();
  11449. t.join();
  11450. ASSERT_FALSE(svr.is_running());
  11451. ASSERT_TRUE(handled);
  11452. });
  11453. svr.wait_until_ready();
  11454. UploadFormDataItems items;
  11455. items.reserve(kItemCount);
  11456. for (size_t i = 0; i < kItemCount; i++) {
  11457. items.push_back(
  11458. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11459. }
  11460. Client cli(HOST, port);
  11461. auto res = cli.Post("/upload", items);
  11462. ASSERT_TRUE(res);
  11463. EXPECT_EQ(StatusCode::OK_200, res->status);
  11464. }
  11465. TEST(MultipartFormDataTest, MakeFileProvider) {
  11466. // Verify make_file_provider sends a file's contents correctly.
  11467. const std::string file_content(4096, 'Z');
  11468. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11469. {
  11470. std::ofstream ofs(tmp_path, std::ios::binary);
  11471. ofs.write(file_content.data(),
  11472. static_cast<std::streamsize>(file_content.size()));
  11473. }
  11474. auto handled = false;
  11475. Server svr;
  11476. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11477. const ContentReader &content_reader) {
  11478. ASSERT_TRUE(req.is_multipart_form_data());
  11479. std::vector<FormData> items;
  11480. content_reader(
  11481. [&](const FormData &file) {
  11482. items.push_back(file);
  11483. return true;
  11484. },
  11485. [&](const char *data, size_t data_length) {
  11486. items.back().content.append(data, data_length);
  11487. return true;
  11488. });
  11489. ASSERT_EQ(1u, items.size());
  11490. EXPECT_EQ("myfile", items[0].name);
  11491. EXPECT_EQ("data.bin", items[0].filename);
  11492. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11493. EXPECT_EQ(file_content, items[0].content);
  11494. handled = true;
  11495. });
  11496. auto port = svr.bind_to_any_port(HOST);
  11497. auto t = thread([&] { svr.listen_after_bind(); });
  11498. auto se = detail::scope_exit([&] {
  11499. svr.stop();
  11500. t.join();
  11501. ASSERT_FALSE(svr.is_running());
  11502. ASSERT_TRUE(handled);
  11503. std::remove(tmp_path.c_str());
  11504. });
  11505. svr.wait_until_ready();
  11506. FormDataProviderItems providers;
  11507. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11508. "application/octet-stream"));
  11509. Client cli(HOST, port);
  11510. auto res = cli.Post("/upload", {}, {}, providers);
  11511. ASSERT_TRUE(res);
  11512. EXPECT_EQ(StatusCode::OK_200, res->status);
  11513. }
  11514. TEST(MakeFileBodyTest, Basic) {
  11515. const std::string file_content(4096, 'Z');
  11516. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11517. {
  11518. std::ofstream ofs(tmp_path, std::ios::binary);
  11519. ofs.write(file_content.data(),
  11520. static_cast<std::streamsize>(file_content.size()));
  11521. }
  11522. auto handled = false;
  11523. Server svr;
  11524. svr.Post("/upload", [&](const Request &req, Response &res) {
  11525. EXPECT_EQ(file_content, req.body);
  11526. handled = true;
  11527. res.status = StatusCode::OK_200;
  11528. });
  11529. auto port = svr.bind_to_any_port(HOST);
  11530. auto t = thread([&] { svr.listen_after_bind(); });
  11531. auto se = detail::scope_exit([&] {
  11532. svr.stop();
  11533. t.join();
  11534. ASSERT_FALSE(svr.is_running());
  11535. ASSERT_TRUE(handled);
  11536. std::remove(tmp_path.c_str());
  11537. });
  11538. svr.wait_until_ready();
  11539. auto fb = make_file_body(tmp_path);
  11540. ASSERT_GT(fb.first, 0u);
  11541. Client cli(HOST, port);
  11542. auto res =
  11543. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11544. ASSERT_TRUE(res);
  11545. EXPECT_EQ(StatusCode::OK_200, res->status);
  11546. }
  11547. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11548. static constexpr unsigned int number_of_tasks{1000000};
  11549. std::atomic_uint count{0};
  11550. std::unique_ptr<TaskQueue> task_queue{
  11551. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11552. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11553. auto queued = task_queue->enqueue(
  11554. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11555. EXPECT_TRUE(queued);
  11556. }
  11557. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11558. task_queue->shutdown();
  11559. #else
  11560. EXPECT_NO_THROW(task_queue->shutdown());
  11561. #endif
  11562. EXPECT_EQ(number_of_tasks, count.load());
  11563. }
  11564. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11565. static constexpr unsigned int number_of_tasks{1000000};
  11566. static constexpr unsigned int qlimit{2};
  11567. unsigned int queued_count{0};
  11568. std::atomic_uint count{0};
  11569. std::unique_ptr<TaskQueue> task_queue{
  11570. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11571. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11572. if (task_queue->enqueue(
  11573. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11574. queued_count++;
  11575. }
  11576. }
  11577. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11578. task_queue->shutdown();
  11579. #else
  11580. EXPECT_NO_THROW(task_queue->shutdown());
  11581. #endif
  11582. EXPECT_EQ(queued_count, count.load());
  11583. EXPECT_TRUE(queued_count <= number_of_tasks);
  11584. EXPECT_TRUE(queued_count >= qlimit);
  11585. }
  11586. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11587. // Use a short idle timeout so a dynamic thread spawns, times out and
  11588. // exits during the test, and the pool keeps working afterwards.
  11589. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11590. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11591. /*idle_timeout_sec=*/1}};
  11592. std::atomic_uint count{0};
  11593. std::condition_variable cv;
  11594. std::mutex mtx;
  11595. bool release = false;
  11596. // Block the base thread so the second task spawns a dynamic thread.
  11597. EXPECT_TRUE(task_queue->enqueue([&] {
  11598. std::unique_lock<std::mutex> lock(mtx);
  11599. while (!release) {
  11600. cv.wait(lock);
  11601. }
  11602. count++;
  11603. }));
  11604. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11605. // Let the dynamic thread finish its task and exceed the idle timeout.
  11606. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11607. {
  11608. std::unique_lock<std::mutex> lock(mtx);
  11609. release = true;
  11610. }
  11611. cv.notify_all();
  11612. // The pool must still accept and run tasks after the dynamic thread exited.
  11613. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11614. task_queue->shutdown();
  11615. EXPECT_EQ(3u, count.load());
  11616. }
  11617. TEST(TaskQueueTest, MaxQueuedRequests) {
  11618. static constexpr unsigned int qlimit{3};
  11619. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11620. std::condition_variable sem_cv;
  11621. std::mutex sem_mtx;
  11622. int credits = 0;
  11623. bool queued;
  11624. /* Fill up the queue with tasks that will block until we give them credits to
  11625. * complete. */
  11626. for (unsigned int n = 0; n <= qlimit;) {
  11627. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11628. std::unique_lock<std::mutex> lock(sem_mtx);
  11629. while (credits <= 0) {
  11630. sem_cv.wait(lock);
  11631. }
  11632. /* Consume the credit and signal the test code if they are all gone. */
  11633. if (--credits == 0) { sem_cv.notify_one(); }
  11634. });
  11635. if (n < qlimit) {
  11636. /* The first qlimit enqueues must succeed. */
  11637. EXPECT_TRUE(queued);
  11638. } else {
  11639. /* The last one will succeed only when the worker thread
  11640. * starts and dequeues the first blocking task. Although
  11641. * not necessary for the correctness of this test, we sleep for
  11642. * a short while to avoid busy waiting. */
  11643. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11644. }
  11645. if (queued) { n++; }
  11646. }
  11647. /* Further enqueues must fail since the queue is full. */
  11648. for (auto i = 0; i < 4; i++) {
  11649. queued = task_queue->enqueue([] {});
  11650. EXPECT_FALSE(queued);
  11651. }
  11652. /* Give the credits to allow the previous tasks to complete. */
  11653. {
  11654. std::unique_lock<std::mutex> lock(sem_mtx);
  11655. credits += qlimit + 1;
  11656. }
  11657. sem_cv.notify_all();
  11658. /* Wait for all the credits to be consumed. */
  11659. {
  11660. std::unique_lock<std::mutex> lock(sem_mtx);
  11661. while (credits > 0) {
  11662. sem_cv.wait(lock);
  11663. }
  11664. }
  11665. /* Check that we are able again to enqueue at least qlimit tasks. */
  11666. for (unsigned int i = 0; i < qlimit; i++) {
  11667. queued = task_queue->enqueue([] {});
  11668. EXPECT_TRUE(queued);
  11669. }
  11670. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11671. task_queue->shutdown();
  11672. #else
  11673. EXPECT_NO_THROW(task_queue->shutdown());
  11674. #endif
  11675. }
  11676. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11677. Server svr;
  11678. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11679. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11680. });
  11681. svr.Get("/hello", [](const Request &req, Response &res) {
  11682. res.set_content(req.get_param_value("key"), "text/plain");
  11683. });
  11684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11685. auto se = detail::scope_exit([&] {
  11686. svr.stop();
  11687. thread.join();
  11688. ASSERT_FALSE(svr.is_running());
  11689. });
  11690. svr.wait_until_ready();
  11691. {
  11692. Client cli(HOST, PORT);
  11693. cli.set_follow_location(true);
  11694. auto res = cli.Get("/");
  11695. ASSERT_TRUE(res);
  11696. EXPECT_EQ(StatusCode::OK_200, res->status);
  11697. EXPECT_EQ("val&key2=val2", res->body);
  11698. }
  11699. }
  11700. #endif
  11701. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11702. Server svr;
  11703. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11704. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11705. });
  11706. svr.Get("/hello", [](const Request &req, Response &res) {
  11707. res.set_content(req.get_param_value("key"), "text/plain");
  11708. });
  11709. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11710. auto se = detail::scope_exit([&] {
  11711. svr.stop();
  11712. thread.join();
  11713. ASSERT_FALSE(svr.is_running());
  11714. });
  11715. svr.wait_until_ready();
  11716. {
  11717. Client cli(HOST, PORT);
  11718. cli.set_follow_location(true);
  11719. auto res = cli.Get("/");
  11720. ASSERT_TRUE(res);
  11721. EXPECT_EQ(StatusCode::OK_200, res->status);
  11722. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11723. }
  11724. }
  11725. TEST(RedirectTest, RedirectWithPlusInPath) {
  11726. Server svr;
  11727. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11728. res.set_redirect("/a+b");
  11729. });
  11730. // Route pattern uses regex; escape + as \\+
  11731. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11732. res.set_content(req.path, "text/plain");
  11733. });
  11734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11735. auto se = detail::scope_exit([&] {
  11736. svr.stop();
  11737. thread.join();
  11738. ASSERT_FALSE(svr.is_running());
  11739. });
  11740. svr.wait_until_ready();
  11741. {
  11742. Client cli(HOST, PORT);
  11743. cli.set_follow_location(true);
  11744. auto res = cli.Get("/");
  11745. ASSERT_TRUE(res);
  11746. EXPECT_EQ(StatusCode::OK_200, res->status);
  11747. EXPECT_EQ("/a+b", res->body);
  11748. }
  11749. }
  11750. #ifdef CPPHTTPLIB_SSL_ENABLED
  11751. TEST(RedirectTest, Issue2185_Online) {
  11752. SSLClient client("github.com");
  11753. client.set_follow_location(true);
  11754. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11755. "Coollab-Windows.zip");
  11756. ASSERT_TRUE(res);
  11757. EXPECT_EQ(StatusCode::OK_200, res->status);
  11758. EXPECT_EQ(9920427U, res->body.size());
  11759. }
  11760. #endif
  11761. TEST(VulnerabilityTest, CRLFInjection) {
  11762. Server svr;
  11763. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11764. res.set_content("Hello 1", "text/plain");
  11765. });
  11766. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11767. res.set_content("Hello 2", "text/plain");
  11768. });
  11769. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11770. res.set_content("Hello 3", "text/plain");
  11771. });
  11772. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11773. res.set_content("Hello 4", "text/plain");
  11774. });
  11775. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11776. for (const auto &x : req.headers) {
  11777. auto key = x.first;
  11778. EXPECT_STRNE("evil", key.c_str());
  11779. }
  11780. });
  11781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11782. auto se = detail::scope_exit([&] {
  11783. svr.stop();
  11784. thread.join();
  11785. ASSERT_FALSE(svr.is_running());
  11786. });
  11787. svr.wait_until_ready();
  11788. {
  11789. Client cli(HOST, PORT);
  11790. cli.Post("/test1", "A=B",
  11791. "application/x-www-form-urlencoded\r\nevil: hello1");
  11792. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11793. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11794. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11795. }
  11796. }
  11797. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11798. auto server_thread = std::thread([] {
  11799. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11800. default_socket_options(srv);
  11801. sockaddr_in addr{};
  11802. addr.sin_family = AF_INET;
  11803. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11804. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11805. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11806. ::listen(srv, 1);
  11807. sockaddr_in cli_addr{};
  11808. socklen_t cli_len = sizeof(cli_addr);
  11809. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11810. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11811. std::string buf_all;
  11812. char buf[2048];
  11813. ssize_t n;
  11814. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11815. buf_all.append(buf, static_cast<size_t>(n));
  11816. size_t pos;
  11817. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11818. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11819. auto e = request_block.find("\r\n");
  11820. if (e != std::string::npos) {
  11821. auto request_line = request_block.substr(0, e);
  11822. std::string msg =
  11823. "CRLF injection detected in request line: '" + request_line + "'";
  11824. EXPECT_FALSE(true) << msg;
  11825. }
  11826. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11827. ::send(cli,
  11828. #ifdef _WIN32
  11829. static_cast<const char *>(resp.c_str()),
  11830. static_cast<int>(resp.size()),
  11831. #else
  11832. resp.c_str(), resp.size(),
  11833. #endif
  11834. 0);
  11835. buf_all.erase(0, pos + 4);
  11836. }
  11837. }
  11838. detail::close_socket(cli);
  11839. detail::close_socket(srv);
  11840. });
  11841. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11842. auto cli = Client("127.0.0.1", PORT + 1);
  11843. auto headers = Headers{
  11844. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11845. {"Connection", "keep-alive"}};
  11846. auto res = cli.Get("/hi", headers);
  11847. EXPECT_FALSE(res);
  11848. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11849. server_thread.join();
  11850. }
  11851. TEST(PathParamsTest, StaticMatch) {
  11852. const auto pattern = "/users/all";
  11853. detail::PathParamsMatcher matcher(pattern);
  11854. Request request;
  11855. request.path = "/users/all";
  11856. ASSERT_TRUE(matcher.match(request));
  11857. std::unordered_map<std::string, std::string> expected_params = {};
  11858. EXPECT_EQ(request.path_params, expected_params);
  11859. }
  11860. TEST(PathParamsTest, StaticMismatch) {
  11861. const auto pattern = "/users/all";
  11862. detail::PathParamsMatcher matcher(pattern);
  11863. Request request;
  11864. request.path = "/users/1";
  11865. ASSERT_FALSE(matcher.match(request));
  11866. }
  11867. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11868. const auto pattern = "/users/:id/subscriptions";
  11869. detail::PathParamsMatcher matcher(pattern);
  11870. Request request;
  11871. request.path = "/users/42/subscriptions";
  11872. ASSERT_TRUE(matcher.match(request));
  11873. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11874. EXPECT_EQ(request.path_params, expected_params);
  11875. }
  11876. TEST(PathParamsTest, SingleParamInTheEnd) {
  11877. const auto pattern = "/users/:id";
  11878. detail::PathParamsMatcher matcher(pattern);
  11879. Request request;
  11880. request.path = "/users/24";
  11881. ASSERT_TRUE(matcher.match(request));
  11882. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11883. EXPECT_EQ(request.path_params, expected_params);
  11884. }
  11885. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11886. const auto pattern = "/users/:id/";
  11887. detail::PathParamsMatcher matcher(pattern);
  11888. Request request;
  11889. request.path = "/users/42/";
  11890. ASSERT_TRUE(matcher.match(request));
  11891. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11892. EXPECT_EQ(request.path_params, expected_params);
  11893. }
  11894. TEST(PathParamsTest, EmptyParam) {
  11895. const auto pattern = "/users/:id/";
  11896. detail::PathParamsMatcher matcher(pattern);
  11897. Request request;
  11898. request.path = "/users//";
  11899. ASSERT_TRUE(matcher.match(request));
  11900. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11901. EXPECT_EQ(request.path_params, expected_params);
  11902. }
  11903. TEST(PathParamsTest, FragmentMismatch) {
  11904. const auto pattern = "/users/:id/";
  11905. detail::PathParamsMatcher matcher(pattern);
  11906. Request request;
  11907. request.path = "/admins/24/";
  11908. ASSERT_FALSE(matcher.match(request));
  11909. }
  11910. TEST(PathParamsTest, ExtraFragments) {
  11911. const auto pattern = "/users/:id";
  11912. detail::PathParamsMatcher matcher(pattern);
  11913. Request request;
  11914. request.path = "/users/42/subscriptions";
  11915. ASSERT_FALSE(matcher.match(request));
  11916. }
  11917. TEST(PathParamsTest, MissingTrailingParam) {
  11918. const auto pattern = "/users/:id";
  11919. detail::PathParamsMatcher matcher(pattern);
  11920. Request request;
  11921. request.path = "/users";
  11922. ASSERT_FALSE(matcher.match(request));
  11923. }
  11924. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11925. const auto pattern = "/users/:id/subscriptions";
  11926. detail::PathParamsMatcher matcher(pattern);
  11927. Request request;
  11928. request.path = "/users/subscriptions";
  11929. ASSERT_FALSE(matcher.match(request));
  11930. }
  11931. TEST(PathParamsTest, MultipleParams) {
  11932. const auto pattern = "/users/:userid/subscriptions/:subid";
  11933. detail::PathParamsMatcher matcher(pattern);
  11934. Request request;
  11935. request.path = "/users/42/subscriptions/2";
  11936. ASSERT_TRUE(matcher.match(request));
  11937. std::unordered_map<std::string, std::string> expected_params = {
  11938. {"userid", "42"}, {"subid", "2"}};
  11939. EXPECT_EQ(request.path_params, expected_params);
  11940. }
  11941. TEST(PathParamsTest, SequenceOfParams) {
  11942. const auto pattern = "/values/:x/:y/:z";
  11943. detail::PathParamsMatcher matcher(pattern);
  11944. Request request;
  11945. request.path = "/values/1/2/3";
  11946. ASSERT_TRUE(matcher.match(request));
  11947. std::unordered_map<std::string, std::string> expected_params = {
  11948. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11949. EXPECT_EQ(request.path_params, expected_params);
  11950. }
  11951. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11952. const auto pattern = "/prefix:suffix";
  11953. detail::PathParamsMatcher matcher(pattern);
  11954. Request request;
  11955. request.path = "/prefix:suffix";
  11956. ASSERT_TRUE(matcher.match(request));
  11957. const std::unordered_map<std::string, std::string> expected_params = {};
  11958. EXPECT_EQ(request.path_params, expected_params);
  11959. }
  11960. TEST(ParseUrlTest, VariousPatterns) {
  11961. {
  11962. detail::UrlComponents uc;
  11963. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11964. EXPECT_EQ("http", uc.scheme);
  11965. EXPECT_EQ("example.com", uc.host);
  11966. EXPECT_EQ("8080", uc.port);
  11967. EXPECT_EQ("/path", uc.path);
  11968. EXPECT_EQ("?q=1", uc.query);
  11969. }
  11970. {
  11971. detail::UrlComponents uc;
  11972. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11973. EXPECT_EQ("https", uc.scheme);
  11974. EXPECT_EQ("example.com", uc.host);
  11975. EXPECT_TRUE(uc.port.empty());
  11976. EXPECT_EQ("/path", uc.path);
  11977. }
  11978. {
  11979. detail::UrlComponents uc;
  11980. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11981. EXPECT_EQ("::1", uc.host);
  11982. EXPECT_EQ("8080", uc.port);
  11983. EXPECT_EQ("/path", uc.path);
  11984. }
  11985. {
  11986. detail::UrlComponents uc;
  11987. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11988. }
  11989. {
  11990. detail::UrlComponents uc;
  11991. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11992. EXPECT_TRUE(uc.scheme.empty());
  11993. EXPECT_EQ("example.com", uc.host);
  11994. EXPECT_EQ("/path", uc.path);
  11995. EXPECT_EQ("?q=1", uc.query);
  11996. }
  11997. {
  11998. detail::UrlComponents uc;
  11999. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12000. EXPECT_TRUE(uc.host.empty());
  12001. EXPECT_EQ("/path", uc.path);
  12002. EXPECT_EQ("?q=1", uc.query);
  12003. }
  12004. {
  12005. detail::UrlComponents uc;
  12006. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12007. EXPECT_EQ("example.com", uc.host);
  12008. EXPECT_EQ("8080", uc.port);
  12009. }
  12010. {
  12011. // Unix socket path — must not be parsed as host
  12012. detail::UrlComponents uc;
  12013. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12014. EXPECT_TRUE(uc.host.empty());
  12015. }
  12016. {
  12017. detail::UrlComponents uc;
  12018. ASSERT_TRUE(detail::parse_url("", uc));
  12019. EXPECT_TRUE(uc.host.empty());
  12020. EXPECT_TRUE(uc.path.empty());
  12021. }
  12022. {
  12023. detail::UrlComponents uc;
  12024. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12025. }
  12026. {
  12027. detail::UrlComponents uc;
  12028. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12029. }
  12030. {
  12031. // Accepted by parse_url; callers restrict to http/https
  12032. detail::UrlComponents uc;
  12033. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12034. EXPECT_EQ("ftp", uc.scheme);
  12035. }
  12036. {
  12037. detail::UrlComponents uc;
  12038. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12039. }
  12040. {
  12041. detail::UrlComponents uc;
  12042. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12043. }
  12044. }
  12045. TEST(ParseUrlTest, FragmentHandling) {
  12046. {
  12047. detail::UrlComponents uc;
  12048. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12049. EXPECT_EQ("/path", uc.path);
  12050. EXPECT_TRUE(uc.query.empty());
  12051. }
  12052. {
  12053. detail::UrlComponents uc;
  12054. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12055. EXPECT_TRUE(uc.path.empty());
  12056. EXPECT_TRUE(uc.query.empty());
  12057. }
  12058. }
  12059. TEST(ParseUrlTest, UserinfoHandling) {
  12060. // Userinfo with @ but no colon — host includes @
  12061. detail::UrlComponents uc;
  12062. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12063. EXPECT_EQ("user@host.com", uc.host);
  12064. EXPECT_EQ("/path", uc.path);
  12065. }
  12066. TEST(ParseUrlTest, IPv6EdgeCases) {
  12067. {
  12068. detail::UrlComponents uc;
  12069. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12070. EXPECT_TRUE(uc.scheme.empty());
  12071. EXPECT_EQ("::1", uc.host);
  12072. EXPECT_EQ("8080", uc.port);
  12073. }
  12074. {
  12075. // Zone ID '%25' is not in [a-fA-F0-9:]
  12076. detail::UrlComponents uc;
  12077. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12078. }
  12079. }
  12080. TEST(ParseUrlTest, SchemeEdgeCases) {
  12081. {
  12082. detail::UrlComponents uc;
  12083. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12084. }
  12085. {
  12086. detail::UrlComponents uc;
  12087. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12088. }
  12089. {
  12090. detail::UrlComponents uc;
  12091. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12092. }
  12093. }
  12094. TEST(ParseUrlTest, PortEdgeCases) {
  12095. {
  12096. detail::UrlComponents uc;
  12097. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12098. EXPECT_TRUE(uc.port.empty());
  12099. EXPECT_EQ("/path", uc.path);
  12100. }
  12101. {
  12102. // parse_url accepts any port string; validation is done by parse_port
  12103. detail::UrlComponents uc;
  12104. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12105. EXPECT_EQ("abc", uc.port);
  12106. }
  12107. }
  12108. TEST(ParseUrlTest, WebSocketPatterns) {
  12109. {
  12110. detail::UrlComponents uc;
  12111. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12112. EXPECT_EQ("ws", uc.scheme);
  12113. EXPECT_EQ("echo.example.com", uc.host);
  12114. EXPECT_EQ("8080", uc.port);
  12115. EXPECT_EQ("/ws", uc.path);
  12116. }
  12117. {
  12118. detail::UrlComponents uc;
  12119. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12120. EXPECT_EQ("wss", uc.scheme);
  12121. EXPECT_EQ("echo.example.com", uc.host);
  12122. EXPECT_TRUE(uc.port.empty());
  12123. EXPECT_EQ("/ws", uc.path);
  12124. }
  12125. }
  12126. TEST(ParseUrlTest, QueryOnly) {
  12127. detail::UrlComponents uc;
  12128. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12129. EXPECT_TRUE(uc.host.empty());
  12130. EXPECT_TRUE(uc.path.empty());
  12131. EXPECT_EQ("?q=1&r=2", uc.query);
  12132. }
  12133. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12134. detail::UrlComponents uc;
  12135. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12136. EXPECT_TRUE(uc.scheme.empty());
  12137. EXPECT_EQ("example.com", uc.host);
  12138. EXPECT_EQ("443", uc.port);
  12139. EXPECT_EQ("/path", uc.path);
  12140. }
  12141. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12142. // If ipv6 regex working, regex match codepath is taken.
  12143. // else port will default to 80 in Client impl
  12144. int clientImplMagicPort = 80;
  12145. int port = 4321;
  12146. // above ports must be different to avoid false negative
  12147. EXPECT_NE(clientImplMagicPort, port);
  12148. std::string ipV6TestURL = "http://[ff06::c3]";
  12149. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12150. CLIENT_PRIVATE_KEY_FILE);
  12151. EXPECT_EQ(cli.port(), port);
  12152. }
  12153. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12154. auto file_path = "./www/dir/index.html";
  12155. auto dir_path = "./www/dir";
  12156. detail::FileStat stat_file(file_path);
  12157. EXPECT_TRUE(stat_file.is_file());
  12158. EXPECT_FALSE(stat_file.is_dir());
  12159. detail::FileStat stat_dir(dir_path);
  12160. EXPECT_FALSE(stat_dir.is_file());
  12161. EXPECT_TRUE(stat_dir.is_dir());
  12162. }
  12163. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12164. // IPv4 with default HTTP port (80)
  12165. EXPECT_EQ("example.com",
  12166. detail::make_host_and_port_string("example.com", 80, false));
  12167. // IPv4 with default HTTPS port (443)
  12168. EXPECT_EQ("example.com",
  12169. detail::make_host_and_port_string("example.com", 443, true));
  12170. // IPv4 with non-default HTTP port
  12171. EXPECT_EQ("example.com:8080",
  12172. detail::make_host_and_port_string("example.com", 8080, false));
  12173. // IPv4 with non-default HTTPS port
  12174. EXPECT_EQ("example.com:8443",
  12175. detail::make_host_and_port_string("example.com", 8443, true));
  12176. // IPv6 with default HTTP port (80)
  12177. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12178. // IPv6 with default HTTPS port (443)
  12179. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12180. // IPv6 with non-default HTTP port
  12181. EXPECT_EQ("[::1]:8080",
  12182. detail::make_host_and_port_string("::1", 8080, false));
  12183. // IPv6 with non-default HTTPS port
  12184. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12185. // IPv6 full address with default port
  12186. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12187. detail::make_host_and_port_string(
  12188. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12189. // IPv6 full address with non-default port
  12190. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12191. detail::make_host_and_port_string(
  12192. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12193. // IPv6 localhost with non-default port
  12194. EXPECT_EQ("[::1]:3000",
  12195. detail::make_host_and_port_string("::1", 3000, false));
  12196. // IPv6 with zone ID (link-local address) with default port
  12197. EXPECT_EQ("[fe80::1%eth0]",
  12198. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12199. // IPv6 with zone ID (link-local address) with non-default port
  12200. EXPECT_EQ("[fe80::1%eth0]:8080",
  12201. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12202. // Edge case: Port 443 with is_ssl=false (should add port)
  12203. EXPECT_EQ("example.com:443",
  12204. detail::make_host_and_port_string("example.com", 443, false));
  12205. // Edge case: Port 80 with is_ssl=true (should add port)
  12206. EXPECT_EQ("example.com:80",
  12207. detail::make_host_and_port_string("example.com", 80, true));
  12208. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12209. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12210. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12211. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12212. // Security fix: Already bracketed IPv6 should not get double brackets
  12213. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12214. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12215. EXPECT_EQ("[::1]:8080",
  12216. detail::make_host_and_port_string("[::1]", 8080, false));
  12217. EXPECT_EQ("[2001:db8::1]:8080",
  12218. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12219. EXPECT_EQ("[fe80::1%eth0]",
  12220. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12221. EXPECT_EQ("[fe80::1%eth0]:8080",
  12222. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12223. // Edge case: Empty host (should return as-is)
  12224. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12225. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12226. // This is a known limitation but shouldn't crash
  12227. EXPECT_EQ("[host:name]",
  12228. detail::make_host_and_port_string("host:name", 80, false));
  12229. // Port number edge cases (no validation, but should not crash)
  12230. EXPECT_EQ("example.com:0",
  12231. detail::make_host_and_port_string("example.com", 0, false));
  12232. EXPECT_EQ("example.com:-1",
  12233. detail::make_host_and_port_string("example.com", -1, false));
  12234. EXPECT_EQ("example.com:65535",
  12235. detail::make_host_and_port_string("example.com", 65535, false));
  12236. EXPECT_EQ("example.com:65536",
  12237. detail::make_host_and_port_string("example.com", 65536, false));
  12238. }
  12239. #ifdef CPPHTTPLIB_SSL_ENABLED
  12240. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12241. httplib::SSLClient cli("roblox.com", 443);
  12242. cli.set_follow_location(true);
  12243. auto res = cli.Get("/");
  12244. ASSERT_TRUE(res);
  12245. EXPECT_EQ(StatusCode::OK_200, res->status);
  12246. }
  12247. #endif
  12248. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12249. Server svr;
  12250. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12251. EXPECT_EQ(res.status, 400);
  12252. });
  12253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12254. auto se = detail::scope_exit([&] {
  12255. svr.stop();
  12256. thread.join();
  12257. ASSERT_FALSE(svr.is_running());
  12258. });
  12259. svr.wait_until_ready();
  12260. Client cli(HOST, PORT);
  12261. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12262. }
  12263. TEST(InvalidHeaderCharsTest, is_field_name) {
  12264. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12265. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12266. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12267. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12268. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12269. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12270. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12271. EXPECT_FALSE(detail::fields::is_field_name(""));
  12272. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12273. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12274. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12275. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12276. }
  12277. TEST(InvalidHeaderCharsTest, is_field_value) {
  12278. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12279. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12280. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12281. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12282. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12283. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12284. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12285. EXPECT_TRUE(detail::fields::is_field_value(""));
  12286. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12287. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12288. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12289. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12290. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12291. }
  12292. TEST(InvalidHeaderCharsTest, OnServer) {
  12293. Server svr;
  12294. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12295. std::string header = "Not Set";
  12296. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12297. res.set_header(header, "value");
  12298. res.set_content("Page Content Page Content", "text/plain");
  12299. });
  12300. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12301. std::string header = "Not Set";
  12302. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12303. res.set_header("X-Test", header);
  12304. res.set_content("Page Content Page Content", "text/plain");
  12305. });
  12306. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12307. auto se = detail::scope_exit([&] {
  12308. svr.stop();
  12309. thread.join();
  12310. ASSERT_FALSE(svr.is_running());
  12311. });
  12312. svr.wait_until_ready();
  12313. Client cli(HOST, PORT);
  12314. {
  12315. auto res = cli.Get(
  12316. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12317. ASSERT_TRUE(res);
  12318. EXPECT_EQ("Page Content Page Content", res->body);
  12319. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12320. }
  12321. {
  12322. auto res = cli.Get(
  12323. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12324. ASSERT_TRUE(res);
  12325. EXPECT_EQ("Page Content Page Content", res->body);
  12326. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12327. }
  12328. }
  12329. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12330. auto handled = false;
  12331. Server svr;
  12332. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12333. thread t = thread([&] { svr.listen(HOST, PORT); });
  12334. auto se = detail::scope_exit([&] {
  12335. svr.stop();
  12336. t.join();
  12337. ASSERT_FALSE(svr.is_running());
  12338. ASSERT_FALSE(handled);
  12339. });
  12340. svr.wait_until_ready();
  12341. auto req = "POST /test HTTP/1.1\r\n"
  12342. "Content-Length: x\r\n"
  12343. "\r\n";
  12344. std::string response;
  12345. ASSERT_TRUE(send_request(1, req, &response));
  12346. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12347. response.substr(0, response.find("\r\n")));
  12348. }
  12349. #ifndef _WIN32
  12350. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12351. static constexpr char reject[] = "Unauthorized";
  12352. static constexpr char accept[] = "Upload accepted";
  12353. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12354. Server svr;
  12355. svr.set_expect_100_continue_handler(
  12356. [](const Request & /*req*/, Response &res) {
  12357. res.status = StatusCode::Unauthorized_401;
  12358. res.set_content(reject, "text/plain");
  12359. return res.status;
  12360. });
  12361. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12362. res.set_content(accept, "text/plain");
  12363. });
  12364. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12365. auto se = detail::scope_exit([&] {
  12366. svr.stop();
  12367. thread.join();
  12368. ASSERT_FALSE(svr.is_running());
  12369. });
  12370. svr.wait_until_ready();
  12371. {
  12372. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12373. curl_easy_init(), &curl_easy_cleanup};
  12374. ASSERT_NE(curl, nullptr);
  12375. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12376. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12377. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12378. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12379. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12380. &curl_slist_free_all};
  12381. ASSERT_NE(list, nullptr);
  12382. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12383. struct read_data {
  12384. size_t read_size;
  12385. size_t total_size;
  12386. } data = {0, total_size};
  12387. using read_callback_t =
  12388. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12389. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12390. void *userdata) -> size_t {
  12391. read_data *d = (read_data *)userdata;
  12392. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12393. std::fill_n(ptr, size * nmemb, 'A');
  12394. d->read_size += size * nmemb;
  12395. return size * nmemb;
  12396. };
  12397. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12398. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12399. std::vector<char> buffer;
  12400. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12401. using write_callback_t =
  12402. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12403. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12404. void *userdata) -> size_t {
  12405. std::vector<char> *buf = (std::vector<char> *)userdata;
  12406. buf->reserve(buf->size() + size * nmemb + 1);
  12407. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12408. return size * nmemb;
  12409. };
  12410. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12411. {
  12412. const auto res = curl_easy_perform(curl.get());
  12413. ASSERT_EQ(res, CURLE_OK);
  12414. }
  12415. {
  12416. auto response_code = long{};
  12417. const auto res =
  12418. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12419. ASSERT_EQ(res, CURLE_OK);
  12420. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12421. }
  12422. {
  12423. auto dl = curl_off_t{};
  12424. const auto res =
  12425. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12426. ASSERT_EQ(res, CURLE_OK);
  12427. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12428. }
  12429. {
  12430. buffer.push_back('\0');
  12431. ASSERT_STRCASEEQ(buffer.data(), reject);
  12432. }
  12433. }
  12434. }
  12435. #endif
  12436. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12437. // Regression test for #2458.
  12438. //
  12439. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12440. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12441. // ticket can make the client socket spuriously readable during the
  12442. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12443. // the client withholds the body and then blocks reading a response that never
  12444. // comes, failing with `Failed to read connection`.
  12445. //
  12446. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12447. // within the timeout. This raw OpenSSL server deliberately never sends
  12448. // `100 Continue`; the client must still deliver the body and receive 200.
  12449. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12450. signal(SIGPIPE, SIG_IGN);
  12451. const auto port = PORT + 4;
  12452. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12453. ASSERT_NE(srv, INVALID_SOCKET);
  12454. int opt = 1;
  12455. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12456. sockaddr_in addr{};
  12457. addr.sin_family = AF_INET;
  12458. addr.sin_port = htons(static_cast<uint16_t>(port));
  12459. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12460. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12461. ASSERT_EQ(0, ::listen(srv, 1));
  12462. std::atomic<size_t> server_body_bytes{0};
  12463. auto server_thread = std::thread([&] {
  12464. sockaddr_in cli_addr{};
  12465. socklen_t cli_len = sizeof(cli_addr);
  12466. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12467. if (cli == INVALID_SOCKET) { return; }
  12468. // Bound the lifetime of the server side so a buggy client (which never
  12469. // sends the body) cannot make this thread block forever on join.
  12470. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12471. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12472. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12473. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12474. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12475. SSL *ssl = SSL_new(ctx);
  12476. SSL_set_fd(ssl, static_cast<int>(cli));
  12477. if (SSL_accept(ssl) > 0) {
  12478. // Read the request headers. Reading here also flushes the TLS 1.3
  12479. // session tickets to the client. Deliberately do NOT send
  12480. // `100 Continue`.
  12481. std::string buf;
  12482. char tmp[1024];
  12483. while (buf.find("\r\n\r\n") == std::string::npos) {
  12484. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12485. if (n <= 0) { break; }
  12486. buf.append(tmp, static_cast<size_t>(n));
  12487. }
  12488. // A correct client sends the body now; count what arrives.
  12489. auto pos = buf.find("\r\n\r\n");
  12490. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12491. while (body < 4096) {
  12492. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12493. if (n <= 0) { break; }
  12494. body += static_cast<size_t>(n);
  12495. }
  12496. server_body_bytes = body;
  12497. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12498. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12499. SSL_shutdown(ssl);
  12500. }
  12501. SSL_free(ssl);
  12502. detail::close_socket(cli);
  12503. SSL_CTX_free(ctx);
  12504. });
  12505. auto se = detail::scope_exit([&] {
  12506. server_thread.join();
  12507. detail::close_socket(srv);
  12508. });
  12509. SSLClient cli("127.0.0.1", port);
  12510. cli.enable_server_certificate_verification(false);
  12511. cli.set_connection_timeout(5, 0);
  12512. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12513. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12514. std::string body(4096, 'A');
  12515. auto res = cli.Put("/api/test", body, "application/json");
  12516. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12517. EXPECT_EQ(StatusCode::OK_200, res->status);
  12518. EXPECT_EQ(body.size(), server_body_bytes.load());
  12519. }
  12520. #endif
  12521. template <typename S, typename C>
  12522. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12523. svr.Get("/stream", [&](const Request &, Response &res) {
  12524. auto data = new std::string("01234567890123456789");
  12525. res.set_content_provider(
  12526. data->size(), "text/plain",
  12527. [&, data](size_t offset, size_t length, DataSink &sink) {
  12528. const size_t DATA_CHUNK_SIZE = 4;
  12529. const auto &d = *data;
  12530. std::this_thread::sleep_for(std::chrono::seconds(1));
  12531. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12532. return true;
  12533. },
  12534. [data](bool success) {
  12535. EXPECT_FALSE(success);
  12536. delete data;
  12537. });
  12538. });
  12539. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12540. auto i = new size_t(0);
  12541. res.set_content_provider(
  12542. "text/plain",
  12543. [i](size_t, DataSink &sink) {
  12544. if (*i < 5) {
  12545. std::this_thread::sleep_for(std::chrono::seconds(1));
  12546. sink.write("abcd", 4);
  12547. (*i)++;
  12548. } else {
  12549. sink.done();
  12550. }
  12551. return true;
  12552. },
  12553. [i](bool success) {
  12554. EXPECT_FALSE(success);
  12555. delete i;
  12556. });
  12557. });
  12558. svr.Get("/chunked", [&](const Request &, Response &res) {
  12559. auto i = new size_t(0);
  12560. res.set_chunked_content_provider(
  12561. "text/plain",
  12562. [i](size_t, DataSink &sink) {
  12563. if (*i < 5) {
  12564. std::this_thread::sleep_for(std::chrono::seconds(1));
  12565. sink.os << "abcd";
  12566. (*i)++;
  12567. } else {
  12568. sink.done();
  12569. }
  12570. return true;
  12571. },
  12572. [i](bool success) {
  12573. EXPECT_FALSE(success);
  12574. delete i;
  12575. });
  12576. });
  12577. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12578. auto se = detail::scope_exit([&] {
  12579. svr.stop();
  12580. listen_thread.join();
  12581. ASSERT_FALSE(svr.is_running());
  12582. });
  12583. svr.wait_until_ready();
  12584. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12585. {
  12586. auto start = std::chrono::steady_clock::now();
  12587. auto res = cli.Get("/stream");
  12588. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12589. std::chrono::steady_clock::now() - start)
  12590. .count();
  12591. ASSERT_FALSE(res);
  12592. EXPECT_EQ(Error::Read, res.error());
  12593. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12594. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12595. }
  12596. {
  12597. auto start = std::chrono::steady_clock::now();
  12598. auto res = cli.Get("/stream_without_length");
  12599. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12600. std::chrono::steady_clock::now() - start)
  12601. .count();
  12602. ASSERT_FALSE(res);
  12603. EXPECT_EQ(Error::Read, res.error());
  12604. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12605. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12606. }
  12607. {
  12608. auto start = std::chrono::steady_clock::now();
  12609. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12610. EXPECT_EQ("abcd", string(data, data_length));
  12611. return true;
  12612. });
  12613. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12614. std::chrono::steady_clock::now() - start)
  12615. .count();
  12616. ASSERT_FALSE(res);
  12617. EXPECT_EQ(Error::Read, res.error());
  12618. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12619. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12620. }
  12621. }
  12622. TEST(MaxTimeoutTest, ContentStream) {
  12623. time_t timeout = 2000;
  12624. time_t threshold = 200;
  12625. Server svr;
  12626. Client cli("localhost", PORT);
  12627. max_timeout_test(svr, cli, timeout, threshold);
  12628. }
  12629. #ifdef CPPHTTPLIB_SSL_ENABLED
  12630. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12631. time_t timeout = 2000;
  12632. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12634. SSLClient cli("localhost", PORT);
  12635. cli.enable_server_certificate_verification(false);
  12636. max_timeout_test(svr, cli, timeout, threshold);
  12637. }
  12638. #endif
  12639. class EventDispatcher {
  12640. public:
  12641. EventDispatcher() {}
  12642. bool wait_event(DataSink *sink) {
  12643. unique_lock<mutex> lk(m_);
  12644. int id = id_;
  12645. // Wait with timeout to prevent hanging if client disconnects
  12646. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12647. [&] { return cid_ == id; })) {
  12648. return false; // Timeout occurred
  12649. }
  12650. sink->write(message_.data(), message_.size());
  12651. return true;
  12652. }
  12653. void send_event(const string &message) {
  12654. lock_guard<mutex> lk(m_);
  12655. cid_ = id_++;
  12656. message_ = message;
  12657. cv_.notify_all();
  12658. }
  12659. private:
  12660. mutex m_;
  12661. condition_variable cv_;
  12662. atomic_int id_{0};
  12663. atomic_int cid_{-1};
  12664. string message_;
  12665. };
  12666. TEST(ClientInThreadTest, Issue2068) {
  12667. EventDispatcher ed;
  12668. Server svr;
  12669. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12670. res.set_chunked_content_provider("text/event-stream",
  12671. [&](size_t /*offset*/, DataSink &sink) {
  12672. return ed.wait_event(&sink);
  12673. });
  12674. });
  12675. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12676. svr.wait_until_ready();
  12677. thread event_thread([&] {
  12678. int id = 0;
  12679. while (svr.is_running()) {
  12680. this_thread::sleep_for(chrono::milliseconds(500));
  12681. std::stringstream ss;
  12682. ss << "data: " << id << "\n\n";
  12683. ed.send_event(ss.str());
  12684. id++;
  12685. }
  12686. });
  12687. auto se = detail::scope_exit([&] {
  12688. svr.stop();
  12689. listen_thread.join();
  12690. event_thread.join();
  12691. ASSERT_FALSE(svr.is_running());
  12692. });
  12693. {
  12694. auto client = detail::make_unique<Client>(HOST, PORT);
  12695. client->set_read_timeout(std::chrono::minutes(10));
  12696. std::atomic<bool> stop{false};
  12697. std::thread t([&] {
  12698. client->Get("/event1",
  12699. [&](const char *, size_t) -> bool { return !stop; });
  12700. });
  12701. std::this_thread::sleep_for(std::chrono::seconds(2));
  12702. stop = true;
  12703. client->stop();
  12704. t.join();
  12705. // Reset client after thread has finished
  12706. client.reset();
  12707. }
  12708. }
  12709. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12710. auto handled = false;
  12711. Server svr;
  12712. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12713. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12714. auto se = detail::scope_exit([&] {
  12715. svr.stop();
  12716. t.join();
  12717. ASSERT_FALSE(svr.is_running());
  12718. ASSERT_FALSE(handled);
  12719. });
  12720. svr.wait_until_ready();
  12721. // Two Content-Length headers with different values — must be rejected
  12722. auto req = "POST /test HTTP/1.1\r\n"
  12723. "Content-Length: 5\r\n"
  12724. "Content-Length: 10\r\n"
  12725. "\r\n"
  12726. "hello";
  12727. std::string response;
  12728. ASSERT_TRUE(send_request(1, req, &response));
  12729. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12730. response.substr(0, response.find("\r\n")));
  12731. }
  12732. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12733. auto handled = false;
  12734. Server svr;
  12735. svr.Post("/test", [&](const Request &, Response &res) {
  12736. handled = true;
  12737. res.set_content("ok", "text/plain");
  12738. });
  12739. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12740. auto se = detail::scope_exit([&] {
  12741. svr.stop();
  12742. t.join();
  12743. ASSERT_FALSE(svr.is_running());
  12744. ASSERT_TRUE(handled);
  12745. });
  12746. svr.wait_until_ready();
  12747. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12748. auto req = "POST /test HTTP/1.1\r\n"
  12749. "Content-Length: 5\r\n"
  12750. "Content-Length: 5\r\n"
  12751. "\r\n"
  12752. "hello";
  12753. std::string response;
  12754. ASSERT_TRUE(send_request(1, req, &response));
  12755. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12756. }
  12757. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12758. Server svr;
  12759. svr.Get("/", [](const Request &req, Response &res) {
  12760. EXPECT_EQ(2U, req.trailers.size());
  12761. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12762. // Denied
  12763. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12764. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12765. // Accepted
  12766. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12767. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12768. EXPECT_TRUE(req.has_trailer("X-World"));
  12769. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12770. res.set_content("ok", "text/plain");
  12771. });
  12772. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12773. auto se = detail::scope_exit([&] {
  12774. svr.stop();
  12775. t.join();
  12776. ASSERT_FALSE(svr.is_running());
  12777. });
  12778. svr.wait_until_ready();
  12779. const std::string req = "GET / HTTP/1.1\r\n"
  12780. "Transfer-Encoding: chunked\r\n"
  12781. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12782. "\r\n"
  12783. "0\r\n"
  12784. "Content-Length: 10\r\n"
  12785. "Host: internal.local\r\n"
  12786. "Content-Type: malicious/content\r\n"
  12787. "Cookie: any\r\n"
  12788. "Set-Cookie: any\r\n"
  12789. "X-Forwarded-For: attacker.com\r\n"
  12790. "X-Real-Ip: 1.1.1.1\r\n"
  12791. "X-Hello: hello\r\n"
  12792. "X-World: world\r\n"
  12793. "\r\n";
  12794. std::string res;
  12795. ASSERT_TRUE(send_request(1, req, &res));
  12796. }
  12797. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12798. Server svr;
  12799. std::string observed_remote_addr;
  12800. std::string observed_xff;
  12801. svr.Get("/ip", [&](const Request &req, Response &res) {
  12802. observed_remote_addr = req.remote_addr;
  12803. observed_xff = req.get_header_value("X-Forwarded-For");
  12804. res.set_content("ok", "text/plain");
  12805. });
  12806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12807. auto se = detail::scope_exit([&] {
  12808. svr.stop();
  12809. t.join();
  12810. ASSERT_FALSE(svr.is_running());
  12811. });
  12812. svr.wait_until_ready();
  12813. Client cli(HOST, PORT);
  12814. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12815. ASSERT_TRUE(res);
  12816. EXPECT_EQ(StatusCode::OK_200, res->status);
  12817. EXPECT_EQ(observed_xff, "203.0.113.66");
  12818. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12819. observed_remote_addr == "127.0.0.1");
  12820. }
  12821. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12822. Server svr;
  12823. svr.set_trusted_proxies({"203.0.113.66"});
  12824. std::string observed_remote_addr;
  12825. std::string observed_xff;
  12826. svr.Get("/ip", [&](const Request &req, Response &res) {
  12827. observed_remote_addr = req.remote_addr;
  12828. observed_xff = req.get_header_value("X-Forwarded-For");
  12829. res.set_content("ok", "text/plain");
  12830. });
  12831. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12832. auto se = detail::scope_exit([&] {
  12833. svr.stop();
  12834. t.join();
  12835. ASSERT_FALSE(svr.is_running());
  12836. });
  12837. svr.wait_until_ready();
  12838. Client cli(HOST, PORT);
  12839. auto res = cli.Get("/ip");
  12840. ASSERT_TRUE(res);
  12841. EXPECT_EQ(StatusCode::OK_200, res->status);
  12842. EXPECT_EQ(observed_xff, "");
  12843. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12844. observed_remote_addr == "127.0.0.1");
  12845. }
  12846. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12847. Server svr;
  12848. svr.set_trusted_proxies({"203.0.113.66"});
  12849. std::string observed_remote_addr;
  12850. std::string observed_xff;
  12851. svr.Get("/ip", [&](const Request &req, Response &res) {
  12852. observed_remote_addr = req.remote_addr;
  12853. observed_xff = req.get_header_value("X-Forwarded-For");
  12854. res.set_content("ok", "text/plain");
  12855. });
  12856. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12857. auto se = detail::scope_exit([&] {
  12858. svr.stop();
  12859. t.join();
  12860. ASSERT_FALSE(svr.is_running());
  12861. });
  12862. svr.wait_until_ready();
  12863. Client cli(HOST, PORT);
  12864. auto res = cli.Get(
  12865. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12866. ASSERT_TRUE(res);
  12867. EXPECT_EQ(StatusCode::OK_200, res->status);
  12868. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12869. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12870. }
  12871. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12872. Server svr;
  12873. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  12874. std::string observed_remote_addr;
  12875. std::string observed_xff;
  12876. svr.Get("/ip", [&](const Request &req, Response &res) {
  12877. observed_remote_addr = req.remote_addr;
  12878. observed_xff = req.get_header_value("X-Forwarded-For");
  12879. res.set_content("ok", "text/plain");
  12880. });
  12881. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12882. auto se = detail::scope_exit([&] {
  12883. svr.stop();
  12884. t.join();
  12885. ASSERT_FALSE(svr.is_running());
  12886. });
  12887. svr.wait_until_ready();
  12888. Client cli(HOST, PORT);
  12889. auto res = cli.Get(
  12890. "/ip",
  12891. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12892. ASSERT_TRUE(res);
  12893. EXPECT_EQ(StatusCode::OK_200, res->status);
  12894. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12895. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12896. }
  12897. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  12898. Server svr;
  12899. svr.set_trusted_proxies({"192.0.2.45"});
  12900. std::string observed_remote_addr;
  12901. std::string observed_xff;
  12902. svr.Get("/ip", [&](const Request &req, Response &res) {
  12903. observed_remote_addr = req.remote_addr;
  12904. observed_xff = req.get_header_value("X-Forwarded-For");
  12905. res.set_content("ok", "text/plain");
  12906. });
  12907. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12908. auto se = detail::scope_exit([&] {
  12909. svr.stop();
  12910. t.join();
  12911. ASSERT_FALSE(svr.is_running());
  12912. });
  12913. svr.wait_until_ready();
  12914. Client cli(HOST, PORT);
  12915. auto res = cli.Get(
  12916. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12917. ASSERT_TRUE(res);
  12918. EXPECT_EQ(StatusCode::OK_200, res->status);
  12919. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12920. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12921. }
  12922. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12923. Server svr;
  12924. svr.set_trusted_proxies({"192.0.2.45"});
  12925. std::string observed_remote_addr;
  12926. std::string observed_xff;
  12927. svr.Get("/ip", [&](const Request &req, Response &res) {
  12928. observed_remote_addr = req.remote_addr;
  12929. observed_xff = req.get_header_value("X-Forwarded-For");
  12930. res.set_content("ok", "text/plain");
  12931. });
  12932. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12933. auto se = detail::scope_exit([&] {
  12934. svr.stop();
  12935. t.join();
  12936. ASSERT_FALSE(svr.is_running());
  12937. });
  12938. svr.wait_until_ready();
  12939. Client cli(HOST, PORT);
  12940. auto res = cli.Get(
  12941. "/ip",
  12942. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12943. ASSERT_TRUE(res);
  12944. EXPECT_EQ(StatusCode::OK_200, res->status);
  12945. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12946. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12947. }
  12948. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12949. Server svr;
  12950. svr.set_trusted_proxies({"192.0.2.45"});
  12951. std::string observed_remote_addr;
  12952. std::string observed_xff;
  12953. svr.Get("/ip", [&](const Request &req, Response &res) {
  12954. observed_remote_addr = req.remote_addr;
  12955. observed_xff = req.get_header_value("X-Forwarded-For");
  12956. res.set_content("ok", "text/plain");
  12957. });
  12958. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12959. auto se = detail::scope_exit([&] {
  12960. svr.stop();
  12961. t.join();
  12962. ASSERT_FALSE(svr.is_running());
  12963. });
  12964. svr.wait_until_ready();
  12965. std::string raw_req =
  12966. "GET /ip HTTP/1.1\r\n"
  12967. "Host: localhost\r\n"
  12968. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12969. "Connection: close\r\n"
  12970. "\r\n";
  12971. std::string out;
  12972. ASSERT_TRUE(send_request(5, raw_req, &out));
  12973. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12974. // Header parser trims surrounding whitespace of the header value
  12975. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12976. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12977. }
  12978. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12979. // crash the server (it used to call front() on an empty vector inside
  12980. // get_client_ip). The connection-level remote address must be retained instead.
  12981. static void run_malformed_xff_test(const std::string &xff_value) {
  12982. Server svr;
  12983. svr.set_trusted_proxies({"192.0.2.45"});
  12984. std::string observed_remote_addr;
  12985. svr.Get("/ip", [&](const Request &req, Response &res) {
  12986. observed_remote_addr = req.remote_addr;
  12987. res.set_content("ok", "text/plain");
  12988. });
  12989. int port = 0;
  12990. thread t = thread([&]() {
  12991. port = svr.bind_to_any_port(HOST);
  12992. svr.listen_after_bind();
  12993. });
  12994. auto se = detail::scope_exit([&] {
  12995. svr.stop();
  12996. t.join();
  12997. ASSERT_FALSE(svr.is_running());
  12998. });
  12999. svr.wait_until_ready();
  13000. Client cli(HOST, port);
  13001. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13002. ASSERT_TRUE(res);
  13003. EXPECT_EQ(StatusCode::OK_200, res->status);
  13004. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13005. observed_remote_addr == "127.0.0.1");
  13006. }
  13007. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13008. run_malformed_xff_test("");
  13009. }
  13010. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13011. run_malformed_xff_test(",");
  13012. }
  13013. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13014. run_malformed_xff_test(", , ,");
  13015. }
  13016. #ifndef _WIN32
  13017. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13018. Server svr;
  13019. svr.Post("/post", [&](const Request &req, Response &res) {
  13020. res.set_content(req.body, "text/plain");
  13021. });
  13022. svr.Put("/put", [&](const Request &req, Response &res) {
  13023. res.set_content(req.body, "text/plain");
  13024. });
  13025. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13026. res.set_content(req.body, "text/plain");
  13027. });
  13028. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13029. res.set_content(req.body, "text/plain");
  13030. });
  13031. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13032. auto se = detail::scope_exit([&] {
  13033. svr.stop();
  13034. t.join();
  13035. ASSERT_FALSE(svr.is_running());
  13036. });
  13037. svr.wait_until_ready();
  13038. std::string resp;
  13039. // POST without Content-Length
  13040. ASSERT_TRUE(send_request(5,
  13041. "POST /post HTTP/1.1\r\n"
  13042. "Host: localhost\r\n"
  13043. "Connection: close\r\n"
  13044. "\r\n",
  13045. &resp));
  13046. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13047. // PUT without Content-Length
  13048. resp.clear();
  13049. ASSERT_TRUE(send_request(5,
  13050. "PUT /put HTTP/1.1\r\n"
  13051. "Host: localhost\r\n"
  13052. "Connection: close\r\n"
  13053. "\r\n",
  13054. &resp));
  13055. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13056. // PATCH without Content-Length
  13057. resp.clear();
  13058. ASSERT_TRUE(send_request(5,
  13059. "PATCH /patch HTTP/1.1\r\n"
  13060. "Host: localhost\r\n"
  13061. "Connection: close\r\n"
  13062. "\r\n",
  13063. &resp));
  13064. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13065. // DELETE without Content-Length
  13066. resp.clear();
  13067. ASSERT_TRUE(send_request(5,
  13068. "DELETE /delete HTTP/1.1\r\n"
  13069. "Host: localhost\r\n"
  13070. "Connection: close\r\n"
  13071. "\r\n",
  13072. &resp));
  13073. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13074. }
  13075. #endif
  13076. //==============================================================================
  13077. // open_stream() Tests
  13078. //==============================================================================
  13079. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13080. std::string result;
  13081. char buf[8192];
  13082. ssize_t n;
  13083. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13084. result.append(buf, static_cast<size_t>(n));
  13085. }
  13086. return result;
  13087. }
  13088. // Mock stream for unit tests
  13089. class MockStream : public Stream {
  13090. public:
  13091. std::string data;
  13092. size_t pos = 0;
  13093. ssize_t error_after = -1; // -1 = no error
  13094. explicit MockStream(const std::string &d, ssize_t err = -1)
  13095. : data(d), error_after(err) {}
  13096. bool is_readable() const override { return true; }
  13097. bool wait_readable() const override { return true; }
  13098. bool wait_writable() const override { return true; }
  13099. ssize_t read(char *ptr, size_t size) override {
  13100. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13101. if (pos >= data.size()) return 0;
  13102. size_t limit =
  13103. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13104. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13105. std::memcpy(ptr, data.data() + pos, to_read);
  13106. pos += to_read;
  13107. return static_cast<ssize_t>(to_read);
  13108. }
  13109. ssize_t write(const char *, size_t) override { return -1; }
  13110. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13111. ip = "127.0.0.1";
  13112. port = 0;
  13113. }
  13114. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13115. ip = "127.0.0.1";
  13116. port = 0;
  13117. }
  13118. socket_t socket() const override { return INVALID_SOCKET; }
  13119. time_t duration() const override { return 0; }
  13120. };
  13121. TEST(StreamHandleTest, Basic) {
  13122. ClientImpl::StreamHandle handle;
  13123. EXPECT_FALSE(handle.is_valid());
  13124. handle.response = detail::make_unique<Response>();
  13125. handle.error = Error::Connection;
  13126. EXPECT_FALSE(handle.is_valid());
  13127. handle.error = Error::Success;
  13128. EXPECT_TRUE(handle.is_valid());
  13129. }
  13130. TEST(BodyReaderTest, Basic) {
  13131. MockStream stream("Hello, World!");
  13132. detail::BodyReader reader;
  13133. reader.stream = &stream;
  13134. reader.content_length = 13;
  13135. char buf[32];
  13136. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13137. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13138. EXPECT_TRUE(reader.eof);
  13139. }
  13140. TEST(BodyReaderTest, NoStream) {
  13141. detail::BodyReader reader;
  13142. char buf[32];
  13143. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13144. EXPECT_EQ(Error::Connection, reader.last_error);
  13145. }
  13146. TEST(BodyReaderTest, Error) {
  13147. MockStream stream("Hello, World!", 5);
  13148. detail::BodyReader reader;
  13149. reader.stream = &stream;
  13150. reader.content_length = 13;
  13151. char buf[32];
  13152. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13153. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13154. EXPECT_EQ(Error::Read, reader.last_error);
  13155. }
  13156. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13157. // Mock-based StreamHandle tests relying on private internals are removed.
  13158. class OpenStreamTest : public ::testing::Test {
  13159. protected:
  13160. void SetUp() override {
  13161. svr_.Get("/hello", [](const Request &, Response &res) {
  13162. res.set_content("Hello World!", "text/plain");
  13163. });
  13164. svr_.Get("/large", [](const Request &, Response &res) {
  13165. res.set_content(std::string(10000, 'X'), "text/plain");
  13166. });
  13167. svr_.Get("/chunked", [](const Request &, Response &res) {
  13168. res.set_chunked_content_provider("text/plain",
  13169. [](size_t offset, DataSink &sink) {
  13170. if (offset < 15) {
  13171. sink.write("chunk", 5);
  13172. return true;
  13173. }
  13174. sink.done();
  13175. return true;
  13176. });
  13177. });
  13178. svr_.Get("/compressible", [](const Request &, Response &res) {
  13179. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13180. DataSink &sink) {
  13181. if (offset < 100 * 1024) {
  13182. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13183. sink.write(chunk.data(), chunk.size());
  13184. return true;
  13185. }
  13186. sink.done();
  13187. return true;
  13188. });
  13189. });
  13190. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13191. [](const Request & /*req*/, Response &res) {
  13192. auto i = new int(0);
  13193. res.set_header("Trailer", "Content-Length, X-Allowed");
  13194. res.set_chunked_content_provider(
  13195. "text/plain",
  13196. [i](size_t /*offset*/, DataSink &sink) {
  13197. switch (*i) {
  13198. case 0: sink.os << "123"; break;
  13199. case 1: sink.os << "456"; break;
  13200. case 2: sink.os << "789"; break;
  13201. case 3: {
  13202. sink.done_with_trailer(
  13203. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13204. } break;
  13205. }
  13206. (*i)++;
  13207. return true;
  13208. },
  13209. [i](bool success) {
  13210. EXPECT_TRUE(success);
  13211. delete i;
  13212. });
  13213. });
  13214. // Echo headers endpoint for header-related tests
  13215. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13216. std::string body;
  13217. for (const auto &h : req.headers) {
  13218. body.append(h.first);
  13219. body.push_back(':');
  13220. body.append(h.second);
  13221. body.push_back('\n');
  13222. }
  13223. res.set_content(body, "text/plain");
  13224. });
  13225. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13226. std::string body;
  13227. for (const auto &h : req.headers) {
  13228. body.append(h.first);
  13229. body.push_back(':');
  13230. body.append(h.second);
  13231. body.push_back('\n');
  13232. }
  13233. res.set_content(body, "text/plain");
  13234. });
  13235. port_ = svr_.bind_to_any_port("127.0.0.1");
  13236. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13237. svr_.wait_until_ready();
  13238. }
  13239. void TearDown() override {
  13240. svr_.stop();
  13241. if (thread_.joinable()) thread_.join();
  13242. }
  13243. Server svr_;
  13244. std::thread thread_;
  13245. int port_ = 0;
  13246. };
  13247. TEST_F(OpenStreamTest, Basic) {
  13248. Client cli("127.0.0.1", port_);
  13249. auto handle = cli.open_stream("GET", "/hello");
  13250. EXPECT_TRUE(handle.is_valid());
  13251. EXPECT_EQ("Hello World!", read_all(handle));
  13252. }
  13253. TEST_F(OpenStreamTest, SmallBuffer) {
  13254. Client cli("127.0.0.1", port_);
  13255. auto handle = cli.open_stream("GET", "/hello");
  13256. std::string result;
  13257. char buf[4];
  13258. ssize_t n;
  13259. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13260. result.append(buf, static_cast<size_t>(n));
  13261. EXPECT_EQ("Hello World!", result);
  13262. }
  13263. TEST_F(OpenStreamTest, DefaultHeaders) {
  13264. Client cli("127.0.0.1", port_);
  13265. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13266. {
  13267. auto handle = cli.open_stream("GET", "/echo-headers");
  13268. ASSERT_TRUE(handle.is_valid());
  13269. auto body = read_all(handle);
  13270. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13271. std::string::npos);
  13272. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13273. std::string::npos);
  13274. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13275. }
  13276. // open_stream POST with body and no explicit content_type should NOT add
  13277. // text/plain Content-Type (behavior differs from non-streaming path), but
  13278. // should include Content-Length
  13279. {
  13280. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13281. ASSERT_TRUE(handle.is_valid());
  13282. auto body = read_all(handle);
  13283. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13284. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13285. }
  13286. // open_stream POST with explicit Content-Type should preserve it
  13287. {
  13288. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13289. {{"Content-Type", "application/custom"}},
  13290. "{}", "application/custom");
  13291. ASSERT_TRUE(handle.is_valid());
  13292. auto body = read_all(handle);
  13293. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13294. }
  13295. // User-specified User-Agent must not be overwritten for stream API
  13296. {
  13297. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13298. {{"User-Agent", "MyAgent/1.2"}});
  13299. ASSERT_TRUE(handle.is_valid());
  13300. auto body = read_all(handle);
  13301. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13302. }
  13303. }
  13304. TEST_F(OpenStreamTest, Large) {
  13305. Client cli("127.0.0.1", port_);
  13306. auto handle = cli.open_stream("GET", "/large");
  13307. EXPECT_EQ(10000u, read_all(handle).size());
  13308. }
  13309. TEST_F(OpenStreamTest, ConnectionError) {
  13310. Client cli("127.0.0.1", 9999);
  13311. auto handle = cli.open_stream("GET", "/hello");
  13312. EXPECT_FALSE(handle.is_valid());
  13313. }
  13314. TEST_F(OpenStreamTest, Chunked) {
  13315. Client cli("127.0.0.1", port_);
  13316. auto handle = cli.open_stream("GET", "/chunked");
  13317. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13318. "Transfer-Encoding") == "chunked");
  13319. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13320. }
  13321. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13322. Client cli("127.0.0.1", port_);
  13323. auto handle =
  13324. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13325. ASSERT_TRUE(handle.is_valid());
  13326. // Consume body to allow trailers to be received/parsed
  13327. auto body = read_all(handle);
  13328. // Explicitly parse trailers (ensure trailers are available for assertion)
  13329. handle.parse_trailers_if_needed();
  13330. EXPECT_EQ(std::string("123456789"), body);
  13331. // The response should include a Trailer header declaring both names
  13332. ASSERT_TRUE(handle.response);
  13333. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13334. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13335. handle.response->get_header_value("Trailer"));
  13336. // Prohibited trailer must not be present
  13337. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13338. // Allowed trailer should be present
  13339. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13340. EXPECT_EQ(std::string("yes"),
  13341. handle.response->get_trailer_value("X-Allowed"));
  13342. // Verify trailers are NOT present as regular headers
  13343. EXPECT_EQ(std::string(""),
  13344. handle.response->get_header_value("Content-Length"));
  13345. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13346. }
  13347. static std::thread serve_single_response(std::promise<int> &port_promise,
  13348. const std::string &response) {
  13349. return std::thread([&port_promise, response] {
  13350. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13351. default_socket_options(srv);
  13352. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13353. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13354. sockaddr_in addr{};
  13355. addr.sin_family = AF_INET;
  13356. addr.sin_port = htons(0); // Let OS assign a free port
  13357. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13358. int opt = 1;
  13359. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13360. #ifdef _WIN32
  13361. reinterpret_cast<const char *>(&opt),
  13362. #else
  13363. &opt,
  13364. #endif
  13365. sizeof(opt));
  13366. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13367. ::listen(srv, 1) != 0) {
  13368. port_promise.set_value(-1);
  13369. detail::close_socket(srv);
  13370. return;
  13371. }
  13372. socklen_t addr_len = sizeof(addr);
  13373. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13374. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13375. sockaddr_in cli_addr{};
  13376. socklen_t cli_len = sizeof(cli_addr);
  13377. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13378. if (cli != INVALID_SOCKET) {
  13379. // Read the complete HTTP request (until the blank line that terminates
  13380. // headers) before sending the response. If the server closes the socket
  13381. // while the client's request data is still unread in the kernel receive
  13382. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13383. // connection on both sides: it discards the client's receive buffer
  13384. // (which already holds our response) and causes any in-progress write on
  13385. // the client to fail with ECONNRESET. Reading all request data first
  13386. // ensures close() emits a graceful FIN.
  13387. {
  13388. char rbuf[256];
  13389. std::string req;
  13390. while (req.find("\r\n\r\n") == std::string::npos) {
  13391. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13392. if (n <= 0) { break; }
  13393. req.append(rbuf, static_cast<size_t>(n));
  13394. }
  13395. }
  13396. ::send(cli,
  13397. #ifdef _WIN32
  13398. static_cast<const char *>(response.c_str()),
  13399. static_cast<int>(response.size()),
  13400. #else
  13401. response.c_str(), response.size(),
  13402. #endif
  13403. 0);
  13404. detail::close_socket(cli);
  13405. }
  13406. detail::close_socket(srv);
  13407. });
  13408. }
  13409. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13410. #ifndef _WIN32
  13411. signal(SIGPIPE, SIG_IGN);
  13412. #endif
  13413. std::promise<int> port_promise;
  13414. auto port_future = port_promise.get_future();
  13415. auto server_thread =
  13416. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13417. "Content-Type: text/plain\r\n"
  13418. "Content-Length: not-a-number\r\n"
  13419. "Connection: close\r\n"
  13420. "\r\n"
  13421. "hello");
  13422. auto port = port_future.get();
  13423. ASSERT_GT(port, 0);
  13424. Client cli("127.0.0.1", port);
  13425. auto handle = cli.open_stream("GET", "/");
  13426. EXPECT_FALSE(handle.is_valid());
  13427. server_thread.join();
  13428. }
  13429. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13430. #ifndef _WIN32
  13431. signal(SIGPIPE, SIG_IGN);
  13432. #endif
  13433. std::promise<int> port_promise;
  13434. auto port_future = port_promise.get_future();
  13435. auto server_thread = serve_single_response(
  13436. port_promise, "HTTP/1.1 200 OK\r\n"
  13437. "Content-Type: text/plain\r\n"
  13438. "Content-Length: 99999999999999999999999999\r\n"
  13439. "Connection: close\r\n"
  13440. "\r\n"
  13441. "hello");
  13442. auto port = port_future.get();
  13443. ASSERT_GT(port, 0);
  13444. // Historically std::stoull would throw std::out_of_range here and crash
  13445. // the process, then strtoull silently clamped to ULLONG_MAX and the
  13446. // stream opened with a bogus framing length. Now the out-of-range value
  13447. // is flagged invalid, so the stream fails to open, matching the
  13448. // not-a-number case above. The process still must NOT terminate.
  13449. Client cli("127.0.0.1", port);
  13450. auto handle = cli.open_stream("GET", "/");
  13451. EXPECT_FALSE(handle.is_valid());
  13452. server_thread.join();
  13453. }
  13454. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13455. TEST_F(OpenStreamTest, Gzip) {
  13456. Client cli("127.0.0.1", port_);
  13457. auto handle = cli.open_stream("GET", "/compressible", {},
  13458. {{"Accept-Encoding", "gzip"}});
  13459. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13460. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13461. }
  13462. #endif
  13463. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13464. TEST_F(OpenStreamTest, Brotli) {
  13465. Client cli("127.0.0.1", port_);
  13466. auto handle =
  13467. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13468. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13469. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13470. }
  13471. #endif
  13472. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13473. TEST_F(OpenStreamTest, Zstd) {
  13474. Client cli("127.0.0.1", port_);
  13475. auto handle = cli.open_stream("GET", "/compressible", {},
  13476. {{"Accept-Encoding", "zstd"}});
  13477. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13478. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13479. }
  13480. #endif
  13481. #ifdef CPPHTTPLIB_SSL_ENABLED
  13482. class SSLOpenStreamTest : public ::testing::Test {
  13483. protected:
  13484. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13485. void SetUp() override {
  13486. svr_.Get("/hello", [](const Request &, Response &res) {
  13487. res.set_content("Hello SSL World!", "text/plain");
  13488. });
  13489. svr_.Get("/chunked", [](const Request &, Response &res) {
  13490. res.set_chunked_content_provider("text/plain",
  13491. [](size_t offset, DataSink &sink) {
  13492. if (offset < 15) {
  13493. sink.write("chunk", 5);
  13494. return true;
  13495. }
  13496. sink.done();
  13497. return true;
  13498. });
  13499. });
  13500. svr_.Post("/echo", [](const Request &req, Response &res) {
  13501. res.set_content(req.body, req.get_header_value("Content-Type"));
  13502. });
  13503. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13504. std::string body = req.body;
  13505. res.set_chunked_content_provider(
  13506. "text/plain", [body](size_t offset, DataSink &sink) {
  13507. if (offset < body.size()) {
  13508. sink.write(body.data() + offset, body.size() - offset);
  13509. }
  13510. sink.done();
  13511. return true;
  13512. });
  13513. });
  13514. port_ = svr_.bind_to_any_port("127.0.0.1");
  13515. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13516. svr_.wait_until_ready();
  13517. }
  13518. void TearDown() override {
  13519. svr_.stop();
  13520. if (thread_.joinable()) thread_.join();
  13521. }
  13522. SSLServer svr_;
  13523. std::thread thread_;
  13524. int port_ = 0;
  13525. };
  13526. TEST_F(SSLOpenStreamTest, Basic) {
  13527. SSLClient cli("127.0.0.1", port_);
  13528. cli.enable_server_certificate_verification(false);
  13529. auto handle = cli.open_stream("GET", "/hello");
  13530. ASSERT_TRUE(handle.is_valid());
  13531. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13532. }
  13533. TEST_F(SSLOpenStreamTest, Chunked) {
  13534. SSLClient cli("127.0.0.1", port_);
  13535. cli.enable_server_certificate_verification(false);
  13536. auto handle = cli.open_stream("GET", "/chunked");
  13537. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13538. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13539. "Transfer-Encoding") == "chunked");
  13540. auto body = read_all(handle);
  13541. EXPECT_EQ("chunkchunkchunk", body);
  13542. }
  13543. TEST_F(SSLOpenStreamTest, Post) {
  13544. SSLClient cli("127.0.0.1", port_);
  13545. cli.enable_server_certificate_verification(false);
  13546. auto handle =
  13547. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13548. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13549. EXPECT_EQ(200, handle.response->status);
  13550. auto body = read_all(handle);
  13551. EXPECT_EQ("Hello SSL POST", body);
  13552. }
  13553. TEST_F(SSLOpenStreamTest, PostChunked) {
  13554. SSLClient cli("127.0.0.1", port_);
  13555. cli.enable_server_certificate_verification(false);
  13556. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13557. "Chunked SSL Data", "text/plain");
  13558. ASSERT_TRUE(handle.is_valid());
  13559. EXPECT_EQ(200, handle.response->status);
  13560. auto body = read_all(handle);
  13561. EXPECT_EQ("Chunked SSL Data", body);
  13562. }
  13563. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13564. // Content-Length is terminated by the server closing the connection. When the
  13565. // SSL peer sends a close_notify after the body, the client must treat it as a
  13566. // clean EOF and return a successful response rather than an error.
  13567. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13569. ASSERT_TRUE(svr.is_valid());
  13570. svr.set_keep_alive_max_count(1);
  13571. const std::string expected_body = "Hello from connection-close response!";
  13572. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13573. res.set_content_provider("text/plain",
  13574. [&](size_t offset, DataSink &sink) -> bool {
  13575. if (offset < expected_body.size()) {
  13576. sink.write(expected_body.data() + offset,
  13577. expected_body.size() - offset);
  13578. }
  13579. sink.done();
  13580. return true;
  13581. });
  13582. });
  13583. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13584. auto se = detail::scope_exit([&] {
  13585. svr.stop();
  13586. listen_thread.join();
  13587. ASSERT_FALSE(svr.is_running());
  13588. });
  13589. svr.wait_until_ready();
  13590. SSLClient cli(HOST, PORT);
  13591. cli.enable_server_certificate_verification(false);
  13592. auto res = cli.Get("/no-content-length");
  13593. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13594. EXPECT_EQ(StatusCode::OK_200, res->status);
  13595. EXPECT_EQ(expected_body, res->body);
  13596. }
  13597. #endif // CPPHTTPLIB_SSL_ENABLED
  13598. //==============================================================================
  13599. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13600. // results for various scenarios.
  13601. //==============================================================================
  13602. TEST(ParityTest, GetVsOpenStream) {
  13603. Server svr;
  13604. const std::string path = "/parity";
  13605. const std::string content = "Parity test content: hello world";
  13606. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13607. res.set_content(content, "text/plain");
  13608. });
  13609. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13610. auto se = detail::scope_exit([&] {
  13611. svr.stop();
  13612. t.join();
  13613. ASSERT_FALSE(svr.is_running());
  13614. });
  13615. svr.wait_until_ready();
  13616. Client cli(HOST, PORT);
  13617. // Non-stream path
  13618. auto r1 = cli.Get(path);
  13619. ASSERT_TRUE(r1);
  13620. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13621. // Stream path
  13622. auto h = cli.open_stream("GET", path);
  13623. ASSERT_TRUE(h.is_valid());
  13624. EXPECT_EQ(r1->body, read_all(h));
  13625. }
  13626. // Helper to compress data with provided compressor type T
  13627. template <typename Compressor>
  13628. static std::string compress_payload_for_parity(const std::string &in) {
  13629. std::string out;
  13630. Compressor compressor;
  13631. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13632. [&](const char *data, size_t n) {
  13633. out.append(data, n);
  13634. return true;
  13635. });
  13636. EXPECT_TRUE(ok);
  13637. return out;
  13638. }
  13639. // Helper function for compression parity tests
  13640. template <typename Compressor>
  13641. static void test_compression_parity(const std::string &original,
  13642. const std::string &path,
  13643. const std::string &encoding) {
  13644. const std::string compressed =
  13645. compress_payload_for_parity<Compressor>(original);
  13646. Server svr;
  13647. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13648. res.set_content(compressed, "application/octet-stream");
  13649. res.set_header("Content-Encoding", encoding);
  13650. });
  13651. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13652. auto se = detail::scope_exit([&] {
  13653. svr.stop();
  13654. t.join();
  13655. ASSERT_FALSE(svr.is_running());
  13656. });
  13657. svr.wait_until_ready();
  13658. Client cli(HOST, PORT);
  13659. // Non-streaming
  13660. {
  13661. auto res = cli.Get(path);
  13662. ASSERT_TRUE(res);
  13663. EXPECT_EQ(StatusCode::OK_200, res->status);
  13664. EXPECT_EQ(original, res->body);
  13665. }
  13666. // Streaming
  13667. {
  13668. auto h = cli.open_stream("GET", path);
  13669. ASSERT_TRUE(h.is_valid());
  13670. EXPECT_EQ(original, read_all(h));
  13671. }
  13672. }
  13673. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13674. TEST(ParityTest, Gzip) {
  13675. test_compression_parity<detail::gzip_compressor>(
  13676. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13677. }
  13678. #endif
  13679. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13680. TEST(ParityTest, Brotli) {
  13681. test_compression_parity<detail::brotli_compressor>(
  13682. "Hello, brotli parity test payload", "/parity-br", "br");
  13683. }
  13684. #endif
  13685. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13686. TEST(ParityTest, Zstd) {
  13687. test_compression_parity<detail::zstd_compressor>(
  13688. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13689. }
  13690. #endif
  13691. //==============================================================================
  13692. // New Stream API Tests
  13693. //==============================================================================
  13694. inline std::string read_body(httplib::stream::Result &result) {
  13695. std::string body;
  13696. while (result.next()) {
  13697. body.append(result.data(), result.size());
  13698. }
  13699. return body;
  13700. }
  13701. TEST(ClientConnectionTest, Basic) {
  13702. httplib::ClientConnection conn;
  13703. EXPECT_FALSE(conn.is_open());
  13704. conn.sock = 1;
  13705. EXPECT_TRUE(conn.is_open());
  13706. httplib::ClientConnection conn2(std::move(conn));
  13707. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13708. conn2.sock = INVALID_SOCKET;
  13709. }
  13710. // Unified test server for all stream::* tests
  13711. class StreamApiTest : public ::testing::Test {
  13712. protected:
  13713. void SetUp() override {
  13714. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13715. res.set_content("Hello World!", "text/plain");
  13716. });
  13717. svr_.Get("/echo-params",
  13718. [](const httplib::Request &req, httplib::Response &res) {
  13719. std::string r;
  13720. for (const auto &p : req.params) {
  13721. if (!r.empty()) r += "&";
  13722. r += p.first + "=" + p.second;
  13723. }
  13724. res.set_content(r, "text/plain");
  13725. });
  13726. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13727. res.set_content(req.body, req.get_header_value("Content-Type"));
  13728. });
  13729. svr_.Post("/echo-headers",
  13730. [](const httplib::Request &req, httplib::Response &res) {
  13731. std::string r;
  13732. for (const auto &h : req.headers)
  13733. r += h.first + ": " + h.second + "\n";
  13734. res.set_content(r, "text/plain");
  13735. });
  13736. svr_.Post("/echo-params",
  13737. [](const httplib::Request &req, httplib::Response &res) {
  13738. std::string r = "params:";
  13739. for (const auto &p : req.params)
  13740. r += p.first + "=" + p.second + ";";
  13741. res.set_content(r + " body:" + req.body, "text/plain");
  13742. });
  13743. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13744. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13745. });
  13746. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13747. res.set_content("PUT:" + req.body, "text/plain");
  13748. });
  13749. svr_.Patch("/echo",
  13750. [](const httplib::Request &req, httplib::Response &res) {
  13751. res.set_content("PATCH:" + req.body, "text/plain");
  13752. });
  13753. svr_.Delete(
  13754. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13755. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13756. "text/plain");
  13757. });
  13758. svr_.Get("/head-test",
  13759. [](const httplib::Request &, httplib::Response &res) {
  13760. res.set_content("body for HEAD", "text/plain");
  13761. });
  13762. svr_.Options("/options",
  13763. [](const httplib::Request &, httplib::Response &res) {
  13764. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13765. });
  13766. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13767. svr_.wait_until_ready();
  13768. }
  13769. void TearDown() override {
  13770. svr_.stop();
  13771. if (thread_.joinable()) thread_.join();
  13772. }
  13773. httplib::Server svr_;
  13774. std::thread thread_;
  13775. };
  13776. // stream::Get tests
  13777. TEST_F(StreamApiTest, GetBasic) {
  13778. httplib::Client cli(HOST, PORT);
  13779. auto result = httplib::stream::Get(cli, "/hello");
  13780. ASSERT_TRUE(result.is_valid());
  13781. EXPECT_EQ(200, result.status());
  13782. EXPECT_EQ("Hello World!", read_body(result));
  13783. }
  13784. TEST_F(StreamApiTest, GetWithParams) {
  13785. httplib::Client cli(HOST, PORT);
  13786. httplib::Params params{{"foo", "bar"}};
  13787. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13788. ASSERT_TRUE(result.is_valid());
  13789. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13790. }
  13791. TEST_F(StreamApiTest, GetConnectionError) {
  13792. httplib::Client cli(HOST, 9999);
  13793. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13794. }
  13795. TEST_F(StreamApiTest, Get404) {
  13796. httplib::Client cli(HOST, PORT);
  13797. auto result = httplib::stream::Get(cli, "/nonexistent");
  13798. EXPECT_TRUE(result.is_valid());
  13799. EXPECT_EQ(404, result.status());
  13800. }
  13801. // stream::Post tests
  13802. TEST_F(StreamApiTest, PostBasic) {
  13803. httplib::Client cli(HOST, PORT);
  13804. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13805. "application/json");
  13806. ASSERT_TRUE(result.is_valid());
  13807. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13808. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13809. }
  13810. TEST_F(StreamApiTest, PostWithHeaders) {
  13811. httplib::Client cli(HOST, PORT);
  13812. httplib::Headers headers{{"X-Custom", "value"}};
  13813. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13814. "text/plain");
  13815. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13816. }
  13817. TEST_F(StreamApiTest, PostWithParams) {
  13818. httplib::Client cli(HOST, PORT);
  13819. httplib::Params params{{"k", "v"}};
  13820. auto result =
  13821. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13822. auto body = read_body(result);
  13823. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13824. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13825. }
  13826. TEST_F(StreamApiTest, PostLarge) {
  13827. httplib::Client cli(HOST, PORT);
  13828. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13829. size_t total = 0;
  13830. while (result.next()) {
  13831. total += result.size();
  13832. }
  13833. EXPECT_EQ(100u * 1024u, total);
  13834. }
  13835. // stream::Put/Patch tests
  13836. TEST_F(StreamApiTest, PutAndPatch) {
  13837. httplib::Client cli(HOST, PORT);
  13838. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13839. EXPECT_EQ("PUT:test", read_body(put));
  13840. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13841. EXPECT_EQ("PATCH:test", read_body(patch));
  13842. }
  13843. // stream::Delete tests
  13844. TEST_F(StreamApiTest, Delete) {
  13845. httplib::Client cli(HOST, PORT);
  13846. auto del1 = httplib::stream::Delete(cli, "/resource");
  13847. EXPECT_EQ("Deleted", read_body(del1));
  13848. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13849. EXPECT_EQ("Deleted:data", read_body(del2));
  13850. }
  13851. // stream::Head/Options tests
  13852. TEST_F(StreamApiTest, HeadAndOptions) {
  13853. httplib::Client cli(HOST, PORT);
  13854. auto head = httplib::stream::Head(cli, "/head-test");
  13855. EXPECT_TRUE(head.is_valid());
  13856. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13857. auto opts = httplib::stream::Options(cli, "/options");
  13858. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13859. }
  13860. // SSL stream::* tests
  13861. #ifdef CPPHTTPLIB_SSL_ENABLED
  13862. class SSLStreamApiTest : public ::testing::Test {
  13863. protected:
  13864. void SetUp() override {
  13865. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13866. res.set_content("Hello SSL!", "text/plain");
  13867. });
  13868. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13869. res.set_content(req.body, "text/plain");
  13870. });
  13871. port_ = svr_.bind_to_any_port("127.0.0.1");
  13872. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13873. svr_.wait_until_ready();
  13874. }
  13875. void TearDown() override {
  13876. svr_.stop();
  13877. if (thread_.joinable()) thread_.join();
  13878. }
  13879. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  13880. std::thread thread_;
  13881. int port_ = 0;
  13882. };
  13883. TEST_F(SSLStreamApiTest, GetAndPost) {
  13884. httplib::SSLClient cli("127.0.0.1", port_);
  13885. cli.enable_server_certificate_verification(false);
  13886. auto get = httplib::stream::Get(cli, "/hello");
  13887. EXPECT_EQ("Hello SSL!", read_body(get));
  13888. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  13889. EXPECT_EQ("test", read_body(post));
  13890. }
  13891. #endif
  13892. // Tests for Error::Timeout and Error::ConnectionClosed error types
  13893. // These errors are set in SocketStream/SSLSocketStream and propagated through
  13894. // BodyReader
  13895. TEST(ErrorHandlingTest, StreamReadTimeout) {
  13896. // Test that read timeout during streaming is detected
  13897. // Use a large content-length response where server delays mid-stream
  13898. Server svr;
  13899. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13900. // Send a large response with delay in the middle
  13901. res.set_content_provider(
  13902. 1000, // content_length
  13903. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  13904. if (offset < 100) {
  13905. // Send first 100 bytes immediately
  13906. std::string data(100, 'A');
  13907. sink.write(data.c_str(), data.size());
  13908. return true;
  13909. }
  13910. // Then delay longer than client timeout
  13911. std::this_thread::sleep_for(std::chrono::seconds(3));
  13912. std::string data(900, 'B');
  13913. sink.write(data.c_str(), data.size());
  13914. return true;
  13915. });
  13916. });
  13917. auto port = 8091;
  13918. std::thread t([&]() { svr.listen("localhost", port); });
  13919. svr.wait_until_ready();
  13920. Client cli("localhost", port);
  13921. cli.set_read_timeout(1, 0); // 1 second timeout
  13922. auto handle = cli.open_stream("GET", "/slow-stream");
  13923. ASSERT_TRUE(handle.is_valid());
  13924. char buf[256];
  13925. ssize_t total = 0;
  13926. ssize_t n;
  13927. bool got_error = false;
  13928. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13929. total += n;
  13930. }
  13931. if (n < 0) {
  13932. got_error = true;
  13933. // Should be timeout or read error
  13934. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13935. handle.get_read_error() == Error::Read)
  13936. << "Actual error: " << to_string(handle.get_read_error());
  13937. }
  13938. // Either we got an error, or we got less data than expected
  13939. EXPECT_TRUE(got_error || total < 1000)
  13940. << "Expected timeout but got all " << total << " bytes";
  13941. svr.stop();
  13942. t.join();
  13943. }
  13944. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13945. // Test connection closed detection via BodyReader
  13946. Server svr;
  13947. std::atomic<bool> close_now{false};
  13948. svr.Get("/will-close", [&](const Request &, Response &res) {
  13949. res.set_content_provider(
  13950. 10000, // Large content_length that we won't fully send
  13951. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13952. if (offset < 100) {
  13953. std::string data(100, 'X');
  13954. sink.write(data.c_str(), data.size());
  13955. return true;
  13956. }
  13957. // Wait for signal then abort
  13958. while (!close_now) {
  13959. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13960. }
  13961. return false; // Abort - server will close connection
  13962. });
  13963. });
  13964. auto port = 8092;
  13965. std::thread t([&]() { svr.listen("localhost", port); });
  13966. svr.wait_until_ready();
  13967. Client cli("localhost", port);
  13968. auto handle = cli.open_stream("GET", "/will-close");
  13969. ASSERT_TRUE(handle.is_valid());
  13970. char buf[256];
  13971. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13972. EXPECT_GT(n, 0) << "First read should succeed";
  13973. // Signal server to close
  13974. close_now = true;
  13975. // Keep reading until error or EOF
  13976. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13977. // Keep reading
  13978. }
  13979. // Should get an error since content_length wasn't satisfied
  13980. if (n < 0) {
  13981. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13982. handle.get_read_error() == Error::Read)
  13983. << "Actual error: " << to_string(handle.get_read_error());
  13984. }
  13985. svr.stop();
  13986. t.join();
  13987. }
  13988. #ifdef CPPHTTPLIB_SSL_ENABLED
  13989. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13990. // Test that read timeout during SSL streaming is detected
  13991. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13992. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13993. res.set_content_provider(
  13994. 1000, "text/plain",
  13995. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13996. if (offset < 100) {
  13997. std::string data(100, 'A');
  13998. sink.write(data.c_str(), data.size());
  13999. return true;
  14000. }
  14001. std::this_thread::sleep_for(std::chrono::seconds(3));
  14002. std::string data(900, 'B');
  14003. sink.write(data.c_str(), data.size());
  14004. return true;
  14005. });
  14006. });
  14007. auto port = 8093;
  14008. std::thread t([&]() { svr.listen("localhost", port); });
  14009. svr.wait_until_ready();
  14010. SSLClient cli("localhost", port);
  14011. cli.enable_server_certificate_verification(false);
  14012. cli.set_read_timeout(1, 0); // 1 second timeout
  14013. auto handle = cli.open_stream("GET", "/slow-stream");
  14014. ASSERT_TRUE(handle.is_valid());
  14015. char buf[256];
  14016. ssize_t total = 0;
  14017. ssize_t n;
  14018. bool got_error = false;
  14019. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14020. total += n;
  14021. }
  14022. if (n < 0) {
  14023. got_error = true;
  14024. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14025. handle.get_read_error() == Error::Read)
  14026. << "Actual error: " << to_string(handle.get_read_error());
  14027. }
  14028. EXPECT_TRUE(got_error || total < 1000)
  14029. << "Expected timeout but got all " << total << " bytes";
  14030. svr.stop();
  14031. t.join();
  14032. }
  14033. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14034. // Test SSL connection closed detection
  14035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14036. std::atomic<bool> close_now{false};
  14037. svr.Get("/will-close", [&](const Request &, Response &res) {
  14038. res.set_content_provider(
  14039. 10000, "text/plain",
  14040. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14041. if (offset < 100) {
  14042. std::string data(100, 'X');
  14043. sink.write(data.c_str(), data.size());
  14044. return true;
  14045. }
  14046. while (!close_now) {
  14047. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14048. }
  14049. return false;
  14050. });
  14051. });
  14052. auto port = 8094;
  14053. std::thread t([&]() { svr.listen("localhost", port); });
  14054. svr.wait_until_ready();
  14055. SSLClient cli("localhost", port);
  14056. cli.enable_server_certificate_verification(false);
  14057. auto handle = cli.open_stream("GET", "/will-close");
  14058. ASSERT_TRUE(handle.is_valid());
  14059. char buf[256];
  14060. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14061. EXPECT_GT(n, 0);
  14062. // Signal server to close
  14063. close_now = true;
  14064. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14065. // Keep reading
  14066. }
  14067. if (n < 0) {
  14068. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14069. handle.get_read_error() == Error::Read)
  14070. << "Actual error: " << to_string(handle.get_read_error());
  14071. }
  14072. svr.stop();
  14073. t.join();
  14074. }
  14075. #endif
  14076. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14077. using namespace httplib;
  14078. // Create a test file
  14079. const char *fname = "etag_testfile.txt";
  14080. const char *content = "etag-content";
  14081. {
  14082. std::ofstream ofs(fname);
  14083. ofs << content;
  14084. ASSERT_TRUE(ofs.good());
  14085. }
  14086. Server svr;
  14087. svr.set_mount_point("/static", ".");
  14088. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14089. svr.wait_until_ready();
  14090. Client cli(HOST, PORT);
  14091. // First request: should get 200 with ETag header
  14092. auto res1 = cli.Get("/static/etag_testfile.txt");
  14093. ASSERT_TRUE(res1);
  14094. ASSERT_EQ(200, res1->status);
  14095. ASSERT_TRUE(res1->has_header("ETag"));
  14096. std::string etag = res1->get_header_value("ETag");
  14097. EXPECT_FALSE(etag.empty());
  14098. // Verify ETag format: W/"hex-hex"
  14099. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14100. EXPECT_EQ('W', etag[0]);
  14101. EXPECT_EQ('/', etag[1]);
  14102. EXPECT_EQ('"', etag[2]);
  14103. EXPECT_EQ('"', etag.back());
  14104. // Exact match: expect 304 Not Modified
  14105. Headers h2 = {{"If-None-Match", etag}};
  14106. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14107. ASSERT_TRUE(res2);
  14108. EXPECT_EQ(304, res2->status);
  14109. // Wildcard match: expect 304 Not Modified
  14110. Headers h3 = {{"If-None-Match", "*"}};
  14111. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14112. ASSERT_TRUE(res3);
  14113. EXPECT_EQ(304, res3->status);
  14114. // Non-matching ETag: expect 200
  14115. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14116. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14117. ASSERT_TRUE(res4);
  14118. EXPECT_EQ(200, res4->status);
  14119. // Multiple ETags with one matching: expect 304
  14120. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14121. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14122. ASSERT_TRUE(res5);
  14123. EXPECT_EQ(304, res5->status);
  14124. svr.stop();
  14125. t.join();
  14126. std::remove(fname);
  14127. }
  14128. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14129. using namespace httplib;
  14130. Server svr;
  14131. svr.set_mount_point("/static", ".");
  14132. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14133. svr.wait_until_ready();
  14134. Client cli(HOST, PORT);
  14135. // Send If-None-Match: * to a non-existent file
  14136. Headers h = {{"If-None-Match", "*"}};
  14137. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14138. ASSERT_TRUE(res);
  14139. EXPECT_EQ(404, res->status);
  14140. svr.stop();
  14141. t.join();
  14142. }
  14143. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14144. using namespace httplib;
  14145. // Create a test file
  14146. const char *fname = "etag_boundary_testfile.txt";
  14147. const char *content = "boundary-test";
  14148. {
  14149. std::ofstream ofs(fname);
  14150. ofs << content;
  14151. ASSERT_TRUE(ofs.good());
  14152. }
  14153. Server svr;
  14154. svr.set_mount_point("/static", ".");
  14155. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14156. svr.wait_until_ready();
  14157. Client cli(HOST, PORT);
  14158. // Get the actual ETag
  14159. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14160. ASSERT_TRUE(res1);
  14161. ASSERT_EQ(200, res1->status);
  14162. ASSERT_TRUE(res1->has_header("ETag"));
  14163. std::string etag = res1->get_header_value("ETag");
  14164. // Test 1: Very long ETag value (longer than actual ETag)
  14165. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14166. Headers h1 = {{"If-None-Match", "W/"
  14167. "\"very-long-etag-value-that-is-much-longer-"
  14168. "than-the-actual-etag-value\""}};
  14169. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14170. ASSERT_TRUE(res2);
  14171. EXPECT_EQ(200, res2->status); // Should not match
  14172. // Test 2: Long string followed by wildcard
  14173. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14174. // string)
  14175. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14176. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14177. ASSERT_TRUE(res3);
  14178. EXPECT_EQ(304, res3->status); // Should match on "*"
  14179. // Test 3: Wildcard followed by long string
  14180. // Should match on "*" immediately and return 304
  14181. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14182. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14183. ASSERT_TRUE(res4);
  14184. EXPECT_EQ(304, res4->status); // Should match on "*"
  14185. // Test 4: Multiple long non-matching values
  14186. // Should NOT match and return 200 (test that all comparisons are safe)
  14187. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14188. "W/\"second-long-non-matching-value\", "
  14189. "W/\"third-long-non-matching-value\""}};
  14190. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14191. ASSERT_TRUE(res5);
  14192. EXPECT_EQ(200, res5->status); // Should not match
  14193. // Test 5: Single character that is not "*" (edge case)
  14194. Headers h5 = {{"If-None-Match", "X"}};
  14195. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14196. ASSERT_TRUE(res6);
  14197. EXPECT_EQ(200, res6->status); // Should not match
  14198. svr.stop();
  14199. t.join();
  14200. std::remove(fname);
  14201. }
  14202. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14203. using namespace httplib;
  14204. // Create a test file
  14205. const char *fname = "ims_testfile.txt";
  14206. const char *content = "if-modified-since-test";
  14207. {
  14208. std::ofstream ofs(fname);
  14209. ofs << content;
  14210. ASSERT_TRUE(ofs.good());
  14211. }
  14212. Server svr;
  14213. svr.set_mount_point("/static", ".");
  14214. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14215. svr.wait_until_ready();
  14216. Client cli(HOST, PORT);
  14217. // First request: should get 200 with Last-Modified header
  14218. auto res1 = cli.Get("/static/ims_testfile.txt");
  14219. ASSERT_TRUE(res1);
  14220. ASSERT_EQ(200, res1->status);
  14221. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14222. std::string last_modified = res1->get_header_value("Last-Modified");
  14223. EXPECT_FALSE(last_modified.empty());
  14224. // If-Modified-Since with same time: expect 304
  14225. Headers h2 = {{"If-Modified-Since", last_modified}};
  14226. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14227. ASSERT_TRUE(res2);
  14228. EXPECT_EQ(304, res2->status);
  14229. // If-Modified-Since with future time: expect 304
  14230. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14231. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14232. ASSERT_TRUE(res3);
  14233. EXPECT_EQ(304, res3->status);
  14234. // If-Modified-Since with past time: expect 200
  14235. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14236. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14237. ASSERT_TRUE(res4);
  14238. EXPECT_EQ(200, res4->status);
  14239. // If-None-Match takes precedence over If-Modified-Since
  14240. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14241. ASSERT_TRUE(res1->has_header("ETag"));
  14242. std::string etag = res1->get_header_value("ETag");
  14243. Headers h5 = {{"If-None-Match", etag},
  14244. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14245. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14246. ASSERT_TRUE(res5);
  14247. EXPECT_EQ(304, res5->status);
  14248. svr.stop();
  14249. t.join();
  14250. std::remove(fname);
  14251. }
  14252. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14253. using namespace httplib;
  14254. Server svr;
  14255. // Endpoint that returns compressible content
  14256. svr.Get("/compressible", [](const Request &, Response &res) {
  14257. // Return a large enough body to trigger compression
  14258. std::string body(1000, 'a');
  14259. res.set_content(body, "text/plain");
  14260. });
  14261. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14262. svr.wait_until_ready();
  14263. Client cli(HOST, PORT);
  14264. // Request with gzip support: should get Vary header when compressed
  14265. cli.set_compress(true);
  14266. auto res1 = cli.Get("/compressible");
  14267. ASSERT_TRUE(res1);
  14268. EXPECT_EQ(200, res1->status);
  14269. // If Content-Encoding is set, Vary should also be set
  14270. if (res1->has_header("Content-Encoding")) {
  14271. EXPECT_TRUE(res1->has_header("Vary"));
  14272. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14273. }
  14274. // Request without Accept-Encoding header: should not have compression
  14275. Headers h_no_compress;
  14276. auto res2 = cli.Get("/compressible", h_no_compress);
  14277. ASSERT_TRUE(res2);
  14278. EXPECT_EQ(200, res2->status);
  14279. // Verify Vary header is present when compression is applied
  14280. // (the exact behavior depends on server configuration)
  14281. svr.stop();
  14282. t.join();
  14283. }
  14284. TEST(ETagTest, IfRangeWithETag) {
  14285. using namespace httplib;
  14286. // Create a test file with known content
  14287. const char *fname = "if_range_testfile.txt";
  14288. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14289. {
  14290. std::ofstream ofs(fname);
  14291. ofs << content;
  14292. ASSERT_TRUE(ofs.good());
  14293. }
  14294. Server svr;
  14295. svr.set_mount_point("/static", ".");
  14296. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14297. svr.wait_until_ready();
  14298. Client cli(HOST, PORT);
  14299. // First request: get ETag
  14300. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14301. ASSERT_TRUE(res1);
  14302. ASSERT_EQ(200, res1->status);
  14303. ASSERT_TRUE(res1->has_header("ETag"));
  14304. std::string etag = res1->get_header_value("ETag");
  14305. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14306. // Since our server generates weak ETags (W/"..."), If-Range with our
  14307. // ETag should NOT result in partial content - it should return full content.
  14308. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14309. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14310. ASSERT_TRUE(res2);
  14311. // Weak ETag in If-Range -> full content (200), not partial (206)
  14312. EXPECT_EQ(200, res2->status);
  14313. EXPECT_EQ(content, res2->body);
  14314. EXPECT_FALSE(res2->has_header("Content-Range"));
  14315. // Range request with non-matching If-Range (ETag): should get 200 (full
  14316. // content)
  14317. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14318. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14319. ASSERT_TRUE(res3);
  14320. EXPECT_EQ(200, res3->status);
  14321. EXPECT_EQ(content, res3->body);
  14322. EXPECT_FALSE(res3->has_header("Content-Range"));
  14323. // Range request with strong ETag (hypothetical - our server doesn't generate
  14324. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14325. // should return full content)
  14326. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14327. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14328. ASSERT_TRUE(res4);
  14329. EXPECT_EQ(200, res4->status);
  14330. EXPECT_EQ(content, res4->body);
  14331. EXPECT_FALSE(res4->has_header("Content-Range"));
  14332. svr.stop();
  14333. t.join();
  14334. std::remove(fname);
  14335. }
  14336. TEST(ETagTest, IfRangeWithDate) {
  14337. using namespace httplib;
  14338. // Create a test file
  14339. const char *fname = "if_range_date_testfile.txt";
  14340. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14341. {
  14342. std::ofstream ofs(fname);
  14343. ofs << content;
  14344. ASSERT_TRUE(ofs.good());
  14345. }
  14346. Server svr;
  14347. svr.set_mount_point("/static", ".");
  14348. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14349. svr.wait_until_ready();
  14350. Client cli(HOST, PORT);
  14351. // First request: get Last-Modified
  14352. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14353. ASSERT_TRUE(res1);
  14354. ASSERT_EQ(200, res1->status);
  14355. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14356. std::string last_modified = res1->get_header_value("Last-Modified");
  14357. // Range request with matching If-Range (date): should get 206
  14358. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14359. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14360. ASSERT_TRUE(res2);
  14361. EXPECT_EQ(206, res2->status);
  14362. EXPECT_EQ("FGHIJ", res2->body);
  14363. // Range request with old If-Range date: should get 200 (full content)
  14364. Headers h3 = {{"Range", "bytes=5-9"},
  14365. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14366. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14367. ASSERT_TRUE(res3);
  14368. EXPECT_EQ(200, res3->status);
  14369. EXPECT_EQ(content, res3->body);
  14370. // Range request with future If-Range date: should get 206
  14371. Headers h4 = {{"Range", "bytes=0-4"},
  14372. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14373. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14374. ASSERT_TRUE(res4);
  14375. EXPECT_EQ(206, res4->status);
  14376. EXPECT_EQ("ABCDE", res4->body);
  14377. svr.stop();
  14378. t.join();
  14379. std::remove(fname);
  14380. }
  14381. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14382. using namespace httplib;
  14383. const char *fname = "etag_malformed.txt";
  14384. const char *content = "malformed-etag";
  14385. {
  14386. std::ofstream ofs(fname);
  14387. ofs << content;
  14388. ASSERT_TRUE(ofs.good());
  14389. }
  14390. Server svr;
  14391. svr.set_mount_point("/static", ".");
  14392. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14393. svr.wait_until_ready();
  14394. Client cli(HOST, PORT);
  14395. // baseline: should get 200 and an ETag
  14396. auto res1 = cli.Get("/static/etag_malformed.txt");
  14397. ASSERT_TRUE(res1);
  14398. ASSERT_EQ(200, res1->status);
  14399. ASSERT_TRUE(res1->has_header("ETag"));
  14400. // Malformed ETag value (missing quotes) should be treated as non-matching
  14401. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14402. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14403. ASSERT_TRUE(res_bad);
  14404. EXPECT_EQ(200, res_bad->status);
  14405. // Whitespace-only header value should be considered invalid / non-matching
  14406. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14407. "Host: localhost\r\n"
  14408. "If-None-Match: \r\n"
  14409. "Connection: close\r\n"
  14410. "\r\n";
  14411. std::string out;
  14412. ASSERT_TRUE(send_request(5, raw_req, &out));
  14413. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14414. svr.stop();
  14415. t.join();
  14416. std::remove(fname);
  14417. }
  14418. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14419. using namespace httplib;
  14420. const char *fname = "ims_invalid_format.txt";
  14421. const char *content = "ims-bad-format";
  14422. {
  14423. std::ofstream ofs(fname);
  14424. ofs << content;
  14425. ASSERT_TRUE(ofs.good());
  14426. }
  14427. Server svr;
  14428. svr.set_mount_point("/static", ".");
  14429. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14430. svr.wait_until_ready();
  14431. Client cli(HOST, PORT);
  14432. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14433. ASSERT_TRUE(res1);
  14434. ASSERT_EQ(200, res1->status);
  14435. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14436. // If-Modified-Since with invalid format should not result in 304
  14437. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14438. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14439. ASSERT_TRUE(res_bad);
  14440. EXPECT_EQ(200, res_bad->status);
  14441. // If-Range with invalid date format should be treated as mismatch -> full
  14442. // content (200)
  14443. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14444. {"If-Range", "invalid-date"}};
  14445. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14446. ASSERT_TRUE(res_ifrange);
  14447. EXPECT_EQ(200, res_ifrange->status);
  14448. svr.stop();
  14449. t.join();
  14450. std::remove(fname);
  14451. }
  14452. TEST(ETagTest, IfRangeWithMalformedETag) {
  14453. using namespace httplib;
  14454. const char *fname = "ifrange_malformed.txt";
  14455. const std::string content = "0123456789";
  14456. {
  14457. std::ofstream ofs(fname);
  14458. ofs << content;
  14459. ASSERT_TRUE(ofs.good());
  14460. }
  14461. Server svr;
  14462. svr.set_mount_point("/static", ".");
  14463. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14464. svr.wait_until_ready();
  14465. Client cli(HOST, PORT);
  14466. // First request: get ETag
  14467. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14468. ASSERT_TRUE(res1);
  14469. ASSERT_EQ(200, res1->status);
  14470. ASSERT_TRUE(res1->has_header("ETag"));
  14471. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14472. // full content (200)
  14473. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14474. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14475. ASSERT_TRUE(res2);
  14476. EXPECT_EQ(200, res2->status);
  14477. EXPECT_EQ(content, res2->body);
  14478. svr.stop();
  14479. t.join();
  14480. std::remove(fname);
  14481. }
  14482. TEST(ETagTest, ExtremeLargeDateValues) {
  14483. using namespace httplib;
  14484. const char *fname = "ims_extreme_date.txt";
  14485. const char *content = "ims-extreme-date";
  14486. {
  14487. std::ofstream ofs(fname);
  14488. ofs << content;
  14489. ASSERT_TRUE(ofs.good());
  14490. }
  14491. Server svr;
  14492. svr.set_mount_point("/static", ".");
  14493. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14494. svr.wait_until_ready();
  14495. Client cli(HOST, PORT);
  14496. auto res1 = cli.Get(std::string("/static/") + fname);
  14497. ASSERT_TRUE(res1);
  14498. ASSERT_EQ(200, res1->status);
  14499. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14500. // Extremely large year that may overflow date parsing routines.
  14501. Headers h_large_date = {
  14502. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14503. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14504. ASSERT_TRUE(res_bad);
  14505. // Expect server to treat this as invalid/mismatch and return full content
  14506. EXPECT_EQ(200, res_bad->status);
  14507. // If-Range with extremely large date should be treated as mismatch -> full
  14508. // content (200)
  14509. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14510. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14511. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14512. ASSERT_TRUE(res_ifrange);
  14513. EXPECT_EQ(200, res_ifrange->status);
  14514. svr.stop();
  14515. t.join();
  14516. std::remove(fname);
  14517. }
  14518. TEST(ETagTest, NegativeFileModificationTime) {
  14519. using namespace httplib;
  14520. const char *fname = "ims_negative_mtime.txt";
  14521. const std::string content = "negative-mtime";
  14522. {
  14523. std::ofstream ofs(fname);
  14524. ofs << content;
  14525. ASSERT_TRUE(ofs.good());
  14526. }
  14527. // Try to set file mtime to a negative value. This may fail on some
  14528. // platforms/filesystems; if it fails, the test will still verify server
  14529. // behaves safely by performing a regular conditional request.
  14530. #if defined(__APPLE__) || defined(__linux__)
  14531. bool set_negative = false;
  14532. do {
  14533. struct timeval times[2];
  14534. // access time: now
  14535. times[0].tv_sec = time(nullptr);
  14536. times[0].tv_usec = 0;
  14537. // modification time: negative (e.g., -1)
  14538. times[1].tv_sec = -1;
  14539. times[1].tv_usec = 0;
  14540. if (utimes(fname, times) == 0) { set_negative = true; }
  14541. } while (0);
  14542. #else
  14543. bool set_negative = false;
  14544. #endif
  14545. Server svr;
  14546. svr.set_mount_point("/static", ".");
  14547. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14548. svr.wait_until_ready();
  14549. Client cli(HOST, PORT);
  14550. auto res1 = cli.Get(std::string("/static/") + fname);
  14551. ASSERT_TRUE(res1);
  14552. ASSERT_EQ(200, res1->status);
  14553. bool has_last_modified = res1->has_header("Last-Modified");
  14554. std::string last_modified;
  14555. if (has_last_modified) {
  14556. last_modified = res1->get_header_value("Last-Modified");
  14557. }
  14558. if (set_negative) {
  14559. // If we successfully set a negative mtime, ensure server returns a
  14560. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14561. // with an old date and ensure server handles it without crash.
  14562. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14563. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14564. ASSERT_TRUE(res2);
  14565. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14566. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14567. } else {
  14568. // Could not set negative mtime on this platform; fall back to verifying
  14569. // that normal invalid/malformed dates are treated safely (non-304).
  14570. Headers h_bad_date = {
  14571. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14572. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14573. ASSERT_TRUE(res_bad);
  14574. EXPECT_EQ(200, res_bad->status);
  14575. }
  14576. svr.stop();
  14577. t.join();
  14578. std::remove(fname);
  14579. }
  14580. //==============================================================================
  14581. // SSE Parsing Tests
  14582. //==============================================================================
  14583. class SSEParsingTest : public ::testing::Test {
  14584. protected:
  14585. // Test helper that mimics SSE parsing behavior
  14586. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14587. int &retry_ms) {
  14588. // Blank line signals end of event
  14589. if (line.empty() || line == "\r") { return true; }
  14590. // Lines starting with ':' are comments (ignored)
  14591. if (!line.empty() && line[0] == ':') { return false; }
  14592. // Find the colon separator
  14593. auto colon_pos = line.find(':');
  14594. if (colon_pos == std::string::npos) {
  14595. // Line with no colon is treated as field name with empty value
  14596. return false;
  14597. }
  14598. std::string field = line.substr(0, colon_pos);
  14599. std::string value;
  14600. // Value starts after colon, skip optional single space
  14601. if (colon_pos + 1 < line.size()) {
  14602. size_t value_start = colon_pos + 1;
  14603. if (line[value_start] == ' ') { value_start++; }
  14604. value = line.substr(value_start);
  14605. // Remove trailing \r if present
  14606. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14607. }
  14608. // Handle known fields
  14609. if (field == "event") {
  14610. msg.event = value;
  14611. } else if (field == "data") {
  14612. // Multiple data lines are concatenated with newlines
  14613. if (!msg.data.empty()) { msg.data += "\n"; }
  14614. msg.data += value;
  14615. } else if (field == "id") {
  14616. // Empty id is valid (clears the last event ID)
  14617. msg.id = value;
  14618. } else if (field == "retry") {
  14619. // Parse retry interval in milliseconds
  14620. {
  14621. int v = 0;
  14622. auto res =
  14623. detail::from_chars(value.data(), value.data() + value.size(), v);
  14624. if (res.ec == std::errc{}) { retry_ms = v; }
  14625. }
  14626. }
  14627. // Unknown fields are ignored per SSE spec
  14628. return false;
  14629. }
  14630. };
  14631. // Test: Single-line data
  14632. TEST_F(SSEParsingTest, SingleLineData) {
  14633. sse::SSEMessage msg;
  14634. int retry_ms = 3000;
  14635. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14636. EXPECT_EQ(msg.data, "hello");
  14637. EXPECT_EQ(msg.event, "message");
  14638. // Blank line ends event
  14639. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14640. }
  14641. // Test: Multi-line data
  14642. TEST_F(SSEParsingTest, MultiLineData) {
  14643. sse::SSEMessage msg;
  14644. int retry_ms = 3000;
  14645. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14646. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14647. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14648. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14649. }
  14650. // Test: Custom event types
  14651. TEST_F(SSEParsingTest, CustomEventType) {
  14652. sse::SSEMessage msg;
  14653. int retry_ms = 3000;
  14654. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14655. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14656. EXPECT_EQ(msg.event, "update");
  14657. EXPECT_EQ(msg.data, "payload");
  14658. }
  14659. // Test: Event ID handling
  14660. TEST_F(SSEParsingTest, EventIdHandling) {
  14661. sse::SSEMessage msg;
  14662. int retry_ms = 3000;
  14663. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14664. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14665. EXPECT_EQ(msg.id, "12345");
  14666. }
  14667. // Test: Empty event ID (clears last event ID)
  14668. TEST_F(SSEParsingTest, EmptyEventId) {
  14669. sse::SSEMessage msg;
  14670. msg.id = "previous";
  14671. int retry_ms = 3000;
  14672. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14673. EXPECT_EQ(msg.id, "");
  14674. }
  14675. // Test: Retry field parsing
  14676. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14677. sse::SSEMessage msg;
  14678. int retry_ms = 3000;
  14679. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14680. EXPECT_EQ(retry_ms, 5000);
  14681. }
  14682. // Test: Invalid retry value
  14683. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14684. sse::SSEMessage msg;
  14685. int retry_ms = 3000;
  14686. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14687. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14688. }
  14689. // Test: Comments (lines starting with :)
  14690. TEST_F(SSEParsingTest, CommentsIgnored) {
  14691. sse::SSEMessage msg;
  14692. int retry_ms = 3000;
  14693. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14694. EXPECT_EQ(msg.data, "");
  14695. EXPECT_EQ(msg.event, "message");
  14696. }
  14697. // Test: Colon in value
  14698. TEST_F(SSEParsingTest, ColonInValue) {
  14699. sse::SSEMessage msg;
  14700. int retry_ms = 3000;
  14701. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14702. EXPECT_EQ(msg.data, "hello:world:test");
  14703. }
  14704. // Test: Line with no colon (field name only)
  14705. TEST_F(SSEParsingTest, FieldNameOnly) {
  14706. sse::SSEMessage msg;
  14707. int retry_ms = 3000;
  14708. // According to SSE spec, this is treated as field name with empty value
  14709. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14710. // Since we don't recognize "data" without colon, data should be empty
  14711. EXPECT_EQ(msg.data, "");
  14712. }
  14713. // Test: Trailing \r handling
  14714. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14715. sse::SSEMessage msg;
  14716. int retry_ms = 3000;
  14717. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14718. EXPECT_EQ(msg.data, "hello");
  14719. }
  14720. // Test: Unknown fields ignored
  14721. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14722. sse::SSEMessage msg;
  14723. int retry_ms = 3000;
  14724. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14725. EXPECT_EQ(msg.data, "");
  14726. EXPECT_EQ(msg.event, "message");
  14727. }
  14728. // Test: Space after colon is optional
  14729. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14730. sse::SSEMessage msg1, msg2;
  14731. int retry_ms = 3000;
  14732. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14733. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14734. EXPECT_EQ(msg1.data, "hello");
  14735. EXPECT_EQ(msg2.data, "hello");
  14736. }
  14737. // Test: SSEMessage clear
  14738. TEST_F(SSEParsingTest, MessageClear) {
  14739. sse::SSEMessage msg;
  14740. msg.event = "custom";
  14741. msg.data = "some data";
  14742. msg.id = "123";
  14743. msg.clear();
  14744. EXPECT_EQ(msg.event, "message");
  14745. EXPECT_EQ(msg.data, "");
  14746. EXPECT_EQ(msg.id, "");
  14747. }
  14748. // Test: Complete event parsing
  14749. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14750. sse::SSEMessage msg;
  14751. int retry_ms = 3000;
  14752. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14753. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14754. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14755. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14756. // Blank line ends event
  14757. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14758. EXPECT_EQ(msg.event, "notification");
  14759. EXPECT_EQ(msg.id, "evt-42");
  14760. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14761. EXPECT_EQ(retry_ms, 1000);
  14762. }
  14763. //==============================================================================
  14764. // Integration Tests with Server
  14765. //==============================================================================
  14766. class SSEIntegrationTest : public ::testing::Test {
  14767. protected:
  14768. void SetUp() override {
  14769. stop_server_.store(false);
  14770. events_.clear();
  14771. server_ = httplib::detail::make_unique<Server>();
  14772. setup_server();
  14773. start_server();
  14774. }
  14775. void TearDown() override {
  14776. stop_server_.store(true);
  14777. event_cv_.notify_all();
  14778. server_->stop();
  14779. if (server_thread_.joinable()) { server_thread_.join(); }
  14780. }
  14781. void setup_server() {
  14782. // Simple SSE endpoint
  14783. server_->Get("/events", [this](const Request &req, Response &res) {
  14784. auto last_id = req.get_header_value("Last-Event-ID");
  14785. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14786. res.set_chunked_content_provider(
  14787. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14788. std::unique_lock<std::mutex> lock(event_mutex_);
  14789. if (event_cv_.wait_for(
  14790. lock, std::chrono::milliseconds(200), [this] {
  14791. return !events_.empty() || stop_server_.load();
  14792. })) {
  14793. if (stop_server_.load()) { return false; }
  14794. if (!events_.empty()) {
  14795. std::string event = events_.front();
  14796. events_.erase(events_.begin());
  14797. sink.write(event.data(), event.size());
  14798. return true;
  14799. }
  14800. }
  14801. return !stop_server_.load();
  14802. });
  14803. });
  14804. // Endpoint that returns error
  14805. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14806. res.status = 500;
  14807. res.set_content("Internal Server Error", "text/plain");
  14808. });
  14809. // Endpoint for custom event types
  14810. server_->Get("/custom-events", [](const Request &, Response &res) {
  14811. res.set_chunked_content_provider(
  14812. "text/event-stream", [](size_t offset, DataSink &sink) {
  14813. if (offset == 0) {
  14814. std::string event = "event: update\ndata: updated\n\n"
  14815. "event: delete\ndata: deleted\n\n";
  14816. sink.write(event.data(), event.size());
  14817. }
  14818. return false; // End stream after sending
  14819. });
  14820. });
  14821. }
  14822. void start_server() {
  14823. port_ = server_->bind_to_any_port(HOST);
  14824. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14825. // Wait for server to start
  14826. while (!server_->is_running()) {
  14827. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14828. }
  14829. }
  14830. int get_port() const { return port_; }
  14831. void send_event(const std::string &event) {
  14832. std::lock_guard<std::mutex> lock(event_mutex_);
  14833. events_.push_back(event);
  14834. event_cv_.notify_all();
  14835. }
  14836. std::unique_ptr<Server> server_;
  14837. std::thread server_thread_;
  14838. std::mutex event_mutex_;
  14839. std::condition_variable event_cv_;
  14840. std::vector<std::string> events_;
  14841. std::atomic<bool> stop_server_{false};
  14842. std::string last_received_event_id_;
  14843. int port_ = 0;
  14844. };
  14845. // Test: Successful connection and on_open callback
  14846. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14847. // Add a simple endpoint that sends one event and closes
  14848. server_->Get("/simple-event", [](const Request &, Response &res) {
  14849. res.set_chunked_content_provider(
  14850. "text/event-stream", [](size_t offset, DataSink &sink) {
  14851. if (offset == 0) {
  14852. std::string event = "data: hello\n\n";
  14853. sink.write(event.data(), event.size());
  14854. }
  14855. return false; // Close stream after sending
  14856. });
  14857. });
  14858. Client client("localhost", get_port());
  14859. sse::SSEClient sse(client, "/simple-event");
  14860. std::atomic<bool> open_called{false};
  14861. std::atomic<bool> message_received{false};
  14862. sse.on_open([&open_called]() { open_called.store(true); });
  14863. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14864. if (msg.data == "hello") { message_received.store(true); }
  14865. });
  14866. sse.set_reconnect_interval(100);
  14867. sse.set_max_reconnect_attempts(1);
  14868. // Start async
  14869. sse.start_async();
  14870. // Wait for message to be processed
  14871. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14872. sse.stop();
  14873. EXPECT_TRUE(open_called.load());
  14874. EXPECT_TRUE(message_received.load());
  14875. }
  14876. // Test: on_message callback
  14877. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  14878. // Endpoint that sends multiple events then closes
  14879. server_->Get("/multi-event", [](const Request &, Response &res) {
  14880. res.set_chunked_content_provider(
  14881. "text/event-stream", [](size_t offset, DataSink &sink) {
  14882. if (offset == 0) {
  14883. std::string events = "data: message1\n\ndata: message2\n\n";
  14884. sink.write(events.data(), events.size());
  14885. }
  14886. return false;
  14887. });
  14888. });
  14889. Client client("localhost", get_port());
  14890. sse::SSEClient sse(client, "/multi-event");
  14891. std::vector<std::string> received_messages;
  14892. std::mutex messages_mutex;
  14893. sse.on_message([&](const sse::SSEMessage &msg) {
  14894. std::lock_guard<std::mutex> lock(messages_mutex);
  14895. received_messages.push_back(msg.data);
  14896. });
  14897. sse.set_reconnect_interval(100);
  14898. sse.set_max_reconnect_attempts(1);
  14899. sse.start_async();
  14900. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14901. sse.stop();
  14902. std::lock_guard<std::mutex> lock(messages_mutex);
  14903. EXPECT_GE(received_messages.size(), 2u);
  14904. if (received_messages.size() >= 2) {
  14905. EXPECT_EQ(received_messages[0], "message1");
  14906. EXPECT_EQ(received_messages[1], "message2");
  14907. }
  14908. }
  14909. // Test: on_event for specific types
  14910. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14911. Client client("localhost", get_port());
  14912. sse::SSEClient sse(client, "/custom-events");
  14913. std::atomic<bool> update_received{false};
  14914. std::atomic<bool> delete_received{false};
  14915. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14916. if (msg.data == "updated") { update_received.store(true); }
  14917. });
  14918. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14919. if (msg.data == "deleted") { delete_received.store(true); }
  14920. });
  14921. sse.set_max_reconnect_attempts(1);
  14922. sse.start_async();
  14923. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14924. sse.stop();
  14925. EXPECT_TRUE(update_received.load());
  14926. EXPECT_TRUE(delete_received.load());
  14927. }
  14928. // Test: on_error callback on connection failure
  14929. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14930. // Connect to a non-existent port
  14931. Client client("localhost", 59999);
  14932. sse::SSEClient sse(client, "/events");
  14933. std::atomic<bool> error_called{false};
  14934. Error received_error = Error::Success;
  14935. sse.on_error([&](Error err) {
  14936. error_called.store(true);
  14937. received_error = err;
  14938. });
  14939. sse.set_reconnect_interval(50);
  14940. sse.set_max_reconnect_attempts(1);
  14941. sse.start_async();
  14942. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14943. sse.stop();
  14944. EXPECT_TRUE(error_called.load());
  14945. EXPECT_NE(received_error, Error::Success);
  14946. }
  14947. // Test: Last-Event-ID header sent on reconnect
  14948. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14949. // Endpoint that sends event with ID
  14950. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14951. res.set_chunked_content_provider(
  14952. "text/event-stream", [](size_t offset, DataSink &sink) {
  14953. if (offset == 0) {
  14954. std::string event = "id: evt-123\ndata: test\n\n";
  14955. sink.write(event.data(), event.size());
  14956. }
  14957. return false;
  14958. });
  14959. });
  14960. Client client("localhost", get_port());
  14961. sse::SSEClient sse(client, "/event-with-id");
  14962. std::atomic<bool> id_received{false};
  14963. sse.on_message([&](const sse::SSEMessage &msg) {
  14964. if (!msg.id.empty()) { id_received.store(true); }
  14965. });
  14966. sse.set_reconnect_interval(100);
  14967. sse.set_max_reconnect_attempts(1);
  14968. sse.start_async();
  14969. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14970. sse.stop();
  14971. EXPECT_TRUE(id_received.load());
  14972. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14973. }
  14974. // Test: Manual stop
  14975. TEST_F(SSEIntegrationTest, ManualStop) {
  14976. // Endpoint that sends one event and stays open briefly
  14977. std::atomic<bool> handler_running{true};
  14978. server_->Get("/stay-open", [&handler_running](const Request &,
  14979. Response &res) {
  14980. res.set_chunked_content_provider(
  14981. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14982. if (offset == 0) {
  14983. std::string event = "data: connected\n\n";
  14984. sink.write(event.data(), event.size());
  14985. }
  14986. // Keep connection open while handler_running is true
  14987. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14988. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14989. }
  14990. return false;
  14991. });
  14992. });
  14993. Client client("localhost", get_port());
  14994. sse::SSEClient sse(client, "/stay-open");
  14995. std::atomic<bool> connected{false};
  14996. sse.on_open([&connected]() { connected.store(true); });
  14997. sse.set_reconnect_interval(100);
  14998. sse.set_max_reconnect_attempts(1);
  14999. sse.start_async();
  15000. // Wait for connection to establish
  15001. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15002. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15003. }
  15004. EXPECT_TRUE(connected.load());
  15005. EXPECT_TRUE(sse.is_connected());
  15006. // Signal handler to stop
  15007. handler_running.store(false);
  15008. // Stop SSE client
  15009. sse.stop();
  15010. EXPECT_FALSE(sse.is_connected());
  15011. }
  15012. // Test: SSEClient with custom headers
  15013. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15014. // Setup a server endpoint that checks for custom header
  15015. std::atomic<bool> header_received{false};
  15016. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15017. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15018. header_received.store(true);
  15019. }
  15020. res.set_chunked_content_provider("text/event-stream",
  15021. [](size_t, DataSink &) { return false; });
  15022. });
  15023. Client client("localhost", get_port());
  15024. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15025. sse::SSEClient sse(client, "/header-check", headers);
  15026. sse.set_max_reconnect_attempts(1);
  15027. sse.start_async();
  15028. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15029. sse.stop();
  15030. EXPECT_TRUE(header_received.load());
  15031. }
  15032. // Test: Reconnect interval configuration
  15033. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15034. Client client("localhost", get_port());
  15035. sse::SSEClient sse(client, "/events");
  15036. auto &result = sse.set_reconnect_interval(500);
  15037. // Builder pattern should return reference to self
  15038. EXPECT_EQ(&result, &sse);
  15039. }
  15040. // Test: Max reconnect attempts
  15041. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15042. // Connect to non-existent port to force reconnects
  15043. Client client("localhost", 59998);
  15044. sse::SSEClient sse(client, "/events");
  15045. std::atomic<int> error_count{0};
  15046. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15047. sse.set_reconnect_interval(50);
  15048. sse.set_max_reconnect_attempts(2);
  15049. auto start = std::chrono::steady_clock::now();
  15050. sse.start(); // Blocking call
  15051. auto end = std::chrono::steady_clock::now();
  15052. // Should have stopped after 2 failed attempts
  15053. EXPECT_GE(error_count.load(), 2);
  15054. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15055. auto duration =
  15056. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15057. #ifdef _WIN32
  15058. // Windows is much slower for socket connection failures
  15059. EXPECT_LT(duration.count(), 7000);
  15060. #else
  15061. EXPECT_LT(duration.count(), 1000);
  15062. #endif
  15063. }
  15064. // Test: Multi-line data in integration
  15065. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15066. // Endpoint with multi-line data
  15067. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15068. res.set_chunked_content_provider(
  15069. "text/event-stream", [](size_t offset, DataSink &sink) {
  15070. if (offset == 0) {
  15071. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15072. sink.write(event.data(), event.size());
  15073. }
  15074. return false;
  15075. });
  15076. });
  15077. Client client("localhost", get_port());
  15078. sse::SSEClient sse(client, "/multiline-data");
  15079. std::string received_data;
  15080. std::mutex data_mutex;
  15081. sse.on_message([&](const sse::SSEMessage &msg) {
  15082. std::lock_guard<std::mutex> lock(data_mutex);
  15083. received_data = msg.data;
  15084. });
  15085. sse.set_reconnect_interval(100);
  15086. sse.set_max_reconnect_attempts(1);
  15087. sse.start_async();
  15088. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15089. sse.stop();
  15090. std::lock_guard<std::mutex> lock(data_mutex);
  15091. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15092. }
  15093. // Test: Auto-reconnect after server disconnection
  15094. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15095. std::atomic<int> connection_count{0};
  15096. std::atomic<int> message_count{0};
  15097. // Endpoint that sends one event and closes, forcing reconnect
  15098. server_->Get("/reconnect-test",
  15099. [&connection_count](const Request &, Response &res) {
  15100. connection_count.fetch_add(1);
  15101. res.set_chunked_content_provider(
  15102. "text/event-stream", [](size_t offset, DataSink &sink) {
  15103. if (offset == 0) {
  15104. std::string event = "data: hello\n\n";
  15105. sink.write(event.data(), event.size());
  15106. }
  15107. return false; // Close connection after sending
  15108. });
  15109. });
  15110. Client client("localhost", get_port());
  15111. sse::SSEClient sse(client, "/reconnect-test");
  15112. sse.on_message([&message_count](const sse::SSEMessage &) {
  15113. message_count.fetch_add(1);
  15114. });
  15115. sse.set_reconnect_interval(100);
  15116. sse.set_max_reconnect_attempts(3);
  15117. sse.start_async();
  15118. // Wait long enough for multiple reconnects
  15119. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15120. sse.stop();
  15121. // Should have connected multiple times (initial + reconnects)
  15122. EXPECT_GE(connection_count.load(), 2);
  15123. // Should have received messages from multiple connections
  15124. EXPECT_GE(message_count.load(), 2);
  15125. }
  15126. // Test: Last-Event-ID sent on reconnect
  15127. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15128. std::atomic<int> connection_count{0};
  15129. std::vector<std::string> received_last_event_ids;
  15130. std::mutex id_mutex;
  15131. // Endpoint that checks Last-Event-ID header and sends event with ID
  15132. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15133. int conn = connection_count.fetch_add(1);
  15134. // Capture the Last-Event-ID header from each connection
  15135. {
  15136. std::lock_guard<std::mutex> lock(id_mutex);
  15137. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15138. }
  15139. res.set_chunked_content_provider(
  15140. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15141. if (offset == 0) {
  15142. std::string event =
  15143. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15144. sink.write(event.data(), event.size());
  15145. }
  15146. return false;
  15147. });
  15148. });
  15149. Client client("localhost", get_port());
  15150. sse::SSEClient sse(client, "/reconnect-with-id");
  15151. sse.set_reconnect_interval(100);
  15152. sse.set_max_reconnect_attempts(3);
  15153. sse.start_async();
  15154. // Wait for at least 2 connections
  15155. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15156. sse.stop();
  15157. // Verify behavior
  15158. std::lock_guard<std::mutex> lock(id_mutex);
  15159. EXPECT_GE(received_last_event_ids.size(), 2u);
  15160. // First connection should have no Last-Event-ID
  15161. if (!received_last_event_ids.empty()) {
  15162. EXPECT_EQ(received_last_event_ids[0], "");
  15163. }
  15164. // Second connection should have Last-Event-ID from first connection
  15165. if (received_last_event_ids.size() >= 2) {
  15166. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15167. }
  15168. }
  15169. // Test: set_headers updates headers used on reconnect
  15170. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15171. std::vector<std::string> received_tokens;
  15172. std::mutex token_mutex;
  15173. // Endpoint that captures Authorization header
  15174. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15175. {
  15176. std::lock_guard<std::mutex> lock(token_mutex);
  15177. received_tokens.push_back(req.get_header_value("Authorization"));
  15178. }
  15179. res.set_chunked_content_provider(
  15180. "text/event-stream", [](size_t offset, DataSink &sink) {
  15181. if (offset == 0) {
  15182. std::string event = "data: hello\n\n";
  15183. sink.write(event.data(), event.size());
  15184. }
  15185. return false; // Close connection to trigger reconnect
  15186. });
  15187. });
  15188. Client client("localhost", get_port());
  15189. Headers headers = {{"Authorization", "Bearer old-token"}};
  15190. sse::SSEClient sse(client, "/auth-check", headers);
  15191. // Update headers on each successful connection
  15192. sse.on_open(
  15193. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15194. sse.set_reconnect_interval(100);
  15195. sse.set_max_reconnect_attempts(3);
  15196. sse.start_async();
  15197. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15198. sse.stop();
  15199. std::lock_guard<std::mutex> lock(token_mutex);
  15200. ASSERT_GE(received_tokens.size(), 2u);
  15201. // First connection uses original header
  15202. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15203. // Second connection uses updated header from set_headers
  15204. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15205. }
  15206. // Test: 401 allows reconnection (so on_error can refresh headers)
  15207. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15208. std::atomic<int> connection_count{0};
  15209. // Endpoint: returns 401 on first attempt, 200 on second
  15210. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15211. int conn = connection_count.fetch_add(1);
  15212. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15213. res.status = StatusCode::Unauthorized_401;
  15214. res.set_content("Unauthorized", "text/plain");
  15215. return;
  15216. }
  15217. res.set_chunked_content_provider(
  15218. "text/event-stream", [](size_t offset, DataSink &sink) {
  15219. if (offset == 0) {
  15220. std::string event = "data: authenticated\n\n";
  15221. sink.write(event.data(), event.size());
  15222. }
  15223. return false;
  15224. });
  15225. });
  15226. Client client("localhost", get_port());
  15227. Headers headers = {{"Authorization", "Bearer expired"}};
  15228. sse::SSEClient sse(client, "/auth-retry", headers);
  15229. std::atomic<bool> message_received{false};
  15230. // Refresh token on error
  15231. sse.on_error(
  15232. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15233. sse.on_message([&](const sse::SSEMessage &msg) {
  15234. if (msg.data == "authenticated") { message_received.store(true); }
  15235. });
  15236. sse.set_reconnect_interval(100);
  15237. sse.set_max_reconnect_attempts(3);
  15238. sse.start_async();
  15239. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15240. sse.stop();
  15241. // Should have reconnected after 401 and succeeded with new token
  15242. EXPECT_GE(connection_count.load(), 2);
  15243. EXPECT_TRUE(message_received.load());
  15244. }
  15245. TEST(Issue2318Test, EmptyHostString) {
  15246. {
  15247. httplib::Client cli_empty("", PORT);
  15248. auto res = cli_empty.Get("/");
  15249. ASSERT_FALSE(res);
  15250. EXPECT_EQ(httplib::Error::Connection, res.error());
  15251. }
  15252. {
  15253. httplib::Client cli(" ", PORT);
  15254. auto res = cli.Get("/");
  15255. ASSERT_FALSE(res);
  15256. EXPECT_EQ(httplib::Error::Connection, res.error());
  15257. }
  15258. }
  15259. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15260. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15261. Server svr;
  15262. // Set a small payload limit (1KB)
  15263. svr.set_payload_max_length(1024);
  15264. svr.Post("/test", [&](const Request &req, Response &res) {
  15265. res.set_content("Body size: " + std::to_string(req.body.size()),
  15266. "text/plain");
  15267. });
  15268. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15269. auto se = detail::scope_exit([&] {
  15270. svr.stop();
  15271. listen_thread.join();
  15272. });
  15273. svr.wait_until_ready();
  15274. // Create data that compresses well but exceeds limit when decompressed
  15275. // 8KB of repeated null bytes compresses to a very small size
  15276. std::string original_data(8 * 1024, '\0');
  15277. // Compress the data using gzip
  15278. std::string compressed_data;
  15279. detail::gzip_compressor compressor;
  15280. compressor.compress(original_data.data(), original_data.size(), true,
  15281. [&](const char *data, size_t size) {
  15282. compressed_data.append(data, size);
  15283. return true;
  15284. });
  15285. // Verify compression worked (compressed should be much smaller)
  15286. ASSERT_LT(compressed_data.size(), original_data.size());
  15287. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15288. // Send compressed data with Content-Encoding: gzip
  15289. Client cli(HOST, PORT);
  15290. Headers headers = {{"Content-Encoding", "gzip"}};
  15291. auto res =
  15292. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15293. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15294. ASSERT_TRUE(res);
  15295. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15296. }
  15297. #endif
  15298. // ============================================================================
  15299. // OpenSSL-Specific Tests
  15300. // ============================================================================
  15301. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15302. X509 *readCertificate(const std::string &strFileName) {
  15303. std::ifstream inStream(strFileName);
  15304. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15305. std::istreambuf_iterator<char>());
  15306. if (strCertPEM.empty()) return (nullptr);
  15307. BIO *pbCert = BIO_new(BIO_s_mem());
  15308. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15309. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15310. BIO_free(pbCert);
  15311. return (pCert);
  15312. }
  15313. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15314. std::ifstream inStream(strFileName);
  15315. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15316. std::istreambuf_iterator<char>());
  15317. if (strPrivateKeyPEM.empty()) return (nullptr);
  15318. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15319. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15320. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15321. BIO_free(pbPrivKey);
  15322. return (pPrivateKey);
  15323. }
  15324. TEST(BindServerTest, UpdateCerts) {
  15325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15326. int port = svr.bind_to_any_port("0.0.0.0");
  15327. ASSERT_TRUE(svr.is_valid());
  15328. ASSERT_TRUE(port > 0);
  15329. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15330. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15331. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15332. ASSERT_TRUE(cert != nullptr);
  15333. ASSERT_TRUE(ca_cert != nullptr);
  15334. ASSERT_TRUE(key != nullptr);
  15335. X509_STORE *cert_store = X509_STORE_new();
  15336. X509_STORE_add_cert(cert_store, ca_cert);
  15337. // svr.update_certs(cert, key, cert_store); // deprecated
  15338. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15339. CLIENT_CA_CERT_FILE);
  15340. ASSERT_TRUE(svr.is_valid());
  15341. svr.stop();
  15342. X509_STORE_free(cert_store);
  15343. X509_free(cert);
  15344. X509_free(ca_cert);
  15345. EVP_PKEY_free(key);
  15346. }
  15347. // Test that update_certs() updates client CA list correctly
  15348. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15349. // Start with file-based constructor
  15350. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15351. ASSERT_TRUE(svr.is_valid());
  15352. // Initially no client CA list should be set
  15353. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15354. ASSERT_TRUE(ssl_ctx != nullptr);
  15355. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15356. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15357. EXPECT_EQ(0, count_before);
  15358. // Now update with client CA (PEM string)
  15359. std::string cert_pem, key_pem, ca_pem;
  15360. read_file(SERVER_CERT_FILE, cert_pem);
  15361. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15362. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15363. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15364. ASSERT_TRUE(svr.is_valid());
  15365. // Now client CA list should be set
  15366. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15367. ASSERT_TRUE(ca_list_after != nullptr);
  15368. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15369. }
  15370. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15371. // Test that the file-path SSLServer constructor properly sets the client CA
  15372. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15374. ASSERT_TRUE(svr.is_valid());
  15375. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15376. ASSERT_TRUE(ssl_ctx != nullptr);
  15377. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15378. ASSERT_TRUE(ca_list != nullptr);
  15379. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15380. }
  15381. #endif
  15382. // ============================================================================
  15383. // MbedTLS-Specific Tests
  15384. // ============================================================================
  15385. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15386. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15387. using namespace httplib::tls;
  15388. // Track if callback was invoked
  15389. bool callback_invoked = false;
  15390. // The callback receives void* ctx which is actually MbedTlsContext*
  15391. // We can access the mbedtls_ssl_config via the context
  15392. auto setup_callback = [&callback_invoked](void *ctx) {
  15393. callback_invoked = true;
  15394. // Cast to MbedTlsContext* to access the ssl config
  15395. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15396. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15397. // Use static variables to hold certificate data (simplified for test)
  15398. static mbedtls_x509_crt own_cert;
  15399. static mbedtls_pk_context own_key;
  15400. static mbedtls_x509_crt ca_chain;
  15401. static bool initialized = false;
  15402. if (!initialized) {
  15403. mbedtls_x509_crt_init(&own_cert);
  15404. mbedtls_pk_init(&own_key);
  15405. mbedtls_x509_crt_init(&ca_chain);
  15406. // Load server certificate
  15407. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15408. return false;
  15409. }
  15410. // Load server private key
  15411. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15412. #if MBEDTLS_VERSION_MAJOR >= 3
  15413. ,
  15414. mbedtls_ctr_drbg_random, nullptr
  15415. #endif
  15416. ) != 0) {
  15417. return false;
  15418. }
  15419. // Load CA chain for client verification
  15420. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15421. return false;
  15422. }
  15423. initialized = true;
  15424. }
  15425. // Configure the SSL config
  15426. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15427. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15428. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15429. // Set minimum TLS version using mbedTLS native API
  15430. #if MBEDTLS_VERSION_MAJOR >= 3
  15431. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15432. #else
  15433. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15434. MBEDTLS_SSL_MINOR_VERSION_3);
  15435. #endif
  15436. return true;
  15437. };
  15438. SSLServer svr(setup_callback);
  15439. ASSERT_TRUE(svr.is_valid());
  15440. ASSERT_TRUE(callback_invoked);
  15441. svr.Get("/test", [&](const Request &req, Response &res) {
  15442. res.set_content("test", "text/plain");
  15443. auto cert = req.peer_cert();
  15444. ASSERT_TRUE(static_cast<bool>(cert));
  15445. auto common_name = cert.subject_cn();
  15446. EXPECT_EQ("Common Name", common_name);
  15447. });
  15448. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15449. auto se = detail::scope_exit([&] {
  15450. svr.stop();
  15451. t.join();
  15452. ASSERT_FALSE(svr.is_running());
  15453. });
  15454. svr.wait_until_ready();
  15455. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15456. cli.enable_server_certificate_verification(false);
  15457. cli.set_connection_timeout(30);
  15458. auto res = cli.Get("/test");
  15459. ASSERT_TRUE(res);
  15460. ASSERT_EQ(StatusCode::OK_200, res->status);
  15461. }
  15462. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15463. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15464. // keep-alive SSL session, which reads through that config in
  15465. // mbedtls_ssl_close_notify.
  15466. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15467. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15468. ASSERT_TRUE(svr.is_valid());
  15469. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15470. res.set_content("test", "text/plain");
  15471. });
  15472. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15473. auto se = detail::scope_exit([&] {
  15474. svr.stop();
  15475. t.join();
  15476. ASSERT_FALSE(svr.is_running());
  15477. });
  15478. svr.wait_until_ready();
  15479. {
  15480. SSLClient cli(HOST, PORT);
  15481. cli.enable_server_certificate_verification(false);
  15482. cli.set_keep_alive(true);
  15483. auto res = cli.Get("/test");
  15484. ASSERT_TRUE(res);
  15485. ASSERT_EQ(StatusCode::OK_200, res->status);
  15486. // cli is destructed here with the keep-alive SSL session still open.
  15487. }
  15488. }
  15489. #endif
  15490. // WebSocket Tests
  15491. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15492. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15493. // defining the meaning of these bits has been negotiated.
  15494. auto make_frame = [](uint8_t first_byte) {
  15495. std::string frame;
  15496. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15497. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15498. frame += "Hello";
  15499. return frame;
  15500. };
  15501. // RSV1 set (0x40)
  15502. {
  15503. detail::BufferStream strm;
  15504. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15505. ws::Opcode opcode;
  15506. std::string payload;
  15507. bool fin;
  15508. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15509. false, 1024));
  15510. }
  15511. // RSV2 set (0x20)
  15512. {
  15513. detail::BufferStream strm;
  15514. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15515. ws::Opcode opcode;
  15516. std::string payload;
  15517. bool fin;
  15518. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15519. false, 1024));
  15520. }
  15521. // RSV3 set (0x10)
  15522. {
  15523. detail::BufferStream strm;
  15524. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15525. ws::Opcode opcode;
  15526. std::string payload;
  15527. bool fin;
  15528. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15529. false, 1024));
  15530. }
  15531. // No RSV bits set - should succeed
  15532. {
  15533. detail::BufferStream strm;
  15534. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15535. ws::Opcode opcode;
  15536. std::string payload;
  15537. bool fin;
  15538. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15539. false, 1024));
  15540. EXPECT_EQ(ws::Opcode::Text, opcode);
  15541. EXPECT_EQ("Hello", payload);
  15542. EXPECT_TRUE(fin);
  15543. }
  15544. }
  15545. TEST(WebSocketTest, ControlFrameValidation) {
  15546. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15547. // payload length <= 125.
  15548. // Ping with FIN=0 - must be rejected
  15549. {
  15550. detail::BufferStream strm;
  15551. std::string frame;
  15552. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15553. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15554. strm.write(frame.data(), frame.size());
  15555. ws::Opcode opcode;
  15556. std::string payload;
  15557. bool fin;
  15558. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15559. false, 1024));
  15560. }
  15561. // Close with FIN=0 - must be rejected
  15562. {
  15563. detail::BufferStream strm;
  15564. std::string frame;
  15565. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15566. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15567. strm.write(frame.data(), frame.size());
  15568. ws::Opcode opcode;
  15569. std::string payload;
  15570. bool fin;
  15571. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15572. false, 1024));
  15573. }
  15574. // Ping with payload_len=126 (extended length) - must be rejected
  15575. {
  15576. detail::BufferStream strm;
  15577. std::string frame;
  15578. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15579. frame += static_cast<char>(126); // payload_len=126 (>125)
  15580. frame += static_cast<char>(0x00); // extended length high byte
  15581. frame += static_cast<char>(126); // extended length low byte
  15582. frame += std::string(126, 'x');
  15583. strm.write(frame.data(), frame.size());
  15584. ws::Opcode opcode;
  15585. std::string payload;
  15586. bool fin;
  15587. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15588. false, 1024));
  15589. }
  15590. // Ping with FIN=1 and payload_len=125 - should succeed
  15591. {
  15592. detail::BufferStream strm;
  15593. std::string frame;
  15594. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15595. frame += static_cast<char>(125); // payload_len=125
  15596. frame += std::string(125, 'x');
  15597. strm.write(frame.data(), frame.size());
  15598. ws::Opcode opcode;
  15599. std::string payload;
  15600. bool fin;
  15601. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15602. false, 1024));
  15603. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15604. EXPECT_EQ(125u, payload.size());
  15605. EXPECT_TRUE(fin);
  15606. }
  15607. }
  15608. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15609. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15610. // length MUST be 0.
  15611. // MSB set - must be rejected
  15612. {
  15613. detail::BufferStream strm;
  15614. std::string frame;
  15615. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15616. frame += static_cast<char>(127); // 64-bit extended length
  15617. frame += static_cast<char>(0x80); // MSB set (invalid)
  15618. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15619. strm.write(frame.data(), frame.size());
  15620. ws::Opcode opcode;
  15621. std::string payload;
  15622. bool fin;
  15623. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15624. false, 1024));
  15625. }
  15626. // MSB clear - should pass length parsing (will be rejected by max_len,
  15627. // but that's a different check; use a small length to verify)
  15628. {
  15629. detail::BufferStream strm;
  15630. std::string frame;
  15631. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15632. frame += static_cast<char>(127); // 64-bit extended length
  15633. frame += std::string(7, '\0'); // high bytes = 0
  15634. frame += static_cast<char>(0x03); // length = 3
  15635. frame += "abc";
  15636. strm.write(frame.data(), frame.size());
  15637. ws::Opcode opcode;
  15638. std::string payload;
  15639. bool fin;
  15640. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15641. false, 1024));
  15642. EXPECT_EQ(ws::Opcode::Text, opcode);
  15643. EXPECT_EQ("abc", payload);
  15644. }
  15645. }
  15646. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15647. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15648. // Valid UTF-8
  15649. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15650. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15651. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15652. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15653. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15654. // Invalid UTF-8
  15655. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15656. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15657. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15658. EXPECT_FALSE(
  15659. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15660. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15661. }
  15662. TEST(WebSocketTest, ConnectAndDisconnect) {
  15663. Server svr;
  15664. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15665. std::string msg;
  15666. while (ws.read(msg)) {}
  15667. });
  15668. auto port = svr.bind_to_any_port(HOST);
  15669. std::thread t([&]() { svr.listen_after_bind(); });
  15670. svr.wait_until_ready();
  15671. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15672. ASSERT_TRUE(client.connect());
  15673. EXPECT_TRUE(client.is_open());
  15674. client.close();
  15675. EXPECT_FALSE(client.is_open());
  15676. svr.stop();
  15677. t.join();
  15678. }
  15679. TEST(WebSocketTest, ValidURL) {
  15680. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15681. EXPECT_TRUE(ws1.is_valid());
  15682. ws::WebSocketClient ws2("ws://example.com/path");
  15683. EXPECT_TRUE(ws2.is_valid());
  15684. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15685. EXPECT_TRUE(ws3.is_valid());
  15686. #ifdef CPPHTTPLIB_SSL_ENABLED
  15687. ws::WebSocketClient wss1("wss://example.com/path");
  15688. EXPECT_TRUE(wss1.is_valid());
  15689. ws::WebSocketClient wss2("wss://example.com:443/path");
  15690. EXPECT_TRUE(wss2.is_valid());
  15691. #endif
  15692. }
  15693. TEST(WebSocketTest, InvalidURL) {
  15694. // No scheme
  15695. ws::WebSocketClient ws1("localhost:8080/path");
  15696. EXPECT_FALSE(ws1.is_valid());
  15697. // No path
  15698. ws::WebSocketClient ws2("ws://localhost:8080");
  15699. EXPECT_FALSE(ws2.is_valid());
  15700. // Empty string
  15701. ws::WebSocketClient ws3("");
  15702. EXPECT_FALSE(ws3.is_valid());
  15703. // Missing host
  15704. ws::WebSocketClient ws4("ws://:8080/path");
  15705. EXPECT_FALSE(ws4.is_valid());
  15706. // Port number overflow — should not crash
  15707. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15708. EXPECT_FALSE(ws5.is_valid());
  15709. // Port out of range
  15710. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15711. EXPECT_FALSE(ws6.is_valid());
  15712. }
  15713. TEST(WebSocketTest, UnsupportedScheme) {
  15714. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15715. ws::WebSocketClient ws1("http://localhost:8080/path");
  15716. EXPECT_FALSE(ws1.is_valid());
  15717. ws::WebSocketClient ws2("https://localhost:8080/path");
  15718. EXPECT_FALSE(ws2.is_valid());
  15719. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15720. EXPECT_FALSE(ws3.is_valid());
  15721. #else
  15722. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15723. std::invalid_argument);
  15724. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15725. std::invalid_argument);
  15726. #endif
  15727. }
  15728. TEST(WebSocketTest, ConnectWhenInvalid) {
  15729. ws::WebSocketClient ws("not a valid url");
  15730. EXPECT_FALSE(ws.is_valid());
  15731. EXPECT_FALSE(ws.connect());
  15732. }
  15733. TEST(WebSocketTest, DefaultPort) {
  15734. ws::WebSocketClient ws1("ws://example.com/path");
  15735. EXPECT_TRUE(ws1.is_valid());
  15736. // ws:// defaults to port 80 (verified by successful parse)
  15737. #ifdef CPPHTTPLIB_SSL_ENABLED
  15738. ws::WebSocketClient ws2("wss://example.com/path");
  15739. EXPECT_TRUE(ws2.is_valid());
  15740. // wss:// defaults to port 443 (verified by successful parse)
  15741. #endif
  15742. }
  15743. TEST(WebSocketTest, IPv6LiteralAddress) {
  15744. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15745. EXPECT_TRUE(ws1.is_valid());
  15746. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15747. EXPECT_TRUE(ws2.is_valid());
  15748. }
  15749. TEST(WebSocketTest, ComplexPath) {
  15750. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15751. EXPECT_TRUE(ws1.is_valid());
  15752. ws::WebSocketClient ws2("ws://localhost:8080/");
  15753. EXPECT_TRUE(ws2.is_valid());
  15754. }
  15755. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15756. Server svr;
  15757. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15758. std::string msg;
  15759. while (ws.read(msg)) {}
  15760. });
  15761. auto port = svr.bind_to_any_port(HOST);
  15762. std::thread t([&]() { svr.listen_after_bind(); });
  15763. svr.wait_until_ready();
  15764. auto another_host = "example.com";
  15765. auto wrong_ip = "192.0.2.1";
  15766. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15767. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15768. ASSERT_TRUE(client.connect());
  15769. EXPECT_TRUE(client.is_open());
  15770. client.close();
  15771. svr.stop();
  15772. t.join();
  15773. }
  15774. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15775. Server svr;
  15776. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15777. std::string msg;
  15778. while (ws.read(msg)) {}
  15779. });
  15780. auto port = svr.bind_to_any_port(HOST);
  15781. std::thread t([&]() { svr.listen_after_bind(); });
  15782. svr.wait_until_ready();
  15783. auto wrong_ip = "192.0.2.1";
  15784. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15785. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15786. client.set_connection_timeout(1);
  15787. client.set_read_timeout(1);
  15788. client.set_write_timeout(1);
  15789. EXPECT_FALSE(client.connect());
  15790. EXPECT_FALSE(client.is_open());
  15791. svr.stop();
  15792. t.join();
  15793. }
  15794. class WebSocketIntegrationTest : public ::testing::Test {
  15795. protected:
  15796. void SetUp() override {
  15797. server_ = httplib::detail::make_unique<Server>();
  15798. setup_server();
  15799. start_server();
  15800. }
  15801. void TearDown() override {
  15802. server_->stop();
  15803. if (server_thread_.joinable()) { server_thread_.join(); }
  15804. }
  15805. void setup_server() {
  15806. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15807. std::string msg;
  15808. ws::ReadResult ret;
  15809. while ((ret = ws.read(msg))) {
  15810. if (ret == ws::Binary) {
  15811. ws.send(msg.data(), msg.size());
  15812. } else {
  15813. ws.send(msg);
  15814. }
  15815. }
  15816. });
  15817. server_->WebSocket("/ws-echo-string",
  15818. [](const Request &, ws::WebSocket &ws) {
  15819. std::string msg;
  15820. while (ws.read(msg)) {
  15821. ws.send("echo: " + msg);
  15822. }
  15823. });
  15824. server_->WebSocket(
  15825. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15826. // Echo back request metadata
  15827. ws.send("path:" + req.path);
  15828. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15829. std::string msg;
  15830. while (ws.read(msg)) {}
  15831. });
  15832. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15833. std::string msg;
  15834. ws.read(msg); // wait for a message
  15835. ws.close();
  15836. });
  15837. server_->WebSocket("/ws-close-status",
  15838. [](const Request &, ws::WebSocket &ws) {
  15839. std::string msg;
  15840. ws.read(msg); // wait for a message
  15841. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15842. });
  15843. server_->WebSocket(
  15844. "/ws-subprotocol",
  15845. [](const Request &, ws::WebSocket &ws) {
  15846. std::string msg;
  15847. while (ws.read(msg)) {
  15848. ws.send(msg);
  15849. }
  15850. },
  15851. [](const std::vector<std::string> &protocols) -> std::string {
  15852. for (const auto &p : protocols) {
  15853. if (p == "graphql-ws") { return p; }
  15854. }
  15855. return "";
  15856. });
  15857. }
  15858. void start_server() {
  15859. port_ = server_->bind_to_any_port(HOST);
  15860. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15861. server_->wait_until_ready();
  15862. }
  15863. std::unique_ptr<Server> server_;
  15864. std::thread server_thread_;
  15865. int port_ = 0;
  15866. };
  15867. TEST_F(WebSocketIntegrationTest, TextEcho) {
  15868. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15869. "/ws-echo");
  15870. ASSERT_TRUE(client.connect());
  15871. ASSERT_TRUE(client.is_open());
  15872. ASSERT_TRUE(client.send("Hello WebSocket"));
  15873. std::string msg;
  15874. EXPECT_EQ(ws::Text, client.read(msg));
  15875. EXPECT_EQ("Hello WebSocket", msg);
  15876. client.close();
  15877. }
  15878. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  15879. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15880. "/ws-echo");
  15881. ASSERT_TRUE(client.connect());
  15882. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  15883. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  15884. std::string msg;
  15885. EXPECT_EQ(ws::Binary, client.read(msg));
  15886. EXPECT_EQ(binary_data, msg);
  15887. client.close();
  15888. }
  15889. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  15890. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15891. "/ws-echo");
  15892. ASSERT_TRUE(client.connect());
  15893. for (int i = 0; i < 10; i++) {
  15894. auto text = "message " + std::to_string(i);
  15895. ASSERT_TRUE(client.send(text));
  15896. std::string msg;
  15897. ASSERT_TRUE(client.read(msg));
  15898. EXPECT_EQ(text, msg);
  15899. }
  15900. client.close();
  15901. }
  15902. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  15903. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15904. "/ws-close");
  15905. ASSERT_TRUE(client.connect());
  15906. // Send a message to trigger the server to close
  15907. ASSERT_TRUE(client.send("trigger close"));
  15908. // The server will close, so read should return false
  15909. std::string msg;
  15910. EXPECT_FALSE(client.read(msg));
  15911. EXPECT_FALSE(client.is_open());
  15912. }
  15913. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  15914. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15915. "/ws-echo");
  15916. ASSERT_TRUE(client.connect());
  15917. // 128KB message
  15918. std::string large_data(128 * 1024, 'X');
  15919. ASSERT_TRUE(client.send(large_data));
  15920. std::string msg;
  15921. ASSERT_TRUE(client.read(msg));
  15922. EXPECT_EQ(large_data, msg);
  15923. client.close();
  15924. }
  15925. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  15926. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15927. "/ws-echo");
  15928. ASSERT_TRUE(client.connect());
  15929. const int num_threads = 4;
  15930. std::vector<std::thread> threads;
  15931. std::atomic<int> send_count{0};
  15932. for (int t = 0; t < num_threads; t++) {
  15933. threads.emplace_back([&client, &send_count, t]() {
  15934. for (int i = 0; i < 5; i++) {
  15935. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15936. if (client.send(text)) { send_count++; }
  15937. }
  15938. });
  15939. }
  15940. for (auto &th : threads) {
  15941. th.join();
  15942. }
  15943. int received = 0;
  15944. std::string msg;
  15945. while (received < send_count.load()) {
  15946. if (!client.read(msg)) { break; }
  15947. received++;
  15948. }
  15949. EXPECT_EQ(send_count.load(), received);
  15950. client.close();
  15951. }
  15952. TEST_F(WebSocketIntegrationTest, ReadString) {
  15953. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15954. "/ws-echo-string");
  15955. ASSERT_TRUE(client.connect());
  15956. ASSERT_TRUE(client.send("hello"));
  15957. std::string msg;
  15958. ASSERT_TRUE(client.read(msg));
  15959. EXPECT_EQ("echo: hello", msg);
  15960. ASSERT_TRUE(client.send("world"));
  15961. ASSERT_TRUE(client.read(msg));
  15962. EXPECT_EQ("echo: world", msg);
  15963. client.close();
  15964. }
  15965. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15966. Headers headers = {{"X-Test-Header", "test-value"}};
  15967. ws::WebSocketClient client(
  15968. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15969. ASSERT_TRUE(client.connect());
  15970. std::string msg;
  15971. ASSERT_TRUE(client.read(msg));
  15972. EXPECT_EQ("path:/ws-request-info", msg);
  15973. ASSERT_TRUE(client.read(msg));
  15974. EXPECT_EQ("header:test-value", msg);
  15975. client.close();
  15976. }
  15977. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15978. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15979. "/ws-echo");
  15980. client.set_read_timeout(1, 0); // 1 second
  15981. ASSERT_TRUE(client.connect());
  15982. // Don't send anything — server echo handler waits for a message,
  15983. // so read() should time out and return false.
  15984. std::string msg;
  15985. EXPECT_FALSE(client.read(msg));
  15986. }
  15987. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15989. "/ws-echo");
  15990. client.set_read_timeout(5, 0);
  15991. ASSERT_TRUE(client.connect());
  15992. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15993. // The server should reject it and close the connection.
  15994. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15995. client.send(oversized);
  15996. // The server's read() should have failed due to payload limit,
  15997. // so our read() should return false (connection closed).
  15998. std::string msg;
  15999. EXPECT_FALSE(client.read(msg));
  16000. }
  16001. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16002. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16003. "/ws-echo");
  16004. client.set_read_timeout(10, 0);
  16005. ASSERT_TRUE(client.connect());
  16006. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16007. // This should succeed.
  16008. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16009. ASSERT_TRUE(client.send(at_limit));
  16010. std::string msg;
  16011. ASSERT_TRUE(client.read(msg));
  16012. EXPECT_EQ(at_limit.size(), msg.size());
  16013. client.close();
  16014. }
  16015. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16016. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16017. "/nonexistent");
  16018. EXPECT_FALSE(client.connect());
  16019. EXPECT_FALSE(client.is_open());
  16020. }
  16021. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16023. "/ws-echo");
  16024. ASSERT_TRUE(client.connect());
  16025. ASSERT_TRUE(client.send(""));
  16026. std::string msg;
  16027. EXPECT_EQ(ws::Text, client.read(msg));
  16028. EXPECT_EQ("", msg);
  16029. client.close();
  16030. }
  16031. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16032. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16033. "/ws-echo");
  16034. // First connection
  16035. ASSERT_TRUE(client.connect());
  16036. ASSERT_TRUE(client.send("first"));
  16037. std::string msg;
  16038. ASSERT_TRUE(client.read(msg));
  16039. EXPECT_EQ("first", msg);
  16040. client.close();
  16041. EXPECT_FALSE(client.is_open());
  16042. // Reconnect using the same client object
  16043. ASSERT_TRUE(client.connect());
  16044. ASSERT_TRUE(client.is_open());
  16045. ASSERT_TRUE(client.send("second"));
  16046. ASSERT_TRUE(client.read(msg));
  16047. EXPECT_EQ("second", msg);
  16048. client.close();
  16049. }
  16050. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16051. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16052. "/ws-close-status");
  16053. ASSERT_TRUE(client.connect());
  16054. // Trigger the server to close with GoingAway status
  16055. ASSERT_TRUE(client.send("trigger"));
  16056. // read() should return false after receiving the close frame
  16057. std::string msg;
  16058. EXPECT_FALSE(client.read(msg));
  16059. EXPECT_FALSE(client.is_open());
  16060. }
  16061. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16062. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16063. "/ws-echo");
  16064. ASSERT_TRUE(client.connect());
  16065. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16066. EXPECT_FALSE(client.is_open());
  16067. }
  16068. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16069. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16070. ws::WebSocketClient client(
  16071. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16072. ASSERT_TRUE(client.connect());
  16073. // Server should have selected graphql-ws
  16074. EXPECT_EQ("graphql-ws", client.subprotocol());
  16075. client.close();
  16076. }
  16077. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16078. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16079. ws::WebSocketClient client(
  16080. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16081. ASSERT_TRUE(client.connect());
  16082. // Server should not have selected any subprotocol
  16083. EXPECT_TRUE(client.subprotocol().empty());
  16084. client.close();
  16085. }
  16086. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16087. // Connect without requesting any subprotocol
  16088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16089. "/ws-subprotocol");
  16090. ASSERT_TRUE(client.connect());
  16091. EXPECT_TRUE(client.subprotocol().empty());
  16092. client.close();
  16093. }
  16094. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16095. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16096. "/ws-echo");
  16097. client.set_tcp_nodelay(true);
  16098. client.set_connection_timeout(3, 0);
  16099. bool socket_options_called = false;
  16100. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16101. ASSERT_TRUE(client.connect());
  16102. ASSERT_TRUE(client.is_open());
  16103. EXPECT_TRUE(socket_options_called);
  16104. ASSERT_TRUE(client.send("hello"));
  16105. std::string msg;
  16106. auto result = client.read(msg);
  16107. EXPECT_EQ(result, ws::ReadResult::Text);
  16108. EXPECT_EQ(msg, "hello");
  16109. client.close();
  16110. }
  16111. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16112. Server svr;
  16113. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16114. if (!req.has_header("Authorization")) {
  16115. res.status = StatusCode::Unauthorized_401;
  16116. res.set_content("Unauthorized", "text/plain");
  16117. return Server::HandlerResponse::Handled;
  16118. }
  16119. return Server::HandlerResponse::Unhandled;
  16120. });
  16121. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16122. std::string msg;
  16123. while (ws.read(msg)) {
  16124. ws.send(msg);
  16125. }
  16126. });
  16127. auto port = svr.bind_to_any_port("localhost");
  16128. std::thread t([&]() { svr.listen_after_bind(); });
  16129. svr.wait_until_ready();
  16130. // Without Authorization header - should be rejected before upgrade
  16131. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16132. EXPECT_FALSE(client1.connect());
  16133. // With Authorization header - should succeed
  16134. Headers headers = {{"Authorization", "Bearer token123"}};
  16135. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16136. headers);
  16137. ASSERT_TRUE(client2.connect());
  16138. ASSERT_TRUE(client2.send("hello"));
  16139. std::string msg;
  16140. ASSERT_TRUE(client2.read(msg));
  16141. EXPECT_EQ("hello", msg);
  16142. client2.close();
  16143. svr.stop();
  16144. t.join();
  16145. }
  16146. TEST(WebSocketTest, QueryStringInHandshake) {
  16147. Server svr;
  16148. std::mutex mtx;
  16149. std::string received_target;
  16150. std::string received_token;
  16151. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16152. {
  16153. std::lock_guard<std::mutex> lock(mtx);
  16154. received_target = req.target;
  16155. if (req.has_param("token")) {
  16156. received_token = req.get_param_value("token");
  16157. }
  16158. }
  16159. std::string msg;
  16160. while (ws.read(msg)) {
  16161. ws.send(msg);
  16162. }
  16163. });
  16164. auto port = svr.bind_to_any_port("localhost");
  16165. std::thread t([&]() { svr.listen_after_bind(); });
  16166. svr.wait_until_ready();
  16167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16168. "/ws?token=ABC&session=123");
  16169. ASSERT_TRUE(client.connect());
  16170. // Round-trip ensures the handler has run and captured the request.
  16171. ASSERT_TRUE(client.send("hello"));
  16172. std::string msg;
  16173. ASSERT_TRUE(client.read(msg));
  16174. EXPECT_EQ("hello", msg);
  16175. client.close();
  16176. {
  16177. std::lock_guard<std::mutex> lock(mtx);
  16178. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16179. EXPECT_EQ("ABC", received_token);
  16180. }
  16181. svr.stop();
  16182. t.join();
  16183. }
  16184. TEST(WebSocketTest, HostHeaderInHandshake) {
  16185. Server svr;
  16186. std::mutex mtx;
  16187. std::string received_host;
  16188. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16189. {
  16190. std::lock_guard<std::mutex> lock(mtx);
  16191. received_host = req.get_header_value("Host");
  16192. }
  16193. std::string msg;
  16194. while (ws.read(msg)) {
  16195. ws.send(msg);
  16196. }
  16197. });
  16198. auto port = svr.bind_to_any_port("localhost");
  16199. std::thread t([&]() { svr.listen_after_bind(); });
  16200. svr.wait_until_ready();
  16201. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16202. ASSERT_TRUE(client.connect());
  16203. // Round-trip ensures the handler has run and captured the request.
  16204. ASSERT_TRUE(client.send("hello"));
  16205. std::string msg;
  16206. ASSERT_TRUE(client.read(msg));
  16207. client.close();
  16208. {
  16209. std::lock_guard<std::mutex> lock(mtx);
  16210. // Non-default port must be present in the Host header. Default ports
  16211. // (80/443) are omitted; that logic is covered by
  16212. // MakeHostAndPortStringTest.
  16213. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16214. }
  16215. svr.stop();
  16216. t.join();
  16217. }
  16218. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16219. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16220. protected:
  16221. void SetUp() override {
  16222. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16223. SERVER_PRIVATE_KEY_FILE);
  16224. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16225. std::string msg;
  16226. ws::ReadResult ret;
  16227. while ((ret = ws.read(msg))) {
  16228. if (ret == ws::Binary) {
  16229. ws.send(msg.data(), msg.size());
  16230. } else {
  16231. ws.send(msg);
  16232. }
  16233. }
  16234. });
  16235. port_ = server_->bind_to_any_port(HOST);
  16236. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16237. server_->wait_until_ready();
  16238. }
  16239. void TearDown() override {
  16240. server_->stop();
  16241. if (server_thread_.joinable()) { server_thread_.join(); }
  16242. }
  16243. std::unique_ptr<SSLServer> server_;
  16244. std::thread server_thread_;
  16245. int port_ = 0;
  16246. };
  16247. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16248. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16249. "/ws-echo");
  16250. client.enable_server_certificate_verification(false);
  16251. ASSERT_TRUE(client.connect());
  16252. ASSERT_TRUE(client.is_open());
  16253. ASSERT_TRUE(client.send("Hello WSS"));
  16254. std::string msg;
  16255. EXPECT_EQ(ws::Text, client.read(msg));
  16256. EXPECT_EQ("Hello WSS", msg);
  16257. client.close();
  16258. }
  16259. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16260. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16261. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16262. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16263. // client (without calling close() first) is the only path that runs
  16264. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16265. // bug exactly.
  16266. //
  16267. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16268. // when linked against an instrumented libssl; run under Valgrind to catch it
  16269. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16270. // suite (the freed session otherwise stalls on the close handshake) — this test
  16271. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16272. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16273. {
  16274. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16275. "/ws-echo");
  16276. client.enable_server_certificate_verification(false);
  16277. client.set_read_timeout(2, 0);
  16278. client.set_write_timeout(2, 0);
  16279. ASSERT_TRUE(client.connect());
  16280. ASSERT_TRUE(client.is_open());
  16281. ASSERT_TRUE(client.send("still open"));
  16282. // Intentionally do NOT call client.close(): leaving scope runs
  16283. // shutdown_and_close() with the WebSocket still open, which must send the
  16284. // close frame while the TLS session is still alive.
  16285. }
  16286. }
  16287. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16288. // shutdown_and_close() at the start of connect(), reproducing the same
  16289. // use-after-free within the test body rather than at scope exit. The second
  16290. // connect must succeed and echo, proving the close handshake ran over a live
  16291. // session. See the note above about memory-tool requirements.
  16292. TEST_F(WebSocketSSLIntegrationTest,
  16293. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16294. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16295. "/ws-echo");
  16296. client.enable_server_certificate_verification(false);
  16297. client.set_read_timeout(2, 0);
  16298. client.set_write_timeout(2, 0);
  16299. ASSERT_TRUE(client.connect());
  16300. ASSERT_TRUE(client.is_open());
  16301. ASSERT_TRUE(client.send("still open"));
  16302. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16303. // the still-open connection, which must not touch a freed TLS session.
  16304. ASSERT_TRUE(client.connect());
  16305. ASSERT_TRUE(client.is_open());
  16306. ASSERT_TRUE(client.send("after reconnect"));
  16307. std::string msg;
  16308. EXPECT_EQ(ws::Text, client.read(msg));
  16309. EXPECT_EQ("after reconnect", msg);
  16310. client.close();
  16311. }
  16312. #endif
  16313. #ifdef CPPHTTPLIB_SSL_ENABLED
  16314. class WebSocketSSLCATest : public ::testing::Test {
  16315. protected:
  16316. void SetUp() override {
  16317. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16318. SERVER_PRIVATE_KEY_FILE);
  16319. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16320. std::string msg;
  16321. while (ws.read(msg)) {
  16322. ws.send(msg);
  16323. }
  16324. });
  16325. port_ = server_->bind_to_any_port("127.0.0.1");
  16326. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16327. server_->wait_until_ready();
  16328. }
  16329. void TearDown() override {
  16330. server_->stop();
  16331. if (server_thread_.joinable()) { server_thread_.join(); }
  16332. }
  16333. std::string url() const {
  16334. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16335. }
  16336. std::unique_ptr<SSLServer> server_;
  16337. std::thread server_thread_;
  16338. int port_ = 0;
  16339. };
  16340. // A custom CA loaded as PEM verifies the server with full certificate
  16341. // verification enabled
  16342. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16343. ws::WebSocketClient client(url());
  16344. std::string cert;
  16345. read_file(SERVER_CERT2_FILE, cert);
  16346. client.load_ca_cert_store(cert.c_str(), cert.size());
  16347. ASSERT_TRUE(client.connect());
  16348. ASSERT_TRUE(client.send("hello"));
  16349. std::string msg;
  16350. EXPECT_EQ(ws::Text, client.read(msg));
  16351. EXPECT_EQ("hello", msg);
  16352. client.close();
  16353. }
  16354. // A custom CA that does not cover the server must fail verification (the
  16355. // custom CA is exclusive; system certs are not loaded alongside it)
  16356. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16357. ws::WebSocketClient client(url());
  16358. std::string cert;
  16359. read_file(CLIENT_CA_CERT_FILE, cert);
  16360. client.load_ca_cert_store(cert.c_str(), cert.size());
  16361. ASSERT_FALSE(client.connect());
  16362. }
  16363. // Regression test: reconnecting with a native custom CA store used to reuse
  16364. // a store handle the previous TLS context had already freed (use-after-free
  16365. // under the OpenSSL backend). The context now lives as long as the client.
  16366. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16367. ws::WebSocketClient client(url());
  16368. std::string cert;
  16369. read_file(SERVER_CERT2_FILE, cert);
  16370. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16371. ASSERT_TRUE(client.connect());
  16372. client.close();
  16373. ASSERT_TRUE(client.connect());
  16374. ASSERT_TRUE(client.send("again"));
  16375. std::string msg;
  16376. EXPECT_EQ(ws::Text, client.read(msg));
  16377. EXPECT_EQ("again", msg);
  16378. client.close();
  16379. }
  16380. // Regression test: a certificate with a trusted chain but no identity match
  16381. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16382. // verification entirely for IP hosts, so this connection succeeded there.
  16383. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16384. // chain verification while the identity check must still fail.
  16385. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16387. ASSERT_TRUE(svr.is_valid());
  16388. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16389. std::string msg;
  16390. while (ws.read(msg)) {
  16391. ws.send(msg);
  16392. }
  16393. });
  16394. auto port = svr.bind_to_any_port("127.0.0.1");
  16395. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16396. auto se = detail::scope_exit([&] {
  16397. svr.stop();
  16398. t.join();
  16399. });
  16400. svr.wait_until_ready();
  16401. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16402. "/echo");
  16403. std::string cert;
  16404. read_file(SERVER_CERT_FILE, cert);
  16405. client.load_ca_cert_store(cert.c_str(), cert.size());
  16406. ASSERT_FALSE(client.connect());
  16407. }
  16408. #endif
  16409. #if !defined(_WIN32)
  16410. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16411. auto secret_dir = std::string("./symlink_test_secret");
  16412. auto served_dir = std::string("./symlink_test_served");
  16413. auto secret_file = secret_dir + "/secret.txt";
  16414. auto symlink_path = served_dir + "/escape";
  16415. // Setup: create directories and files
  16416. mkdir(secret_dir.c_str(), 0755);
  16417. mkdir(served_dir.c_str(), 0755);
  16418. {
  16419. std::ofstream ofs(secret_file);
  16420. ofs << "SECRET_DATA";
  16421. }
  16422. // Create symlink using absolute path so it resolves correctly
  16423. #ifdef PATH_MAX
  16424. char abs_secret[PATH_MAX];
  16425. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16426. #else
  16427. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16428. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16429. ASSERT_NE(nullptr, abs_secret);
  16430. #endif
  16431. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16432. auto se = detail::scope_exit([&] {
  16433. unlink(symlink_path.c_str());
  16434. unlink(secret_file.c_str());
  16435. rmdir(served_dir.c_str());
  16436. rmdir(secret_dir.c_str());
  16437. });
  16438. Server svr;
  16439. svr.set_mount_point("/", served_dir);
  16440. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16441. auto se2 = detail::scope_exit([&] {
  16442. svr.stop();
  16443. listen_thread.join();
  16444. });
  16445. svr.wait_until_ready();
  16446. Client cli("localhost", PORT);
  16447. // Symlink pointing outside base dir should be blocked
  16448. auto res = cli.Get("/escape/secret.txt");
  16449. ASSERT_TRUE(res);
  16450. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16451. }
  16452. #endif
  16453. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16454. // A GET request with Content-Length to a static file handler must have its
  16455. // body drained before the keep-alive connection is reused. Otherwise the
  16456. // unread body bytes are interpreted as the next HTTP request.
  16457. //
  16458. // The body is sent AFTER receiving the first response (as in the original
  16459. // PoC) so that the stream_line_reader cannot buffer it together with the
  16460. // headers of the first request.
  16461. Server svr;
  16462. svr.set_mount_point("/", "./www");
  16463. std::atomic<int> smuggled_count(0);
  16464. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16465. smuggled_count++;
  16466. res.set_content("oops", "text/plain");
  16467. });
  16468. auto port = svr.bind_to_any_port("localhost");
  16469. thread t = thread([&] { svr.listen_after_bind(); });
  16470. auto se = detail::scope_exit([&] {
  16471. svr.stop();
  16472. t.join();
  16473. });
  16474. svr.wait_until_ready();
  16475. auto error = Error::Success;
  16476. auto sock = detail::create_client_socket(
  16477. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16478. /*connection_timeout_sec=*/2, 0,
  16479. /*read_timeout_sec=*/2, 0,
  16480. /*write_timeout_sec=*/2, 0, std::string(), error);
  16481. ASSERT_NE(INVALID_SOCKET, sock);
  16482. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16483. // The "smuggled" request will be sent as the body of the outer GET
  16484. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16485. "Host: localhost\r\n"
  16486. "Connection: close\r\n"
  16487. "\r\n";
  16488. // Step 1: Send only the outer request headers (no body yet)
  16489. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16490. "Host: localhost\r\n"
  16491. "Content-Length: " +
  16492. std::to_string(smuggled.size()) +
  16493. "\r\n"
  16494. "\r\n";
  16495. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16496. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16497. // Step 2: Read the first response (server serves file without reading body)
  16498. std::string first_response;
  16499. char buf[4096];
  16500. for (;;) {
  16501. auto n = recv(sock, buf, sizeof(buf), 0);
  16502. if (n <= 0) break;
  16503. first_response.append(buf, static_cast<size_t>(n));
  16504. // Stop once we have a complete response (headers + body)
  16505. auto hdr_end = first_response.find("\r\n\r\n");
  16506. if (hdr_end != std::string::npos) {
  16507. // Check for Content-Length to know when the body is complete
  16508. auto cl_pos = first_response.find("Content-Length:");
  16509. if (cl_pos != std::string::npos) {
  16510. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16511. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16512. auto cl = std::stoul(
  16513. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16514. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16515. } else {
  16516. break; // No Content-Length, assume headers-only response
  16517. }
  16518. }
  16519. }
  16520. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16521. // Step 3: Now send the body, which looks like a new HTTP request.
  16522. // On a vulnerable server the keep-alive loop reads this as a second request.
  16523. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16524. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16525. // Step 4: Try to read a second response (should NOT exist after fix)
  16526. std::string second_response;
  16527. for (;;) {
  16528. auto n = recv(sock, buf, sizeof(buf), 0);
  16529. if (n <= 0) break;
  16530. second_response.append(buf, static_cast<size_t>(n));
  16531. }
  16532. // The smuggled request must NOT have been processed
  16533. EXPECT_EQ(0, smuggled_count.load());
  16534. }
  16535. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16536. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16537. // must be rejected with 400 Bad Request.
  16538. Server svr;
  16539. svr.Post("/test", [&](const Request &, Response &res) {
  16540. res.set_content("ok", "text/plain");
  16541. });
  16542. thread t = thread([&] { svr.listen(HOST, PORT); });
  16543. auto se = detail::scope_exit([&] {
  16544. svr.stop();
  16545. t.join();
  16546. ASSERT_FALSE(svr.is_running());
  16547. });
  16548. svr.wait_until_ready();
  16549. // Exact "chunked"
  16550. {
  16551. auto req = "POST /test HTTP/1.1\r\n"
  16552. "Host: localhost\r\n"
  16553. "Content-Length: 5\r\n"
  16554. "Transfer-Encoding: chunked\r\n"
  16555. "Connection: close\r\n"
  16556. "\r\n"
  16557. "hello";
  16558. std::string response;
  16559. ASSERT_TRUE(send_request(1, req, &response));
  16560. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16561. response.substr(0, response.find("\r\n")));
  16562. }
  16563. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16564. {
  16565. auto req = "POST /test HTTP/1.1\r\n"
  16566. "Host: localhost\r\n"
  16567. "Content-Length: 5\r\n"
  16568. "Transfer-Encoding: gzip, chunked\r\n"
  16569. "Connection: close\r\n"
  16570. "\r\n"
  16571. "hello";
  16572. std::string response;
  16573. ASSERT_TRUE(send_request(1, req, &response));
  16574. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16575. response.substr(0, response.find("\r\n")));
  16576. }
  16577. }
  16578. // Regression for issue #2450: a DELETE without Content-Length on a
  16579. // keep-alive connection must not let the post-response drain consume the
  16580. // next request's bytes.
  16581. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16582. Server svr;
  16583. std::atomic<int> delete_count(0);
  16584. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16585. delete_count++;
  16586. res.status = StatusCode::NoContent_204;
  16587. });
  16588. auto port = svr.bind_to_any_port(HOST);
  16589. thread t = thread([&] { svr.listen_after_bind(); });
  16590. auto se = detail::scope_exit([&] {
  16591. svr.stop();
  16592. t.join();
  16593. });
  16594. svr.wait_until_ready();
  16595. auto error = Error::Success;
  16596. auto sock = detail::create_client_socket(
  16597. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16598. /*connection_timeout_sec=*/2, 0,
  16599. /*read_timeout_sec=*/2, 0,
  16600. /*write_timeout_sec=*/2, 0, std::string(), error);
  16601. ASSERT_NE(INVALID_SOCKET, sock);
  16602. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16603. auto send_request_and_read_response = [&](const std::string &req,
  16604. std::string &out) -> bool {
  16605. auto sent = send(sock, req.data(), req.size(), 0);
  16606. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16607. char buf[4096];
  16608. for (;;) {
  16609. auto n = recv(sock, buf, sizeof(buf), 0);
  16610. if (n <= 0) { return !out.empty(); }
  16611. out.append(buf, static_cast<size_t>(n));
  16612. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16613. }
  16614. };
  16615. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16616. "Host: localhost\r\n"
  16617. "\r\n";
  16618. std::string resp1;
  16619. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16620. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16621. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16622. "Host: localhost\r\n"
  16623. "Connection: close\r\n"
  16624. "\r\n";
  16625. std::string resp2;
  16626. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16627. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16628. EXPECT_EQ(2, delete_count.load());
  16629. }
  16630. namespace no_proxy_test {
  16631. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16632. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16633. // calling listen().
  16634. class ScopedServer {
  16635. public:
  16636. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16637. ~ScopedServer() {
  16638. svr_.stop();
  16639. if (th_.joinable()) { th_.join(); }
  16640. }
  16641. Server &svr() { return svr_; }
  16642. int port() const { return port_; }
  16643. void listen() {
  16644. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16645. svr_.wait_until_ready();
  16646. }
  16647. private:
  16648. Server svr_;
  16649. std::thread th_;
  16650. int port_ = 0;
  16651. };
  16652. class ProxyAndTargetServers {
  16653. public:
  16654. ProxyAndTargetServers() {
  16655. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16656. proxy_hits_++;
  16657. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16658. res.set_content("via-proxy", "text/plain");
  16659. });
  16660. target_.Get(".*", [this](const Request &req, Response &res) {
  16661. target_hits_++;
  16662. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16663. res.set_content("direct", "text/plain");
  16664. });
  16665. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16666. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16667. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16668. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16669. proxy_mock_.wait_until_ready();
  16670. target_.wait_until_ready();
  16671. }
  16672. ~ProxyAndTargetServers() {
  16673. proxy_mock_.stop();
  16674. target_.stop();
  16675. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16676. if (target_thread_.joinable()) { target_thread_.join(); }
  16677. }
  16678. Server &proxy_mock() { return proxy_mock_; }
  16679. Server &target() { return target_; }
  16680. int proxy_port() const { return proxy_port_; }
  16681. int target_port() const { return target_port_; }
  16682. int proxy_hits() const { return proxy_hits_.load(); }
  16683. int target_hits() const { return target_hits_.load(); }
  16684. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16685. void reset_counters() {
  16686. proxy_hits_ = 0;
  16687. target_hits_ = 0;
  16688. last_had_proxy_authz_ = false;
  16689. }
  16690. private:
  16691. Server proxy_mock_;
  16692. Server target_;
  16693. std::thread proxy_thread_;
  16694. std::thread target_thread_;
  16695. int proxy_port_ = 0;
  16696. int target_port_ = 0;
  16697. std::atomic<int> proxy_hits_{0};
  16698. std::atomic<int> target_hits_{0};
  16699. std::atomic<bool> last_had_proxy_authz_{false};
  16700. };
  16701. inline std::unique_ptr<Client> make_client(const std::string &host,
  16702. ProxyAndTargetServers &s) {
  16703. auto cli = detail::make_unique<Client>(host, s.target_port());
  16704. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16705. cli->set_proxy("127.0.0.1", s.proxy_port());
  16706. return cli;
  16707. }
  16708. } // namespace no_proxy_test
  16709. using no_proxy_test::make_client;
  16710. using no_proxy_test::ProxyAndTargetServers;
  16711. TEST(NoProxyTest, ExactHostnameBypasses) {
  16712. ProxyAndTargetServers s;
  16713. auto cli = make_client("example.com", s);
  16714. cli->set_no_proxy({"example.com"});
  16715. auto res = cli->Get("/");
  16716. ASSERT_TRUE(res);
  16717. EXPECT_EQ(0, s.proxy_hits());
  16718. EXPECT_EQ(1, s.target_hits());
  16719. }
  16720. TEST(NoProxyTest, SubdomainBypasses) {
  16721. ProxyAndTargetServers s;
  16722. auto cli = make_client("foo.example.com", s);
  16723. cli->set_no_proxy({"example.com"});
  16724. auto res = cli->Get("/");
  16725. ASSERT_TRUE(res);
  16726. EXPECT_EQ(0, s.proxy_hits());
  16727. EXPECT_EQ(1, s.target_hits());
  16728. }
  16729. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16730. // Regression guard: "evilexample.com" must not be considered a subdomain
  16731. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16732. // check would let traffic bypass the proxy and leak credentials direct
  16733. // to the attacker host.
  16734. ProxyAndTargetServers s;
  16735. auto cli = make_client("evilexample.com", s);
  16736. cli->set_no_proxy({"example.com"});
  16737. auto res = cli->Get("/");
  16738. ASSERT_TRUE(res);
  16739. EXPECT_GE(s.proxy_hits(), 1);
  16740. EXPECT_EQ(0, s.target_hits());
  16741. }
  16742. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16743. ProxyAndTargetServers s;
  16744. auto cli = make_client("example.com.evil.com", s);
  16745. cli->set_no_proxy({"example.com"});
  16746. auto res = cli->Get("/");
  16747. ASSERT_TRUE(res);
  16748. EXPECT_GE(s.proxy_hits(), 1);
  16749. EXPECT_EQ(0, s.target_hits());
  16750. }
  16751. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16752. ProxyAndTargetServers s;
  16753. auto cli = make_client("example.com", s);
  16754. cli->set_no_proxy({".example.com"});
  16755. auto res = cli->Get("/");
  16756. ASSERT_TRUE(res);
  16757. EXPECT_EQ(0, s.proxy_hits());
  16758. EXPECT_EQ(1, s.target_hits());
  16759. }
  16760. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16761. ProxyAndTargetServers s;
  16762. auto cli = make_client("Example.COM", s);
  16763. cli->set_no_proxy({"EXAMPLE.com"});
  16764. auto res = cli->Get("/");
  16765. ASSERT_TRUE(res);
  16766. EXPECT_EQ(0, s.proxy_hits());
  16767. EXPECT_EQ(1, s.target_hits());
  16768. }
  16769. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16770. ProxyAndTargetServers s;
  16771. auto cli = make_client("example.com.", s);
  16772. cli->set_no_proxy({"example.com"});
  16773. auto res = cli->Get("/");
  16774. ASSERT_TRUE(res);
  16775. EXPECT_EQ(0, s.proxy_hits());
  16776. EXPECT_EQ(1, s.target_hits());
  16777. }
  16778. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16779. // Trailing dots must be normalized on BOTH sides — host and entry.
  16780. // An implementation that only strips the host-side trailing dot would
  16781. // fail to match host "example.com" against entry "example.com." because
  16782. // a literal substring search would compare 11 chars against 12.
  16783. ProxyAndTargetServers s;
  16784. auto cli = make_client("example.com", s);
  16785. cli->set_no_proxy({"example.com."});
  16786. auto res = cli->Get("/");
  16787. ASSERT_TRUE(res);
  16788. EXPECT_EQ(0, s.proxy_hits());
  16789. EXPECT_EQ(1, s.target_hits());
  16790. }
  16791. TEST(NoProxyTest, WildcardBypassesEverything) {
  16792. ProxyAndTargetServers s;
  16793. auto cli = make_client("anything.invalid.test", s);
  16794. cli->set_no_proxy({"*"});
  16795. auto res = cli->Get("/");
  16796. ASSERT_TRUE(res);
  16797. EXPECT_EQ(0, s.proxy_hits());
  16798. EXPECT_EQ(1, s.target_hits());
  16799. }
  16800. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16801. ProxyAndTargetServers s;
  16802. Client cli("127.0.0.1", s.target_port());
  16803. cli.set_proxy("127.0.0.1", s.proxy_port());
  16804. cli.set_no_proxy({"127.0.0.1"});
  16805. auto res = cli.Get("/");
  16806. ASSERT_TRUE(res);
  16807. EXPECT_EQ(0, s.proxy_hits());
  16808. EXPECT_EQ(1, s.target_hits());
  16809. }
  16810. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16811. ProxyAndTargetServers s;
  16812. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16813. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16814. cli.set_proxy("127.0.0.1", s.proxy_port());
  16815. cli.set_no_proxy({"::1"});
  16816. auto res = cli.Get("/");
  16817. ASSERT_TRUE(res);
  16818. EXPECT_EQ(0, s.proxy_hits());
  16819. EXPECT_EQ(1, s.target_hits());
  16820. }
  16821. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  16822. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  16823. // must still be recognized as IPv6 for CIDR matching. Implementations
  16824. // that detect IPv6 only when the host begins with '[' would parse the
  16825. // host as a hostname and miss the match.
  16826. ProxyAndTargetServers s;
  16827. Client cli("fe80::1", s.target_port());
  16828. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16829. cli.set_proxy("127.0.0.1", s.proxy_port());
  16830. cli.set_no_proxy({"fe80::/10"});
  16831. auto res = cli.Get("/");
  16832. ASSERT_TRUE(res);
  16833. EXPECT_EQ(0, s.proxy_hits());
  16834. EXPECT_EQ(1, s.target_hits());
  16835. }
  16836. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  16837. ProxyAndTargetServers s;
  16838. Client cli("::1", s.target_port());
  16839. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  16840. cli.set_proxy("127.0.0.1", s.proxy_port());
  16841. cli.set_no_proxy({"[::1]"});
  16842. auto res = cli.Get("/");
  16843. ASSERT_TRUE(res);
  16844. EXPECT_EQ(0, s.proxy_hits());
  16845. EXPECT_EQ(1, s.target_hits());
  16846. }
  16847. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  16848. ProxyAndTargetServers s;
  16849. Client cli("fe80::1", s.target_port());
  16850. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  16851. cli.set_proxy("127.0.0.1", s.proxy_port());
  16852. cli.set_no_proxy({"[fe80::]/10"});
  16853. auto res = cli.Get("/");
  16854. ASSERT_TRUE(res);
  16855. EXPECT_EQ(0, s.proxy_hits());
  16856. EXPECT_EQ(1, s.target_hits());
  16857. }
  16858. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  16859. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  16860. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  16861. // tricks via address-family conversion.
  16862. ProxyAndTargetServers s;
  16863. Client cli("::ffff:127.0.0.1", s.target_port());
  16864. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  16865. cli.set_proxy("127.0.0.1", s.proxy_port());
  16866. cli.set_no_proxy({"127.0.0.1"});
  16867. auto res = cli.Get("/");
  16868. ASSERT_TRUE(res);
  16869. EXPECT_GE(s.proxy_hits(), 1);
  16870. EXPECT_EQ(0, s.target_hits());
  16871. }
  16872. TEST(NoProxyTest, IPv4CidrMatch) {
  16873. ProxyAndTargetServers s;
  16874. Client cli("127.0.0.1", s.target_port());
  16875. cli.set_proxy("127.0.0.1", s.proxy_port());
  16876. cli.set_no_proxy({"127.0.0.0/8"});
  16877. auto res = cli.Get("/");
  16878. ASSERT_TRUE(res);
  16879. EXPECT_EQ(0, s.proxy_hits());
  16880. EXPECT_EQ(1, s.target_hits());
  16881. }
  16882. TEST(NoProxyTest, IPv4CidrNonMatch) {
  16883. ProxyAndTargetServers s;
  16884. Client cli("127.0.0.1", s.target_port());
  16885. cli.set_proxy("127.0.0.1", s.proxy_port());
  16886. cli.set_no_proxy({"10.0.0.0/8"});
  16887. auto res = cli.Get("/");
  16888. ASSERT_TRUE(res);
  16889. EXPECT_GE(s.proxy_hits(), 1);
  16890. EXPECT_EQ(0, s.target_hits());
  16891. }
  16892. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  16893. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  16894. // IPv4 target matches.
  16895. ProxyAndTargetServers s;
  16896. Client cli("127.0.0.1", s.target_port());
  16897. cli.set_proxy("127.0.0.1", s.proxy_port());
  16898. cli.set_no_proxy({"0.0.0.0/0"});
  16899. auto res = cli.Get("/");
  16900. ASSERT_TRUE(res);
  16901. EXPECT_EQ(0, s.proxy_hits());
  16902. EXPECT_EQ(1, s.target_hits());
  16903. }
  16904. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  16905. ProxyAndTargetServers s;
  16906. Client cli("127.0.0.1", s.target_port());
  16907. cli.set_proxy("127.0.0.1", s.proxy_port());
  16908. cli.set_no_proxy({"127.0.0.1"});
  16909. auto res = cli.Get("/");
  16910. ASSERT_TRUE(res);
  16911. EXPECT_EQ(0, s.proxy_hits());
  16912. EXPECT_EQ(1, s.target_hits());
  16913. }
  16914. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  16915. ProxyAndTargetServers s;
  16916. Client cli("127.0.0.1", s.target_port());
  16917. cli.set_proxy("127.0.0.1", s.proxy_port());
  16918. cli.set_no_proxy({"127.0.0.0/33"});
  16919. auto res = cli.Get("/");
  16920. ASSERT_TRUE(res);
  16921. EXPECT_GE(s.proxy_hits(), 1);
  16922. EXPECT_EQ(0, s.target_hits());
  16923. }
  16924. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  16925. // Empty prefix after the slash must be rejected, not silently treated as /32.
  16926. ProxyAndTargetServers s;
  16927. Client cli("127.0.0.1", s.target_port());
  16928. cli.set_proxy("127.0.0.1", s.proxy_port());
  16929. cli.set_no_proxy({"127.0.0.1/"});
  16930. auto res = cli.Get("/");
  16931. ASSERT_TRUE(res);
  16932. EXPECT_GE(s.proxy_hits(), 1);
  16933. EXPECT_EQ(0, s.target_hits());
  16934. }
  16935. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  16936. ProxyAndTargetServers s;
  16937. auto cli = make_client("internal.corp", s);
  16938. cli->set_proxy_basic_auth("u", "p");
  16939. cli->set_no_proxy({"internal.corp"});
  16940. auto res = cli->Get("/");
  16941. ASSERT_TRUE(res);
  16942. EXPECT_EQ(1, s.target_hits());
  16943. EXPECT_EQ(0, s.proxy_hits());
  16944. EXPECT_FALSE(s.last_had_proxy_authz())
  16945. << "Proxy-Authorization must not be sent direct to the target";
  16946. }
  16947. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  16948. ProxyAndTargetServers s;
  16949. auto cli = make_client("public.example", s);
  16950. cli->set_proxy_basic_auth("u", "p");
  16951. cli->set_no_proxy({"internal.corp"}); // does not match
  16952. auto res = cli->Get("/");
  16953. ASSERT_TRUE(res);
  16954. EXPECT_GE(s.proxy_hits(), 1);
  16955. EXPECT_TRUE(s.last_had_proxy_authz());
  16956. }
  16957. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  16958. ProxyAndTargetServers s;
  16959. auto cli = make_client("anything.test", s);
  16960. auto res = cli->Get("/");
  16961. ASSERT_TRUE(res);
  16962. EXPECT_GE(s.proxy_hits(), 1);
  16963. EXPECT_EQ(0, s.target_hits());
  16964. }
  16965. TEST(NoProxyTest, PortSpecificEntryRejected) {
  16966. ProxyAndTargetServers s;
  16967. auto cli = make_client("example.com", s);
  16968. cli->set_no_proxy({"example.com:8080"});
  16969. auto res = cli->Get("/");
  16970. ASSERT_TRUE(res);
  16971. EXPECT_GE(s.proxy_hits(), 1);
  16972. EXPECT_EQ(0, s.target_hits());
  16973. }
  16974. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  16975. ProxyAndTargetServers s;
  16976. auto cli = make_client("anything.test", s);
  16977. cli->set_no_proxy({"", " ", "\t"});
  16978. auto res = cli->Get("/");
  16979. ASSERT_TRUE(res);
  16980. EXPECT_GE(s.proxy_hits(), 1);
  16981. EXPECT_EQ(0, s.target_hits());
  16982. }
  16983. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  16984. // An entry with leading/trailing whitespace must still match — env-style
  16985. // values are commonly pasted with stray spaces and an implementation
  16986. // that feeds the raw token directly to inet_pton would fail to match
  16987. // valid CIDRs because of the spaces.
  16988. ProxyAndTargetServers s;
  16989. Client cli("127.0.0.1", s.target_port());
  16990. cli.set_proxy("127.0.0.1", s.proxy_port());
  16991. cli.set_no_proxy({" 127.0.0.0/8 "});
  16992. auto res = cli.Get("/");
  16993. ASSERT_TRUE(res);
  16994. EXPECT_EQ(0, s.proxy_hits());
  16995. EXPECT_EQ(1, s.target_hits());
  16996. }
  16997. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  16998. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  16999. // go direct and must NOT carry Proxy-Authorization.
  17000. std::atomic<int> proxy_hits{0};
  17001. std::atomic<int> target_hits{0};
  17002. std::atomic<bool> target_saw_authz{false};
  17003. no_proxy_test::ScopedServer proxy_mock, target;
  17004. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17005. proxy_hits++;
  17006. res.status = 302;
  17007. res.set_header("Location", "http://127.0.0.1:" +
  17008. std::to_string(target.port()) + "/landed");
  17009. });
  17010. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17011. target_hits++;
  17012. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17013. res.set_content("direct", "text/plain");
  17014. });
  17015. proxy_mock.listen();
  17016. target.listen();
  17017. Client cli("public.example", target.port());
  17018. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17019. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17020. cli.set_proxy_basic_auth("u", "p");
  17021. cli.set_no_proxy({"127.0.0.1"});
  17022. cli.set_follow_location(true);
  17023. auto res = cli.Get("/redir");
  17024. ASSERT_TRUE(res);
  17025. EXPECT_GE(proxy_hits.load(), 1);
  17026. EXPECT_GE(target_hits.load(), 1);
  17027. EXPECT_FALSE(target_saw_authz.load());
  17028. }
  17029. #ifdef CPPHTTPLIB_SSL_ENABLED
  17030. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17031. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17032. // proxy creds would be sent to the (possibly hostile) origin.
  17033. std::atomic<int> target_hits{0};
  17034. std::atomic<bool> target_saw_proxy_authz{false};
  17035. no_proxy_test::ScopedServer target;
  17036. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17037. target_hits++;
  17038. if (req.has_header("Proxy-Authorization")) {
  17039. target_saw_proxy_authz = true;
  17040. }
  17041. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17042. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17043. "nonce=\"abc\", algorithm=MD5");
  17044. });
  17045. target.listen();
  17046. // The proxy address is set to the target's port: the bypass MUST kick in;
  17047. // if it doesn't, the test still routes "via proxy" to the same server and
  17048. // the Proxy-Authorization assertion below catches the leak.
  17049. Client cli("evil.example", target.port());
  17050. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17051. cli.set_proxy("127.0.0.1", target.port());
  17052. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17053. cli.set_no_proxy({"evil.example"});
  17054. auto res = cli.Get("/x");
  17055. ASSERT_TRUE(res);
  17056. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17057. EXPECT_EQ(1, target_hits.load());
  17058. EXPECT_FALSE(target_saw_proxy_authz.load());
  17059. }
  17060. #endif
  17061. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17062. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17063. std::atomic<int> proxy_hits{0};
  17064. std::atomic<int> bypass_hits{0};
  17065. std::atomic<bool> proxy_saw_c_url{false};
  17066. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17067. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17068. proxy_hits++;
  17069. if (req.path.find("/start") != std::string::npos) {
  17070. res.status = 302;
  17071. res.set_header("Location", "http://127.0.0.1:" +
  17072. std::to_string(bypass_server.port()) +
  17073. "/middle");
  17074. return;
  17075. }
  17076. if (req.path.find("/end") != std::string::npos) {
  17077. proxy_saw_c_url = true;
  17078. res.set_content("c-via-proxy", "text/plain");
  17079. return;
  17080. }
  17081. res.set_content("unexpected", "text/plain");
  17082. });
  17083. // public.example's "advertised" port is arbitrary (the request never lands
  17084. // there — it goes through the proxy), but use a dynamic value to stay
  17085. // friendly with sharded parallel runs.
  17086. int public_port = bypass_server.port();
  17087. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17088. bypass_hits++;
  17089. res.status = 302;
  17090. res.set_header("Location", "http://public.example:" +
  17091. std::to_string(public_port) + "/end");
  17092. });
  17093. proxy_mock.listen();
  17094. bypass_server.listen();
  17095. Client cli("public.example", public_port);
  17096. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17097. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17098. cli.set_no_proxy({"127.0.0.1"});
  17099. cli.set_follow_location(true);
  17100. auto res = cli.Get("/start");
  17101. ASSERT_TRUE(res);
  17102. EXPECT_EQ(StatusCode::OK_200, res->status);
  17103. EXPECT_EQ("c-via-proxy", res->body);
  17104. EXPECT_GE(proxy_hits.load(), 2);
  17105. EXPECT_GE(bypass_hits.load(), 1);
  17106. EXPECT_TRUE(proxy_saw_c_url.load());
  17107. }
  17108. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17109. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17110. // request reconnects to the correct endpoint.
  17111. std::atomic<int> proxy_hits{0};
  17112. std::atomic<int> target_hits{0};
  17113. no_proxy_test::ScopedServer proxy_mock, target;
  17114. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17115. proxy_hits++;
  17116. res.set_content("via-proxy", "text/plain");
  17117. });
  17118. target.svr().Get(".*", [&](const Request &, Response &res) {
  17119. target_hits++;
  17120. res.set_content("direct", "text/plain");
  17121. });
  17122. proxy_mock.listen();
  17123. target.listen();
  17124. Client cli("public.example", target.port());
  17125. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17126. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17127. cli.set_keep_alive(true);
  17128. auto res1 = cli.Get("/a");
  17129. ASSERT_TRUE(res1);
  17130. EXPECT_EQ("via-proxy", res1->body);
  17131. EXPECT_EQ(1, proxy_hits.load());
  17132. EXPECT_EQ(0, target_hits.load());
  17133. cli.set_no_proxy({"public.example"});
  17134. auto res2 = cli.Get("/b");
  17135. ASSERT_TRUE(res2);
  17136. EXPECT_EQ("direct", res2->body);
  17137. EXPECT_EQ(1, proxy_hits.load());
  17138. EXPECT_EQ(1, target_hits.load());
  17139. }
  17140. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17141. namespace proxy_tunnel_test {
  17142. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17143. class ScopedSSLServer {
  17144. public:
  17145. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17146. port_ = svr_.bind_to_any_port("127.0.0.1");
  17147. }
  17148. ~ScopedSSLServer() {
  17149. svr_.stop();
  17150. if (th_.joinable()) { th_.join(); }
  17151. }
  17152. SSLServer &svr() { return svr_; }
  17153. int port() const { return port_; }
  17154. void listen() {
  17155. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17156. svr_.wait_until_ready();
  17157. }
  17158. private:
  17159. SSLServer svr_;
  17160. std::thread th_;
  17161. int port_ = 0;
  17162. };
  17163. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17164. class ScopedConnectProxy {
  17165. public:
  17166. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17167. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17168. if (listen_fd_ < 0) { return; }
  17169. int yes = 1;
  17170. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17171. sockaddr_in a{};
  17172. a.sin_family = AF_INET;
  17173. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17174. a.sin_port = 0;
  17175. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17176. return;
  17177. }
  17178. socklen_t alen = sizeof(a);
  17179. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17180. 0) {
  17181. return;
  17182. }
  17183. port_ = ntohs(a.sin_port);
  17184. if (::listen(listen_fd_, 1) != 0) { return; }
  17185. th_ = std::thread([this] { run(); });
  17186. }
  17187. ~ScopedConnectProxy() {
  17188. stop_ = true;
  17189. if (listen_fd_ >= 0) {
  17190. ::shutdown(listen_fd_, SHUT_RDWR);
  17191. ::close(listen_fd_);
  17192. }
  17193. if (th_.joinable()) { th_.join(); }
  17194. }
  17195. int port() const { return port_; }
  17196. int connect_hits() const { return connect_hits_.load(); }
  17197. private:
  17198. void run() {
  17199. while (!stop_.load()) {
  17200. fd_set rfds;
  17201. FD_ZERO(&rfds);
  17202. FD_SET(listen_fd_, &rfds);
  17203. timeval tv{0, 100 * 1000};
  17204. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17205. if (sel <= 0) { continue; }
  17206. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17207. if (client_fd < 0) { continue; }
  17208. std::string req;
  17209. char buf[2048];
  17210. while (req.find("\r\n\r\n") == std::string::npos) {
  17211. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17212. if (n <= 0) { break; }
  17213. req.append(buf, static_cast<size_t>(n));
  17214. }
  17215. if (req.compare(0, 7, "CONNECT") != 0) {
  17216. ::close(client_fd);
  17217. continue;
  17218. }
  17219. connect_hits_++;
  17220. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17221. ::send(client_fd, ok, std::strlen(ok), 0);
  17222. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17223. sockaddr_in o{};
  17224. o.sin_family = AF_INET;
  17225. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17226. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17227. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17228. 0) {
  17229. ::close(client_fd);
  17230. ::close(origin_fd);
  17231. continue;
  17232. }
  17233. auto forward = [](int from, int to) {
  17234. char b[8192];
  17235. for (;;) {
  17236. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17237. if (n <= 0) { break; }
  17238. ssize_t off = 0;
  17239. while (off < n) {
  17240. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17241. if (s <= 0) {
  17242. off = n;
  17243. break;
  17244. }
  17245. off += s;
  17246. }
  17247. }
  17248. ::shutdown(to, SHUT_WR);
  17249. };
  17250. std::thread t1([&] { forward(client_fd, origin_fd); });
  17251. std::thread t2([&] { forward(origin_fd, client_fd); });
  17252. t1.join();
  17253. t2.join();
  17254. ::close(client_fd);
  17255. ::close(origin_fd);
  17256. }
  17257. }
  17258. int forward_port_ = -1;
  17259. int listen_fd_ = -1;
  17260. int port_ = 0;
  17261. std::thread th_;
  17262. std::atomic<bool> stop_{false};
  17263. std::atomic<int> connect_hits_{0};
  17264. };
  17265. } // namespace proxy_tunnel_test
  17266. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17267. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17268. // retry; otherwise proxy creds would be sent to the origin.
  17269. std::atomic<int> origin_hits{0};
  17270. std::atomic<bool> origin_saw_proxy_authz{false};
  17271. proxy_tunnel_test::ScopedSSLServer origin;
  17272. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17273. origin_hits++;
  17274. if (req.has_header("Proxy-Authorization")) {
  17275. origin_saw_proxy_authz = true;
  17276. }
  17277. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17278. res.set_header("Proxy-Authenticate",
  17279. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17280. "algorithm=MD5");
  17281. });
  17282. origin.listen();
  17283. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17284. ASSERT_NE(0, proxy.port());
  17285. SSLClient cli(HOST, origin.port());
  17286. cli.enable_server_certificate_verification(false);
  17287. cli.set_proxy(HOST, proxy.port());
  17288. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17289. auto res = cli.Get("/x");
  17290. ASSERT_TRUE(res);
  17291. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17292. EXPECT_EQ(1, origin_hits.load());
  17293. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17294. EXPECT_EQ(1, proxy.connect_hits());
  17295. }
  17296. #endif