test.cc 664 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  38. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  39. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  40. #define CA_CERT_FILE "./ca-bundle.crt"
  41. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  42. #define CLIENT_CA_CERT_DIR "."
  43. #define CLIENT_CERT_FILE "./client.cert.pem"
  44. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  45. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  46. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  47. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  48. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  49. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  50. #else
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  52. #endif
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  54. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  55. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  56. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  57. #ifdef CPPHTTPLIB_SSL_ENABLED
  58. namespace httplib {
  59. namespace tls {
  60. // Declared here for the split build, where the TLS abstraction declarations
  61. // live below the split border; the definition is linked from httplib.cc.
  62. ca_store_t create_ca_store(const char *pem, size_t len);
  63. } // namespace tls
  64. } // namespace httplib
  65. #endif
  66. using namespace std;
  67. using namespace httplib;
  68. const char *HOST = "localhost";
  69. static int get_base_port() {
  70. const char *shard = getenv("GTEST_SHARD_INDEX");
  71. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  72. }
  73. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  74. // New standalone tests MUST use svr.bind_to_any_port() instead.
  75. const int PORT = get_base_port();
  76. const string LONG_QUERY_VALUE = string(25000, '@');
  77. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  78. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  79. const string TOO_LONG_QUERY_URL =
  80. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  81. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  82. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  83. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  84. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  85. return file.name == key;
  86. });
  87. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  88. return *it;
  89. #else
  90. if (it != items.end()) { return *it; }
  91. throw std::runtime_error("invalid multipart form data name error");
  92. #endif
  93. }
  94. static void read_file(const std::string &path, std::string &out) {
  95. std::ifstream fs(path, std::ios_base::binary);
  96. if (!fs) {
  97. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  98. return;
  99. #else
  100. throw std::runtime_error("File not found: " + path);
  101. #endif
  102. }
  103. fs.seekg(0, std::ios_base::end);
  104. auto size = fs.tellg();
  105. fs.seekg(0);
  106. out.resize(static_cast<size_t>(size));
  107. fs.read(&out[0], static_cast<std::streamsize>(size));
  108. }
  109. class UnixSocketTest : public ::testing::Test {
  110. protected:
  111. void TearDown() override { std::remove(pathname_.c_str()); }
  112. void client_GET(const std::string &addr) {
  113. httplib::Client cli{addr};
  114. cli.set_address_family(AF_UNIX);
  115. ASSERT_TRUE(cli.is_valid());
  116. const auto &result = cli.Get(pattern_);
  117. ASSERT_TRUE(result) << "error: " << result.error();
  118. const auto &resp = result.value();
  119. EXPECT_EQ(resp.status, StatusCode::OK_200);
  120. EXPECT_EQ(resp.body, content_);
  121. }
  122. static std::string make_sock_path() {
  123. const char *shard = getenv("GTEST_SHARD_INDEX");
  124. return shard ? std::string("./httplib-server-") + shard + ".sock"
  125. : "./httplib-server.sock";
  126. }
  127. const std::string pathname_{make_sock_path()};
  128. const std::string pattern_{"/hi"};
  129. const std::string content_{"Hello World!"};
  130. };
  131. TEST_F(UnixSocketTest, pathname) {
  132. httplib::Server svr;
  133. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  134. res.set_content(content_, "text/plain");
  135. });
  136. std::thread t{[&] {
  137. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  138. }};
  139. auto se = detail::scope_exit([&] {
  140. svr.stop();
  141. t.join();
  142. ASSERT_FALSE(svr.is_running());
  143. });
  144. svr.wait_until_ready();
  145. ASSERT_TRUE(svr.is_running());
  146. client_GET(pathname_);
  147. }
  148. #if defined(__linux__) || \
  149. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  150. TEST_F(UnixSocketTest, PeerPid) {
  151. httplib::Server svr;
  152. std::string remote_port_val;
  153. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  154. res.set_content(content_, "text/plain");
  155. remote_port_val = std::to_string(req.remote_port);
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. client_GET(pathname_);
  168. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  169. }
  170. #endif
  171. #ifdef __linux__
  172. TEST_F(UnixSocketTest, abstract) {
  173. constexpr char svr_path[]{"\x00httplib-server.sock"};
  174. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  175. httplib::Server svr;
  176. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  177. res.set_content(content_, "text/plain");
  178. });
  179. std::thread t{[&] {
  180. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  181. }};
  182. auto se = detail::scope_exit([&] {
  183. svr.stop();
  184. t.join();
  185. ASSERT_FALSE(svr.is_running());
  186. });
  187. svr.wait_until_ready();
  188. ASSERT_TRUE(svr.is_running());
  189. client_GET(abstract_addr);
  190. }
  191. #endif
  192. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  193. httplib::Server svr;
  194. std::string received_host_header;
  195. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  196. // Capture the Host header sent by the client
  197. auto host_iter = req.headers.find("Host");
  198. if (host_iter != req.headers.end()) {
  199. received_host_header = host_iter->second;
  200. }
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. // Test that Host header is automatically set to "localhost" for Unix socket
  214. // connections
  215. httplib::Client cli{pathname_};
  216. cli.set_address_family(AF_UNIX);
  217. ASSERT_TRUE(cli.is_valid());
  218. const auto &result = cli.Get(pattern_);
  219. ASSERT_TRUE(result) << "error: " << result.error();
  220. const auto &resp = result.value();
  221. EXPECT_EQ(resp.status, StatusCode::OK_200);
  222. EXPECT_EQ(resp.body, content_);
  223. // Verify that Host header was automatically set to "localhost"
  224. EXPECT_EQ(received_host_header, "localhost");
  225. }
  226. #ifndef _WIN32
  227. TEST(SocketStream, wait_writable_UNIX) {
  228. int fds[2];
  229. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  230. const auto asSocketStream = [&](socket_t fd,
  231. std::function<bool(Stream &)> func) {
  232. return detail::process_client_socket(
  233. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  234. };
  235. asSocketStream(fds[0], [&](Stream &s0) {
  236. EXPECT_EQ(s0.socket(), fds[0]);
  237. EXPECT_TRUE(s0.wait_writable());
  238. EXPECT_TRUE(s0.is_peer_alive());
  239. EXPECT_EQ(0, close(fds[1]));
  240. EXPECT_FALSE(s0.is_peer_alive());
  241. return true;
  242. });
  243. EXPECT_EQ(0, close(fds[0]));
  244. }
  245. TEST(SocketStream, wait_writable_INET) {
  246. sockaddr_in addr;
  247. memset(&addr, 0, sizeof(addr));
  248. addr.sin_family = AF_INET;
  249. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  250. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  251. int disconnected_svr_sock = -1;
  252. std::thread svr{[&] {
  253. const int s = socket(AF_INET, SOCK_STREAM, 0);
  254. ASSERT_LE(0, s);
  255. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  256. ASSERT_EQ(0, listen(s, 1));
  257. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  258. ASSERT_EQ(0, close(s));
  259. }};
  260. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  261. std::thread cli{[&] {
  262. const int s = socket(AF_INET, SOCK_STREAM, 0);
  263. ASSERT_LE(0, s);
  264. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  265. ASSERT_EQ(0, close(s));
  266. }};
  267. cli.join();
  268. svr.join();
  269. ASSERT_NE(disconnected_svr_sock, -1);
  270. const auto asSocketStream = [&](socket_t fd,
  271. std::function<bool(Stream &)> func) {
  272. return detail::process_client_socket(
  273. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  274. };
  275. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  276. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  277. // wait_writable() returns true because select_write() only checks if the
  278. // send buffer has space. Peer disconnection is detected later by send().
  279. EXPECT_TRUE(ss.wait_writable());
  280. return true;
  281. });
  282. ASSERT_EQ(0, close(disconnected_svr_sock));
  283. }
  284. #endif // #ifndef _WIN32
  285. TEST(SetSocketOptTest, TcpNoDelay) {
  286. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  287. ASSERT_NE(sock, INVALID_SOCKET);
  288. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  289. int val = 0;
  290. socklen_t len = sizeof(val);
  291. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  292. reinterpret_cast<char *>(&val), &len));
  293. EXPECT_NE(val, 0);
  294. detail::close_socket(sock);
  295. }
  296. TEST(ClientTest, MoveConstructible) {
  297. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  298. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  299. }
  300. TEST(ClientTest, MoveAssignable) {
  301. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  302. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  303. }
  304. #ifdef _WIN32
  305. TEST(StartupTest, WSAStartup) {
  306. WSADATA wsaData;
  307. int ret = WSAStartup(0x0002, &wsaData);
  308. ASSERT_EQ(0, ret);
  309. }
  310. #endif
  311. TEST(DecodePathTest, PercentCharacter) {
  312. EXPECT_EQ(
  313. decode_path_component(
  314. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  315. U8("descrip=Gastos áéíóúñÑ 6"));
  316. }
  317. TEST(DecodePathTest, PercentCharacterNUL) {
  318. string expected;
  319. expected.push_back('x');
  320. expected.push_back('\0');
  321. expected.push_back('x');
  322. EXPECT_EQ(decode_path_component("x%00x"), expected);
  323. }
  324. TEST(DecodePathTest, UnicodeEncoding) {
  325. // %u0041 = 'A' (1-byte UTF-8)
  326. EXPECT_EQ("A", decode_path_component("%u0041"));
  327. // %u00E9 = 'é' (2-byte UTF-8)
  328. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  329. // %u3042 = 'あ' (3-byte UTF-8)
  330. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  331. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  332. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  333. // %uD800 = surrogate (invalid, silently dropped)
  334. EXPECT_EQ("", decode_path_component("%uD800"));
  335. }
  336. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  337. // A sign or whitespace inside the two-character escape window must not be
  338. // accepted as a valid percent-encoding; the sequence is passed through
  339. // literally, matching decode_uri_component / decode_path_component.
  340. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  341. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  342. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  343. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  344. // Well-formed escapes still decode.
  345. EXPECT_EQ("-", decode_query_component("%2D", false));
  346. EXPECT_EQ("A", decode_query_component("%41", false));
  347. }
  348. TEST(SanitizeFilenameTest, VariousPatterns) {
  349. // Path traversal
  350. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  351. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  352. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  353. // Normal and edge cases
  354. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  355. EXPECT_EQ("filename.txt",
  356. httplib::sanitize_filename("/path/to/filename.txt"));
  357. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  358. EXPECT_EQ("", httplib::sanitize_filename(".."));
  359. EXPECT_EQ("", httplib::sanitize_filename(""));
  360. // Null bytes stripped
  361. EXPECT_EQ("safe.txt",
  362. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  363. // Whitespace-only rejected
  364. EXPECT_EQ("", httplib::sanitize_filename(" "));
  365. }
  366. // Forward declaration (see the base64_encode note below): split builds move the
  367. // definition into httplib.cc, so re-declaring it here lets the test link.
  368. namespace httplib {
  369. namespace detail {
  370. bool is_chunked_transfer_encoding(const Headers &headers);
  371. } // namespace detail
  372. } // namespace httplib
  373. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  374. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  375. auto make = [](std::initializer_list<const char *> lines) {
  376. Headers h;
  377. for (auto te : lines) {
  378. if (te) { h.emplace("Transfer-Encoding", te); }
  379. }
  380. return h;
  381. };
  382. // Sole coding, matched case-insensitively.
  383. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  384. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  386. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  388. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  390. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  391. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  392. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  395. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  396. // portable, so any line naming chunked is treated as chunked (fail safe).
  397. // The result must not depend on the order the lines were added.
  398. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  399. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  400. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  401. }
  402. // Forward declaration: in split builds split.py strips `inline` and moves the
  403. // definition into httplib.cc, so detail::base64_encode is not visible from the
  404. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  405. // in both header-only and split builds.
  406. namespace httplib {
  407. namespace detail {
  408. std::string base64_encode(const std::string &in);
  409. } // namespace detail
  410. } // namespace httplib
  411. TEST(Base64EncodeTest, KnownAnswers) {
  412. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  413. // where the accumulator's top bit is already set before the next shift.
  414. EXPECT_EQ("", detail::base64_encode(""));
  415. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  416. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  417. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  418. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  419. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  420. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  421. // High bytes keep the top bit set across several rounds.
  422. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  423. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  424. }
  425. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  426. string unescapedCharacters = "-_.!~*'()";
  427. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  428. }
  429. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  430. string reservedCharacters = ";,/?:@&=+$";
  431. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  432. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  433. }
  434. TEST(ClientQueryOrder, PreserveOrder) {
  435. // This test reproduces Issue #2259: client may reorder query parameters
  436. // when sending a GET request. The expected behavior is that the client
  437. // preserves the original query string order when the caller supplied it
  438. // as part of the path.
  439. Server svr;
  440. svr.Get("/", [&](const Request &req, Response &res) {
  441. // Echo back the raw target so the test can assert ordering
  442. res.set_content(req.target, "text/plain");
  443. });
  444. std::thread t{[&] { svr.listen(HOST, PORT); }};
  445. auto se = detail::scope_exit([&] {
  446. svr.stop();
  447. t.join();
  448. ASSERT_FALSE(svr.is_running());
  449. });
  450. svr.wait_until_ready();
  451. Client cli(HOST, PORT);
  452. ASSERT_TRUE(cli.is_valid());
  453. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  454. auto res = cli.Get(original);
  455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  456. // Expect the echoed target to exactly match the original path (order
  457. // preserved)
  458. EXPECT_EQ(res->body, original);
  459. }
  460. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  461. string chineseCharacters = U8("中国語");
  462. string russianCharacters = U8("дом");
  463. string brazilianCharacters = U8("óculos");
  464. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  465. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  466. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  467. "%D0%B4%D0%BE%D0%BC");
  468. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  469. }
  470. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  471. string unescapedCharacters = "-_.!~*'()";
  472. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  473. }
  474. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  475. string reservedCharacters = ";,/?:@&=+$";
  476. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  477. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  478. }
  479. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  480. string chineseCharacters = U8("中国語");
  481. string russianCharacters = U8("дом");
  482. string brazilianCharacters = U8("óculos");
  483. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  484. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  485. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  486. "%D0%B4%D0%BE%D0%BC");
  487. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  488. }
  489. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  490. // Issue #2082 use case: encoding path component with ampersand
  491. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  492. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  493. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  494. }
  495. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  496. string unescapedCharacters = "-_.!~*'()";
  497. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  498. }
  499. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  500. string reservedCharacters = ";,/?:@&=+$#";
  501. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  502. }
  503. TEST(EncodeUriTest, TestUTF8Characters) {
  504. string chineseCharacters = U8("中国語");
  505. string russianCharacters = U8("дом");
  506. string brazilianCharacters = U8("óculos");
  507. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  508. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  509. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  510. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  511. }
  512. TEST(EncodeUriTest, TestCompleteUri) {
  513. string uri =
  514. "https://example.com/path/to/resource?query=value&param=test#fragment";
  515. EXPECT_EQ(
  516. httplib::encode_uri(uri),
  517. "https://example.com/path/to/resource?query=value&param=test#fragment");
  518. }
  519. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  520. string uri =
  521. "https://example.com/path with spaces/file name.html?q=hello world";
  522. EXPECT_EQ(httplib::encode_uri(uri),
  523. "https://example.com/path%20with%20spaces/"
  524. "file%20name.html?q=hello%20world");
  525. }
  526. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  527. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  528. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  529. }
  530. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  531. string unescapedCharacters = "-_.!~*'()";
  532. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  533. }
  534. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  535. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  536. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  537. string encodedBrazilian = "%C3%B3culos";
  538. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  539. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  540. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  541. }
  542. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  543. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  544. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  545. "Piri Tommy Villiers - on & on");
  546. }
  547. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  548. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  549. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  550. }
  551. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  552. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  553. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  554. }
  555. TEST(DecodeUriTest, TestUTF8Characters) {
  556. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  557. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  558. string encodedBrazilian = "%C3%B3culos";
  559. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  560. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  561. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  562. }
  563. TEST(DecodeUriTest, TestCompleteUri) {
  564. string encodedUri = "https://example.com/path%20with%20spaces/"
  565. "file%20name.html?q=hello%20world";
  566. EXPECT_EQ(
  567. httplib::decode_uri(encodedUri),
  568. "https://example.com/path with spaces/file name.html?q=hello world");
  569. }
  570. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  571. string original =
  572. "https://example.com/path with spaces/file name.html?q=hello world";
  573. string encoded = httplib::encode_uri(original);
  574. string decoded = httplib::decode_uri(encoded);
  575. EXPECT_EQ(decoded, original);
  576. }
  577. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  578. string original = "Piri Tommy Villiers - on & on";
  579. string encoded = httplib::encode_uri_component(original);
  580. string decoded = httplib::decode_uri_component(encoded);
  581. EXPECT_EQ(decoded, original);
  582. }
  583. TEST(TrimTests, TrimStringTests) {
  584. EXPECT_EQ("abc", detail::trim_copy("abc"));
  585. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  586. EXPECT_TRUE(detail::trim_copy("").empty());
  587. }
  588. TEST(AsciiTest, LocaleIndependentClassification) {
  589. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  590. // which consult the global C locale: std::isalnum(0xC5) can return true
  591. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  592. // helpers must classify every byte by the ASCII grammar alone.
  593. for (int i = 0; i < 256; i++) {
  594. auto c = static_cast<char>(i);
  595. auto is_digit = i >= '0' && i <= '9';
  596. auto is_upper = i >= 'A' && i <= 'Z';
  597. auto is_lower = i >= 'a' && i <= 'z';
  598. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  599. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  600. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  601. << "byte " << i;
  602. }
  603. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  604. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  605. // Non-ASCII bytes must be percent-encoded, never passed through as
  606. // alphanumeric.
  607. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  608. }
  609. TEST(FromCharsTest, Double) {
  610. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  611. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  612. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  613. auto parse = [](const std::string &s, double &v) {
  614. return detail::from_chars(s.data(), s.data() + s.size(), v);
  615. };
  616. double v = -1.0;
  617. // Representative quality values.
  618. EXPECT_EQ(parse("0", v).ec, std::errc{});
  619. EXPECT_DOUBLE_EQ(v, 0.0);
  620. EXPECT_EQ(parse("1", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 1.0);
  622. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  623. EXPECT_DOUBLE_EQ(v, 0.8);
  624. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  625. EXPECT_DOUBLE_EQ(v, 0.001);
  626. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  627. EXPECT_DOUBLE_EQ(v, 1.0);
  628. // A missing integer or fractional part is tolerated.
  629. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  630. EXPECT_DOUBLE_EQ(v, 0.5);
  631. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 5.0);
  633. // Values outside [0, 1] still parse; the caller range-checks them.
  634. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  635. EXPECT_DOUBLE_EQ(v, 123.456);
  636. // Stops at the first byte that is not part of the number and reports where.
  637. std::string trailing = "0.9, text/html";
  638. auto r = parse(trailing, v);
  639. EXPECT_EQ(r.ec, std::errc{});
  640. EXPECT_DOUBLE_EQ(v, 0.9);
  641. EXPECT_EQ(*r.ptr, ',');
  642. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  643. // outright, and an 'e'/'E' simply ends the number.
  644. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  645. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  646. std::string exp_input = "1.5e3";
  647. r = parse(exp_input, v);
  648. EXPECT_EQ(r.ec, std::errc{});
  649. EXPECT_DOUBLE_EQ(v, 1.5);
  650. EXPECT_EQ(*r.ptr, 'e');
  651. // Invalid inputs.
  652. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  653. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  654. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  655. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  657. // Pathological but well-formed inputs must stay bounded (no overflow, no
  658. // out-of-bounds table access) and stay within [0, 1] for the caller.
  659. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  660. std::errc{});
  661. EXPECT_DOUBLE_EQ(v, 0.0);
  662. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  663. std::errc{});
  664. EXPECT_GE(v, 0.0);
  665. EXPECT_LE(v, 1.0);
  666. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  667. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  668. }
  669. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  670. // Simple case without quality values
  671. std::vector<std::string> result1;
  672. EXPECT_TRUE(detail::parse_accept_header(
  673. "text/html,application/json,text/plain", result1));
  674. EXPECT_EQ(result1.size(), 3U);
  675. EXPECT_EQ(result1[0], "text/html");
  676. EXPECT_EQ(result1[1], "application/json");
  677. EXPECT_EQ(result1[2], "text/plain");
  678. // With quality values
  679. std::vector<std::string> result2;
  680. EXPECT_TRUE(detail::parse_accept_header(
  681. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  682. EXPECT_EQ(result2.size(), 3U);
  683. EXPECT_EQ(result2[0], "application/json"); // highest q value
  684. EXPECT_EQ(result2[1], "text/html");
  685. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  686. }
  687. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  688. // Mixed with and without quality values
  689. std::vector<std::string> result;
  690. EXPECT_TRUE(detail::parse_accept_header(
  691. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  692. EXPECT_EQ(result.size(), 3U);
  693. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  694. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  695. EXPECT_EQ(result[2], "application/json"); // q=0.5
  696. }
  697. TEST(ParseAcceptHeaderTest, EdgeCases) {
  698. // Empty header
  699. std::vector<std::string> empty_result;
  700. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  701. EXPECT_TRUE(empty_result.empty());
  702. // Single type
  703. std::vector<std::string> single_result;
  704. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  705. EXPECT_EQ(single_result.size(), 1U);
  706. EXPECT_EQ(single_result[0], "application/json");
  707. // Wildcard types
  708. std::vector<std::string> wildcard_result;
  709. EXPECT_TRUE(detail::parse_accept_header(
  710. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  711. EXPECT_EQ(wildcard_result.size(), 3U);
  712. EXPECT_EQ(wildcard_result[0], "application/json");
  713. EXPECT_EQ(wildcard_result[1], "text/*");
  714. EXPECT_EQ(wildcard_result[2], "*/*");
  715. }
  716. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  717. // Common browser Accept header
  718. std::vector<std::string> browser_result;
  719. EXPECT_TRUE(
  720. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  721. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  722. browser_result));
  723. EXPECT_EQ(browser_result.size(), 6U);
  724. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  725. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  726. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  727. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  728. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  729. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  730. // API client header
  731. std::vector<std::string> api_result;
  732. EXPECT_TRUE(detail::parse_accept_header(
  733. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  734. api_result));
  735. EXPECT_EQ(api_result.size(), 3U);
  736. EXPECT_EQ(api_result[0], "application/json");
  737. EXPECT_EQ(api_result[1], "application/xml");
  738. EXPECT_EQ(api_result[2], "text/plain");
  739. }
  740. TEST(ParseAcceptHeaderTest, SpecialCases) {
  741. // Quality value with 3 decimal places
  742. std::vector<std::string> decimal_result;
  743. EXPECT_TRUE(detail::parse_accept_header(
  744. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  745. EXPECT_EQ(decimal_result.size(), 2U);
  746. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  747. EXPECT_EQ(decimal_result[1], "text/html");
  748. // Zero quality (should still be included but with lowest priority)
  749. std::vector<std::string> zero_q_result;
  750. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  751. zero_q_result));
  752. EXPECT_EQ(zero_q_result.size(), 2U);
  753. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  754. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  755. // No spaces around commas
  756. std::vector<std::string> no_space_result;
  757. EXPECT_TRUE(detail::parse_accept_header(
  758. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  759. no_space_result));
  760. EXPECT_EQ(no_space_result.size(), 3U);
  761. EXPECT_EQ(no_space_result[0], "text/html");
  762. EXPECT_EQ(no_space_result[1], "application/json");
  763. EXPECT_EQ(no_space_result[2], "text/plain");
  764. }
  765. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  766. // Quality values always use '.' as the decimal separator, so parsing must
  767. // not depend on the process locale. An embedding application may have
  768. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  769. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  770. std::string saved = cur ? cur : "C";
  771. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  772. "fr_FR.UTF-8"};
  773. bool switched = false;
  774. for (const auto loc : comma_locales) {
  775. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  776. std::localeconv()->decimal_point[0] == ',') {
  777. switched = true;
  778. break;
  779. }
  780. }
  781. if (!switched) {
  782. std::setlocale(LC_NUMERIC, saved.c_str());
  783. GTEST_SKIP() << "no comma-decimal locale available on this host";
  784. }
  785. // The higher-weighted type appears later in the list, so a correct parse
  786. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  787. // sensitive parse reads both weights as 0 and leaves the original order.
  788. std::vector<std::string> result;
  789. EXPECT_TRUE(detail::parse_accept_header(
  790. "application/json;q=0.1,text/html;q=0.9", result));
  791. ASSERT_EQ(result.size(), 2U);
  792. EXPECT_EQ(result[0], "text/html");
  793. EXPECT_EQ(result[1], "application/json");
  794. std::setlocale(LC_NUMERIC, saved.c_str());
  795. }
  796. TEST(ParseAcceptHeaderTest, InvalidCases) {
  797. std::vector<std::string> result;
  798. // Invalid quality value (> 1.0)
  799. EXPECT_FALSE(
  800. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  801. // Invalid quality value (< 0.0)
  802. EXPECT_FALSE(
  803. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  804. // Invalid quality value (not a number)
  805. EXPECT_FALSE(detail::parse_accept_header(
  806. "text/html;q=invalid,application/json", result));
  807. // Empty quality value
  808. EXPECT_FALSE(
  809. detail::parse_accept_header("text/html;q=,application/json", result));
  810. // Invalid media type format (no slash and not wildcard)
  811. EXPECT_FALSE(
  812. detail::parse_accept_header("invalidtype,application/json", result));
  813. // Empty media type
  814. result.clear();
  815. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  816. // Only commas
  817. result.clear();
  818. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  819. // Valid cases should still work
  820. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  821. EXPECT_EQ(result.size(), 1U);
  822. EXPECT_EQ(result[0], "*/*");
  823. EXPECT_TRUE(detail::parse_accept_header("*", result));
  824. EXPECT_EQ(result.size(), 1U);
  825. EXPECT_EQ(result[0], "*");
  826. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  827. EXPECT_EQ(result.size(), 1U);
  828. EXPECT_EQ(result[0], "text/*");
  829. }
  830. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  831. Server svr;
  832. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  833. EXPECT_EQ(req.accept_content_types.size(), 3U);
  834. EXPECT_EQ(req.accept_content_types[0], "application/json");
  835. EXPECT_EQ(req.accept_content_types[1], "text/html");
  836. EXPECT_EQ(req.accept_content_types[2], "*/*");
  837. res.set_content("ok", "text/plain");
  838. });
  839. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  840. EXPECT_TRUE(false);
  841. res.set_content("bad request", "text/plain");
  842. });
  843. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  844. auto se = detail::scope_exit([&] {
  845. svr.stop();
  846. listen_thread.join();
  847. ASSERT_FALSE(svr.is_running());
  848. });
  849. svr.wait_until_ready();
  850. Client cli("localhost", PORT);
  851. {
  852. auto res = cli.Get(
  853. "/accept_ok",
  854. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  856. EXPECT_EQ(StatusCode::OK_200, res->status);
  857. }
  858. {
  859. auto res = cli.Get("/accept_bad_request",
  860. Headers{{"Accept", "text/html;q=abc,application/json"}});
  861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  862. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  863. }
  864. }
  865. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  866. Server svr;
  867. svr.Get("/", [](const Request & /*req*/, Response &res) {
  868. res.set_content("ok", "text/plain");
  869. });
  870. std::atomic<int> start_count{0};
  871. std::atomic<bool> running_when_called{false};
  872. svr.set_start_handler([&]() {
  873. running_when_called = svr.is_running();
  874. start_count++;
  875. });
  876. auto port = svr.bind_to_any_port(HOST);
  877. std::thread t([&]() { svr.listen_after_bind(); });
  878. auto se = detail::scope_exit([&] {
  879. svr.stop();
  880. t.join();
  881. ASSERT_FALSE(svr.is_running());
  882. });
  883. svr.wait_until_ready();
  884. // A successful request proves the accept loop is running, which the start
  885. // handler precedes; so by now the handler must have run exactly once.
  886. Client cli(HOST, port);
  887. cli.set_connection_timeout(std::chrono::seconds(5));
  888. auto res = cli.Get("/");
  889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  890. EXPECT_EQ(StatusCode::OK_200, res->status);
  891. EXPECT_EQ(1, start_count.load());
  892. EXPECT_TRUE(running_when_called.load());
  893. }
  894. TEST(DivideTest, DivideStringTests) {
  895. auto divide = [](const std::string &str, char d) {
  896. std::string lhs;
  897. std::string rhs;
  898. detail::divide(str, d,
  899. [&](const char *lhs_data, std::size_t lhs_size,
  900. const char *rhs_data, std::size_t rhs_size) {
  901. lhs.assign(lhs_data, lhs_size);
  902. rhs.assign(rhs_data, rhs_size);
  903. });
  904. return std::make_pair(std::move(lhs), std::move(rhs));
  905. };
  906. {
  907. const auto res = divide("", '=');
  908. EXPECT_EQ(res.first, "");
  909. EXPECT_EQ(res.second, "");
  910. }
  911. {
  912. const auto res = divide("=", '=');
  913. EXPECT_EQ(res.first, "");
  914. EXPECT_EQ(res.second, "");
  915. }
  916. {
  917. const auto res = divide(" ", '=');
  918. EXPECT_EQ(res.first, " ");
  919. EXPECT_EQ(res.second, "");
  920. }
  921. {
  922. const auto res = divide("a", '=');
  923. EXPECT_EQ(res.first, "a");
  924. EXPECT_EQ(res.second, "");
  925. }
  926. {
  927. const auto res = divide("a=", '=');
  928. EXPECT_EQ(res.first, "a");
  929. EXPECT_EQ(res.second, "");
  930. }
  931. {
  932. const auto res = divide("=b", '=');
  933. EXPECT_EQ(res.first, "");
  934. EXPECT_EQ(res.second, "b");
  935. }
  936. {
  937. const auto res = divide("a=b", '=');
  938. EXPECT_EQ(res.first, "a");
  939. EXPECT_EQ(res.second, "b");
  940. }
  941. {
  942. const auto res = divide("a=b=", '=');
  943. EXPECT_EQ(res.first, "a");
  944. EXPECT_EQ(res.second, "b=");
  945. }
  946. {
  947. const auto res = divide("a=b=c", '=');
  948. EXPECT_EQ(res.first, "a");
  949. EXPECT_EQ(res.second, "b=c");
  950. }
  951. }
  952. TEST(SplitTest, ParseQueryString) {
  953. string s = "key1=val1&key2=val2&key3=val3";
  954. Params dic;
  955. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  956. [&](const char *b, const char *e) {
  957. string key, val;
  958. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  959. if (key.empty()) {
  960. key.assign(b2, e2);
  961. } else {
  962. val.assign(b2, e2);
  963. }
  964. });
  965. dic.emplace(key, val);
  966. });
  967. EXPECT_EQ("val1", dic.find("key1")->second);
  968. EXPECT_EQ("val2", dic.find("key2")->second);
  969. EXPECT_EQ("val3", dic.find("key3")->second);
  970. }
  971. TEST(SplitTest, ParseInvalidQueryTests) {
  972. {
  973. string s = " ";
  974. Params dict;
  975. detail::parse_query_text(s, dict);
  976. EXPECT_TRUE(dict.empty());
  977. }
  978. {
  979. string s = " = =";
  980. Params dict;
  981. detail::parse_query_text(s, dict);
  982. EXPECT_TRUE(dict.empty());
  983. }
  984. }
  985. TEST(ParseQueryTest, ParseQueryString) {
  986. {
  987. std::string s = "key1=val1&key2=val2&key3=val3";
  988. Params dic;
  989. detail::parse_query_text(s, dic);
  990. EXPECT_EQ("val1", dic.find("key1")->second);
  991. EXPECT_EQ("val2", dic.find("key2")->second);
  992. EXPECT_EQ("val3", dic.find("key3")->second);
  993. }
  994. {
  995. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  996. Params dic;
  997. detail::parse_query_text(s, dic);
  998. EXPECT_EQ("", dic.find("key1")->second);
  999. EXPECT_EQ("val1", dic.find("key2")->second);
  1000. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1001. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1002. }
  1003. }
  1004. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1005. Params dic;
  1006. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1007. dic.emplace("key1", "val1");
  1008. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1009. dic.emplace("key2", "val2");
  1010. dic.emplace("key3", "val3");
  1011. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1012. }
  1013. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1014. string content_type = "multipart/form-data; boundary=something";
  1015. string boundary;
  1016. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1017. EXPECT_TRUE(ret);
  1018. EXPECT_EQ(boundary, "something");
  1019. }
  1020. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1021. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1022. string boundary;
  1023. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1024. EXPECT_TRUE(ret);
  1025. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1026. }
  1027. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1028. string content_type =
  1029. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1030. string boundary;
  1031. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1032. EXPECT_TRUE(ret);
  1033. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1034. }
  1035. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1036. string content_type =
  1037. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1038. string boundary;
  1039. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1040. EXPECT_TRUE(ret);
  1041. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1042. }
  1043. TEST(GetHeaderValueTest, DefaultValue) {
  1044. Headers headers = {{"Dummy", "Dummy"}};
  1045. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1046. EXPECT_STREQ("text/plain", val);
  1047. }
  1048. TEST(GetHeaderValueTest, DefaultValueInt) {
  1049. Headers headers = {{"Dummy", "Dummy"}};
  1050. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1051. EXPECT_EQ(100ull, val);
  1052. }
  1053. TEST(GetHeaderValueTest, RegularValue) {
  1054. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1055. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1056. EXPECT_STREQ("text/html", val);
  1057. }
  1058. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1059. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1060. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1061. EXPECT_STREQ("text/html", val);
  1062. }
  1063. TEST(GetHeaderValueTest, SetContent) {
  1064. Response res;
  1065. res.set_content("html", "text/html");
  1066. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1067. res.set_content("text", "text/plain");
  1068. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1069. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1070. }
  1071. TEST(GetHeaderValueTest, RegularValueInt) {
  1072. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1073. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1074. EXPECT_EQ(100ull, val);
  1075. }
  1076. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1077. Headers headers = {{"Content-Length", "x"}};
  1078. auto is_invalid_value = false;
  1079. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1080. is_invalid_value);
  1081. EXPECT_EQ(0ull, val);
  1082. EXPECT_TRUE(is_invalid_value);
  1083. }
  1084. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1085. // An all-digit value that overflows size_t must be reported as invalid, not
  1086. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1087. // a large length to a small one on 32-bit builds, leaving the framing length
  1088. // wrong while is_invalid_value stayed false.
  1089. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1090. auto is_invalid_value = false;
  1091. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1092. is_invalid_value);
  1093. EXPECT_TRUE(is_invalid_value);
  1094. // A well-formed length is unaffected.
  1095. Headers ok = {{"Content-Length", "1234"}};
  1096. is_invalid_value = false;
  1097. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1098. is_invalid_value);
  1099. EXPECT_EQ(1234ull, val);
  1100. EXPECT_FALSE(is_invalid_value);
  1101. }
  1102. TEST(GetHeaderValueTest, Range) {
  1103. {
  1104. Headers headers = {make_range_header({{1, -1}})};
  1105. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1106. EXPECT_STREQ("bytes=1-", val);
  1107. }
  1108. {
  1109. Headers headers = {make_range_header({{-1, 1}})};
  1110. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1111. EXPECT_STREQ("bytes=-1", val);
  1112. }
  1113. {
  1114. Headers headers = {make_range_header({{1, 10}})};
  1115. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1116. EXPECT_STREQ("bytes=1-10", val);
  1117. }
  1118. {
  1119. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1120. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1121. EXPECT_STREQ("bytes=1-10, 100-", val);
  1122. }
  1123. {
  1124. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1125. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1126. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1127. }
  1128. {
  1129. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1130. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1131. EXPECT_STREQ("bytes=0-0, -1", val);
  1132. }
  1133. }
  1134. TEST(ParseHeaderValueTest, Range) {
  1135. {
  1136. Ranges ranges;
  1137. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1138. EXPECT_TRUE(ret);
  1139. EXPECT_EQ(1u, ranges.size());
  1140. EXPECT_EQ(1u, ranges[0].first);
  1141. EXPECT_EQ(-1, ranges[0].second);
  1142. }
  1143. {
  1144. Ranges ranges;
  1145. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1146. EXPECT_TRUE(ret);
  1147. EXPECT_EQ(1u, ranges.size());
  1148. EXPECT_EQ(-1, ranges[0].first);
  1149. EXPECT_EQ(1u, ranges[0].second);
  1150. }
  1151. {
  1152. Ranges ranges;
  1153. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1154. EXPECT_TRUE(ret);
  1155. EXPECT_EQ(1u, ranges.size());
  1156. EXPECT_EQ(1u, ranges[0].first);
  1157. EXPECT_EQ(10u, ranges[0].second);
  1158. }
  1159. {
  1160. Ranges ranges;
  1161. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1162. EXPECT_FALSE(ret);
  1163. }
  1164. {
  1165. Ranges ranges;
  1166. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1167. EXPECT_TRUE(ret);
  1168. EXPECT_EQ(2u, ranges.size());
  1169. EXPECT_EQ(1u, ranges[0].first);
  1170. EXPECT_EQ(10u, ranges[0].second);
  1171. EXPECT_EQ(100u, ranges[1].first);
  1172. EXPECT_EQ(-1, ranges[1].second);
  1173. }
  1174. {
  1175. Ranges ranges;
  1176. auto ret =
  1177. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1178. EXPECT_TRUE(ret);
  1179. EXPECT_EQ(3u, ranges.size());
  1180. EXPECT_EQ(1u, ranges[0].first);
  1181. EXPECT_EQ(10u, ranges[0].second);
  1182. EXPECT_EQ(100u, ranges[1].first);
  1183. EXPECT_EQ(200u, ranges[1].second);
  1184. EXPECT_EQ(300u, ranges[2].first);
  1185. EXPECT_EQ(400u, ranges[2].second);
  1186. }
  1187. {
  1188. Ranges ranges;
  1189. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1190. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1191. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1192. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1193. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1194. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1195. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1196. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1197. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1198. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1199. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1200. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1201. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1202. EXPECT_TRUE(ranges.empty());
  1203. }
  1204. }
  1205. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1206. Request req;
  1207. req.set_header("Accept-Encoding", "gzip");
  1208. Response res;
  1209. res.set_header("Content-Type", "text/plain");
  1210. auto ret = detail::encoding_type(req, res);
  1211. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1212. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1213. #else
  1214. EXPECT_TRUE(ret == detail::EncodingType::None);
  1215. #endif
  1216. }
  1217. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1218. Request req;
  1219. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1220. Response res;
  1221. res.set_header("Content-Type", "text/plain");
  1222. auto ret = detail::encoding_type(req, res);
  1223. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1224. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1225. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1226. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1227. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1228. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1229. #else
  1230. EXPECT_TRUE(ret == detail::EncodingType::None);
  1231. #endif
  1232. }
  1233. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1234. Request req;
  1235. req.set_header("Accept-Encoding",
  1236. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1237. Response res;
  1238. res.set_header("Content-Type", "text/plain");
  1239. auto ret = detail::encoding_type(req, res);
  1240. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1241. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1242. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1243. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1244. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1245. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1246. #else
  1247. EXPECT_TRUE(ret == detail::EncodingType::None);
  1248. #endif
  1249. }
  1250. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1251. // All supported encodings rejected with q=0 should return None
  1252. Request req;
  1253. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1254. Response res;
  1255. res.set_header("Content-Type", "text/plain");
  1256. auto ret = detail::encoding_type(req, res);
  1257. EXPECT_TRUE(ret == detail::EncodingType::None);
  1258. }
  1259. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1260. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1261. Request req;
  1262. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1263. Response res;
  1264. res.set_header("Content-Type", "text/plain");
  1265. auto ret = detail::encoding_type(req, res);
  1266. EXPECT_TRUE(ret == detail::EncodingType::None);
  1267. }
  1268. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1269. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1270. Request req;
  1271. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1272. Response res;
  1273. res.set_header("Content-Type", "text/plain");
  1274. auto ret = detail::encoding_type(req, res);
  1275. EXPECT_TRUE(ret == detail::EncodingType::None);
  1276. }
  1277. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1278. // RFC 7231: Accept-Encoding values are case-insensitive
  1279. Request req;
  1280. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1281. Response res;
  1282. res.set_header("Content-Type", "text/plain");
  1283. auto ret = detail::encoding_type(req, res);
  1284. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1285. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1286. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1287. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1288. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1289. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1290. #else
  1291. EXPECT_TRUE(ret == detail::EncodingType::None);
  1292. #endif
  1293. }
  1294. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1295. // q value should determine priority, not hardcoded order
  1296. Request req;
  1297. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1298. Response res;
  1299. res.set_header("Content-Type", "text/plain");
  1300. auto ret = detail::encoding_type(req, res);
  1301. // gzip has highest q=1.0, so it should be selected even though
  1302. // br and zstd are also supported
  1303. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1304. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1305. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1306. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1307. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1308. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1309. #else
  1310. EXPECT_TRUE(ret == detail::EncodingType::None);
  1311. #endif
  1312. }
  1313. TEST(BufferStreamTest, read) {
  1314. detail::BufferStream strm1;
  1315. Stream &strm = strm1;
  1316. EXPECT_EQ(5, strm.write("hello"));
  1317. char buf[512];
  1318. EXPECT_EQ(2, strm.read(buf, 2));
  1319. EXPECT_EQ('h', buf[0]);
  1320. EXPECT_EQ('e', buf[1]);
  1321. EXPECT_EQ(2, strm.read(buf, 2));
  1322. EXPECT_EQ('l', buf[0]);
  1323. EXPECT_EQ('l', buf[1]);
  1324. EXPECT_EQ(1, strm.read(buf, 1));
  1325. EXPECT_EQ('o', buf[0]);
  1326. EXPECT_EQ(0, strm.read(buf, 1));
  1327. }
  1328. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1329. auto host = "www.httpwatch.com";
  1330. auto ip = hosted_at(host);
  1331. EXPECT_EQ("23.96.13.243", ip);
  1332. std::vector<std::string> addrs;
  1333. hosted_at(host, addrs);
  1334. EXPECT_EQ(1u, addrs.size());
  1335. }
  1336. #if 0 // It depends on each test environment...
  1337. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1338. auto host = "www.youtube.com";
  1339. std::vector<std::string> addrs;
  1340. hosted_at(host, addrs);
  1341. EXPECT_EQ(20u, addrs.size());
  1342. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1343. EXPECT_TRUE(it != addrs.end());
  1344. }
  1345. #endif
  1346. class ChunkedEncodingTest : public ::testing::Test {
  1347. protected:
  1348. ChunkedEncodingTest()
  1349. : cli_(HOST, PORT)
  1350. #ifdef CPPHTTPLIB_SSL_ENABLED
  1351. ,
  1352. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1353. #endif
  1354. {
  1355. cli_.set_connection_timeout(2);
  1356. #ifdef CPPHTTPLIB_SSL_ENABLED
  1357. cli_.enable_server_certificate_verification(false);
  1358. #endif
  1359. }
  1360. virtual void SetUp() {
  1361. read_file("./image.jpg", image_data_);
  1362. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1363. res.set_content("Hello World!", "text/plain");
  1364. });
  1365. svr_.Get(
  1366. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1367. res.set_chunked_content_provider(
  1368. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1369. size_t remaining = image_data_.size() - offset;
  1370. if (remaining == 0) {
  1371. sink.done();
  1372. } else {
  1373. constexpr size_t CHUNK_SIZE = 1024;
  1374. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1375. sink.write(&image_data_[offset], send_size);
  1376. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1377. }
  1378. return true;
  1379. });
  1380. });
  1381. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1382. svr_.wait_until_ready();
  1383. }
  1384. virtual void TearDown() {
  1385. svr_.stop();
  1386. if (!request_threads_.empty()) {
  1387. std::this_thread::sleep_for(std::chrono::seconds(1));
  1388. for (auto &t : request_threads_) {
  1389. t.join();
  1390. }
  1391. }
  1392. t_.join();
  1393. }
  1394. #ifdef CPPHTTPLIB_SSL_ENABLED
  1395. SSLClient cli_;
  1396. SSLServer svr_;
  1397. #else
  1398. Client cli_;
  1399. Server svr_;
  1400. #endif
  1401. thread t_;
  1402. std::vector<thread> request_threads_;
  1403. std::string image_data_;
  1404. };
  1405. TEST_F(ChunkedEncodingTest, NormalGet) {
  1406. auto res = cli_.Get("/chunked");
  1407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1408. std::string out;
  1409. read_file("./image.jpg", out);
  1410. EXPECT_EQ(StatusCode::OK_200, res->status);
  1411. EXPECT_EQ(out, res->body);
  1412. }
  1413. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1414. std::string body;
  1415. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1416. body.append(data, data_length);
  1417. return true;
  1418. });
  1419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1420. std::string out;
  1421. read_file("./image.jpg", out);
  1422. EXPECT_EQ(StatusCode::OK_200, res->status);
  1423. EXPECT_EQ(out, body);
  1424. }
  1425. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1426. std::string body;
  1427. auto res = cli_.Get(
  1428. "/chunked",
  1429. [&](const Response &response) {
  1430. EXPECT_EQ(StatusCode::OK_200, response.status);
  1431. return true;
  1432. },
  1433. [&](const char *data, size_t data_length) {
  1434. body.append(data, data_length);
  1435. return true;
  1436. });
  1437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1438. std::string out;
  1439. read_file("./image.jpg", out);
  1440. EXPECT_EQ(StatusCode::OK_200, res->status);
  1441. EXPECT_EQ(out, body);
  1442. }
  1443. TEST(RangeTest, FromHTTPBin_Online) {
  1444. auto host = "httpbingo.org";
  1445. auto path = std::string{"/range/32"};
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 443;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 80;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(5);
  1454. {
  1455. auto res = cli.Get(path);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1458. EXPECT_EQ(StatusCode::OK_200, res->status);
  1459. }
  1460. {
  1461. Headers headers = {make_range_header({{1, -1}})};
  1462. auto res = cli.Get(path, headers);
  1463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1464. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1466. }
  1467. {
  1468. Headers headers = {make_range_header({{1, 10}})};
  1469. auto res = cli.Get(path, headers);
  1470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1471. EXPECT_EQ("bcdefghijk", res->body);
  1472. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1473. }
  1474. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1475. // entire resource, while the original httpbin returned 200. Both are
  1476. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1477. {
  1478. Headers headers = {make_range_header({{0, 31}})};
  1479. auto res = cli.Get(path, headers);
  1480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1481. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1482. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1483. res->status == StatusCode::PartialContent_206);
  1484. }
  1485. {
  1486. Headers headers = {make_range_header({{0, -1}})};
  1487. auto res = cli.Get(path, headers);
  1488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1489. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1490. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1491. res->status == StatusCode::PartialContent_206);
  1492. }
  1493. // go-httpbin returns 206 with clamped range for over-range requests,
  1494. // while the original httpbin returned 416. Both behaviors are observed
  1495. // in real servers, so we only verify the request succeeds.
  1496. {
  1497. Headers headers = {make_range_header({{0, 32}})};
  1498. auto res = cli.Get(path, headers);
  1499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1500. }
  1501. }
  1502. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1503. auto host = "unresolvableaddress.local";
  1504. auto path = std::string{"/"};
  1505. #ifdef CPPHTTPLIB_SSL_ENABLED
  1506. auto port = 443;
  1507. SSLClient cli(host, port);
  1508. #else
  1509. auto port = 80;
  1510. Client cli(host, port);
  1511. #endif
  1512. cli.set_connection_timeout(1);
  1513. {
  1514. auto res = cli.Get(path);
  1515. ASSERT_FALSE(res);
  1516. }
  1517. std::this_thread::sleep_for(std::chrono::seconds(8));
  1518. }
  1519. #if defined(__linux__) && defined(__GLIBC__) && \
  1520. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1521. // Forward declaration: in split builds split.py strips `inline` and moves the
  1522. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1523. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1524. // against the symbol in both header-only and split builds.
  1525. namespace httplib {
  1526. namespace detail {
  1527. int getaddrinfo_with_timeout(const char *node, const char *service,
  1528. const struct addrinfo *hints,
  1529. struct addrinfo **res, time_t timeout_sec);
  1530. } // namespace detail
  1531. } // namespace httplib
  1532. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1533. //
  1534. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1535. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1536. // gai_suspend() call hits the connection timeout the function calls
  1537. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1538. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1539. // still alive and still references the now-destroyed stack frame.
  1540. //
  1541. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1542. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1543. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1544. // and runs them in a container.
  1545. namespace {
  1546. bool should_run_issue_2431_tests() {
  1547. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1548. return v && *v && std::string(v) != "0";
  1549. }
  1550. std::string unique_unresolvable_host(int n) {
  1551. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1552. // glibc still asks the configured nameserver — which is exactly the path
  1553. // we want to exercise. A unique label per call avoids the resolver cache.
  1554. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1555. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1556. std::to_string(n) + ".invalid";
  1557. }
  1558. } // namespace
  1559. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1560. if (!should_run_issue_2431_tests()) {
  1561. GTEST_SKIP()
  1562. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1563. }
  1564. for (int i = 0; i < 8; ++i) {
  1565. struct addrinfo hints;
  1566. memset(&hints, 0, sizeof(hints));
  1567. hints.ai_family = AF_UNSPEC;
  1568. hints.ai_socktype = SOCK_STREAM;
  1569. auto host = unique_unresolvable_host(i);
  1570. struct addrinfo *result = nullptr;
  1571. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1572. &result, /*timeout_sec=*/1);
  1573. if (rc == 0 && result) { freeaddrinfo(result); }
  1574. }
  1575. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1576. // stack region they still believe holds their gaicb.
  1577. std::this_thread::sleep_for(std::chrono::seconds(3));
  1578. }
  1579. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1580. if (!should_run_issue_2431_tests()) {
  1581. GTEST_SKIP()
  1582. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1583. }
  1584. std::atomic<bool> stop{false};
  1585. std::vector<std::thread> threads;
  1586. for (int t = 0; t < 8; ++t) {
  1587. threads.emplace_back([t, &stop] {
  1588. int i = 0;
  1589. while (!stop.load(std::memory_order_relaxed)) {
  1590. struct addrinfo hints;
  1591. memset(&hints, 0, sizeof(hints));
  1592. hints.ai_family = AF_UNSPEC;
  1593. hints.ai_socktype = SOCK_STREAM;
  1594. auto host = unique_unresolvable_host(t * 100000 + i++);
  1595. struct addrinfo *result = nullptr;
  1596. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1597. &result, /*timeout_sec=*/1);
  1598. if (rc == 0 && result) { freeaddrinfo(result); }
  1599. }
  1600. });
  1601. }
  1602. std::this_thread::sleep_for(std::chrono::seconds(8));
  1603. stop.store(true, std::memory_order_relaxed);
  1604. for (auto &th : threads) {
  1605. th.join();
  1606. }
  1607. std::this_thread::sleep_for(std::chrono::seconds(3));
  1608. }
  1609. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1610. if (!should_run_issue_2431_tests()) {
  1611. GTEST_SKIP()
  1612. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1613. }
  1614. std::atomic<bool> stop{false};
  1615. std::vector<std::thread> threads;
  1616. for (int t = 0; t < 8; ++t) {
  1617. threads.emplace_back([t, &stop] {
  1618. int i = 0;
  1619. while (!stop.load(std::memory_order_relaxed)) {
  1620. auto host = unique_unresolvable_host(t * 100000 + i++);
  1621. Client cli(host, 80);
  1622. cli.set_connection_timeout(1, 0);
  1623. cli.set_read_timeout(1, 0);
  1624. cli.set_write_timeout(1, 0);
  1625. (void)cli.Get("/");
  1626. }
  1627. });
  1628. }
  1629. std::this_thread::sleep_for(std::chrono::seconds(8));
  1630. stop.store(true, std::memory_order_relaxed);
  1631. for (auto &th : threads) {
  1632. th.join();
  1633. }
  1634. std::this_thread::sleep_for(std::chrono::seconds(3));
  1635. }
  1636. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1637. TEST(ConnectionErrorTest, InvalidHost) {
  1638. auto host = "-abcde.com";
  1639. #ifdef CPPHTTPLIB_SSL_ENABLED
  1640. auto port = 443;
  1641. SSLClient cli(host, port);
  1642. #else
  1643. auto port = 80;
  1644. Client cli(host, port);
  1645. #endif
  1646. cli.set_connection_timeout(std::chrono::seconds(2));
  1647. auto res = cli.Get("/");
  1648. ASSERT_TRUE(!res);
  1649. EXPECT_EQ(Error::Connection, res.error());
  1650. }
  1651. TEST(ConnectionErrorTest, InvalidHost2) {
  1652. auto host = "httpcan.org/";
  1653. #ifdef CPPHTTPLIB_SSL_ENABLED
  1654. SSLClient cli(host);
  1655. #else
  1656. Client cli(host);
  1657. #endif
  1658. cli.set_connection_timeout(std::chrono::seconds(2));
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(!res);
  1661. EXPECT_EQ(Error::Connection, res.error());
  1662. }
  1663. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1664. auto host = "httpcan.org/";
  1665. #ifdef CPPHTTPLIB_SSL_ENABLED
  1666. SSLClient cli(host);
  1667. #else
  1668. Client cli(host);
  1669. #endif
  1670. cli.set_connection_timeout(std::chrono::seconds(2));
  1671. auto res = cli.Get("/");
  1672. ASSERT_TRUE(!res);
  1673. stringstream s;
  1674. s << "error code: " << res.error();
  1675. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1676. }
  1677. TEST(ConnectionErrorTest, InvalidPort) {
  1678. auto host = "localhost";
  1679. auto port = 44380;
  1680. #ifdef CPPHTTPLIB_SSL_ENABLED
  1681. SSLClient cli(host, port);
  1682. #else
  1683. Client cli(host, port);
  1684. #endif
  1685. cli.set_connection_timeout(std::chrono::seconds(2));
  1686. auto res = cli.Get("/");
  1687. ASSERT_TRUE(!res);
  1688. EXPECT_TRUE(Error::Connection == res.error() ||
  1689. Error::ConnectionTimeout == res.error());
  1690. }
  1691. TEST(ConnectionErrorTest, Timeout_Online) {
  1692. auto host = "google.com";
  1693. #ifdef CPPHTTPLIB_SSL_ENABLED
  1694. auto port = 44380;
  1695. SSLClient cli(host, port);
  1696. #else
  1697. auto port = 8080;
  1698. Client cli(host, port);
  1699. #endif
  1700. cli.set_connection_timeout(std::chrono::seconds(2));
  1701. // only probe one address type so that the error reason
  1702. // correlates to the timed-out IPv4, not the unsupported
  1703. // IPv6 connection attempt
  1704. cli.set_address_family(AF_INET);
  1705. auto res = cli.Get("/");
  1706. ASSERT_TRUE(!res);
  1707. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1708. }
  1709. TEST(CancelTest, NoCancel_Online) {
  1710. auto host = "httpbingo.org";
  1711. auto path = std::string{"/range/32"};
  1712. #ifdef CPPHTTPLIB_SSL_ENABLED
  1713. auto port = 443;
  1714. SSLClient cli(host, port);
  1715. #else
  1716. auto port = 80;
  1717. Client cli(host, port);
  1718. #endif
  1719. cli.set_connection_timeout(std::chrono::seconds(5));
  1720. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1722. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1723. EXPECT_EQ(StatusCode::OK_200, res->status);
  1724. }
  1725. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1726. // Use /bytes with a large payload so that the DownloadProgress callback
  1727. // (which only fires for Content-Length responses) is invoked before the
  1728. // entire body is received, giving cancellation a chance to fire.
  1729. auto host = "httpbingo.org";
  1730. auto path = std::string{"/bytes/524288"};
  1731. #ifdef CPPHTTPLIB_SSL_ENABLED
  1732. auto port = 443;
  1733. SSLClient cli(host, port);
  1734. #else
  1735. auto port = 80;
  1736. Client cli(host, port);
  1737. #endif
  1738. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1739. cli.set_connection_timeout(std::chrono::seconds(5));
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayload_Online) {
  1744. auto host = "httpbingo.org";
  1745. auto path = std::string{"/bytes/524288"};
  1746. #ifdef CPPHTTPLIB_SSL_ENABLED
  1747. auto port = 443;
  1748. SSLClient cli(host, port);
  1749. #else
  1750. auto port = 80;
  1751. Client cli(host, port);
  1752. #endif
  1753. cli.set_connection_timeout(std::chrono::seconds(5));
  1754. uint32_t count = 0;
  1755. auto res =
  1756. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::Canceled, res.error());
  1759. }
  1760. TEST(CancelTest, NoCancelPost) {
  1761. Server svr;
  1762. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1763. res.set_content("Hello World!", "text/plain");
  1764. });
  1765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1766. auto se = detail::scope_exit([&] {
  1767. svr.stop();
  1768. thread.join();
  1769. ASSERT_FALSE(svr.is_running());
  1770. });
  1771. svr.wait_until_ready();
  1772. Client cli(HOST, PORT);
  1773. cli.set_connection_timeout(std::chrono::seconds(5));
  1774. auto res =
  1775. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1776. "application/json", [](uint64_t, uint64_t) { return true; });
  1777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1778. EXPECT_EQ("Hello World!", res->body);
  1779. EXPECT_EQ(StatusCode::OK_200, res->status);
  1780. }
  1781. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1782. Server svr;
  1783. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1784. res.set_content("Hello World!", "text/plain");
  1785. });
  1786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1787. auto se = detail::scope_exit([&] {
  1788. svr.stop();
  1789. thread.join();
  1790. ASSERT_FALSE(svr.is_running());
  1791. });
  1792. svr.wait_until_ready();
  1793. Client cli(HOST, PORT);
  1794. cli.set_connection_timeout(std::chrono::seconds(5));
  1795. auto res =
  1796. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1797. "application/json", [](uint64_t, uint64_t) { return false; });
  1798. ASSERT_TRUE(!res);
  1799. EXPECT_EQ(Error::Canceled, res.error());
  1800. }
  1801. TEST(CancelTest, WithCancelLargePayloadPost) {
  1802. Server svr;
  1803. svr.set_payload_max_length(200 * 1024 * 1024);
  1804. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1805. res.set_content(LARGE_DATA, "text/plain");
  1806. });
  1807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1808. auto se = detail::scope_exit([&] {
  1809. svr.stop();
  1810. thread.join();
  1811. ASSERT_FALSE(svr.is_running());
  1812. });
  1813. svr.wait_until_ready();
  1814. Client cli(HOST, PORT);
  1815. cli.set_payload_max_length(200 * 1024 * 1024);
  1816. cli.set_connection_timeout(std::chrono::seconds(5));
  1817. auto res =
  1818. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1819. "application/json", [](uint64_t, uint64_t) { return false; });
  1820. ASSERT_TRUE(!res);
  1821. EXPECT_EQ(Error::Canceled, res.error());
  1822. }
  1823. TEST(CancelTest, NoCancelPut) {
  1824. Server svr;
  1825. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1826. res.set_content("Hello World!", "text/plain");
  1827. });
  1828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1829. auto se = detail::scope_exit([&] {
  1830. svr.stop();
  1831. thread.join();
  1832. ASSERT_FALSE(svr.is_running());
  1833. });
  1834. svr.wait_until_ready();
  1835. Client cli(HOST, PORT);
  1836. cli.set_connection_timeout(std::chrono::seconds(5));
  1837. auto res =
  1838. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1839. "application/json", [](uint64_t, uint64_t) { return true; });
  1840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1841. EXPECT_EQ("Hello World!", res->body);
  1842. EXPECT_EQ(StatusCode::OK_200, res->status);
  1843. }
  1844. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1845. Server svr;
  1846. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("Hello World!", "text/plain");
  1848. });
  1849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1850. auto se = detail::scope_exit([&] {
  1851. svr.stop();
  1852. thread.join();
  1853. ASSERT_FALSE(svr.is_running());
  1854. });
  1855. svr.wait_until_ready();
  1856. Client cli(HOST, PORT);
  1857. cli.set_connection_timeout(std::chrono::seconds(5));
  1858. auto res =
  1859. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1860. "application/json", [](uint64_t, uint64_t) { return false; });
  1861. ASSERT_TRUE(!res);
  1862. EXPECT_EQ(Error::Canceled, res.error());
  1863. }
  1864. TEST(CancelTest, WithCancelLargePayloadPut) {
  1865. Server svr;
  1866. svr.set_payload_max_length(200 * 1024 * 1024);
  1867. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1868. res.set_content(LARGE_DATA, "text/plain");
  1869. });
  1870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1871. auto se = detail::scope_exit([&] {
  1872. svr.stop();
  1873. thread.join();
  1874. ASSERT_FALSE(svr.is_running());
  1875. });
  1876. svr.wait_until_ready();
  1877. Client cli(HOST, PORT);
  1878. cli.set_payload_max_length(200 * 1024 * 1024);
  1879. cli.set_connection_timeout(std::chrono::seconds(5));
  1880. auto res =
  1881. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1882. "application/json", [](uint64_t, uint64_t) { return false; });
  1883. ASSERT_TRUE(!res);
  1884. EXPECT_EQ(Error::Canceled, res.error());
  1885. }
  1886. TEST(CancelTest, NoCancelPatch) {
  1887. Server svr;
  1888. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("Hello World!", "text/plain");
  1890. });
  1891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1892. auto se = detail::scope_exit([&] {
  1893. svr.stop();
  1894. thread.join();
  1895. ASSERT_FALSE(svr.is_running());
  1896. });
  1897. svr.wait_until_ready();
  1898. Client cli(HOST, PORT);
  1899. cli.set_connection_timeout(std::chrono::seconds(5));
  1900. auto res =
  1901. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1902. "application/json", [](uint64_t, uint64_t) { return true; });
  1903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1904. EXPECT_EQ("Hello World!", res->body);
  1905. EXPECT_EQ(StatusCode::OK_200, res->status);
  1906. }
  1907. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1908. Server svr;
  1909. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1910. res.set_content("Hello World!", "text/plain");
  1911. });
  1912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1913. auto se = detail::scope_exit([&] {
  1914. svr.stop();
  1915. thread.join();
  1916. ASSERT_FALSE(svr.is_running());
  1917. });
  1918. svr.wait_until_ready();
  1919. Client cli(HOST, PORT);
  1920. cli.set_connection_timeout(std::chrono::seconds(5));
  1921. auto res =
  1922. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1923. "application/json", [](uint64_t, uint64_t) { return false; });
  1924. ASSERT_TRUE(!res);
  1925. EXPECT_EQ(Error::Canceled, res.error());
  1926. }
  1927. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1928. Server svr;
  1929. svr.set_payload_max_length(200 * 1024 * 1024);
  1930. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1931. res.set_content(LARGE_DATA, "text/plain");
  1932. });
  1933. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1934. auto se = detail::scope_exit([&] {
  1935. svr.stop();
  1936. thread.join();
  1937. ASSERT_FALSE(svr.is_running());
  1938. });
  1939. svr.wait_until_ready();
  1940. Client cli(HOST, PORT);
  1941. cli.set_payload_max_length(200 * 1024 * 1024);
  1942. cli.set_connection_timeout(std::chrono::seconds(5));
  1943. auto res =
  1944. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1945. "application/json", [](uint64_t, uint64_t) { return false; });
  1946. ASSERT_TRUE(!res);
  1947. EXPECT_EQ(Error::Canceled, res.error());
  1948. }
  1949. TEST(CancelTest, NoCancelDelete) {
  1950. Server svr;
  1951. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1952. res.set_content("Hello World!", "text/plain");
  1953. });
  1954. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1955. auto se = detail::scope_exit([&] {
  1956. svr.stop();
  1957. thread.join();
  1958. ASSERT_FALSE(svr.is_running());
  1959. });
  1960. svr.wait_until_ready();
  1961. Client cli(HOST, PORT);
  1962. cli.set_connection_timeout(std::chrono::seconds(5));
  1963. auto res =
  1964. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1965. "application/json", [](uint64_t, uint64_t) { return true; });
  1966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1967. EXPECT_EQ("Hello World!", res->body);
  1968. EXPECT_EQ(StatusCode::OK_200, res->status);
  1969. }
  1970. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1971. Server svr;
  1972. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1973. res.set_content("Hello World!", "text/plain");
  1974. });
  1975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1976. auto se = detail::scope_exit([&] {
  1977. svr.stop();
  1978. thread.join();
  1979. ASSERT_FALSE(svr.is_running());
  1980. });
  1981. svr.wait_until_ready();
  1982. Client cli(HOST, PORT);
  1983. cli.set_connection_timeout(std::chrono::seconds(5));
  1984. auto res =
  1985. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1986. "application/json", [](uint64_t, uint64_t) { return false; });
  1987. ASSERT_TRUE(!res);
  1988. EXPECT_EQ(Error::Canceled, res.error());
  1989. }
  1990. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1991. Server svr;
  1992. svr.set_payload_max_length(200 * 1024 * 1024);
  1993. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1994. res.set_content(LARGE_DATA, "text/plain");
  1995. });
  1996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1997. auto se = detail::scope_exit([&] {
  1998. svr.stop();
  1999. thread.join();
  2000. ASSERT_FALSE(svr.is_running());
  2001. });
  2002. svr.wait_until_ready();
  2003. Client cli(HOST, PORT);
  2004. cli.set_payload_max_length(200 * 1024 * 1024);
  2005. cli.set_connection_timeout(std::chrono::seconds(5));
  2006. auto res =
  2007. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2008. "application/json", [](uint64_t, uint64_t) { return false; });
  2009. ASSERT_TRUE(!res);
  2010. EXPECT_EQ(Error::Canceled, res.error());
  2011. }
  2012. static std::string remove_whitespace(const std::string &input) {
  2013. std::string output;
  2014. output.reserve(input.size());
  2015. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2016. [](unsigned char c) { return !std::isspace(c); });
  2017. return output;
  2018. }
  2019. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2020. auto host = "httpbingo.org";
  2021. auto path = std::string{"/basic-auth/hello/world"};
  2022. #ifdef CPPHTTPLIB_SSL_ENABLED
  2023. auto port = 443;
  2024. SSLClient cli(host, port);
  2025. #else
  2026. auto port = 80;
  2027. Client cli(host, port);
  2028. #endif
  2029. {
  2030. auto res = cli.Get(path);
  2031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2032. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2033. }
  2034. {
  2035. auto res = cli.Get(
  2036. path, Headers{make_basic_authentication_header("hello", "world")});
  2037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2038. auto body = remove_whitespace(res->body);
  2039. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2040. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2041. EXPECT_EQ(StatusCode::OK_200, res->status);
  2042. }
  2043. {
  2044. cli.set_basic_auth("hello", "world");
  2045. auto res = cli.Get(path);
  2046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2047. auto body = remove_whitespace(res->body);
  2048. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2049. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2050. EXPECT_EQ(StatusCode::OK_200, res->status);
  2051. }
  2052. {
  2053. cli.set_basic_auth("hello", "bad");
  2054. auto res = cli.Get(path);
  2055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2056. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2057. }
  2058. {
  2059. cli.set_basic_auth("bad", "world");
  2060. auto res = cli.Get(path);
  2061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2062. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2063. }
  2064. }
  2065. #ifdef CPPHTTPLIB_SSL_ENABLED
  2066. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2067. auto host = "httpbingo.org";
  2068. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2069. auto paths = std::vector<std::string>{
  2070. "/digest-auth/auth/hello/world/MD5",
  2071. "/digest-auth/auth/hello/world/SHA-256",
  2072. };
  2073. auto port = 443;
  2074. SSLClient cli(host, port);
  2075. {
  2076. auto res = cli.Get(unauth_path);
  2077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2078. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2079. }
  2080. {
  2081. cli.set_digest_auth("hello", "world");
  2082. for (const auto &path : paths) {
  2083. auto res = cli.Get(path.c_str());
  2084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2085. auto body = remove_whitespace(res->body);
  2086. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2087. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2088. EXPECT_EQ(StatusCode::OK_200, res->status);
  2089. }
  2090. cli.set_digest_auth("hello", "bad");
  2091. for (const auto &path : paths) {
  2092. auto res = cli.Get(path.c_str());
  2093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2094. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2095. }
  2096. }
  2097. }
  2098. #endif
  2099. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2100. auto host = "google.com";
  2101. auto another_host = "example.com";
  2102. auto wrong_ip = "0.0.0.0";
  2103. #ifdef CPPHTTPLIB_SSL_ENABLED
  2104. SSLClient cli(host);
  2105. #else
  2106. Client cli(host);
  2107. #endif
  2108. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2109. auto res = cli.Get("/");
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2112. }
  2113. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2114. auto host = "google.com";
  2115. auto wrong_ip = "0.0.0.0";
  2116. #ifdef CPPHTTPLIB_SSL_ENABLED
  2117. SSLClient cli(host);
  2118. #else
  2119. Client cli(host);
  2120. #endif
  2121. cli.set_hostname_addr_map({{host, wrong_ip}});
  2122. auto res = cli.Get("/");
  2123. ASSERT_TRUE(!res);
  2124. EXPECT_EQ(Error::Connection, res.error());
  2125. }
  2126. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2127. auto host = "httpbingo.org";
  2128. auto path = std::string{"/absolute-redirect/3"};
  2129. #ifdef CPPHTTPLIB_SSL_ENABLED
  2130. SSLClient cli(host);
  2131. #else
  2132. Client cli(host);
  2133. #endif
  2134. cli.set_follow_location(true);
  2135. auto res = cli.Get(path);
  2136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2137. EXPECT_EQ(StatusCode::OK_200, res->status);
  2138. }
  2139. TEST(RedirectTest, Redirect_Online) {
  2140. auto host = "httpbingo.org";
  2141. auto path = std::string{"/redirect/3"};
  2142. #ifdef CPPHTTPLIB_SSL_ENABLED
  2143. SSLClient cli(host);
  2144. #else
  2145. Client cli(host);
  2146. #endif
  2147. cli.set_follow_location(true);
  2148. auto res = cli.Get(path);
  2149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2150. EXPECT_EQ(StatusCode::OK_200, res->status);
  2151. }
  2152. TEST(RelativeRedirectTest, Redirect_Online) {
  2153. auto host = "httpbingo.org";
  2154. auto path = std::string{"/relative-redirect/3"};
  2155. #ifdef CPPHTTPLIB_SSL_ENABLED
  2156. SSLClient cli(host);
  2157. #else
  2158. Client cli(host);
  2159. #endif
  2160. cli.set_follow_location(true);
  2161. auto res = cli.Get(path);
  2162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2163. EXPECT_EQ(StatusCode::OK_200, res->status);
  2164. }
  2165. TEST(TooManyRedirectTest, Redirect_Online) {
  2166. auto host = "httpbingo.org";
  2167. auto path = std::string{"/redirect/21"};
  2168. #ifdef CPPHTTPLIB_SSL_ENABLED
  2169. SSLClient cli(host);
  2170. #else
  2171. Client cli(host);
  2172. #endif
  2173. cli.set_follow_location(true);
  2174. auto res = cli.Get(path);
  2175. ASSERT_TRUE(!res);
  2176. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2177. }
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. TEST(YahooRedirectTest, Redirect_Online) {
  2180. Client cli("yahoo.com");
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2183. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2184. cli.set_follow_location(true);
  2185. res = cli.Get("/");
  2186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2187. EXPECT_EQ(StatusCode::OK_200, res->status);
  2188. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2189. }
  2190. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2191. #define REDIR_HOST "httpbingo.org"
  2192. #define REDIR_PATH "/redirect-to"
  2193. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2194. SSLClient cli(REDIR_HOST);
  2195. cli.set_follow_location(true);
  2196. auto res =
  2197. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. EXPECT_EQ(StatusCode::OK_200, res->status);
  2200. }
  2201. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2202. SSLClient cli(REDIR_HOST);
  2203. cli.set_follow_location(true);
  2204. Params params;
  2205. params.emplace("url", "http://example.com");
  2206. params.emplace("status_code", "302");
  2207. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2209. EXPECT_EQ(StatusCode::OK_200, res->status);
  2210. }
  2211. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2212. SSLClient cli(REDIR_HOST);
  2213. cli.set_follow_location(true);
  2214. Params params;
  2215. params.emplace("url", "http://example.com");
  2216. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2218. EXPECT_EQ(StatusCode::OK_200, res->status);
  2219. }
  2220. TEST(UrlWithSpace, Redirect_Online) {
  2221. SSLClient cli("edge.forgecdn.net");
  2222. cli.set_follow_location(true);
  2223. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2227. }
  2228. #endif
  2229. #if !defined(_WIN32) && !defined(_WIN64)
  2230. TEST(ReceiveSignals, Signal) {
  2231. auto setupSignalHandlers = []() {
  2232. struct sigaction act;
  2233. sigemptyset(&act.sa_mask);
  2234. act.sa_flags = SA_SIGINFO;
  2235. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2236. switch (sig) {
  2237. case SIGINT:
  2238. default: break;
  2239. }
  2240. };
  2241. ::sigaction(SIGINT, &act, nullptr);
  2242. };
  2243. Server svr;
  2244. int port = 0;
  2245. auto thread = std::thread([&]() {
  2246. setupSignalHandlers();
  2247. port = svr.bind_to_any_port(HOST);
  2248. svr.listen_after_bind();
  2249. });
  2250. auto se = detail::scope_exit([&] {
  2251. svr.stop();
  2252. thread.join();
  2253. ASSERT_FALSE(svr.is_running());
  2254. });
  2255. svr.wait_until_ready();
  2256. ASSERT_TRUE(svr.is_running());
  2257. pthread_kill(thread.native_handle(), SIGINT);
  2258. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2259. ASSERT_TRUE(svr.is_running());
  2260. }
  2261. #endif
  2262. TEST(RedirectToDifferentPort, Redirect) {
  2263. Server svr1;
  2264. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2265. res.set_content("Hello World!", "text/plain");
  2266. });
  2267. int svr1_port = 0;
  2268. auto thread1 = std::thread([&]() {
  2269. svr1_port = svr1.bind_to_any_port(HOST);
  2270. svr1.listen_after_bind();
  2271. });
  2272. Server svr2;
  2273. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2274. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2275. });
  2276. int svr2_port = 0;
  2277. auto thread2 = std::thread([&]() {
  2278. svr2_port = svr2.bind_to_any_port(HOST);
  2279. svr2.listen_after_bind();
  2280. });
  2281. auto se = detail::scope_exit([&] {
  2282. svr2.stop();
  2283. thread2.join();
  2284. svr1.stop();
  2285. thread1.join();
  2286. ASSERT_FALSE(svr2.is_running());
  2287. ASSERT_FALSE(svr1.is_running());
  2288. });
  2289. svr1.wait_until_ready();
  2290. svr2.wait_until_ready();
  2291. Client cli("localhost", svr2_port);
  2292. cli.set_follow_location(true);
  2293. auto res = cli.Get("/2");
  2294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2295. EXPECT_EQ(StatusCode::OK_200, res->status);
  2296. EXPECT_EQ("Hello World!", res->body);
  2297. }
  2298. static void
  2299. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2300. Server svr1;
  2301. std::string captured_authorization;
  2302. svr1.Get("/target", [&](const Request &req, Response &res) {
  2303. captured_authorization = req.get_header_value("Authorization");
  2304. res.set_content("OK", "text/plain");
  2305. });
  2306. int svr1_port = 0;
  2307. auto thread1 = std::thread([&]() {
  2308. svr1_port = svr1.bind_to_any_port(HOST);
  2309. svr1.listen_after_bind();
  2310. });
  2311. Server svr2;
  2312. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2313. res.set_redirect(
  2314. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2315. });
  2316. int svr2_port = 0;
  2317. auto thread2 = std::thread([&]() {
  2318. svr2_port = svr2.bind_to_any_port(HOST);
  2319. svr2.listen_after_bind();
  2320. });
  2321. auto se = detail::scope_exit([&] {
  2322. svr2.stop();
  2323. thread2.join();
  2324. svr1.stop();
  2325. thread1.join();
  2326. ASSERT_FALSE(svr2.is_running());
  2327. ASSERT_FALSE(svr1.is_running());
  2328. });
  2329. svr1.wait_until_ready();
  2330. svr2.wait_until_ready();
  2331. Client cli("localhost", svr2_port);
  2332. cli.set_follow_location(true);
  2333. set_auth(cli);
  2334. auto res = cli.Get("/redir");
  2335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2336. EXPECT_EQ(StatusCode::OK_200, res->status);
  2337. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2338. EXPECT_TRUE(captured_authorization.empty());
  2339. }
  2340. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2341. TestDoNotForwardCredentialsOnRedirect(
  2342. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2343. }
  2344. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2345. TestDoNotForwardCredentialsOnRedirect(
  2346. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2347. }
  2348. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2349. Server svr1;
  2350. std::string captured_cookie;
  2351. bool target_hit = false;
  2352. svr1.Get("/target", [&](const Request &req, Response &res) {
  2353. captured_cookie = req.get_header_value("Cookie");
  2354. target_hit = true;
  2355. res.set_content("OK", "text/plain");
  2356. });
  2357. int svr1_port = 0;
  2358. auto thread1 = std::thread([&]() {
  2359. svr1_port = svr1.bind_to_any_port(HOST);
  2360. svr1.listen_after_bind();
  2361. });
  2362. Server svr2;
  2363. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2364. res.set_redirect(
  2365. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2366. });
  2367. int svr2_port = 0;
  2368. auto thread2 = std::thread([&]() {
  2369. svr2_port = svr2.bind_to_any_port(HOST);
  2370. svr2.listen_after_bind();
  2371. });
  2372. auto se = detail::scope_exit([&] {
  2373. svr2.stop();
  2374. thread2.join();
  2375. svr1.stop();
  2376. thread1.join();
  2377. ASSERT_FALSE(svr2.is_running());
  2378. ASSERT_FALSE(svr1.is_running());
  2379. });
  2380. svr1.wait_until_ready();
  2381. svr2.wait_until_ready();
  2382. Client cli("localhost", svr2_port);
  2383. cli.set_follow_location(true);
  2384. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2385. auto res = cli.Get("/redir", headers);
  2386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2387. EXPECT_EQ(StatusCode::OK_200, res->status);
  2388. EXPECT_TRUE(target_hit);
  2389. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2390. EXPECT_TRUE(captured_cookie.empty());
  2391. }
  2392. TEST(RedirectToSamePort, ForwardCookie) {
  2393. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2394. // header so that ordinary session flows keep working.
  2395. Server svr;
  2396. std::string captured_cookie;
  2397. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2398. res.set_redirect("/target", 302);
  2399. });
  2400. svr.Get("/target", [&](const Request &req, Response &res) {
  2401. captured_cookie = req.get_header_value("Cookie");
  2402. res.set_content("OK", "text/plain");
  2403. });
  2404. auto port = svr.bind_to_any_port(HOST);
  2405. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2406. auto se = detail::scope_exit([&] {
  2407. svr.stop();
  2408. thread.join();
  2409. ASSERT_FALSE(svr.is_running());
  2410. });
  2411. svr.wait_until_ready();
  2412. Client cli(HOST, port);
  2413. cli.set_follow_location(true);
  2414. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2415. auto res = cli.Get("/redir", headers);
  2416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2417. EXPECT_EQ(StatusCode::OK_200, res->status);
  2418. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2419. }
  2420. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2421. Server svr;
  2422. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2423. // Port number that overflows int — should not crash
  2424. res.set_redirect("http://localhost:99999999999999999999/target");
  2425. });
  2426. auto port = svr.bind_to_any_port(HOST);
  2427. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2428. auto se = detail::scope_exit([&] {
  2429. svr.stop();
  2430. thread.join();
  2431. ASSERT_FALSE(svr.is_running());
  2432. });
  2433. svr.wait_until_ready();
  2434. Client cli(HOST, port);
  2435. cli.set_follow_location(true);
  2436. auto res = cli.Get("/redir");
  2437. // Should fail gracefully, not crash (no valid response due to bad port)
  2438. EXPECT_FALSE(res);
  2439. }
  2440. TEST(RedirectFromPageWithContent, Redirect) {
  2441. Server svr;
  2442. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2443. res.set_content("___", "text/plain");
  2444. res.set_redirect("/2");
  2445. });
  2446. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2447. res.set_content("Hello World!", "text/plain");
  2448. });
  2449. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2450. auto se = detail::scope_exit([&] {
  2451. svr.stop();
  2452. th.join();
  2453. ASSERT_FALSE(svr.is_running());
  2454. });
  2455. svr.wait_until_ready();
  2456. {
  2457. Client cli("localhost", PORT);
  2458. cli.set_follow_location(true);
  2459. std::string body;
  2460. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2461. body.append(data, data_length);
  2462. return true;
  2463. });
  2464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2465. EXPECT_EQ(StatusCode::OK_200, res->status);
  2466. EXPECT_EQ("Hello World!", body);
  2467. }
  2468. {
  2469. Client cli("localhost", PORT);
  2470. std::string body;
  2471. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2472. body.append(data, data_length);
  2473. return true;
  2474. });
  2475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2476. EXPECT_EQ(StatusCode::Found_302, res->status);
  2477. EXPECT_EQ("___", body);
  2478. }
  2479. }
  2480. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2481. Server svr;
  2482. auto port_str = std::to_string(PORT);
  2483. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2484. auto expected_host = "[::1]:" + port_str;
  2485. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2486. res.set_content("___", "text/plain");
  2487. // res.set_redirect("/2");
  2488. res.set_redirect(redirect_url);
  2489. });
  2490. svr.Get("/2", [&](const Request &req, Response &res) {
  2491. auto host_header = req.headers.find("Host");
  2492. ASSERT_TRUE(host_header != req.headers.end());
  2493. EXPECT_EQ(expected_host, host_header->second);
  2494. res.set_content("Hello World!", "text/plain");
  2495. });
  2496. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2497. auto se = detail::scope_exit([&] {
  2498. svr.stop();
  2499. th.join();
  2500. ASSERT_FALSE(svr.is_running());
  2501. });
  2502. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2503. // actually starts anything, so the condition !svr.is_running() will
  2504. // always remain true, and the loop never stops.
  2505. // This basically counts how many milliseconds have passed since the
  2506. // call to svr.listen(), and if after 5 seconds nothing started yet
  2507. // aborts the test.
  2508. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2509. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2510. ASSERT_LT(milliseconds, 5000U);
  2511. }
  2512. {
  2513. Client cli("::1", PORT);
  2514. cli.set_follow_location(true);
  2515. std::string body;
  2516. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2517. body.append(data, data_length);
  2518. return true;
  2519. });
  2520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2521. EXPECT_EQ(StatusCode::OK_200, res->status);
  2522. EXPECT_EQ("Hello World!", body);
  2523. }
  2524. {
  2525. Client cli("::1", PORT);
  2526. std::string body;
  2527. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2528. body.append(data, data_length);
  2529. return true;
  2530. });
  2531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2532. EXPECT_EQ(StatusCode::Found_302, res->status);
  2533. EXPECT_EQ("___", body);
  2534. }
  2535. }
  2536. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2537. Server svr;
  2538. svr.Get("/foo", [](const Request &req, Response &res) {
  2539. auto a = req.params.find("a");
  2540. if (a != req.params.end()) {
  2541. res.set_content((*a).second, "text/plain");
  2542. res.status = StatusCode::OK_200;
  2543. } else {
  2544. res.status = StatusCode::BadRequest_400;
  2545. }
  2546. });
  2547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2548. auto se = detail::scope_exit([&] {
  2549. svr.stop();
  2550. thread.join();
  2551. ASSERT_FALSE(svr.is_running());
  2552. });
  2553. svr.wait_until_ready();
  2554. {
  2555. Client cli(HOST, PORT);
  2556. cli.set_path_encode(false);
  2557. auto res = cli.Get("/foo?a=explicitly+encoded");
  2558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2559. EXPECT_EQ(StatusCode::OK_200, res->status);
  2560. // This expects it back with a space, as the `+` won't have been
  2561. // url-encoded, and server-side the params get decoded turning `+`
  2562. // into spaces.
  2563. EXPECT_EQ("explicitly encoded", res->body);
  2564. }
  2565. }
  2566. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2567. // When path encoding is disabled the client must transmit the supplied
  2568. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2569. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2570. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2571. // than a space (0x20). Assert on the raw wire target to catch this.
  2572. Server svr;
  2573. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2574. svr.Get("/foo", [&](const Request &req, Response &res) {
  2575. EXPECT_EQ(expected_target, req.target);
  2576. res.status = StatusCode::OK_200;
  2577. });
  2578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2579. auto se = detail::scope_exit([&] {
  2580. svr.stop();
  2581. thread.join();
  2582. ASSERT_FALSE(svr.is_running());
  2583. });
  2584. svr.wait_until_ready();
  2585. {
  2586. Client cli(HOST, PORT);
  2587. cli.set_path_encode(false);
  2588. auto res = cli.Get(expected_target.c_str());
  2589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2590. EXPECT_EQ(StatusCode::OK_200, res->status);
  2591. }
  2592. }
  2593. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2594. Server svr;
  2595. svr.Get("/", [](const Request &req, Response &) {
  2596. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. {
  2606. Client cli(HOST, PORT);
  2607. cli.set_path_encode(false);
  2608. auto res = cli.Get("/?something=%0A");
  2609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. }
  2613. TEST(BindServerTest, BindDualStack) {
  2614. Server svr;
  2615. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2616. res.set_content("Hello World!", "text/plain");
  2617. });
  2618. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2619. auto se = detail::scope_exit([&] {
  2620. svr.stop();
  2621. thread.join();
  2622. ASSERT_FALSE(svr.is_running());
  2623. });
  2624. svr.wait_until_ready();
  2625. {
  2626. Client cli("127.0.0.1", PORT);
  2627. auto res = cli.Get("/1");
  2628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. EXPECT_EQ("Hello World!", res->body);
  2631. }
  2632. {
  2633. Client cli("::1", PORT);
  2634. auto res = cli.Get("/1");
  2635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2636. EXPECT_EQ(StatusCode::OK_200, res->status);
  2637. EXPECT_EQ("Hello World!", res->body);
  2638. }
  2639. }
  2640. TEST(BindServerTest, BindAndListenSeparately) {
  2641. Server svr;
  2642. int port = svr.bind_to_any_port("0.0.0.0");
  2643. ASSERT_TRUE(svr.is_valid());
  2644. ASSERT_TRUE(port > 0);
  2645. svr.stop();
  2646. }
  2647. #ifdef CPPHTTPLIB_SSL_ENABLED
  2648. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2650. CLIENT_CA_CERT_DIR);
  2651. int port = svr.bind_to_any_port("0.0.0.0");
  2652. ASSERT_TRUE(svr.is_valid());
  2653. ASSERT_TRUE(port > 0);
  2654. svr.stop();
  2655. }
  2656. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2657. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2658. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2659. int port = svr.bind_to_any_port("0.0.0.0");
  2660. ASSERT_TRUE(svr.is_valid());
  2661. ASSERT_TRUE(port > 0);
  2662. svr.stop();
  2663. }
  2664. TEST(BindServerTest, UpdateCertsPem) {
  2665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2666. int port = svr.bind_to_any_port("0.0.0.0");
  2667. ASSERT_TRUE(svr.is_valid());
  2668. ASSERT_TRUE(port > 0);
  2669. // Read PEM files
  2670. std::string cert_pem, key_pem, ca_pem;
  2671. read_file(SERVER_CERT_FILE, cert_pem);
  2672. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2673. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2674. // Update server certificates using PEM API
  2675. ASSERT_TRUE(
  2676. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2677. ASSERT_TRUE(svr.is_valid());
  2678. svr.stop();
  2679. }
  2680. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2681. // Start server with client CA (enables client auth)
  2682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2683. ASSERT_TRUE(svr.is_valid());
  2684. bool handler_called = false;
  2685. svr.Get("/test", [&](const Request &req, Response &res) {
  2686. handler_called = true;
  2687. // Verify client certificate is present
  2688. auto cert = req.peer_cert();
  2689. EXPECT_TRUE(static_cast<bool>(cert));
  2690. res.set_content("ok", "text/plain");
  2691. });
  2692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. t.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. // Read PEM files
  2700. std::string cert_pem, key_pem, ca_pem;
  2701. read_file(SERVER_CERT_FILE, cert_pem);
  2702. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2703. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2704. // Update server certificates and client CA using PEM API while server running
  2705. ASSERT_TRUE(
  2706. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2707. // Connect with client certificate
  2708. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2709. cli.enable_server_certificate_verification(false);
  2710. cli.set_connection_timeout(30);
  2711. auto res = cli.Get("/test");
  2712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2713. ASSERT_EQ(StatusCode::OK_200, res->status);
  2714. ASSERT_TRUE(handler_called);
  2715. EXPECT_EQ("ok", res->body);
  2716. }
  2717. #endif
  2718. TEST(ErrorHandlerTest, ContentLength) {
  2719. Server svr;
  2720. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2721. res.status = StatusCode::OK_200;
  2722. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2723. "text/html"); // <= Content-Length still 13
  2724. });
  2725. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2726. res.set_content("Hello World!\n", "text/plain");
  2727. res.status = 524;
  2728. });
  2729. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2730. auto se = detail::scope_exit([&] {
  2731. svr.stop();
  2732. thread.join();
  2733. ASSERT_FALSE(svr.is_running());
  2734. });
  2735. svr.wait_until_ready();
  2736. {
  2737. Client cli(HOST, PORT);
  2738. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2740. EXPECT_EQ(StatusCode::OK_200, res->status);
  2741. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2742. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2743. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2744. }
  2745. }
  2746. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2747. TEST(ExceptionTest, WithoutExceptionHandler) {
  2748. Server svr;
  2749. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2750. throw std::runtime_error("exception...");
  2751. });
  2752. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2753. throw std::runtime_error("exception\r\n...");
  2754. });
  2755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. listen_thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli("localhost", PORT);
  2763. {
  2764. auto res = cli.Get("/exception");
  2765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2766. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2767. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2768. }
  2769. {
  2770. auto res = cli.Get("/unknown");
  2771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2772. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2773. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2774. }
  2775. }
  2776. TEST(ExceptionTest, WithExceptionHandler) {
  2777. Server svr;
  2778. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2779. std::exception_ptr ep) {
  2780. EXPECT_FALSE(ep == nullptr);
  2781. try {
  2782. std::rethrow_exception(ep);
  2783. } catch (std::exception &e) {
  2784. EXPECT_EQ("abc", std::string(e.what()));
  2785. } catch (...) {}
  2786. res.status = StatusCode::InternalServerError_500;
  2787. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2788. "text/html"); // <= Content-Length still 13 at this point
  2789. });
  2790. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2791. res.set_content("Hello World!\n", "text/plain");
  2792. throw std::runtime_error("abc");
  2793. });
  2794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2795. auto se = detail::scope_exit([&] {
  2796. svr.stop();
  2797. thread.join();
  2798. ASSERT_FALSE(svr.is_running());
  2799. });
  2800. svr.wait_until_ready();
  2801. for (size_t i = 0; i < 10; i++) {
  2802. Client cli(HOST, PORT);
  2803. for (size_t j = 0; j < 100; j++) {
  2804. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2806. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2807. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2808. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2809. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2810. }
  2811. cli.set_keep_alive(true);
  2812. for (size_t j = 0; j < 100; j++) {
  2813. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2815. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2816. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2817. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2818. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2819. }
  2820. }
  2821. }
  2822. TEST(ExceptionTest, AndErrorHandler) {
  2823. Server svr;
  2824. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2825. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2826. });
  2827. svr.set_exception_handler(
  2828. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2829. EXPECT_FALSE(ep == nullptr);
  2830. try {
  2831. std::rethrow_exception(ep);
  2832. } catch (std::exception &e) {
  2833. res.set_content(e.what(), "text/html");
  2834. } catch (...) {}
  2835. res.status = StatusCode::InternalServerError_500;
  2836. });
  2837. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2838. throw std::runtime_error("EXCEPTION");
  2839. });
  2840. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2841. res.set_content("ERROR", "text/html");
  2842. res.status = StatusCode::InternalServerError_500;
  2843. });
  2844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. thread.join();
  2848. ASSERT_FALSE(svr.is_running());
  2849. });
  2850. svr.wait_until_ready();
  2851. Client cli(HOST, PORT);
  2852. {
  2853. auto res = cli.Get("/exception");
  2854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2855. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2856. EXPECT_EQ("EXCEPTION", res->body);
  2857. }
  2858. {
  2859. auto res = cli.Get("/error");
  2860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2861. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2862. EXPECT_EQ("ERROR", res->body);
  2863. }
  2864. {
  2865. auto res = cli.Get("/invalid");
  2866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2868. EXPECT_EQ("NOT_FOUND", res->body);
  2869. }
  2870. }
  2871. #endif
  2872. TEST(NoContentTest, ContentLength) {
  2873. Server svr;
  2874. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2875. res.status = StatusCode::NoContent_204;
  2876. });
  2877. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2878. auto se = detail::scope_exit([&] {
  2879. svr.stop();
  2880. thread.join();
  2881. ASSERT_FALSE(svr.is_running());
  2882. });
  2883. svr.wait_until_ready();
  2884. {
  2885. Client cli(HOST, PORT);
  2886. auto res = cli.Get("/hi");
  2887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2888. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2889. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2890. }
  2891. }
  2892. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2893. #ifdef CPPHTTPLIB_SSL_ENABLED
  2894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2895. ASSERT_TRUE(svr.is_valid());
  2896. #else
  2897. Server svr;
  2898. #endif
  2899. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2900. if (req.path == "/routing_handler") {
  2901. res.set_header("PRE_ROUTING", "on");
  2902. res.set_content("Routing Handler", "text/plain");
  2903. return httplib::Server::HandlerResponse::Handled;
  2904. }
  2905. return httplib::Server::HandlerResponse::Unhandled;
  2906. });
  2907. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2908. res.set_content("Error", "text/html");
  2909. });
  2910. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2911. if (req.path == "/routing_handler") {
  2912. res.set_header("POST_ROUTING", "on");
  2913. }
  2914. });
  2915. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2916. res.set_content("Hello World!\n", "text/plain");
  2917. });
  2918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2919. auto se = detail::scope_exit([&] {
  2920. svr.stop();
  2921. thread.join();
  2922. ASSERT_FALSE(svr.is_running());
  2923. });
  2924. svr.wait_until_ready();
  2925. {
  2926. #ifdef CPPHTTPLIB_SSL_ENABLED
  2927. SSLClient cli(HOST, PORT);
  2928. cli.enable_server_certificate_verification(false);
  2929. #else
  2930. Client cli(HOST, PORT);
  2931. #endif
  2932. auto res = cli.Get("/routing_handler");
  2933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2934. EXPECT_EQ(StatusCode::OK_200, res->status);
  2935. EXPECT_EQ("Routing Handler", res->body);
  2936. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2937. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2938. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2939. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2940. }
  2941. {
  2942. #ifdef CPPHTTPLIB_SSL_ENABLED
  2943. SSLClient cli(HOST, PORT);
  2944. cli.enable_server_certificate_verification(false);
  2945. #else
  2946. Client cli(HOST, PORT);
  2947. #endif
  2948. auto res = cli.Get("/hi");
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(StatusCode::OK_200, res->status);
  2951. EXPECT_EQ("Hello World!\n", res->body);
  2952. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2953. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2954. }
  2955. {
  2956. #ifdef CPPHTTPLIB_SSL_ENABLED
  2957. SSLClient cli(HOST, PORT);
  2958. cli.enable_server_certificate_verification(false);
  2959. #else
  2960. Client cli(HOST, PORT);
  2961. #endif
  2962. auto res = cli.Get("/aaa");
  2963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2964. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2965. EXPECT_EQ("Error", res->body);
  2966. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2967. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2968. }
  2969. }
  2970. TEST(RequestHandlerTest, PreRequestHandler) {
  2971. auto route_path = "/user/:user";
  2972. Server svr;
  2973. svr.Get("/hi", [](const Request &, Response &res) {
  2974. res.set_content("hi", "text/plain");
  2975. });
  2976. svr.Get(route_path, [](const Request &req, Response &res) {
  2977. res.set_content(req.path_params.at("user"), "text/plain");
  2978. });
  2979. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2980. if (req.matched_route == route_path) {
  2981. auto user = req.path_params.at("user");
  2982. if (user != "john") {
  2983. res.status = StatusCode::Forbidden_403;
  2984. res.set_content("error", "text/html");
  2985. return Server::HandlerResponse::Handled;
  2986. }
  2987. }
  2988. return Server::HandlerResponse::Unhandled;
  2989. });
  2990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2991. auto se = detail::scope_exit([&] {
  2992. svr.stop();
  2993. thread.join();
  2994. ASSERT_FALSE(svr.is_running());
  2995. });
  2996. svr.wait_until_ready();
  2997. Client cli(HOST, PORT);
  2998. {
  2999. auto res = cli.Get("/hi");
  3000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3001. EXPECT_EQ(StatusCode::OK_200, res->status);
  3002. EXPECT_EQ("hi", res->body);
  3003. }
  3004. {
  3005. auto res = cli.Get("/user/john");
  3006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3007. EXPECT_EQ(StatusCode::OK_200, res->status);
  3008. EXPECT_EQ("john", res->body);
  3009. }
  3010. {
  3011. auto res = cli.Get("/user/invalid-user");
  3012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3013. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3014. EXPECT_EQ("error", res->body);
  3015. }
  3016. }
  3017. // The pre-request handler must run before the request body is read, so a
  3018. // rejected request never forces the server to buffer a (potentially large)
  3019. // body. Here the posted body is larger than the payload limit: if the body
  3020. // were read first the server would answer 413, but because the pre-request
  3021. // handler runs first it answers 403 and the body is never read.
  3022. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3023. Server svr;
  3024. svr.set_payload_max_length(8);
  3025. auto handler_ran = false;
  3026. svr.Post("/reject", [&](const Request &req, Response &res) {
  3027. handler_ran = true;
  3028. res.set_content(req.body, "text/plain");
  3029. });
  3030. svr.Post("/accept", [](const Request &req, Response &res) {
  3031. res.set_content(req.body, "text/plain");
  3032. });
  3033. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3034. if (req.matched_route == "/reject") {
  3035. res.status = StatusCode::Forbidden_403;
  3036. res.set_content("denied", "text/plain");
  3037. return Server::HandlerResponse::Handled;
  3038. }
  3039. return Server::HandlerResponse::Unhandled;
  3040. });
  3041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. thread.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. Client cli(HOST, PORT);
  3049. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3050. // rejects with 403 before the body is read, so 413 is never reached.
  3051. {
  3052. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3054. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3055. EXPECT_EQ("denied", res->body);
  3056. EXPECT_FALSE(handler_ran);
  3057. }
  3058. // An approved route still reads the body and enforces the payload limit.
  3059. {
  3060. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3062. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3063. }
  3064. }
  3065. TEST(UserDataTest, BasicOperations) {
  3066. httplib::UserData ud;
  3067. // Initially empty
  3068. EXPECT_FALSE(ud.has("key"));
  3069. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3070. // set and get
  3071. ud.set("key", 42);
  3072. EXPECT_TRUE(ud.has("key"));
  3073. auto *p = ud.get<int>("key");
  3074. ASSERT_NE(nullptr, p);
  3075. EXPECT_EQ(42, *p);
  3076. // Type mismatch → nullptr
  3077. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3078. // Overwrite with different type
  3079. ud.set("key", std::string("hello"));
  3080. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3081. auto *s = ud.get<std::string>("key");
  3082. ASSERT_NE(nullptr, s);
  3083. EXPECT_EQ("hello", *s);
  3084. // erase
  3085. ud.erase("key");
  3086. EXPECT_FALSE(ud.has("key"));
  3087. // clear
  3088. ud.set("a", 1);
  3089. ud.set("b", 2);
  3090. ud.clear();
  3091. EXPECT_FALSE(ud.has("a"));
  3092. EXPECT_FALSE(ud.has("b"));
  3093. }
  3094. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3095. struct AuthCtx {
  3096. std::string user_id;
  3097. };
  3098. Server svr;
  3099. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3100. res.user_data.set("auth", AuthCtx{"alice"});
  3101. return Server::HandlerResponse::Unhandled;
  3102. });
  3103. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3104. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3105. ASSERT_NE(nullptr, ctx);
  3106. res.set_content("Hello " + ctx->user_id, "text/plain");
  3107. });
  3108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3109. auto se = detail::scope_exit([&] {
  3110. svr.stop();
  3111. thread.join();
  3112. ASSERT_FALSE(svr.is_running());
  3113. });
  3114. svr.wait_until_ready();
  3115. Client cli(HOST, PORT);
  3116. auto res = cli.Get("/me");
  3117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3118. EXPECT_EQ(StatusCode::OK_200, res->status);
  3119. EXPECT_EQ("Hello alice", res->body);
  3120. }
  3121. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3122. struct RoleCtx {
  3123. std::string role;
  3124. };
  3125. Server svr;
  3126. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3127. res.user_data.set("role", RoleCtx{"admin"});
  3128. return Server::HandlerResponse::Unhandled;
  3129. });
  3130. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3131. auto *ctx = res.user_data.get<RoleCtx>("role");
  3132. ASSERT_NE(nullptr, ctx);
  3133. res.set_content(ctx->role, "text/plain");
  3134. });
  3135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3136. auto se = detail::scope_exit([&] {
  3137. svr.stop();
  3138. thread.join();
  3139. ASSERT_FALSE(svr.is_running());
  3140. });
  3141. svr.wait_until_ready();
  3142. Client cli(HOST, PORT);
  3143. auto res = cli.Get("/role");
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ("admin", res->body);
  3147. }
  3148. TEST(InvalidFormatTest, StatusCode) {
  3149. Server svr;
  3150. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3151. res.set_content("Hello World!\n", "text/plain");
  3152. res.status = 9999; // Status should be a three-digit code...
  3153. });
  3154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3155. auto se = detail::scope_exit([&] {
  3156. svr.stop();
  3157. thread.join();
  3158. ASSERT_FALSE(svr.is_running());
  3159. });
  3160. svr.wait_until_ready();
  3161. {
  3162. Client cli(HOST, PORT);
  3163. auto res = cli.Get("/hi");
  3164. ASSERT_FALSE(res);
  3165. }
  3166. }
  3167. TEST(URLFragmentTest, WithFragment) {
  3168. Server svr;
  3169. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3170. EXPECT_TRUE(req.target == "/hi");
  3171. });
  3172. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3173. auto se = detail::scope_exit([&] {
  3174. svr.stop();
  3175. thread.join();
  3176. ASSERT_FALSE(svr.is_running());
  3177. });
  3178. svr.wait_until_ready();
  3179. {
  3180. Client cli(HOST, PORT);
  3181. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3182. EXPECT_TRUE(res);
  3183. EXPECT_EQ(StatusCode::OK_200, res->status);
  3184. res = cli.Get("/hi%23key1=val1=key2=val2");
  3185. EXPECT_TRUE(res);
  3186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3187. }
  3188. }
  3189. TEST(HeaderWriter, SetHeaderWriter) {
  3190. Server svr;
  3191. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3192. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3193. return detail::write_headers(strm, hdrs);
  3194. });
  3195. svr.Get("/hi", [](const Request &req, Response &res) {
  3196. auto it = req.headers.find("CustomClientHeader");
  3197. EXPECT_TRUE(it != req.headers.end());
  3198. EXPECT_EQ(it->second, "CustomClientValue");
  3199. res.set_content("Hello World!\n", "text/plain");
  3200. });
  3201. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3202. auto se = detail::scope_exit([&] {
  3203. svr.stop();
  3204. thread.join();
  3205. ASSERT_FALSE(svr.is_running());
  3206. });
  3207. svr.wait_until_ready();
  3208. {
  3209. Client cli(HOST, PORT);
  3210. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3211. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3212. return detail::write_headers(strm, hdrs);
  3213. });
  3214. auto res = cli.Get("/hi");
  3215. EXPECT_TRUE(res);
  3216. EXPECT_EQ(StatusCode::OK_200, res->status);
  3217. auto it = res->headers.find("CustomServerHeader");
  3218. EXPECT_TRUE(it != res->headers.end());
  3219. EXPECT_EQ(it->second, "CustomServerValue");
  3220. }
  3221. }
  3222. class ServerTest : public ::testing::Test {
  3223. protected:
  3224. ServerTest()
  3225. : cli_(HOST, PORT)
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. ,
  3228. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3229. #endif
  3230. {
  3231. #ifdef CPPHTTPLIB_SSL_ENABLED
  3232. cli_.enable_server_certificate_verification(false);
  3233. #endif
  3234. // Allow LARGE_DATA (100MB) responses
  3235. cli_.set_payload_max_length(200 * 1024 * 1024);
  3236. }
  3237. virtual void SetUp() {
  3238. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3239. svr_.set_payload_max_length(200 * 1024 * 1024);
  3240. svr_.set_mount_point("/", "./www");
  3241. svr_.set_mount_point("/mount", "./www2");
  3242. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3243. svr_.Get("/hi",
  3244. [&](const Request & /*req*/, Response &res) {
  3245. res.set_content("Hello World!", "text/plain");
  3246. })
  3247. .Get("/file_content",
  3248. [&](const Request & /*req*/, Response &res) {
  3249. res.set_file_content("./www/dir/test.html");
  3250. })
  3251. .Get("/file_content_with_content_type",
  3252. [&](const Request & /*req*/, Response &res) {
  3253. res.set_file_content("./www/file", "text/plain");
  3254. })
  3255. .Get("/invalid_file_content",
  3256. [&](const Request & /*req*/, Response &res) {
  3257. res.set_file_content("./www/dir/invalid_file_path");
  3258. })
  3259. .Get("/http_response_splitting",
  3260. [&](const Request & /*req*/, Response &res) {
  3261. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3262. EXPECT_EQ(0U, res.headers.size());
  3263. EXPECT_FALSE(res.has_header("a"));
  3264. res.set_header("a", "1\nSet-Cookie: a=1");
  3265. EXPECT_EQ(0U, res.headers.size());
  3266. EXPECT_FALSE(res.has_header("a"));
  3267. res.set_header("a", "1\rSet-Cookie: a=1");
  3268. EXPECT_EQ(0U, res.headers.size());
  3269. EXPECT_FALSE(res.has_header("a"));
  3270. res.set_header("a\r\nb", "0");
  3271. EXPECT_EQ(0U, res.headers.size());
  3272. EXPECT_FALSE(res.has_header("a"));
  3273. res.set_header("a\rb", "0");
  3274. EXPECT_EQ(0U, res.headers.size());
  3275. EXPECT_FALSE(res.has_header("a"));
  3276. res.set_header("a\nb", "0");
  3277. EXPECT_EQ(0U, res.headers.size());
  3278. EXPECT_FALSE(res.has_header("a"));
  3279. res.set_redirect("1\r\nSet-Cookie: a=1");
  3280. EXPECT_EQ(0U, res.headers.size());
  3281. EXPECT_FALSE(res.has_header("Location"));
  3282. })
  3283. .Get("/slow",
  3284. [&](const Request & /*req*/, Response &res) {
  3285. std::this_thread::sleep_for(std::chrono::seconds(4));
  3286. res.set_content("slow", "text/plain");
  3287. })
  3288. #if 0
  3289. .Post("/slowpost",
  3290. [&](const Request & /*req*/, Response &res) {
  3291. std::this_thread::sleep_for(std::chrono::seconds(2));
  3292. res.set_content("slow", "text/plain");
  3293. })
  3294. #endif
  3295. .Get("/remote_addr",
  3296. [&](const Request &req, Response &res) {
  3297. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3298. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3299. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3300. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3301. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3302. #endif
  3303. res.set_content(req.remote_addr, "text/plain");
  3304. })
  3305. .Get("/local_addr",
  3306. [&](const Request &req, Response &res) {
  3307. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3308. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3309. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3310. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3311. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3312. #endif
  3313. auto local_addr = req.local_addr;
  3314. auto local_port = std::to_string(req.local_port);
  3315. res.set_content(local_addr.append(":").append(local_port),
  3316. "text/plain");
  3317. })
  3318. .Get("/endwith%",
  3319. [&](const Request & /*req*/, Response &res) {
  3320. res.set_content("Hello World!", "text/plain");
  3321. })
  3322. .Get("/a\\+\\+b",
  3323. [&](const Request &req, Response &res) {
  3324. ASSERT_TRUE(req.has_param("a +b"));
  3325. auto val = req.get_param_value("a +b");
  3326. res.set_content(val, "text/plain");
  3327. })
  3328. .Get("/", [&](const Request & /*req*/,
  3329. Response &res) { res.set_redirect("/hi"); })
  3330. .Post("/1",
  3331. [](const Request & /*req*/, Response &res) {
  3332. res.set_redirect("/2", StatusCode::SeeOther_303);
  3333. })
  3334. .Get("/2",
  3335. [](const Request & /*req*/, Response &res) {
  3336. res.set_content("redirected.", "text/plain");
  3337. res.status = StatusCode::OK_200;
  3338. })
  3339. .Post("/person",
  3340. [&](const Request &req, Response &res) {
  3341. if (req.has_param("name") && req.has_param("note")) {
  3342. persons_[req.get_param_value("name")] =
  3343. req.get_param_value("note");
  3344. } else {
  3345. res.status = StatusCode::BadRequest_400;
  3346. }
  3347. })
  3348. .Put("/person",
  3349. [&](const Request &req, Response &res) {
  3350. if (req.has_param("name") && req.has_param("note")) {
  3351. persons_[req.get_param_value("name")] =
  3352. req.get_param_value("note");
  3353. } else {
  3354. res.status = StatusCode::BadRequest_400;
  3355. }
  3356. })
  3357. .Get("/person/(.*)",
  3358. [&](const Request &req, Response &res) {
  3359. string name = req.matches[1];
  3360. if (persons_.find(name) != persons_.end()) {
  3361. auto note = persons_[name];
  3362. res.set_content(note, "text/plain");
  3363. } else {
  3364. res.status = StatusCode::NotFound_404;
  3365. }
  3366. })
  3367. .Delete("/person",
  3368. [&](const Request &req, Response &res) {
  3369. if (req.has_param("name")) {
  3370. string name = req.get_param_value("name");
  3371. if (persons_.find(name) != persons_.end()) {
  3372. persons_.erase(name);
  3373. res.set_content("DELETED", "text/plain");
  3374. } else {
  3375. res.status = StatusCode::NotFound_404;
  3376. }
  3377. } else {
  3378. res.status = StatusCode::BadRequest_400;
  3379. }
  3380. })
  3381. .Post("/x-www-form-urlencoded-json",
  3382. [&](const Request &req, Response &res) {
  3383. auto json = req.get_param_value("json");
  3384. ASSERT_EQ(JSON_DATA, json);
  3385. res.set_content(json, "appliation/json");
  3386. res.status = StatusCode::OK_200;
  3387. })
  3388. .Get("/streamed-chunked",
  3389. [&](const Request & /*req*/, Response &res) {
  3390. res.set_chunked_content_provider(
  3391. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3392. sink.os << "123";
  3393. sink.os << "456";
  3394. sink.os << "789";
  3395. sink.done();
  3396. return true;
  3397. });
  3398. })
  3399. .Get("/streamed-chunked-with-prohibited-trailer",
  3400. [&](const Request & /*req*/, Response &res) {
  3401. auto i = new int(0);
  3402. // Declare both a prohibited trailer (Content-Length) and an
  3403. // allowed one
  3404. res.set_header("Trailer", "Content-Length, X-Allowed");
  3405. res.set_chunked_content_provider(
  3406. "text/plain",
  3407. [i](size_t /*offset*/, DataSink &sink) {
  3408. switch (*i) {
  3409. case 0: sink.os << "123"; break;
  3410. case 1: sink.os << "456"; break;
  3411. case 2: sink.os << "789"; break;
  3412. case 3: {
  3413. sink.done_with_trailer(
  3414. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3415. } break;
  3416. }
  3417. (*i)++;
  3418. return true;
  3419. },
  3420. [i](bool success) {
  3421. EXPECT_TRUE(success);
  3422. delete i;
  3423. });
  3424. })
  3425. .Get("/streamed-chunked2",
  3426. [&](const Request & /*req*/, Response &res) {
  3427. auto i = new int(0);
  3428. res.set_chunked_content_provider(
  3429. "text/plain",
  3430. [i](size_t /*offset*/, DataSink &sink) {
  3431. switch (*i) {
  3432. case 0: sink.os << "123"; break;
  3433. case 1: sink.os << "456"; break;
  3434. case 2: sink.os << "789"; break;
  3435. case 3: sink.done(); break;
  3436. }
  3437. (*i)++;
  3438. return true;
  3439. },
  3440. [i](bool success) {
  3441. EXPECT_TRUE(success);
  3442. delete i;
  3443. });
  3444. })
  3445. .Get("/streamed-chunked-with-trailer",
  3446. [&](const Request & /*req*/, Response &res) {
  3447. auto i = new int(0);
  3448. res.set_header("Trailer", "Dummy1, Dummy2");
  3449. res.set_chunked_content_provider(
  3450. "text/plain",
  3451. [i](size_t /*offset*/, DataSink &sink) {
  3452. switch (*i) {
  3453. case 0: sink.os << "123"; break;
  3454. case 1: sink.os << "456"; break;
  3455. case 2: sink.os << "789"; break;
  3456. case 3: {
  3457. sink.done_with_trailer(
  3458. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3459. } break;
  3460. }
  3461. (*i)++;
  3462. return true;
  3463. },
  3464. [i](bool success) {
  3465. EXPECT_TRUE(success);
  3466. delete i;
  3467. });
  3468. })
  3469. .Get("/streamed",
  3470. [&](const Request & /*req*/, Response &res) {
  3471. res.set_content_provider(
  3472. 6, "text/plain",
  3473. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3474. sink.os << (offset < 3 ? "a" : "b");
  3475. return true;
  3476. });
  3477. })
  3478. .Get("/streamed-without-length",
  3479. [&](const Request & /*req*/, Response &res) {
  3480. auto data = new std::string("abcdefg");
  3481. res.set_content_provider(
  3482. "text/plain",
  3483. [data](size_t offset, DataSink &sink) {
  3484. if (offset < data->size()) {
  3485. sink.os << data->substr(offset);
  3486. }
  3487. sink.done();
  3488. return true;
  3489. },
  3490. [data](bool success) {
  3491. EXPECT_TRUE(success);
  3492. delete data;
  3493. });
  3494. })
  3495. .Get("/streamed-with-range",
  3496. [&](const Request &req, Response &res) {
  3497. auto data = new std::string("abcdefg");
  3498. res.set_content_provider(
  3499. data->size(), "text/plain",
  3500. [data](size_t offset, size_t length, DataSink &sink) {
  3501. size_t DATA_CHUNK_SIZE = 4;
  3502. const auto &d = *data;
  3503. auto out_len =
  3504. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3505. auto ret =
  3506. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3507. EXPECT_TRUE(ret);
  3508. return true;
  3509. },
  3510. [data, &req](bool success) {
  3511. EXPECT_EQ(success, !req.has_param("error"));
  3512. delete data;
  3513. });
  3514. })
  3515. .Get("/streamed-cancel",
  3516. [&](const Request & /*req*/, Response &res) {
  3517. res.set_content_provider(
  3518. size_t(-1), "text/plain",
  3519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3520. sink.os << "data_chunk";
  3521. return true;
  3522. });
  3523. })
  3524. .Get("/regex-with-delimiter",
  3525. [&](const Request &req, Response & /*res*/) {
  3526. ASSERT_TRUE(req.has_param("key"));
  3527. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3528. })
  3529. .Get("/with-range",
  3530. [&](const Request & /*req*/, Response &res) {
  3531. res.set_content("abcdefg", "text/plain");
  3532. })
  3533. .Get("/test-start-time",
  3534. [&](const Request &req, Response & /*res*/) {
  3535. EXPECT_NE(req.start_time_,
  3536. std::chrono::steady_clock::time_point::min());
  3537. })
  3538. .Get("/with-range-customized-response",
  3539. [&](const Request & /*req*/, Response &res) {
  3540. res.status = StatusCode::BadRequest_400;
  3541. res.set_content(JSON_DATA, "application/json");
  3542. })
  3543. .Post("/chunked",
  3544. [&](const Request &req, Response & /*res*/) {
  3545. EXPECT_EQ(req.body, "dechunked post body");
  3546. })
  3547. .Post("/large-chunked",
  3548. [&](const Request &req, Response & /*res*/) {
  3549. std::string expected(6 * 30 * 1024u, 'a');
  3550. EXPECT_EQ(req.body, expected);
  3551. })
  3552. .Post("/multipart",
  3553. [&](const Request &req, Response & /*res*/) {
  3554. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3555. req.form.get_field_count("text2") +
  3556. req.form.get_field_count("file3") +
  3557. req.form.get_field_count("file4"));
  3558. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3559. req.form.get_file_count("file2"));
  3560. ASSERT_TRUE(!req.form.has_file("???"));
  3561. ASSERT_TRUE(!req.form.has_field("???"));
  3562. ASSERT_TRUE(req.body.empty());
  3563. {
  3564. const auto &text = req.form.get_field("text1");
  3565. EXPECT_EQ("text default", text);
  3566. }
  3567. {
  3568. const auto &text = req.form.get_field("text2");
  3569. EXPECT_EQ("aωb", text);
  3570. }
  3571. {
  3572. const auto &file = req.form.get_file("file1");
  3573. EXPECT_EQ("hello.txt", file.filename);
  3574. EXPECT_EQ("text/plain", file.content_type);
  3575. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3576. }
  3577. {
  3578. const auto &file = req.form.get_file("file2");
  3579. EXPECT_EQ("world.json", file.filename);
  3580. EXPECT_EQ("application/json", file.content_type);
  3581. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3582. }
  3583. {
  3584. const auto &text = req.form.get_field("file3");
  3585. EXPECT_EQ(0u, text.size());
  3586. }
  3587. {
  3588. const auto &text = req.form.get_field("file4");
  3589. EXPECT_EQ(0u, text.size());
  3590. }
  3591. })
  3592. .Post("/multipart/multi_file_values",
  3593. [&](const Request &req, Response & /*res*/) {
  3594. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3595. req.form.get_field_count("multi_text1"));
  3596. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3597. ASSERT_TRUE(!req.form.has_file("???"));
  3598. ASSERT_TRUE(!req.form.has_field("???"));
  3599. ASSERT_TRUE(req.body.empty());
  3600. {
  3601. const auto &text = req.form.get_field("text");
  3602. EXPECT_EQ("default text", text);
  3603. }
  3604. {
  3605. const auto &text1_values = req.form.get_fields("multi_text1");
  3606. EXPECT_EQ(2u, text1_values.size());
  3607. EXPECT_EQ("aaaaa", text1_values[0]);
  3608. EXPECT_EQ("bbbbb", text1_values[1]);
  3609. }
  3610. {
  3611. const auto &file1_values = req.form.get_files("multi_file1");
  3612. EXPECT_EQ(2u, file1_values.size());
  3613. auto file1 = file1_values[0];
  3614. EXPECT_EQ(file1.filename, "hello.txt");
  3615. EXPECT_EQ(file1.content_type, "text/plain");
  3616. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3617. auto file2 = file1_values[1];
  3618. EXPECT_EQ(file2.filename, "world.json");
  3619. EXPECT_EQ(file2.content_type, "application/json");
  3620. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3621. }
  3622. })
  3623. .Post("/empty",
  3624. [&](const Request &req, Response &res) {
  3625. EXPECT_EQ(req.body, "");
  3626. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3627. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3628. res.set_content("empty", "text/plain");
  3629. })
  3630. .Post("/empty-no-content-type",
  3631. [&](const Request &req, Response &res) {
  3632. EXPECT_EQ(req.body, "");
  3633. EXPECT_FALSE(req.has_header("Content-Type"));
  3634. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3635. res.set_content("empty-no-content-type", "text/plain");
  3636. })
  3637. .Post("/path-only",
  3638. [&](const Request &req, Response &res) {
  3639. EXPECT_EQ(req.body, "");
  3640. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3641. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3642. res.set_content("path-only", "text/plain");
  3643. })
  3644. .Post("/path-headers-only",
  3645. [&](const Request &req, Response &res) {
  3646. EXPECT_EQ(req.body, "");
  3647. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3648. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3649. EXPECT_EQ("world", req.get_header_value("hello"));
  3650. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3651. res.set_content("path-headers-only", "text/plain");
  3652. })
  3653. .Post("/post-large",
  3654. [&](const Request &req, Response &res) {
  3655. EXPECT_EQ(req.body, LARGE_DATA);
  3656. res.set_content(req.body, "text/plain");
  3657. })
  3658. .Post("/post-loopback",
  3659. [&](const Request &, Response &res,
  3660. ContentReader const &content_reader) {
  3661. std::string body;
  3662. content_reader([&](const char *data, size_t data_length) {
  3663. body.append(data, data_length);
  3664. return true;
  3665. });
  3666. res.set_content(body, "text/plain");
  3667. })
  3668. .Put("/put-loopback",
  3669. [&](const Request &, Response &res,
  3670. ContentReader const &content_reader) {
  3671. std::string body;
  3672. content_reader([&](const char *data, size_t data_length) {
  3673. body.append(data, data_length);
  3674. return true;
  3675. });
  3676. res.set_content(body, "text/plain");
  3677. })
  3678. .Patch("/patch-loopback",
  3679. [&](const Request &, Response &res,
  3680. ContentReader const &content_reader) {
  3681. std::string body;
  3682. content_reader([&](const char *data, size_t data_length) {
  3683. body.append(data, data_length);
  3684. return true;
  3685. });
  3686. res.set_content(body, "text/plain");
  3687. })
  3688. .Put("/empty-no-content-type",
  3689. [&](const Request &req, Response &res) {
  3690. EXPECT_EQ(req.body, "");
  3691. EXPECT_FALSE(req.has_header("Content-Type"));
  3692. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3693. res.set_content("empty-no-content-type", "text/plain");
  3694. })
  3695. .Put("/put",
  3696. [&](const Request &req, Response &res) {
  3697. EXPECT_EQ(req.body, "PUT");
  3698. res.set_content(req.body, "text/plain");
  3699. })
  3700. .Put("/put-large",
  3701. [&](const Request &req, Response &res) {
  3702. EXPECT_EQ(req.body, LARGE_DATA);
  3703. res.set_content(req.body, "text/plain");
  3704. })
  3705. .Patch("/patch",
  3706. [&](const Request &req, Response &res) {
  3707. EXPECT_EQ(req.body, "PATCH");
  3708. res.set_content(req.body, "text/plain");
  3709. })
  3710. .Delete("/delete",
  3711. [&](const Request & /*req*/, Response &res) {
  3712. res.set_content("DELETE", "text/plain");
  3713. })
  3714. .Delete("/delete-body",
  3715. [&](const Request &req, Response &res) {
  3716. EXPECT_EQ(req.body, "content");
  3717. res.set_content(req.body, "text/plain");
  3718. })
  3719. .Options(R"(\*)",
  3720. [&](const Request & /*req*/, Response &res) {
  3721. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3722. })
  3723. .Get("/request-target",
  3724. [&](const Request &req, Response & /*res*/) {
  3725. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3726. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3727. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3728. })
  3729. .Get("/long-query-value",
  3730. [&](const Request &req, Response & /*res*/) {
  3731. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3732. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3733. })
  3734. .Get("/too-long-query-value",
  3735. [&](const Request &req, Response & /*res*/) {
  3736. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3737. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3738. })
  3739. .Get("/array-param",
  3740. [&](const Request &req, Response & /*res*/) {
  3741. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3742. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3743. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3744. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3745. })
  3746. .Get("/array-param-values",
  3747. [&](const Request &req, Response & /*res*/) {
  3748. auto values = req.get_param_values("array");
  3749. EXPECT_EQ(3u, values.size());
  3750. EXPECT_EQ("value1", values[0]);
  3751. EXPECT_EQ("value2", values[1]);
  3752. EXPECT_EQ("value3", values[2]);
  3753. auto empty = req.get_param_values("nonexistent");
  3754. EXPECT_TRUE(empty.empty());
  3755. })
  3756. .Post("/validate-no-multiple-headers",
  3757. [&](const Request &req, Response & /*res*/) {
  3758. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3759. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3760. })
  3761. .Post("/content_receiver",
  3762. [&](const Request &req, Response &res,
  3763. const ContentReader &content_reader) {
  3764. if (req.is_multipart_form_data()) {
  3765. std::vector<FormData> items;
  3766. content_reader(
  3767. [&](const FormData &file) {
  3768. items.push_back(file);
  3769. return true;
  3770. },
  3771. [&](const char *data, size_t data_length) {
  3772. items.back().content.append(data, data_length);
  3773. return true;
  3774. });
  3775. EXPECT_EQ(5u, items.size());
  3776. {
  3777. const auto &file = get_file_value(items, "text1");
  3778. EXPECT_TRUE(file.filename.empty());
  3779. EXPECT_EQ("text default", file.content);
  3780. }
  3781. {
  3782. const auto &file = get_file_value(items, "text2");
  3783. EXPECT_TRUE(file.filename.empty());
  3784. EXPECT_EQ("aωb", file.content);
  3785. }
  3786. {
  3787. const auto &file = get_file_value(items, "file1");
  3788. EXPECT_EQ("hello.txt", file.filename);
  3789. EXPECT_EQ("text/plain", file.content_type);
  3790. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3791. }
  3792. {
  3793. const auto &file = get_file_value(items, "file2");
  3794. EXPECT_EQ("world.json", file.filename);
  3795. EXPECT_EQ("application/json", file.content_type);
  3796. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3797. }
  3798. {
  3799. const auto &file = get_file_value(items, "file3");
  3800. EXPECT_TRUE(file.filename.empty());
  3801. EXPECT_EQ("application/octet-stream", file.content_type);
  3802. EXPECT_EQ(0u, file.content.size());
  3803. }
  3804. } else {
  3805. std::string body;
  3806. content_reader([&](const char *data, size_t data_length) {
  3807. EXPECT_EQ(7U, data_length);
  3808. body.append(data, data_length);
  3809. return true;
  3810. });
  3811. EXPECT_EQ(body, "content");
  3812. res.set_content(body, "text/plain");
  3813. }
  3814. })
  3815. .Put("/content_receiver",
  3816. [&](const Request & /*req*/, Response &res,
  3817. const ContentReader &content_reader) {
  3818. std::string body;
  3819. content_reader([&](const char *data, size_t data_length) {
  3820. body.append(data, data_length);
  3821. return true;
  3822. });
  3823. EXPECT_EQ(body, "content");
  3824. res.set_content(body, "text/plain");
  3825. })
  3826. .Patch("/content_receiver",
  3827. [&](const Request & /*req*/, Response &res,
  3828. const ContentReader &content_reader) {
  3829. std::string body;
  3830. content_reader([&](const char *data, size_t data_length) {
  3831. body.append(data, data_length);
  3832. return true;
  3833. });
  3834. EXPECT_EQ(body, "content");
  3835. res.set_content(body, "text/plain");
  3836. })
  3837. .Post("/query-string-and-body",
  3838. [&](const Request &req, Response & /*res*/) {
  3839. ASSERT_TRUE(req.has_param("key"));
  3840. EXPECT_EQ(req.get_param_value("key"), "value");
  3841. EXPECT_EQ(req.body, "content");
  3842. })
  3843. .Get("/last-request",
  3844. [&](const Request &req, Response & /*res*/) {
  3845. EXPECT_EQ("close", req.get_header_value("Connection"));
  3846. })
  3847. .Get(R"(/redirect/(\d+))",
  3848. [&](const Request &req, Response &res) {
  3849. auto num = std::stoi(req.matches[1]) + 1;
  3850. std::string url = "/redirect/" + std::to_string(num);
  3851. res.set_redirect(url);
  3852. })
  3853. .Post("/binary",
  3854. [&](const Request &req, Response &res) {
  3855. EXPECT_EQ(4U, req.body.size());
  3856. EXPECT_EQ("application/octet-stream",
  3857. req.get_header_value("Content-Type"));
  3858. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3859. res.set_content(req.body, "application/octet-stream");
  3860. })
  3861. .Put("/binary",
  3862. [&](const Request &req, Response &res) {
  3863. EXPECT_EQ(4U, req.body.size());
  3864. EXPECT_EQ("application/octet-stream",
  3865. req.get_header_value("Content-Type"));
  3866. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3867. res.set_content(req.body, "application/octet-stream");
  3868. })
  3869. .Patch("/binary",
  3870. [&](const Request &req, Response &res) {
  3871. EXPECT_EQ(4U, req.body.size());
  3872. EXPECT_EQ("application/octet-stream",
  3873. req.get_header_value("Content-Type"));
  3874. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3875. res.set_content(req.body, "application/octet-stream");
  3876. })
  3877. .Delete("/binary",
  3878. [&](const Request &req, Response &res) {
  3879. EXPECT_EQ(4U, req.body.size());
  3880. EXPECT_EQ("application/octet-stream",
  3881. req.get_header_value("Content-Type"));
  3882. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3883. res.set_content(req.body, "application/octet-stream");
  3884. })
  3885. .Get("/issue1772",
  3886. [&](const Request & /*req*/, Response &res) {
  3887. res.status = 401;
  3888. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3889. })
  3890. .Delete("/issue609",
  3891. [](const httplib::Request &, httplib::Response &res,
  3892. const httplib::ContentReader &) {
  3893. res.set_content("ok", "text/plain");
  3894. })
  3895. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3896. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3897. .Get("/compress",
  3898. [&](const Request & /*req*/, Response &res) {
  3899. res.set_content(
  3900. "12345678901234567890123456789012345678901234567890123456789"
  3901. "01234567890123456789012345678901234567890",
  3902. "text/plain");
  3903. })
  3904. .Get("/compress-with-charset",
  3905. [&](const Request & /*req*/, Response &res) {
  3906. res.set_content(
  3907. "12345678901234567890123456789012345678901234567890123456789"
  3908. "01234567890123456789012345678901234567890",
  3909. "application/json; charset=utf-8");
  3910. })
  3911. .Get("/nocompress",
  3912. [&](const Request & /*req*/, Response &res) {
  3913. res.set_content(
  3914. "12345678901234567890123456789012345678901234567890123456789"
  3915. "01234567890123456789012345678901234567890",
  3916. "application/octet-stream");
  3917. })
  3918. .Post("/compress-multipart",
  3919. [&](const Request &req, Response & /*res*/) {
  3920. EXPECT_EQ(2u, req.form.fields.size());
  3921. ASSERT_TRUE(!req.form.has_field("???"));
  3922. {
  3923. const auto &text = req.form.get_field("key1");
  3924. EXPECT_EQ("test", text);
  3925. }
  3926. {
  3927. const auto &text = req.form.get_field("key2");
  3928. EXPECT_EQ("--abcdefg123", text);
  3929. }
  3930. })
  3931. #endif
  3932. ;
  3933. persons_["john"] = "programmer";
  3934. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3935. svr_.wait_until_ready();
  3936. }
  3937. virtual void TearDown() {
  3938. svr_.stop();
  3939. if (!request_threads_.empty()) {
  3940. std::this_thread::sleep_for(std::chrono::seconds(1));
  3941. for (auto &t : request_threads_) {
  3942. t.join();
  3943. }
  3944. }
  3945. t_.join();
  3946. }
  3947. map<string, string> persons_;
  3948. #ifdef CPPHTTPLIB_SSL_ENABLED
  3949. SSLClient cli_;
  3950. SSLServer svr_;
  3951. #else
  3952. Client cli_;
  3953. Server svr_;
  3954. #endif
  3955. thread t_;
  3956. std::vector<thread> request_threads_;
  3957. };
  3958. TEST_F(ServerTest, GetMethod200) {
  3959. auto res = cli_.Get("/hi");
  3960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3961. EXPECT_EQ("HTTP/1.1", res->version);
  3962. EXPECT_EQ(StatusCode::OK_200, res->status);
  3963. EXPECT_EQ("OK", res->reason);
  3964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3965. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3966. EXPECT_EQ("Hello World!", res->body);
  3967. }
  3968. TEST_F(ServerTest, GetEmptyFile) {
  3969. auto res = cli_.Get("/empty_file");
  3970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3974. EXPECT_EQ("", res->body);
  3975. }
  3976. TEST_F(ServerTest, GetFileContent) {
  3977. auto res = cli_.Get("/file_content");
  3978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3979. EXPECT_EQ(StatusCode::OK_200, res->status);
  3980. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3981. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3982. EXPECT_EQ("test.html", res->body);
  3983. }
  3984. TEST_F(ServerTest, GetFileContentWithRange) {
  3985. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  3986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3988. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3989. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3990. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3991. EXPECT_EQ("est", res->body);
  3992. }
  3993. TEST_F(ServerTest, GetFileContentWithContentType) {
  3994. auto res = cli_.Get("/file_content_with_content_type");
  3995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3996. EXPECT_EQ(StatusCode::OK_200, res->status);
  3997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3998. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3999. EXPECT_EQ("file\n", res->body);
  4000. }
  4001. TEST_F(ServerTest, GetInvalidFileContent) {
  4002. auto res = cli_.Get("/invalid_file_content");
  4003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4004. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4005. }
  4006. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4007. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4009. EXPECT_EQ("HTTP/1.1", res->version);
  4010. EXPECT_EQ(StatusCode::OK_200, res->status);
  4011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4012. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4013. EXPECT_EQ("Hello World!", res->body);
  4014. }
  4015. TEST_F(ServerTest, GetMethod302) {
  4016. auto res = cli_.Get("/");
  4017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4018. EXPECT_EQ(StatusCode::Found_302, res->status);
  4019. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4020. }
  4021. TEST_F(ServerTest, GetMethod302Redirect) {
  4022. cli_.set_follow_location(true);
  4023. auto res = cli_.Get("/");
  4024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4025. EXPECT_EQ(StatusCode::OK_200, res->status);
  4026. EXPECT_EQ("Hello World!", res->body);
  4027. EXPECT_EQ("/hi", res->location);
  4028. }
  4029. TEST_F(ServerTest, GetMethod404) {
  4030. auto res = cli_.Get("/invalid");
  4031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4033. }
  4034. TEST_F(ServerTest, HeadMethod200) {
  4035. auto res = cli_.Head("/hi");
  4036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4039. EXPECT_TRUE(res->body.empty());
  4040. }
  4041. TEST_F(ServerTest, HeadMethod200Static) {
  4042. auto res = cli_.Head("/mount/dir/index.html");
  4043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4044. EXPECT_EQ(StatusCode::OK_200, res->status);
  4045. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4046. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4047. EXPECT_TRUE(res->body.empty());
  4048. }
  4049. TEST_F(ServerTest, HeadMethod404) {
  4050. auto res = cli_.Head("/invalid");
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4053. EXPECT_TRUE(res->body.empty());
  4054. }
  4055. TEST_F(ServerTest, GetMethodPersonJohn) {
  4056. auto res = cli_.Get("/person/john");
  4057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4058. EXPECT_EQ(StatusCode::OK_200, res->status);
  4059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4060. EXPECT_EQ("programmer", res->body);
  4061. }
  4062. TEST_F(ServerTest, PostMethod1) {
  4063. auto res = cli_.Get("/person/john1");
  4064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4065. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4066. res = cli_.Post("/person", "name=john1&note=coder",
  4067. "application/x-www-form-urlencoded");
  4068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4069. ASSERT_EQ(StatusCode::OK_200, res->status);
  4070. res = cli_.Get("/person/john1");
  4071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4074. ASSERT_EQ("coder", res->body);
  4075. }
  4076. TEST_F(ServerTest, PostMethod2) {
  4077. auto res = cli_.Get("/person/john2");
  4078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4079. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4080. Params params;
  4081. params.emplace("name", "john2");
  4082. params.emplace("note", "coder");
  4083. res = cli_.Post("/person", params);
  4084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4085. ASSERT_EQ(StatusCode::OK_200, res->status);
  4086. res = cli_.Get("/person/john2");
  4087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4088. ASSERT_EQ(StatusCode::OK_200, res->status);
  4089. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4090. ASSERT_EQ("coder", res->body);
  4091. }
  4092. TEST_F(ServerTest, PutMethod3) {
  4093. auto res = cli_.Get("/person/john3");
  4094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4095. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4096. Params params;
  4097. params.emplace("name", "john3");
  4098. params.emplace("note", "coder");
  4099. res = cli_.Put("/person", params);
  4100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4101. ASSERT_EQ(StatusCode::OK_200, res->status);
  4102. res = cli_.Get("/person/john3");
  4103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4104. ASSERT_EQ(StatusCode::OK_200, res->status);
  4105. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4106. ASSERT_EQ("coder", res->body);
  4107. }
  4108. TEST_F(ServerTest, DeleteMethod1) {
  4109. auto res = cli_.Get("/person/john4");
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4112. Params params;
  4113. params.emplace("name", "john4");
  4114. params.emplace("note", "coder");
  4115. res = cli_.Post("/person", params);
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. ASSERT_EQ(StatusCode::OK_200, res->status);
  4118. res = cli_.Get("/person/john4");
  4119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4120. ASSERT_EQ(StatusCode::OK_200, res->status);
  4121. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4122. ASSERT_EQ("coder", res->body);
  4123. Params delete_params;
  4124. delete_params.emplace("name", "john4");
  4125. res = cli_.Delete("/person", delete_params);
  4126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4127. ASSERT_EQ(StatusCode::OK_200, res->status);
  4128. ASSERT_EQ("DELETED", res->body);
  4129. res = cli_.Get("/person/john4");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4132. }
  4133. TEST_F(ServerTest, DeleteMethod2) {
  4134. auto res = cli_.Get("/person/john5");
  4135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4136. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4137. Params params;
  4138. params.emplace("name", "john5");
  4139. params.emplace("note", "developer");
  4140. res = cli_.Post("/person", params);
  4141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4142. ASSERT_EQ(StatusCode::OK_200, res->status);
  4143. res = cli_.Get("/person/john5");
  4144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4145. ASSERT_EQ(StatusCode::OK_200, res->status);
  4146. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4147. ASSERT_EQ("developer", res->body);
  4148. Params delete_params;
  4149. delete_params.emplace("name", "john5");
  4150. Headers headers;
  4151. headers.emplace("Custom-Header", "test-value");
  4152. res = cli_.Delete("/person", headers, delete_params);
  4153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4154. ASSERT_EQ(StatusCode::OK_200, res->status);
  4155. ASSERT_EQ("DELETED", res->body);
  4156. res = cli_.Get("/person/john5");
  4157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4158. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4159. }
  4160. TEST_F(ServerTest, DeleteMethod3) {
  4161. auto res = cli_.Get("/person/john6");
  4162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4163. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4164. Params params;
  4165. params.emplace("name", "john6");
  4166. params.emplace("note", "tester");
  4167. res = cli_.Post("/person", params);
  4168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4169. ASSERT_EQ(StatusCode::OK_200, res->status);
  4170. res = cli_.Get("/person/john6");
  4171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4172. ASSERT_EQ(StatusCode::OK_200, res->status);
  4173. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4174. ASSERT_EQ("tester", res->body);
  4175. Params delete_params;
  4176. delete_params.emplace("name", "john6");
  4177. Headers headers;
  4178. headers.emplace("Custom-Header", "test-value");
  4179. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4181. ASSERT_EQ(StatusCode::OK_200, res->status);
  4182. ASSERT_EQ("DELETED", res->body);
  4183. res = cli_.Get("/person/john6");
  4184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4185. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4186. }
  4187. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4188. Params params;
  4189. params.emplace("json", JSON_DATA);
  4190. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4192. ASSERT_EQ(StatusCode::OK_200, res->status);
  4193. ASSERT_EQ(JSON_DATA, res->body);
  4194. }
  4195. TEST_F(ServerTest, PostEmptyContent) {
  4196. auto res = cli_.Post("/empty", "", "text/plain");
  4197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4198. ASSERT_EQ(StatusCode::OK_200, res->status);
  4199. ASSERT_EQ("empty", res->body);
  4200. }
  4201. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4202. auto res = cli_.Post("/empty-no-content-type");
  4203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4204. ASSERT_EQ(StatusCode::OK_200, res->status);
  4205. ASSERT_EQ("empty-no-content-type", res->body);
  4206. }
  4207. TEST_F(ServerTest, PostPathOnly) {
  4208. auto res = cli_.Post("/path-only");
  4209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4210. ASSERT_EQ(StatusCode::OK_200, res->status);
  4211. ASSERT_EQ("path-only", res->body);
  4212. }
  4213. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4214. auto res = cli_.Post("/path-headers-only",
  4215. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4217. ASSERT_EQ(StatusCode::OK_200, res->status);
  4218. ASSERT_EQ("path-headers-only", res->body);
  4219. }
  4220. TEST_F(ServerTest, PostLarge) {
  4221. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4223. ASSERT_EQ(StatusCode::OK_200, res->status);
  4224. EXPECT_EQ(LARGE_DATA, res->body);
  4225. }
  4226. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4227. auto res = cli_.Put("/empty-no-content-type");
  4228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4229. ASSERT_EQ(StatusCode::OK_200, res->status);
  4230. ASSERT_EQ("empty-no-content-type", res->body);
  4231. }
  4232. TEST_F(ServerTest, GetMethodDir) {
  4233. auto res = cli_.Get("/dir/");
  4234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4237. auto body = R"(<html>
  4238. <head>
  4239. </head>
  4240. <body>
  4241. <a href="/dir/test.html">Test</a>
  4242. <a href="/hi">hi</a>
  4243. </body>
  4244. </html>
  4245. )";
  4246. EXPECT_EQ(body, res->body);
  4247. }
  4248. TEST_F(ServerTest, GetMethodDirTest) {
  4249. auto res = cli_.Get("/dir/test.html");
  4250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4251. EXPECT_EQ(StatusCode::OK_200, res->status);
  4252. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4253. EXPECT_EQ("test.html", res->body);
  4254. }
  4255. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4256. auto res = cli_.Get("/dir/../dir/test.html");
  4257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4260. EXPECT_EQ("test.html", res->body);
  4261. }
  4262. TEST_F(ServerTest, GetMethodInvalidPath) {
  4263. auto res = cli_.Get("/dir/../test.html");
  4264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4265. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4266. }
  4267. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4268. auto res = cli_.Get("/../www/dir/test.html");
  4269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4270. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4271. }
  4272. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4273. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4275. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4276. }
  4277. TEST_F(ServerTest, GetMethodDirMountTest) {
  4278. auto res = cli_.Get("/mount/dir/test.html");
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ(StatusCode::OK_200, res->status);
  4281. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4282. EXPECT_EQ("test.html", res->body);
  4283. }
  4284. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4285. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4287. EXPECT_EQ(StatusCode::OK_200, res->status);
  4288. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4289. EXPECT_EQ("test.html", res->body);
  4290. }
  4291. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4292. auto res = cli_.Get("/mount/dir/../test.html");
  4293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4294. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4295. }
  4296. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4297. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4300. }
  4301. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4302. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4305. }
  4306. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4307. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4310. }
  4311. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4312. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4315. }
  4316. TEST_F(ServerTest, PostMethod303) {
  4317. auto res = cli_.Post("/1", "body", "text/plain");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4320. EXPECT_EQ("/2", res->get_header_value("Location"));
  4321. }
  4322. TEST_F(ServerTest, PostMethod303Redirect) {
  4323. cli_.set_follow_location(true);
  4324. auto res = cli_.Post("/1", "body", "text/plain");
  4325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ("redirected.", res->body);
  4328. EXPECT_EQ("/2", res->location);
  4329. }
  4330. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4331. auto res = cli_.Get("/dir/test.abcde");
  4332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4335. EXPECT_EQ("abcde", res->body);
  4336. }
  4337. TEST_F(ServerTest, StaticFileRange) {
  4338. auto res =
  4339. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4341. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4342. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4343. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4344. EXPECT_EQ(true, res->has_header("Content-Range"));
  4345. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4346. EXPECT_EQ(std::string("cd"), res->body);
  4347. }
  4348. TEST_F(ServerTest, StaticFileRanges) {
  4349. auto res = cli_.Get("/dir/test.abcde",
  4350. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4353. EXPECT_TRUE(
  4354. res->get_header_value("Content-Type")
  4355. .find(
  4356. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4357. 0);
  4358. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4359. }
  4360. TEST_F(ServerTest, StaticFileRangeHead) {
  4361. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4364. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4365. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4366. EXPECT_EQ(true, res->has_header("Content-Range"));
  4367. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4368. }
  4369. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4370. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4374. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4375. EXPECT_EQ(true, res->has_header("Content-Range"));
  4376. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4377. res->get_header_value("Content-Range"));
  4378. EXPECT_EQ("LAST\n", res->body);
  4379. }
  4380. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4381. auto res =
  4382. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4386. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4389. }
  4390. TEST_F(ServerTest, StaticFileBigFile) {
  4391. auto res = cli_.Get("/dir/1MB.txt");
  4392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4393. EXPECT_EQ(StatusCode::OK_200, res->status);
  4394. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4395. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4396. }
  4397. TEST_F(ServerTest, InvalidBaseDirMount) {
  4398. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4399. }
  4400. TEST_F(ServerTest, Binary) {
  4401. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4402. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4403. "application/octet-stream");
  4404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4405. ASSERT_EQ(StatusCode::OK_200, res->status);
  4406. ASSERT_EQ(4U, res->body.size());
  4407. res = cli_.Put("/binary", binary.data(), binary.size(),
  4408. "application/octet-stream");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. ASSERT_EQ(StatusCode::OK_200, res->status);
  4411. ASSERT_EQ(4U, res->body.size());
  4412. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4413. "application/octet-stream");
  4414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4415. ASSERT_EQ(StatusCode::OK_200, res->status);
  4416. ASSERT_EQ(4U, res->body.size());
  4417. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4418. "application/octet-stream");
  4419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4420. ASSERT_EQ(StatusCode::OK_200, res->status);
  4421. ASSERT_EQ(4U, res->body.size());
  4422. }
  4423. TEST_F(ServerTest, BinaryString) {
  4424. auto binary = std::string("\x00\x01\x02\x03", 4);
  4425. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4427. ASSERT_EQ(StatusCode::OK_200, res->status);
  4428. ASSERT_EQ(4U, res->body.size());
  4429. res = cli_.Put("/binary", binary, "application/octet-stream");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. ASSERT_EQ(StatusCode::OK_200, res->status);
  4432. ASSERT_EQ(4U, res->body.size());
  4433. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4435. ASSERT_EQ(StatusCode::OK_200, res->status);
  4436. ASSERT_EQ(4U, res->body.size());
  4437. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4439. ASSERT_EQ(StatusCode::OK_200, res->status);
  4440. ASSERT_EQ(4U, res->body.size());
  4441. }
  4442. TEST_F(ServerTest, EmptyRequest) {
  4443. auto res = cli_.Get("");
  4444. ASSERT_TRUE(!res);
  4445. EXPECT_EQ(Error::Connection, res.error());
  4446. }
  4447. TEST_F(ServerTest, LongRequest) {
  4448. std::string request;
  4449. for (size_t i = 0; i < 545; i++) {
  4450. request += "/TooLongRequest";
  4451. }
  4452. request += "OK";
  4453. auto res = cli_.Get(request.c_str());
  4454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4455. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4456. }
  4457. TEST_F(ServerTest, TooLongRequest) {
  4458. std::string request;
  4459. for (size_t i = 0; i < 546; i++) {
  4460. request += "/TooLongRequest";
  4461. }
  4462. request += "_NG";
  4463. auto start = std::chrono::high_resolution_clock::now();
  4464. cli_.set_keep_alive(true);
  4465. auto res = cli_.Get(request.c_str());
  4466. auto end = std::chrono::high_resolution_clock::now();
  4467. auto elapsed =
  4468. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4469. .count();
  4470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4471. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4472. EXPECT_LE(elapsed, 1000);
  4473. EXPECT_EQ("close", res->get_header_value("Connection"));
  4474. EXPECT_FALSE(cli_.is_socket_open());
  4475. }
  4476. TEST_F(ServerTest, AlmostTooLongRequest) {
  4477. // test for #2046 - URI length check shouldn't include other content on req
  4478. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4479. // leading /, space, HTTP/1.1)
  4480. std::string request =
  4481. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4482. auto res = cli_.Get(request.c_str());
  4483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4485. }
  4486. TEST_F(ServerTest, LongHeader) {
  4487. Request req;
  4488. req.method = "GET";
  4489. req.path = "/hi";
  4490. std::string host_and_port;
  4491. host_and_port += HOST;
  4492. host_and_port += ":";
  4493. host_and_port += std::to_string(PORT);
  4494. req.headers.emplace("Host", host_and_port.c_str());
  4495. req.headers.emplace("Accept", "*/*");
  4496. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4497. req.headers.emplace(
  4498. "Header-Name",
  4499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4513. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4514. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4515. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4516. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4517. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4518. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4527. "@@@@@@@@@@@@@@@@");
  4528. auto res = std::make_shared<Response>();
  4529. auto error = Error::Success;
  4530. auto ret = cli_.send(req, *res, error);
  4531. ASSERT_TRUE(ret);
  4532. EXPECT_EQ(StatusCode::OK_200, res->status);
  4533. }
  4534. TEST_F(ServerTest, LongQueryValue) {
  4535. auto start = std::chrono::high_resolution_clock::now();
  4536. cli_.set_keep_alive(true);
  4537. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4538. auto end = std::chrono::high_resolution_clock::now();
  4539. auto elapsed =
  4540. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4541. .count();
  4542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4543. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4544. EXPECT_LE(elapsed, 1000);
  4545. EXPECT_EQ("close", res->get_header_value("Connection"));
  4546. EXPECT_FALSE(cli_.is_socket_open());
  4547. }
  4548. TEST_F(ServerTest, TooLongQueryValue) {
  4549. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4550. ASSERT_FALSE(res);
  4551. EXPECT_EQ(Error::Read, res.error());
  4552. }
  4553. TEST_F(ServerTest, TooLongHeader) {
  4554. Request req;
  4555. req.method = "GET";
  4556. req.path = "/hi";
  4557. std::string host_and_port;
  4558. host_and_port += HOST;
  4559. host_and_port += ":";
  4560. host_and_port += std::to_string(PORT);
  4561. req.headers.emplace("Host", host_and_port.c_str());
  4562. req.headers.emplace("Accept", "*/*");
  4563. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4564. req.headers.emplace(
  4565. "Header-Name",
  4566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4594. "@@@@@@@@@@@@@@@@@");
  4595. auto res = std::make_shared<Response>();
  4596. auto error = Error::Success;
  4597. auto ret = cli_.send(req, *res, error);
  4598. ASSERT_TRUE(ret);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. }
  4601. TEST_F(ServerTest, HeaderCountAtLimit) {
  4602. // Test with headers just under the 100 limit
  4603. httplib::Headers headers;
  4604. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4605. // This should keep us just under the 100 header limit
  4606. for (int i = 0; i < 95; i++) {
  4607. std::string name = "X-Test-Header-" + std::to_string(i);
  4608. std::string value = "value" + std::to_string(i);
  4609. headers.emplace(name, value);
  4610. }
  4611. // This should work fine as we're under the limit
  4612. auto res = cli_.Get("/hi", headers);
  4613. EXPECT_TRUE(res);
  4614. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4615. }
  4616. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4617. // Test with many headers to exceed the 100 limit
  4618. httplib::Headers headers;
  4619. // Add 150 headers to definitely exceed the 100 limit
  4620. for (int i = 0; i < 150; i++) {
  4621. std::string name = "X-Test-Header-" + std::to_string(i);
  4622. std::string value = "value" + std::to_string(i);
  4623. headers.emplace(name, value);
  4624. }
  4625. // This should fail due to exceeding header count limit
  4626. cli_.set_keep_alive(true);
  4627. auto res = cli_.Get("/hi", headers);
  4628. // The server should respond with 400 Bad Request
  4629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4630. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4631. EXPECT_EQ("close", res->get_header_value("Connection"));
  4632. EXPECT_FALSE(cli_.is_socket_open());
  4633. }
  4634. TEST_F(ServerTest, PercentEncoding) {
  4635. auto res = cli_.Get("/e%6edwith%");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. TEST_F(ServerTest, PercentEncodingUnicode) {
  4640. auto res = cli_.Get("/e%u006edwith%");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. EXPECT_EQ(StatusCode::OK_200, res->status);
  4643. }
  4644. TEST_F(ServerTest, InvalidPercentEncoding) {
  4645. auto res = cli_.Get("/%endwith%");
  4646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4648. }
  4649. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4650. auto res = cli_.Get("/%uendwith%");
  4651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4653. }
  4654. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4655. auto res = cli_.Get("/hello?aaa=bbb%");
  4656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4657. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4658. }
  4659. TEST_F(ServerTest, PlusSignEncoding) {
  4660. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4662. EXPECT_EQ(StatusCode::OK_200, res->status);
  4663. EXPECT_EQ("a +b", res->body);
  4664. }
  4665. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4666. // This test simulates a potential DoS attack using many headers
  4667. // to verify our security fix prevents memory exhaustion
  4668. httplib::Headers attack_headers;
  4669. // Attempt to add many headers like an attacker would (200 headers to far
  4670. // exceed limit)
  4671. for (int i = 0; i < 200; i++) {
  4672. std::string name = "X-Attack-Header-" + std::to_string(i);
  4673. std::string value = "attack_payload_" + std::to_string(i);
  4674. attack_headers.emplace(name, value);
  4675. }
  4676. // Try to POST with excessive headers
  4677. cli_.set_keep_alive(true);
  4678. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4679. // Should either fail or return 400 Bad Request due to security limit
  4680. if (res) {
  4681. // If we get a response, it should be 400 Bad Request
  4682. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4683. EXPECT_EQ("close", res->get_header_value("Connection"));
  4684. }
  4685. EXPECT_FALSE(cli_.is_socket_open());
  4686. }
  4687. TEST_F(ServerTest, MultipartFormData) {
  4688. UploadFormDataItems items = {
  4689. {"text1", "text default", "", ""},
  4690. {"text2", "aωb", "", ""},
  4691. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4692. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4693. {"file3", "", "", "application/octet-stream"},
  4694. {"file4", "", "", " application/json tmp-string "}};
  4695. auto res = cli_.Post("/multipart", items);
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. }
  4699. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4700. UploadFormDataItems items = {
  4701. {"text", "default text", "", ""},
  4702. {"multi_text1", "aaaaa", "", ""},
  4703. {"multi_text1", "bbbbb", "", ""},
  4704. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4705. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4706. "application/json"},
  4707. };
  4708. auto res = cli_.Post("/multipart/multi_file_values", items);
  4709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. }
  4712. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4713. auto res = cli_.Get("/hi");
  4714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4717. EXPECT_EQ("Hello World!", res->body);
  4718. }
  4719. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4720. Request req;
  4721. req.method = "POST";
  4722. req.path = "/chunked";
  4723. std::string host_and_port;
  4724. host_and_port += HOST;
  4725. host_and_port += ":";
  4726. host_and_port += std::to_string(PORT);
  4727. req.headers.emplace("Host", host_and_port.c_str());
  4728. req.headers.emplace("Accept", "*/*");
  4729. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4730. req.headers.emplace("Content-Type", "text/plain");
  4731. req.headers.emplace("Content-Length", "0");
  4732. req.headers.emplace(
  4733. "Transfer-Encoding",
  4734. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4735. // Client does not chunk, so make a chunked body manually.
  4736. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4737. auto res = std::make_shared<Response>();
  4738. auto error = Error::Success;
  4739. auto ret = cli_.send(req, *res, error);
  4740. ASSERT_TRUE(ret);
  4741. EXPECT_EQ(StatusCode::OK_200, res->status);
  4742. }
  4743. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4744. // rather than treat them as valid lengths.
  4745. template <typename ClientT>
  4746. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4747. Request req;
  4748. req.method = "POST";
  4749. req.path = "/chunked";
  4750. std::string host_and_port;
  4751. host_and_port += HOST;
  4752. host_and_port += ":";
  4753. host_and_port += std::to_string(PORT);
  4754. req.headers.emplace("Host", host_and_port.c_str());
  4755. req.headers.emplace("Content-Length", "0");
  4756. req.headers.emplace("Transfer-Encoding", "chunked");
  4757. req.body = body;
  4758. auto res = std::make_shared<Response>();
  4759. auto error = Error::Success;
  4760. ASSERT_TRUE(cli.send(req, *res, error));
  4761. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4762. }
  4763. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4764. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4765. }
  4766. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4767. expect_chunked_body_rejected(
  4768. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4769. }
  4770. TEST_F(ServerTest, GetStreamed2) {
  4771. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  4772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4773. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4774. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4775. EXPECT_EQ(true, res->has_header("Content-Range"));
  4776. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4777. EXPECT_EQ(std::string("ab"), res->body);
  4778. }
  4779. TEST_F(ServerTest, GetStreamed) {
  4780. auto res = cli_.Get("/streamed");
  4781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4782. EXPECT_EQ(StatusCode::OK_200, res->status);
  4783. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4784. EXPECT_EQ(std::string("aaabbb"), res->body);
  4785. }
  4786. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4787. auto res = cli_.Get("/streamed-without-length",
  4788. Headers{make_range_header({{0, -1}})});
  4789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ(false, res->has_header("Content-Length"));
  4792. EXPECT_EQ(false, res->has_header("Content-Range"));
  4793. EXPECT_EQ(std::string("abcdefg"), res->body);
  4794. }
  4795. TEST_F(ServerTest, GetStreamedWithRange1) {
  4796. auto res =
  4797. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  4798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4800. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4801. EXPECT_EQ(true, res->has_header("Content-Range"));
  4802. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4803. EXPECT_EQ(std::string("def"), res->body);
  4804. }
  4805. TEST_F(ServerTest, GetStreamedWithRange2) {
  4806. auto res =
  4807. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  4808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4809. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4810. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4811. EXPECT_EQ(true, res->has_header("Content-Range"));
  4812. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4813. EXPECT_EQ(std::string("bcdefg"), res->body);
  4814. }
  4815. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4816. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  4817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4819. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4820. EXPECT_EQ(true, res->has_header("Content-Range"));
  4821. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4822. EXPECT_EQ(std::string("efg"), res->body);
  4823. }
  4824. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4825. auto res =
  4826. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  4827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4828. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4829. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4830. EXPECT_EQ(false, res->has_header("Content-Range"));
  4831. EXPECT_EQ(0U, res->body.size());
  4832. }
  4833. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4834. auto res =
  4835. cli_.Get("/streamed-with-range",
  4836. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  4837. "92233720368547758079223372036854775807"}});
  4838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4839. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4840. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4841. EXPECT_EQ(false, res->has_header("Content-Range"));
  4842. EXPECT_EQ(0U, res->body.size());
  4843. }
  4844. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4845. auto res = cli_.Get(
  4846. "/with-range",
  4847. Headers{{"Range",
  4848. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4849. {"Accept-Encoding", ""}});
  4850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4852. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4853. EXPECT_EQ(true, res->has_header("Content-Range"));
  4854. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4855. EXPECT_EQ(std::string("abcdefg"), res->body);
  4856. }
  4857. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4858. auto res = cli_.Get("/with-range", Headers{
  4859. {"Range", "bytes=0-"},
  4860. {"Accept-Encoding", ""},
  4861. });
  4862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4864. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4865. EXPECT_EQ(true, res->has_header("Content-Range"));
  4866. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4867. EXPECT_EQ(std::string("abcdefg"), res->body);
  4868. }
  4869. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4870. auto res = cli_.Get("/streamed-with-range",
  4871. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4874. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4875. EXPECT_EQ(false, res->has_header("Content-Range"));
  4876. EXPECT_EQ(267U, res->body.size());
  4877. // Check that both range contents are present
  4878. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4879. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4880. // Check that Content-Range headers are present for both ranges
  4881. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4882. std::string::npos);
  4883. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4884. std::string::npos);
  4885. }
  4886. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4887. Ranges ranges;
  4888. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4889. ranges.emplace_back(0, -1);
  4890. }
  4891. auto res = cli_.Get("/streamed-with-range?error",
  4892. Headers{{make_range_header(ranges)}});
  4893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4894. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4895. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4896. EXPECT_EQ(false, res->has_header("Content-Range"));
  4897. EXPECT_EQ(0U, res->body.size());
  4898. }
  4899. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4900. auto res = cli_.Get("/streamed-with-range",
  4901. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  4902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4904. EXPECT_EQ(5U, res->body.size());
  4905. // Check that overlapping ranges are coalesced into a single range
  4906. EXPECT_EQ("bcdef", res->body);
  4907. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4908. // Should be single range, not multipart
  4909. EXPECT_TRUE(res->has_header("Content-Range"));
  4910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4911. }
  4912. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4913. auto res = cli_.Get("/streamed-with-range",
  4914. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  4915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4917. EXPECT_EQ(268U, res->body.size());
  4918. // Check that both range contents are present
  4919. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4920. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4921. // Check that Content-Range headers are present for both ranges
  4922. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4923. std::string::npos);
  4924. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4925. std::string::npos);
  4926. }
  4927. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4928. auto res = cli_.Get("/streamed-with-range",
  4929. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  4930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4932. EXPECT_EQ(269U, res->body.size());
  4933. // Check that both duplicate range contents are present
  4934. size_t first_abc = res->body.find("abc\r\n");
  4935. EXPECT_TRUE(first_abc != std::string::npos);
  4936. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4937. EXPECT_TRUE(second_abc != std::string::npos);
  4938. // Check that Content-Range headers are present for both ranges
  4939. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4940. EXPECT_TRUE(first_range != std::string::npos);
  4941. size_t second_range =
  4942. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4943. EXPECT_TRUE(second_range != std::string::npos);
  4944. }
  4945. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4946. auto res =
  4947. cli_.Get("/streamed-with-range?error",
  4948. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4950. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4951. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4952. EXPECT_EQ(false, res->has_header("Content-Range"));
  4953. EXPECT_EQ(0U, res->body.size());
  4954. }
  4955. TEST_F(ServerTest, GetStreamedEndless) {
  4956. uint64_t offset = 0;
  4957. auto res = cli_.Get("/streamed-cancel",
  4958. [&](const char * /*data*/, uint64_t data_length) {
  4959. if (offset < 100) {
  4960. offset += data_length;
  4961. return true;
  4962. }
  4963. return false;
  4964. });
  4965. ASSERT_TRUE(!res);
  4966. EXPECT_EQ(Error::Canceled, res.error());
  4967. }
  4968. TEST_F(ServerTest, ClientStop) {
  4969. std::atomic_size_t count{4};
  4970. std::vector<std::thread> threads;
  4971. for (auto i = count.load(); i != 0; --i) {
  4972. threads.emplace_back([&]() {
  4973. auto res = cli_.Get("/streamed-cancel",
  4974. [&](const char *, uint64_t) { return true; });
  4975. --count;
  4976. ASSERT_TRUE(!res);
  4977. EXPECT_TRUE(res.error() == Error::Canceled ||
  4978. res.error() == Error::Read || res.error() == Error::Write);
  4979. });
  4980. }
  4981. std::this_thread::sleep_for(std::chrono::seconds(2));
  4982. while (count != 0) {
  4983. cli_.stop();
  4984. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4985. }
  4986. for (auto &t : threads) {
  4987. t.join();
  4988. }
  4989. }
  4990. TEST_F(ServerTest, GetWithRange1) {
  4991. auto res = cli_.Get("/with-range", Headers{
  4992. make_range_header({{3, 5}}),
  4993. {"Accept-Encoding", ""},
  4994. });
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4997. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4998. EXPECT_EQ(true, res->has_header("Content-Range"));
  4999. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5000. EXPECT_EQ(std::string("def"), res->body);
  5001. }
  5002. TEST_F(ServerTest, GetWithRange2) {
  5003. auto res = cli_.Get("/with-range", Headers{
  5004. make_range_header({{1, -1}}),
  5005. {"Accept-Encoding", ""},
  5006. });
  5007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5009. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5010. EXPECT_EQ(true, res->has_header("Content-Range"));
  5011. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5012. EXPECT_EQ(std::string("bcdefg"), res->body);
  5013. }
  5014. TEST_F(ServerTest, GetWithRange3) {
  5015. auto res = cli_.Get("/with-range", Headers{
  5016. make_range_header({{0, 0}}),
  5017. {"Accept-Encoding", ""},
  5018. });
  5019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5020. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5021. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5022. EXPECT_EQ(true, res->has_header("Content-Range"));
  5023. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5024. EXPECT_EQ(std::string("a"), res->body);
  5025. }
  5026. TEST_F(ServerTest, GetWithRange4) {
  5027. auto res = cli_.Get("/with-range", Headers{
  5028. make_range_header({{-1, 2}}),
  5029. {"Accept-Encoding", ""},
  5030. });
  5031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5033. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5034. EXPECT_EQ(true, res->has_header("Content-Range"));
  5035. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5036. EXPECT_EQ(std::string("fg"), res->body);
  5037. }
  5038. TEST_F(ServerTest, GetWithRange5) {
  5039. auto res = cli_.Get("/with-range", Headers{
  5040. make_range_header({{0, 5}}),
  5041. {"Accept-Encoding", ""},
  5042. });
  5043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5044. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5045. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5046. EXPECT_EQ(true, res->has_header("Content-Range"));
  5047. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5048. EXPECT_EQ(std::string("abcdef"), res->body);
  5049. }
  5050. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5051. auto res =
  5052. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5055. }
  5056. TEST_F(ServerTest, GetWithRangeMultipart) {
  5057. auto res =
  5058. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5061. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5062. EXPECT_EQ(false, res->has_header("Content-Range"));
  5063. EXPECT_EQ(267U, res->body.size());
  5064. }
  5065. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5066. auto res = cli_.Get("/with-range",
  5067. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5069. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5070. }
  5071. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5072. auto res = cli_.Get("/with-range-customized-response",
  5073. Headers{{make_range_header({{1, 2}})}});
  5074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5075. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5076. EXPECT_EQ(true, res->has_header("Content-Length"));
  5077. EXPECT_EQ(false, res->has_header("Content-Range"));
  5078. EXPECT_EQ(JSON_DATA, res->body);
  5079. }
  5080. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5081. auto res = cli_.Get("/with-range-customized-response",
  5082. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5084. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5085. EXPECT_EQ(true, res->has_header("Content-Length"));
  5086. EXPECT_EQ(false, res->has_header("Content-Range"));
  5087. EXPECT_EQ(JSON_DATA, res->body);
  5088. }
  5089. TEST_F(ServerTest, Issue1772) {
  5090. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5092. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5093. }
  5094. TEST_F(ServerTest, Issue609) {
  5095. auto res = cli_.Delete("/issue609");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ(std::string("ok"), res->body);
  5099. }
  5100. TEST_F(ServerTest, GetStreamedChunked) {
  5101. auto res = cli_.Get("/streamed-chunked");
  5102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ(std::string("123456789"), res->body);
  5105. }
  5106. TEST_F(ServerTest, GetStreamedChunked2) {
  5107. auto res = cli_.Get("/streamed-chunked2");
  5108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5109. EXPECT_EQ(StatusCode::OK_200, res->status);
  5110. EXPECT_EQ(std::string("123456789"), res->body);
  5111. }
  5112. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5113. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5115. EXPECT_EQ(StatusCode::OK_200, res->status);
  5116. EXPECT_EQ(std::string("123456789"), res->body);
  5117. EXPECT_TRUE(res->has_header("Trailer"));
  5118. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5119. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5120. // Trailers are now stored separately from headers (security fix)
  5121. EXPECT_EQ(2U, res->trailers.size());
  5122. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5123. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5124. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5125. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5126. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5127. // Verify trailers are NOT in headers (security verification)
  5128. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5129. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5130. }
  5131. TEST_F(ServerTest, LargeChunkedPost) {
  5132. Request req;
  5133. req.method = "POST";
  5134. req.path = "/large-chunked";
  5135. std::string host_and_port;
  5136. host_and_port += HOST;
  5137. host_and_port += ":";
  5138. host_and_port += std::to_string(PORT);
  5139. req.headers.emplace("Host", host_and_port.c_str());
  5140. req.headers.emplace("Accept", "*/*");
  5141. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5142. req.headers.emplace("Content-Type", "text/plain");
  5143. req.headers.emplace("Content-Length", "0");
  5144. req.headers.emplace("Transfer-Encoding", "chunked");
  5145. std::string long_string(30 * 1024u, 'a');
  5146. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5147. // Attempt to make a large enough post to exceed OS buffers, to test that
  5148. // the server handles short reads if the full chunk data isn't available.
  5149. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5150. auto res = std::make_shared<Response>();
  5151. auto error = Error::Success;
  5152. auto ret = cli_.send(req, *res, error);
  5153. ASSERT_TRUE(ret);
  5154. EXPECT_EQ(StatusCode::OK_200, res->status);
  5155. }
  5156. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5157. auto res = cli_.Get("/remote_addr");
  5158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5161. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5162. }
  5163. TEST_F(ServerTest, GetMethodLocalAddr) {
  5164. auto res = cli_.Get("/local_addr");
  5165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5168. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5169. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5170. }
  5171. TEST_F(ServerTest, HTTPResponseSplitting) {
  5172. auto res = cli_.Get("/http_response_splitting");
  5173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5174. EXPECT_EQ(StatusCode::OK_200, res->status);
  5175. }
  5176. TEST_F(ServerTest, SlowRequest) {
  5177. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5178. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5179. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5180. }
  5181. #if 0
  5182. TEST_F(ServerTest, SlowPost) {
  5183. char buffer[64 * 1024];
  5184. memset(buffer, 0x42, sizeof(buffer));
  5185. auto res = cli_.Post(
  5186. "/slowpost", 64 * 1024 * 1024,
  5187. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5188. auto ret = sink.write(buffer, sizeof(buffer));
  5189. EXPECT_TRUE(ret);
  5190. return true;
  5191. },
  5192. "text/plain");
  5193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5194. EXPECT_EQ(StatusCode::OK_200, res->status);
  5195. }
  5196. TEST_F(ServerTest, SlowPostFail) {
  5197. char buffer[64 * 1024];
  5198. memset(buffer, 0x42, sizeof(buffer));
  5199. cli_.set_write_timeout(std::chrono::seconds(0));
  5200. auto res = cli_.Post(
  5201. "/slowpost", 64 * 1024 * 1024,
  5202. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5203. sink.write(buffer, sizeof(buffer));
  5204. return true;
  5205. },
  5206. "text/plain");
  5207. ASSERT_TRUE(!res);
  5208. EXPECT_EQ(Error::Write, res.error());
  5209. }
  5210. #endif
  5211. TEST_F(ServerTest, Put) {
  5212. auto res = cli_.Put("/put", "PUT", "text/plain");
  5213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. EXPECT_EQ("PUT", res->body);
  5216. }
  5217. TEST_F(ServerTest, PutWithContentProvider) {
  5218. auto res = cli_.Put(
  5219. "/put", 3,
  5220. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5221. sink.os << "PUT";
  5222. return true;
  5223. },
  5224. "text/plain");
  5225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5226. EXPECT_EQ(StatusCode::OK_200, res->status);
  5227. EXPECT_EQ("PUT", res->body);
  5228. }
  5229. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5230. auto res = cli_.Post(
  5231. "/post", 42,
  5232. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5233. return false;
  5234. },
  5235. "text/plain");
  5236. ASSERT_TRUE(!res);
  5237. EXPECT_EQ(Error::Canceled, res.error());
  5238. }
  5239. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5240. auto res = cli_.Put(
  5241. "/put",
  5242. [](size_t /*offset*/, DataSink &sink) {
  5243. sink.os << "PUT";
  5244. sink.done();
  5245. return true;
  5246. },
  5247. "text/plain");
  5248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5249. EXPECT_EQ(StatusCode::OK_200, res->status);
  5250. EXPECT_EQ("PUT", res->body);
  5251. }
  5252. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5253. auto res = cli_.Post(
  5254. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5255. "text/plain");
  5256. ASSERT_TRUE(!res);
  5257. EXPECT_EQ(Error::Canceled, res.error());
  5258. }
  5259. TEST_F(ServerTest, PostLoopBack) {
  5260. std::string body;
  5261. auto res = cli_.Post(
  5262. "/post-loopback", 9,
  5263. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5264. EXPECT_EQ(9u, length);
  5265. sink.write("123", 3);
  5266. sink.write("456", 3);
  5267. sink.write("789", 3);
  5268. return true;
  5269. },
  5270. "text/plain",
  5271. [&body](const char *data, size_t data_length) {
  5272. body.append(data, data_length);
  5273. return true;
  5274. });
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("123456789", body);
  5278. }
  5279. TEST_F(ServerTest, PutLoopBack) {
  5280. std::string body;
  5281. auto res = cli_.Put(
  5282. "/put-loopback", 9,
  5283. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5284. EXPECT_EQ(9u, length);
  5285. sink.write("123", 3);
  5286. sink.write("456", 3);
  5287. sink.write("789", 3);
  5288. return true;
  5289. },
  5290. "text/plain",
  5291. [&body](const char *data, size_t data_length) {
  5292. body.append(data, data_length);
  5293. return true;
  5294. });
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("123456789", body);
  5298. }
  5299. TEST_F(ServerTest, PatchLoopBack) {
  5300. std::string body;
  5301. auto res = cli_.Patch(
  5302. "/patch-loopback", 9,
  5303. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5304. EXPECT_EQ(9u, length);
  5305. sink.write("123", 3);
  5306. sink.write("456", 3);
  5307. sink.write("789", 3);
  5308. return true;
  5309. },
  5310. "text/plain",
  5311. [&body](const char *data, size_t data_length) {
  5312. body.append(data, data_length);
  5313. return true;
  5314. });
  5315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. EXPECT_EQ("123456789", body);
  5318. }
  5319. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5320. std::string body;
  5321. auto res = cli_.Post(
  5322. "/post-loopback",
  5323. [](size_t /*offset*/, DataSink &sink) {
  5324. sink.write("123", 3);
  5325. sink.write("456", 3);
  5326. sink.write("789", 3);
  5327. sink.done();
  5328. return true;
  5329. },
  5330. "text/plain",
  5331. [&body](const char *data, size_t data_length) {
  5332. body.append(data, data_length);
  5333. return true;
  5334. });
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. EXPECT_EQ(StatusCode::OK_200, res->status);
  5337. EXPECT_EQ("123456789", body);
  5338. }
  5339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5340. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5341. cli_.set_compress(true);
  5342. auto res = cli_.Put(
  5343. "/put", 3,
  5344. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5345. sink.os << "PUT";
  5346. return true;
  5347. },
  5348. "text/plain");
  5349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. EXPECT_EQ("PUT", res->body);
  5352. }
  5353. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5354. cli_.set_compress(true);
  5355. auto res = cli_.Post(
  5356. "/post", 42,
  5357. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5358. return false;
  5359. },
  5360. "text/plain");
  5361. ASSERT_TRUE(!res);
  5362. EXPECT_EQ(Error::Canceled, res.error());
  5363. }
  5364. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5365. cli_.set_compress(true);
  5366. auto res = cli_.Put(
  5367. "/put",
  5368. [](size_t /*offset*/, DataSink &sink) {
  5369. sink.os << "PUT";
  5370. sink.done();
  5371. return true;
  5372. },
  5373. "text/plain");
  5374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. EXPECT_EQ("PUT", res->body);
  5377. }
  5378. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5379. cli_.set_compress(true);
  5380. auto res = cli_.Post(
  5381. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5382. "text/plain");
  5383. ASSERT_TRUE(!res);
  5384. EXPECT_EQ(Error::Canceled, res.error());
  5385. }
  5386. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5387. cli_.set_compress(true);
  5388. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ(LARGE_DATA, res->body);
  5392. }
  5393. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5394. #ifdef CPPHTTPLIB_SSL_ENABLED
  5395. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5396. Client cli(s.c_str());
  5397. cli.enable_server_certificate_verification(false);
  5398. #else
  5399. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5400. Client cli(s.c_str());
  5401. #endif
  5402. cli.set_compress(true);
  5403. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5405. EXPECT_EQ(StatusCode::OK_200, res->status);
  5406. EXPECT_EQ(LARGE_DATA, res->body);
  5407. // The compressed size should be less than a 10th of the original. May vary
  5408. // depending on the zlib library.
  5409. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5410. static_cast<uint64_t>(10 * 1024 * 1024));
  5411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5412. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5413. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5414. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5415. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5416. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5417. #endif
  5418. }
  5419. TEST_F(ServerTest, PutContentWithDeflate) {
  5420. cli_.set_compress(false);
  5421. Headers headers;
  5422. headers.emplace("Content-Encoding", "deflate");
  5423. // PUT in deflate format:
  5424. auto res = cli_.Put("/put", headers,
  5425. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5427. EXPECT_EQ(StatusCode::OK_200, res->status);
  5428. EXPECT_EQ("PUT", res->body);
  5429. }
  5430. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "gzip, deflate");
  5433. auto res = cli_.Get("/streamed-chunked", headers);
  5434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ(std::string("123456789"), res->body);
  5437. }
  5438. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5439. Headers headers;
  5440. headers.emplace("Accept-Encoding", "gzip, deflate");
  5441. auto res = cli_.Get("/streamed-chunked2", headers);
  5442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. EXPECT_EQ(std::string("123456789"), res->body);
  5445. }
  5446. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5447. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. EXPECT_EQ(StatusCode::OK_200, res->status);
  5450. }
  5451. TEST(GzipDecompressor, ChunkedDecompression) {
  5452. std::string data;
  5453. for (size_t i = 0; i < 32 * 1024; ++i) {
  5454. data.push_back(static_cast<char>('a' + i % 26));
  5455. }
  5456. std::string compressed_data;
  5457. {
  5458. httplib::detail::gzip_compressor compressor;
  5459. bool result = compressor.compress(
  5460. data.data(), data.size(),
  5461. /*last=*/true,
  5462. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5463. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5464. compressed_data_size);
  5465. return true;
  5466. });
  5467. ASSERT_TRUE(result);
  5468. }
  5469. std::string decompressed_data;
  5470. {
  5471. httplib::detail::gzip_decompressor decompressor;
  5472. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5473. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5474. size_t chunk_size = 130;
  5475. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5476. chunk_begin += chunk_size) {
  5477. size_t current_chunk_size =
  5478. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5479. bool result = decompressor.decompress(
  5480. compressed_data.data() + chunk_begin, current_chunk_size,
  5481. [&](const char *decompressed_data_chunk,
  5482. size_t decompressed_data_chunk_size) {
  5483. decompressed_data.insert(decompressed_data.size(),
  5484. decompressed_data_chunk,
  5485. decompressed_data_chunk_size);
  5486. return true;
  5487. });
  5488. ASSERT_TRUE(result);
  5489. }
  5490. }
  5491. ASSERT_EQ(data, decompressed_data);
  5492. }
  5493. TEST(GzipDecompressor, DeflateDecompression) {
  5494. std::string original_text = "Raw deflate without gzip";
  5495. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5496. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5497. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5498. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5499. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5500. std::string decompressed_data;
  5501. {
  5502. httplib::detail::gzip_decompressor decompressor;
  5503. bool result = decompressor.decompress(
  5504. compressed_data.data(), compressed_data.size(),
  5505. [&](const char *decompressed_data_chunk,
  5506. size_t decompressed_data_chunk_size) {
  5507. decompressed_data.insert(decompressed_data.size(),
  5508. decompressed_data_chunk,
  5509. decompressed_data_chunk_size);
  5510. return true;
  5511. });
  5512. ASSERT_TRUE(result);
  5513. }
  5514. ASSERT_EQ(original_text, decompressed_data);
  5515. }
  5516. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5517. std::string original_text = "Raw deflate without gzip";
  5518. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5519. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5520. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5521. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5522. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5523. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5524. std::string decompressed_data;
  5525. {
  5526. httplib::detail::gzip_decompressor decompressor;
  5527. bool result = decompressor.decompress(
  5528. compressed_data.data(), compressed_data.size(),
  5529. [&](const char *decompressed_data_chunk,
  5530. size_t decompressed_data_chunk_size) {
  5531. decompressed_data.insert(decompressed_data.size(),
  5532. decompressed_data_chunk,
  5533. decompressed_data_chunk_size);
  5534. return true;
  5535. });
  5536. ASSERT_TRUE(result);
  5537. }
  5538. ASSERT_EQ(original_text, decompressed_data);
  5539. }
  5540. #endif
  5541. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5542. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5543. Headers headers;
  5544. headers.emplace("Accept-Encoding", "br");
  5545. auto res = cli_.Get("/streamed-chunked", headers);
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ(std::string("123456789"), res->body);
  5549. }
  5550. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5551. Headers headers;
  5552. headers.emplace("Accept-Encoding", "br");
  5553. auto res = cli_.Get("/streamed-chunked2", headers);
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. EXPECT_EQ(StatusCode::OK_200, res->status);
  5556. EXPECT_EQ(std::string("123456789"), res->body);
  5557. }
  5558. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5559. cli_.set_compress(true);
  5560. auto res = cli_.Put(
  5561. "/put", 3,
  5562. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5563. sink.os << "PUT";
  5564. return true;
  5565. },
  5566. "text/plain");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::OK_200, res->status);
  5569. EXPECT_EQ("PUT", res->body);
  5570. }
  5571. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5572. cli_.set_compress(true);
  5573. auto res = cli_.Put(
  5574. "/put",
  5575. [](size_t /*offset*/, DataSink &sink) {
  5576. sink.os << "PUT";
  5577. sink.done();
  5578. return true;
  5579. },
  5580. "text/plain");
  5581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5582. EXPECT_EQ(StatusCode::OK_200, res->status);
  5583. EXPECT_EQ("PUT", res->body);
  5584. }
  5585. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5586. cli_.set_compress(true);
  5587. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. EXPECT_EQ(StatusCode::OK_200, res->status);
  5590. EXPECT_EQ(LARGE_DATA, res->body);
  5591. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5592. }
  5593. #endif
  5594. TEST_F(ServerTest, Patch) {
  5595. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. EXPECT_EQ("PATCH", res->body);
  5599. }
  5600. TEST_F(ServerTest, Delete) {
  5601. auto res = cli_.Delete("/delete");
  5602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. EXPECT_EQ("DELETE", res->body);
  5605. }
  5606. TEST_F(ServerTest, DeleteContentReceiver) {
  5607. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. EXPECT_EQ("content", res->body);
  5611. }
  5612. TEST_F(ServerTest, Options) {
  5613. auto res = cli_.Options("*");
  5614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5615. EXPECT_EQ(StatusCode::OK_200, res->status);
  5616. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5617. EXPECT_TRUE(res->body.empty());
  5618. }
  5619. TEST_F(ServerTest, URL) {
  5620. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::OK_200, res->status);
  5623. }
  5624. TEST_F(ServerTest, ArrayParam) {
  5625. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. EXPECT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. TEST_F(ServerTest, ArrayParamValues) {
  5630. auto res =
  5631. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. EXPECT_EQ(StatusCode::OK_200, res->status);
  5634. }
  5635. TEST_F(ServerTest, NoMultipleHeaders) {
  5636. Headers headers = {{"Content-Length", "5"}};
  5637. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5638. "text/plain");
  5639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5640. EXPECT_EQ(StatusCode::OK_200, res->status);
  5641. }
  5642. TEST_F(ServerTest, PostContentReceiver) {
  5643. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. ASSERT_EQ(StatusCode::OK_200, res->status);
  5646. ASSERT_EQ("content", res->body);
  5647. }
  5648. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5649. UploadFormDataItems items = {
  5650. {"text1", "text default", "", ""},
  5651. {"text2", "aωb", "", ""},
  5652. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5653. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5654. {"file3", "", "", "application/octet-stream"},
  5655. };
  5656. auto res = cli_.Post("/content_receiver", items);
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. EXPECT_EQ(StatusCode::OK_200, res->status);
  5659. }
  5660. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5661. UploadFormDataItems items = {
  5662. {"text1", "text default", "", ""},
  5663. {"text2", "aωb", "", ""},
  5664. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5665. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5666. {"file3", "", "", "application/octet-stream"},
  5667. };
  5668. auto boundary = std::string("+++++");
  5669. std::string body;
  5670. for (const auto &item : items) {
  5671. body += "--" + boundary + "\r\n";
  5672. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5673. if (!item.filename.empty()) {
  5674. body += "; filename=\"" + item.filename + "\"";
  5675. }
  5676. body += "\r\n";
  5677. if (!item.content_type.empty()) {
  5678. body += "Content-Type: " + item.content_type + "\r\n";
  5679. }
  5680. body += "\r\n";
  5681. body += item.content + "\r\n";
  5682. }
  5683. body += "--" + boundary + "--\r\n";
  5684. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5685. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. }
  5689. TEST(MultipartFormDataTest, FieldEscaping) {
  5690. Server svr;
  5691. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5692. const ContentReader &content_reader) {
  5693. ASSERT_TRUE(req.is_multipart_form_data());
  5694. std::vector<FormData> received;
  5695. content_reader(
  5696. [&](const FormData &file) {
  5697. received.push_back(file);
  5698. return true;
  5699. },
  5700. [&](const char *data, size_t data_length) {
  5701. received.back().content.append(data, data_length);
  5702. return true;
  5703. });
  5704. // '"', CR and LF in names and filenames are escaped following the
  5705. // WHATWG HTML standard, so each part still parses as a single part
  5706. // with no injected headers. Content types get CR/LF escaped too,
  5707. // while '"' (legal there, e.g. quoted charset) is preserved.
  5708. ASSERT_EQ(4U, received.size());
  5709. EXPECT_EQ("na%22me", received[0].name);
  5710. EXPECT_EQ("quoted name", received[0].content);
  5711. EXPECT_EQ("file", received[1].name);
  5712. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5713. received[1].filename);
  5714. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5715. EXPECT_EQ("injected", received[1].content);
  5716. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5717. EXPECT_EQ("my%22file.txt", received[2].filename);
  5718. EXPECT_EQ("cr lf name", received[2].content);
  5719. EXPECT_EQ("typed", received[3].name);
  5720. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5721. received[3].content_type);
  5722. EXPECT_EQ("typed content", received[3].content);
  5723. });
  5724. auto port = svr.bind_to_any_port("localhost");
  5725. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5726. auto se = detail::scope_exit([&] {
  5727. svr.stop();
  5728. t.join();
  5729. ASSERT_FALSE(svr.is_running());
  5730. });
  5731. svr.wait_until_ready();
  5732. Client cli("localhost", port);
  5733. UploadFormDataItems items = {
  5734. {"na\"me", "quoted name", "", ""},
  5735. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5736. "application/octet-stream"},
  5737. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5738. {"typed", "typed content", "",
  5739. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5740. };
  5741. auto res = cli.Post("/post", items);
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. EXPECT_EQ(StatusCode::OK_200, res->status);
  5744. }
  5745. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5746. const UploadFormDataItems items = {
  5747. {"name1", "Content 1", "", ""},
  5748. {"name2", "Content 2", "file2.txt", "text/plain"},
  5749. };
  5750. Server svr;
  5751. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5752. const ContentReader &content_reader) {
  5753. ASSERT_TRUE(req.is_multipart_form_data());
  5754. std::vector<FormData> received;
  5755. content_reader(
  5756. [&](const FormData &file) {
  5757. received.push_back(file);
  5758. return true;
  5759. },
  5760. [&](const char *data, size_t data_length) {
  5761. received.back().content.append(data, data_length);
  5762. return true;
  5763. });
  5764. ASSERT_EQ(2U, received.size());
  5765. EXPECT_EQ("name1", received[0].name);
  5766. EXPECT_EQ("Content 1", received[0].content);
  5767. EXPECT_EQ("name2", received[1].name);
  5768. EXPECT_EQ("Content 2", received[1].content);
  5769. EXPECT_EQ("file2.txt", received[1].filename);
  5770. EXPECT_EQ("text/plain", received[1].content_type);
  5771. });
  5772. auto port = svr.bind_to_any_port("localhost");
  5773. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5774. auto se = detail::scope_exit([&] {
  5775. svr.stop();
  5776. t.join();
  5777. ASSERT_FALSE(svr.is_running());
  5778. });
  5779. svr.wait_until_ready();
  5780. Client cli("localhost", port);
  5781. // Whole-body serialization with a generated boundary
  5782. {
  5783. MultipartFormDataWriter writer;
  5784. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  5785. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  5786. writer.content_type());
  5787. auto body = writer.serialize(items);
  5788. EXPECT_EQ(body.size(), writer.content_length(items));
  5789. auto res = cli.Post("/post", body, writer.content_type());
  5790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. }
  5793. // Per-part framing with a custom boundary via a content provider
  5794. {
  5795. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  5796. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  5797. MultipartFormDataWriter writer("custom-boundary_123");
  5798. EXPECT_EQ("custom-boundary_123", writer.boundary());
  5799. std::string body;
  5800. for (const auto &item : items) {
  5801. body += writer.item_begin(item);
  5802. body += item.content;
  5803. body += MultipartFormDataWriter::item_end();
  5804. }
  5805. body += writer.finish();
  5806. EXPECT_EQ(body.size(), writer.content_length(items));
  5807. auto res = cli.Post(
  5808. "/post", body.size(),
  5809. [&](size_t offset, size_t length, DataSink &sink) {
  5810. sink.write(body.data() + offset, length);
  5811. return true;
  5812. },
  5813. writer.content_type());
  5814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5815. EXPECT_EQ(StatusCode::OK_200, res->status);
  5816. }
  5817. }
  5818. TEST_F(ServerTest, PostContentReceiverGzip) {
  5819. cli_.set_compress(true);
  5820. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5822. ASSERT_EQ(StatusCode::OK_200, res->status);
  5823. ASSERT_EQ("content", res->body);
  5824. }
  5825. TEST_F(ServerTest, PutContentReceiver) {
  5826. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. ASSERT_EQ(StatusCode::OK_200, res->status);
  5829. ASSERT_EQ("content", res->body);
  5830. }
  5831. TEST_F(ServerTest, PatchContentReceiver) {
  5832. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5834. ASSERT_EQ(StatusCode::OK_200, res->status);
  5835. ASSERT_EQ("content", res->body);
  5836. }
  5837. template <typename ClientType>
  5838. void TestWithHeadersAndContentReceiver(
  5839. ClientType &cli,
  5840. std::function<Result(ClientType &, const std::string &, const Headers &,
  5841. const std::string &, const std::string &,
  5842. ContentReceiver, DownloadProgress)>
  5843. request_func) {
  5844. Headers headers;
  5845. headers.emplace("X-Custom-Header", "test-value");
  5846. std::string received_body;
  5847. auto res = request_func(
  5848. cli, "/content_receiver", headers, "content", "application/json",
  5849. [&](const char *data, size_t data_length) {
  5850. received_body.append(data, data_length);
  5851. return true;
  5852. },
  5853. nullptr);
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("content", received_body);
  5857. }
  5858. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5859. #ifdef CPPHTTPLIB_SSL_ENABLED
  5860. using ClientT = SSLClient;
  5861. #else
  5862. using ClientT = Client;
  5863. #endif
  5864. TestWithHeadersAndContentReceiver<ClientT>(
  5865. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5866. const std::string &body, const std::string &content_type,
  5867. ContentReceiver receiver, DownloadProgress progress) {
  5868. return cli.Post(path, headers, body, content_type, receiver, progress);
  5869. });
  5870. }
  5871. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5872. #ifdef CPPHTTPLIB_SSL_ENABLED
  5873. using ClientT = SSLClient;
  5874. #else
  5875. using ClientT = Client;
  5876. #endif
  5877. TestWithHeadersAndContentReceiver<ClientT>(
  5878. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5879. const std::string &body, const std::string &content_type,
  5880. ContentReceiver receiver, DownloadProgress progress) {
  5881. return cli.Put(path, headers, body, content_type, receiver, progress);
  5882. });
  5883. }
  5884. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5885. #ifdef CPPHTTPLIB_SSL_ENABLED
  5886. using ClientT = SSLClient;
  5887. #else
  5888. using ClientT = Client;
  5889. #endif
  5890. TestWithHeadersAndContentReceiver<ClientT>(
  5891. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5892. const std::string &body, const std::string &content_type,
  5893. ContentReceiver receiver, DownloadProgress progress) {
  5894. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5895. });
  5896. }
  5897. template <typename ClientType>
  5898. void TestWithHeadersAndContentReceiverWithProgress(
  5899. ClientType &cli,
  5900. std::function<Result(ClientType &, const std::string &, const Headers &,
  5901. const std::string &, const std::string &,
  5902. ContentReceiver, DownloadProgress)>
  5903. request_func) {
  5904. Headers headers;
  5905. headers.emplace("X-Test-Header", "progress-test");
  5906. std::string received_body;
  5907. auto progress_called = false;
  5908. auto res = request_func(
  5909. cli, "/content_receiver", headers, "content", "text/plain",
  5910. [&](const char *data, size_t data_length) {
  5911. received_body.append(data, data_length);
  5912. return true;
  5913. },
  5914. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5915. progress_called = true;
  5916. return true;
  5917. });
  5918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5919. EXPECT_EQ(StatusCode::OK_200, res->status);
  5920. EXPECT_EQ("content", received_body);
  5921. EXPECT_TRUE(progress_called);
  5922. }
  5923. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5924. #ifdef CPPHTTPLIB_SSL_ENABLED
  5925. using ClientT = SSLClient;
  5926. #else
  5927. using ClientT = Client;
  5928. #endif
  5929. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5931. const std::string &body, const std::string &content_type,
  5932. ContentReceiver receiver, DownloadProgress progress) {
  5933. return cli.Post(path, headers, body, content_type, receiver, progress);
  5934. });
  5935. }
  5936. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5937. #ifdef CPPHTTPLIB_SSL_ENABLED
  5938. using ClientT = SSLClient;
  5939. #else
  5940. using ClientT = Client;
  5941. #endif
  5942. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5944. const std::string &body, const std::string &content_type,
  5945. ContentReceiver receiver, DownloadProgress progress) {
  5946. return cli.Put(path, headers, body, content_type, receiver, progress);
  5947. });
  5948. }
  5949. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5950. #ifdef CPPHTTPLIB_SSL_ENABLED
  5951. using ClientT = SSLClient;
  5952. #else
  5953. using ClientT = Client;
  5954. #endif
  5955. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5956. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5957. const std::string &body, const std::string &content_type,
  5958. ContentReceiver receiver, DownloadProgress progress) {
  5959. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5960. });
  5961. }
  5962. template <typename ClientType>
  5963. void TestWithHeadersAndContentReceiverError(
  5964. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5965. const Headers &, const std::string &,
  5966. const std::string &, ContentReceiver)>
  5967. request_func) {
  5968. Headers headers;
  5969. headers.emplace("X-Error-Test", "true");
  5970. std::string received_body;
  5971. auto receiver_failed = false;
  5972. auto res =
  5973. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5974. [&](const char *data, size_t data_length) {
  5975. received_body.append(data, data_length);
  5976. receiver_failed = true;
  5977. return false;
  5978. });
  5979. ASSERT_FALSE(res);
  5980. EXPECT_TRUE(receiver_failed);
  5981. }
  5982. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5983. #ifdef CPPHTTPLIB_SSL_ENABLED
  5984. using ClientT = SSLClient;
  5985. #else
  5986. using ClientT = Client;
  5987. #endif
  5988. TestWithHeadersAndContentReceiverError<ClientT>(
  5989. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5990. const std::string &body, const std::string &content_type,
  5991. ContentReceiver receiver) {
  5992. return cli.Post(path, headers, body, content_type, receiver);
  5993. });
  5994. }
  5995. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5996. #ifdef CPPHTTPLIB_SSL_ENABLED
  5997. using ClientT = SSLClient;
  5998. #else
  5999. using ClientT = Client;
  6000. #endif
  6001. TestWithHeadersAndContentReceiverError<ClientT>(
  6002. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6003. const std::string &body, const std::string &content_type,
  6004. ContentReceiver receiver) {
  6005. return cli.Put(path, headers, body, content_type, receiver);
  6006. });
  6007. }
  6008. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6009. #ifdef CPPHTTPLIB_SSL_ENABLED
  6010. using ClientT = SSLClient;
  6011. #else
  6012. using ClientT = Client;
  6013. #endif
  6014. TestWithHeadersAndContentReceiverError<ClientT>(
  6015. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6016. const std::string &body, const std::string &content_type,
  6017. ContentReceiver receiver) {
  6018. return cli.Patch(path, headers, body, content_type, receiver);
  6019. });
  6020. }
  6021. TEST_F(ServerTest, PostQueryStringAndBody) {
  6022. auto res =
  6023. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6025. ASSERT_EQ(StatusCode::OK_200, res->status);
  6026. }
  6027. TEST_F(ServerTest, HTTP2Magic) {
  6028. Request req;
  6029. req.method = "PRI";
  6030. req.path = "*";
  6031. req.body = "SM";
  6032. auto res = std::make_shared<Response>();
  6033. auto error = Error::Success;
  6034. auto ret = cli_.send(req, *res, error);
  6035. ASSERT_TRUE(ret);
  6036. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6037. }
  6038. TEST_F(ServerTest, KeepAlive) {
  6039. auto res = cli_.Get("/hi");
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6043. EXPECT_EQ("Hello World!", res->body);
  6044. res = cli_.Get("/hi");
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6048. EXPECT_EQ("Hello World!", res->body);
  6049. res = cli_.Get("/hi");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6053. EXPECT_EQ("Hello World!", res->body);
  6054. res = cli_.Get("/not-exist");
  6055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6056. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6057. res = cli_.Post("/empty", "", "text/plain");
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6061. EXPECT_EQ("empty", res->body);
  6062. EXPECT_EQ("close", res->get_header_value("Connection"));
  6063. res = cli_.Post(
  6064. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6065. "text/plain");
  6066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6067. EXPECT_EQ(StatusCode::OK_200, res->status);
  6068. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6069. EXPECT_EQ("empty", res->body);
  6070. cli_.set_keep_alive(false);
  6071. res = cli_.Get("/last-request");
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. EXPECT_EQ(StatusCode::OK_200, res->status);
  6074. EXPECT_EQ("close", res->get_header_value("Connection"));
  6075. }
  6076. TEST_F(ServerTest, TooManyRedirect) {
  6077. cli_.set_follow_location(true);
  6078. auto res = cli_.Get("/redirect/0");
  6079. ASSERT_TRUE(!res);
  6080. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6081. }
  6082. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6083. Request req;
  6084. req.method = "FOOBAR";
  6085. req.path = "/hi";
  6086. cli_.set_keep_alive(true);
  6087. auto res = cli_.send(req);
  6088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6089. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6090. EXPECT_EQ("close", res->get_header_value("Connection"));
  6091. EXPECT_FALSE(cli_.is_socket_open());
  6092. }
  6093. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6095. TEST_F(ServerTest, Gzip) {
  6096. Headers headers;
  6097. headers.emplace("Accept-Encoding", "gzip, deflate");
  6098. auto res = cli_.Get("/compress", headers);
  6099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6100. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6101. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6102. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6103. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6104. "7890123456789012345678901234567890",
  6105. res->body);
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. }
  6108. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6109. Headers headers;
  6110. headers.emplace("Accept-Encoding", "gzip, deflate");
  6111. auto res = cli_.Get("/compress-with-charset", headers);
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6114. EXPECT_EQ("application/json; charset=utf-8",
  6115. res->get_header_value("Content-Type"));
  6116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6117. "7890123456789012345678901234567890",
  6118. res->body);
  6119. EXPECT_EQ(StatusCode::OK_200, res->status);
  6120. }
  6121. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6122. Headers headers;
  6123. headers.emplace("Accept-Encoding", "");
  6124. auto res = cli_.Get("/compress", headers);
  6125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6126. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6128. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6129. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6130. "7890123456789012345678901234567890",
  6131. res->body);
  6132. EXPECT_EQ(StatusCode::OK_200, res->status);
  6133. }
  6134. TEST_F(ServerTest, GzipWithContentReceiver) {
  6135. Headers headers;
  6136. headers.emplace("Accept-Encoding", "gzip, deflate");
  6137. std::string body;
  6138. auto res = cli_.Get("/compress", headers,
  6139. [&](const char *data, uint64_t data_length) {
  6140. EXPECT_EQ(100U, data_length);
  6141. body.append(data, data_length);
  6142. return true;
  6143. });
  6144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6145. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6146. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6147. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6148. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6149. "7890123456789012345678901234567890",
  6150. body);
  6151. EXPECT_EQ(StatusCode::OK_200, res->status);
  6152. }
  6153. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6154. Headers headers;
  6155. headers.emplace("Accept-Encoding", "gzip, deflate");
  6156. cli_.set_decompress(false);
  6157. auto res = cli_.Get("/compress", headers);
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6161. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6162. EXPECT_EQ(33U, res->body.size());
  6163. EXPECT_EQ(StatusCode::OK_200, res->status);
  6164. }
  6165. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6166. Headers headers;
  6167. headers.emplace("Accept-Encoding", "");
  6168. std::string body;
  6169. auto res = cli_.Get("/compress", headers,
  6170. [&](const char *data, uint64_t data_length) {
  6171. EXPECT_EQ(100U, data_length);
  6172. body.append(data, data_length);
  6173. return true;
  6174. });
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6177. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6178. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6179. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6180. "7890123456789012345678901234567890",
  6181. body);
  6182. EXPECT_EQ(StatusCode::OK_200, res->status);
  6183. }
  6184. TEST_F(ServerTest, NoGzip) {
  6185. Headers headers;
  6186. headers.emplace("Accept-Encoding", "gzip, deflate");
  6187. auto res = cli_.Get("/nocompress", headers);
  6188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6189. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6190. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6191. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6192. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6193. "7890123456789012345678901234567890",
  6194. res->body);
  6195. EXPECT_EQ(StatusCode::OK_200, res->status);
  6196. }
  6197. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6198. Headers headers;
  6199. headers.emplace("Accept-Encoding", "gzip, deflate");
  6200. std::string body;
  6201. auto res = cli_.Get("/nocompress", headers,
  6202. [&](const char *data, uint64_t data_length) {
  6203. EXPECT_EQ(100U, data_length);
  6204. body.append(data, data_length);
  6205. return true;
  6206. });
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6209. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6210. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6211. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6212. "7890123456789012345678901234567890",
  6213. body);
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. TEST_F(ServerTest, MultipartFormDataGzip) {
  6217. UploadFormDataItems items = {
  6218. {"key1", "test", "", ""},
  6219. {"key2", "--abcdefg123", "", ""},
  6220. };
  6221. cli_.set_compress(true);
  6222. auto res = cli_.Post("/compress-multipart", items);
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::OK_200, res->status);
  6225. }
  6226. #endif
  6227. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6228. TEST_F(ServerTest, Brotli) {
  6229. Headers headers;
  6230. headers.emplace("Accept-Encoding", "br");
  6231. auto res = cli_.Get("/compress", headers);
  6232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6233. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6235. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6237. "7890123456789012345678901234567890",
  6238. res->body);
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. }
  6241. #endif
  6242. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6243. TEST_F(ServerTest, Zstd) {
  6244. Headers headers;
  6245. headers.emplace("Accept-Encoding", "zstd");
  6246. auto res = cli_.Get("/compress", headers);
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6249. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6250. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6251. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6252. "7890123456789012345678901234567890",
  6253. res->body);
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. }
  6256. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6257. Headers headers;
  6258. headers.emplace("Accept-Encoding", "");
  6259. auto res = cli_.Get("/compress", headers);
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6263. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6264. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6265. "7890123456789012345678901234567890",
  6266. res->body);
  6267. EXPECT_EQ(StatusCode::OK_200, res->status);
  6268. }
  6269. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6270. Headers headers;
  6271. headers.emplace("Accept-Encoding", "zstd");
  6272. std::string body;
  6273. auto res = cli_.Get("/compress", headers,
  6274. [&](const char *data, uint64_t data_length) {
  6275. EXPECT_EQ(100U, data_length);
  6276. body.append(data, data_length);
  6277. return true;
  6278. });
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6282. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6283. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6284. "7890123456789012345678901234567890",
  6285. body);
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. }
  6288. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6289. Headers headers;
  6290. headers.emplace("Accept-Encoding", "zstd");
  6291. cli_.set_decompress(false);
  6292. auto res = cli_.Get("/compress", headers);
  6293. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6294. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6295. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6296. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6300. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6301. EXPECT_EQ(StatusCode::OK_200, res->status);
  6302. ASSERT_EQ(26U, res->body.size());
  6303. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6304. 0);
  6305. }
  6306. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6307. Headers headers;
  6308. headers.emplace("Accept-Encoding", "");
  6309. std::string body;
  6310. auto res = cli_.Get("/compress", headers,
  6311. [&](const char *data, uint64_t data_length) {
  6312. EXPECT_EQ(100U, data_length);
  6313. body.append(data, data_length);
  6314. return true;
  6315. });
  6316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6317. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6319. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6320. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6321. "7890123456789012345678901234567890",
  6322. body);
  6323. EXPECT_EQ(StatusCode::OK_200, res->status);
  6324. }
  6325. TEST_F(ServerTest, NoZstd) {
  6326. Headers headers;
  6327. headers.emplace("Accept-Encoding", "zstd");
  6328. auto res = cli_.Get("/nocompress", headers);
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6331. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6332. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6333. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6334. "7890123456789012345678901234567890",
  6335. res->body);
  6336. EXPECT_EQ(StatusCode::OK_200, res->status);
  6337. }
  6338. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6339. Headers headers;
  6340. headers.emplace("Accept-Encoding", "zstd");
  6341. std::string body;
  6342. auto res = cli_.Get("/nocompress", headers,
  6343. [&](const char *data, uint64_t data_length) {
  6344. EXPECT_EQ(100U, data_length);
  6345. body.append(data, data_length);
  6346. return true;
  6347. });
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6350. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6351. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6352. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6353. "7890123456789012345678901234567890",
  6354. body);
  6355. EXPECT_EQ(StatusCode::OK_200, res->status);
  6356. }
  6357. // TODO: How to enable zstd ??
  6358. TEST_F(ServerTest, MultipartFormDataZstd) {
  6359. UploadFormDataItems items = {
  6360. {"key1", "test", "", ""},
  6361. {"key2", "--abcdefg123", "", ""},
  6362. };
  6363. Headers headers;
  6364. headers.emplace("Accept-Encoding", "zstd");
  6365. cli_.set_compress(true);
  6366. auto res = cli_.Post("/compress-multipart", headers, items);
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. }
  6370. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6371. Headers headers;
  6372. headers.emplace("Accept-Encoding", "zstd");
  6373. cli_.set_compress(true);
  6374. auto res = cli_.Put(
  6375. "/put", headers, 3,
  6376. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6377. sink.os << "PUT";
  6378. return true;
  6379. },
  6380. "text/plain");
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::OK_200, res->status);
  6383. EXPECT_EQ("PUT", res->body);
  6384. }
  6385. // Pre-compression logging tests
  6386. TEST_F(ServerTest, PreCompressionLogging) {
  6387. // Test data for compression (matches the actual /compress endpoint content)
  6388. const std::string test_content =
  6389. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6390. "3456789012345678901234567890";
  6391. // Variables to capture logging data
  6392. std::string pre_compression_body;
  6393. std::string pre_compression_content_type;
  6394. std::string pre_compression_content_encoding;
  6395. std::string post_compression_body;
  6396. std::string post_compression_content_type;
  6397. std::string post_compression_content_encoding;
  6398. // Set up pre-compression logger
  6399. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6400. const Response &res) {
  6401. pre_compression_body = res.body;
  6402. pre_compression_content_type = res.get_header_value("Content-Type");
  6403. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6404. });
  6405. // Set up post-compression logger
  6406. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6407. post_compression_body = res.body;
  6408. post_compression_content_type = res.get_header_value("Content-Type");
  6409. post_compression_content_encoding =
  6410. res.get_header_value("Content-Encoding");
  6411. });
  6412. // Test with gzip compression
  6413. Headers headers;
  6414. headers.emplace("Accept-Encoding", "gzip");
  6415. auto res = cli_.Get("/compress", headers);
  6416. // Verify response was compressed
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. EXPECT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6420. // Verify pre-compression logger captured uncompressed content
  6421. EXPECT_EQ(test_content, pre_compression_body);
  6422. EXPECT_EQ("text/plain", pre_compression_content_type);
  6423. EXPECT_TRUE(pre_compression_content_encoding
  6424. .empty()); // No encoding header before compression
  6425. // Verify post-compression logger captured compressed content
  6426. EXPECT_NE(test_content,
  6427. post_compression_body); // Should be different after compression
  6428. EXPECT_EQ("text/plain", post_compression_content_type);
  6429. EXPECT_EQ("gzip", post_compression_content_encoding);
  6430. // Verify compressed content is smaller
  6431. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6432. }
  6433. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6434. const std::string test_content =
  6435. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6436. "3456789012345678901234567890";
  6437. std::string pre_compression_body;
  6438. std::string post_compression_body;
  6439. svr_.set_pre_compression_logger(
  6440. [&](const Request & /*req*/, const Response &res) {
  6441. pre_compression_body = res.body;
  6442. });
  6443. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6444. post_compression_body = res.body;
  6445. });
  6446. Headers headers;
  6447. headers.emplace("Accept-Encoding", "br");
  6448. auto res = cli_.Get("/compress", headers);
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::OK_200, res->status);
  6451. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6452. // Verify pre-compression content is uncompressed
  6453. EXPECT_EQ(test_content, pre_compression_body);
  6454. // Verify post-compression content is compressed
  6455. EXPECT_NE(test_content, post_compression_body);
  6456. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6457. }
  6458. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6459. const std::string test_content =
  6460. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6461. "3456789012345678901234567890";
  6462. std::string pre_compression_body;
  6463. std::string post_compression_body;
  6464. svr_.set_pre_compression_logger(
  6465. [&](const Request & /*req*/, const Response &res) {
  6466. pre_compression_body = res.body;
  6467. });
  6468. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6469. post_compression_body = res.body;
  6470. });
  6471. // Request without compression (use /nocompress endpoint)
  6472. Headers headers;
  6473. auto res = cli_.Get("/nocompress", headers);
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. EXPECT_EQ(StatusCode::OK_200, res->status);
  6476. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6477. // Pre-compression logger should not be called when no compression is applied
  6478. EXPECT_TRUE(
  6479. pre_compression_body.empty()); // Pre-compression logger not called
  6480. EXPECT_EQ(
  6481. test_content,
  6482. post_compression_body); // Post-compression logger captures final content
  6483. }
  6484. TEST_F(ServerTest, LoggerSeesContentLength) {
  6485. size_t logged_content_length = 0;
  6486. std::string logged_content_length_header;
  6487. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6488. logged_content_length = res.content_length_;
  6489. logged_content_length_header = res.get_header_value("Content-Length");
  6490. });
  6491. auto res = cli_.Get("/nocompress");
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. EXPECT_EQ(StatusCode::OK_200, res->status);
  6494. EXPECT_EQ(res->body.size(), logged_content_length);
  6495. EXPECT_EQ(std::to_string(logged_content_length),
  6496. logged_content_length_header);
  6497. }
  6498. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6499. const std::string test_content =
  6500. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6501. "3456789012345678901234567890";
  6502. std::string pre_compression_body;
  6503. bool pre_logger_called = false;
  6504. // Set only pre-compression logger
  6505. svr_.set_pre_compression_logger(
  6506. [&](const Request & /*req*/, const Response &res) {
  6507. pre_compression_body = res.body;
  6508. pre_logger_called = true;
  6509. });
  6510. Headers headers;
  6511. headers.emplace("Accept-Encoding", "gzip");
  6512. auto res = cli_.Get("/compress", headers);
  6513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6514. EXPECT_EQ(StatusCode::OK_200, res->status);
  6515. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6516. // Verify pre-compression logger was called
  6517. EXPECT_TRUE(pre_logger_called);
  6518. EXPECT_EQ(test_content, pre_compression_body);
  6519. }
  6520. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6521. {
  6522. // Test with Expect: 100-continue header - success case
  6523. // Server returns 100 Continue, client sends body, server returns 200 OK
  6524. Request req;
  6525. req.method = "POST";
  6526. req.path = "/post-large";
  6527. req.set_header("Expect", "100-continue");
  6528. req.body = LARGE_DATA;
  6529. Response res;
  6530. auto error = Error::Success;
  6531. cli_.set_keep_alive(true);
  6532. auto ret = cli_.send(req, res, error);
  6533. EXPECT_TRUE(ret);
  6534. EXPECT_EQ(StatusCode::OK_200, res.status);
  6535. EXPECT_EQ(LARGE_DATA, res.body);
  6536. }
  6537. {
  6538. // Test with Expect: 100-continue header - error case
  6539. // Client should not send the body when server returns an error
  6540. Request req;
  6541. req.method = "POST";
  6542. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6543. req.set_header("Expect", "100-continue");
  6544. req.body = LARGE_DATA;
  6545. Response res;
  6546. auto error = Error::Success;
  6547. auto start = std::chrono::high_resolution_clock::now();
  6548. cli_.set_keep_alive(true);
  6549. auto ret = cli_.send(req, res, error);
  6550. auto end = std::chrono::high_resolution_clock::now();
  6551. auto elapsed =
  6552. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6553. .count();
  6554. // With Expect: 100-continue, request completes successfully but with error
  6555. EXPECT_TRUE(ret);
  6556. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6557. EXPECT_EQ("close", res.get_header_value("Connection"));
  6558. EXPECT_FALSE(cli_.is_socket_open());
  6559. EXPECT_LE(elapsed, 2000);
  6560. }
  6561. {
  6562. // Send an extra GET request to ensure error recovery without hanging
  6563. Request req;
  6564. req.method = "GET";
  6565. req.path = "/hi";
  6566. auto start = std::chrono::high_resolution_clock::now();
  6567. auto res = cli_.send(req);
  6568. auto end = std::chrono::high_resolution_clock::now();
  6569. auto elapsed =
  6570. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6571. .count();
  6572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6573. EXPECT_EQ(StatusCode::OK_200, res->status);
  6574. EXPECT_EQ("Hello World!", res->body);
  6575. EXPECT_LE(elapsed, 500);
  6576. }
  6577. }
  6578. TEST(ZstdDecompressor, ChunkedDecompression) {
  6579. std::string data;
  6580. for (size_t i = 0; i < 32 * 1024; ++i) {
  6581. data.push_back(static_cast<char>('a' + i % 26));
  6582. }
  6583. std::string compressed_data;
  6584. {
  6585. httplib::detail::zstd_compressor compressor;
  6586. bool result = compressor.compress(
  6587. data.data(), data.size(),
  6588. /*last=*/true,
  6589. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6590. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6591. compressed_data_size);
  6592. return true;
  6593. });
  6594. ASSERT_TRUE(result);
  6595. }
  6596. std::string decompressed_data;
  6597. {
  6598. httplib::detail::zstd_decompressor decompressor;
  6599. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6600. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6601. size_t chunk_size = 130;
  6602. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6603. chunk_begin += chunk_size) {
  6604. size_t current_chunk_size =
  6605. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6606. bool result = decompressor.decompress(
  6607. compressed_data.data() + chunk_begin, current_chunk_size,
  6608. [&](const char *decompressed_data_chunk,
  6609. size_t decompressed_data_chunk_size) {
  6610. decompressed_data.insert(decompressed_data.size(),
  6611. decompressed_data_chunk,
  6612. decompressed_data_chunk_size);
  6613. return true;
  6614. });
  6615. ASSERT_TRUE(result);
  6616. }
  6617. }
  6618. ASSERT_EQ(data, decompressed_data);
  6619. }
  6620. TEST(ZstdDecompressor, Decompress) {
  6621. std::string original_text = "Compressed with ZSTD";
  6622. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6623. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6624. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6625. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6626. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6627. std::string decompressed_data;
  6628. {
  6629. httplib::detail::zstd_decompressor decompressor;
  6630. bool result = decompressor.decompress(
  6631. compressed_data.data(), compressed_data.size(),
  6632. [&](const char *decompressed_data_chunk,
  6633. size_t decompressed_data_chunk_size) {
  6634. decompressed_data.insert(decompressed_data.size(),
  6635. decompressed_data_chunk,
  6636. decompressed_data_chunk_size);
  6637. return true;
  6638. });
  6639. ASSERT_TRUE(result);
  6640. }
  6641. ASSERT_EQ(original_text, decompressed_data);
  6642. }
  6643. #endif
  6644. // Sends a raw request to a server listening at HOST:PORT.
  6645. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6646. std::string *resp = nullptr) {
  6647. auto error = Error::Success;
  6648. auto client_sock = detail::create_client_socket(
  6649. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6650. /*connection_timeout_sec=*/5, 0,
  6651. /*read_timeout_sec=*/5, 0,
  6652. /*write_timeout_sec=*/5, 0, std::string(), error);
  6653. if (client_sock == INVALID_SOCKET) { return false; }
  6654. auto ret = detail::process_client_socket(
  6655. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6656. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6657. if (req.size() !=
  6658. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6659. return false;
  6660. }
  6661. char buf[512];
  6662. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6663. while (line_reader.getline()) {
  6664. if (resp) { *resp += line_reader.ptr(); }
  6665. }
  6666. return true;
  6667. });
  6668. detail::close_socket(client_sock);
  6669. return ret;
  6670. }
  6671. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6672. Server svr;
  6673. std::string header_value;
  6674. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6675. header_value = req.get_header_value("foo");
  6676. res.set_content("ok", "text/plain");
  6677. });
  6678. thread t = thread([&] { svr.listen(HOST, PORT); });
  6679. auto se = detail::scope_exit([&] {
  6680. svr.stop();
  6681. t.join();
  6682. ASSERT_FALSE(svr.is_running());
  6683. });
  6684. svr.wait_until_ready();
  6685. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6686. // like characters are not treated the same - use vertical tab and escape.
  6687. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6688. "foo: \t \v bar \x1B\t \r\n"
  6689. "Connection: close\r\n"
  6690. "\r\n";
  6691. std::string res;
  6692. ASSERT_TRUE(send_request(5, req, &res));
  6693. EXPECT_EQ(header_value, "");
  6694. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6695. }
  6696. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6697. Server svr;
  6698. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6699. auto i = new int(0);
  6700. res.set_header("Trailer", "X-Safe, X-Reflected");
  6701. res.set_chunked_content_provider(
  6702. "text/plain",
  6703. [i](size_t /*offset*/, DataSink &sink) {
  6704. if (*i == 0) {
  6705. sink.os << "body";
  6706. } else {
  6707. Headers trailer;
  6708. // A valid trailer that must survive.
  6709. trailer.emplace("X-Safe", "safe");
  6710. // Attacker-controlled value carrying CR/LF (response splitting).
  6711. trailer.emplace("X-Reflected",
  6712. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6713. // Attacker-controlled name carrying CR/LF.
  6714. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6715. sink.done_with_trailer(trailer);
  6716. }
  6717. (*i)++;
  6718. return true;
  6719. },
  6720. [i](bool /*success*/) { delete i; });
  6721. });
  6722. thread t = thread([&] { svr.listen(HOST, PORT); });
  6723. auto se = detail::scope_exit([&] {
  6724. svr.stop();
  6725. t.join();
  6726. ASSERT_FALSE(svr.is_running());
  6727. });
  6728. svr.wait_until_ready();
  6729. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6730. "Host: " + HOST +
  6731. "\r\n"
  6732. "Connection: close\r\n"
  6733. "\r\n";
  6734. std::string res;
  6735. ASSERT_TRUE(send_request(5, req, &res));
  6736. // The injected fields must not appear anywhere in the raw response.
  6737. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6738. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6739. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6740. // Invalid trailers are dropped entirely, matching set_header().
  6741. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6742. // The valid trailer still passes through.
  6743. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6744. }
  6745. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  6746. Server svr;
  6747. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  6748. // res.headers is a public field an application can populate directly,
  6749. // bypassing set_header()'s validation (e.g. reflecting a request value).
  6750. // A valid header that must survive.
  6751. res.headers.emplace("X-Safe", "safe");
  6752. // Attacker-controlled value carrying CR/LF (response splitting).
  6753. res.headers.emplace("X-Reflected",
  6754. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6755. // Attacker-controlled name carrying CR/LF.
  6756. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6757. res.set_content("body", "text/plain");
  6758. });
  6759. thread t = thread([&] { svr.listen(HOST, PORT); });
  6760. auto se = detail::scope_exit([&] {
  6761. svr.stop();
  6762. t.join();
  6763. ASSERT_FALSE(svr.is_running());
  6764. });
  6765. svr.wait_until_ready();
  6766. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  6767. "Host: " + HOST +
  6768. "\r\n"
  6769. "Connection: close\r\n"
  6770. "\r\n";
  6771. std::string res;
  6772. ASSERT_TRUE(send_request(5, req, &res));
  6773. // The injected fields must not appear anywhere in the raw response.
  6774. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6775. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6776. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6777. // Invalid headers are dropped entirely, matching set_header().
  6778. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6779. // The valid header still passes through.
  6780. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6781. }
  6782. // Forward declaration: in split builds split.py strips `inline` and moves the
  6783. // definition into httplib.cc, so detail::write_request_line is not visible from
  6784. // the public httplib.h. Re-declaring it here lets the tests link against the
  6785. // symbol in both header-only and split builds.
  6786. namespace httplib {
  6787. namespace detail {
  6788. ssize_t write_request_line(Stream &strm, const std::string &method,
  6789. const std::string &path);
  6790. } // namespace detail
  6791. } // namespace httplib
  6792. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  6793. // A well-formed target is written verbatim.
  6794. {
  6795. detail::BufferStream strm;
  6796. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  6797. EXPECT_GT(n, 0);
  6798. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  6799. }
  6800. // A target carrying CR/LF must be rejected before anything reaches the wire,
  6801. // otherwise it splits the request line and injects a header or a whole
  6802. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  6803. // when path encoding is disabled.
  6804. const std::string evil_targets[] = {
  6805. "/a\r\nInjected: pwned",
  6806. "/a\rInjected",
  6807. "/a\nInjected",
  6808. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  6809. };
  6810. for (const auto &evil : evil_targets) {
  6811. detail::BufferStream strm;
  6812. auto n = detail::write_request_line(strm, "GET", evil);
  6813. EXPECT_LT(n, 0);
  6814. EXPECT_TRUE(strm.get_buffer().empty());
  6815. }
  6816. }
  6817. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  6818. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  6819. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  6820. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  6821. // client must fail cleanly with Error::Write instead of putting a
  6822. // request-line-less, header-injecting request on the wire.
  6823. Server svr;
  6824. svr.Get("/a", [](const Request &, Response &res) {
  6825. res.set_content("ok", "text/plain");
  6826. });
  6827. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6828. auto se = detail::scope_exit([&] {
  6829. svr.stop();
  6830. thread.join();
  6831. ASSERT_FALSE(svr.is_running());
  6832. });
  6833. svr.wait_until_ready();
  6834. {
  6835. Client cli(HOST, PORT);
  6836. cli.set_path_encode(false);
  6837. // The request is rejected before anything is written, so the connection
  6838. // stays silent and the subsequent response read would otherwise block for
  6839. // the full default read timeout. Shorten it -- the assertion is on the
  6840. // error, not the timeout.
  6841. cli.set_read_timeout(1, 0);
  6842. auto res = cli.Get("/a\r\nInjected: pwned");
  6843. EXPECT_FALSE(res);
  6844. EXPECT_EQ(Error::Write, res.error());
  6845. }
  6846. }
  6847. // Sends a raw request and verifies that there isn't a crash or exception.
  6848. static void test_raw_request(const std::string &req,
  6849. std::string *out = nullptr) {
  6850. Server svr;
  6851. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6852. res.set_content("ok", "text/plain");
  6853. });
  6854. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6855. res.set_content("ok", "text/plain");
  6856. });
  6857. svr.Get("/header_field_value_check",
  6858. [&](const Request & /*req*/, Response &res) {
  6859. res.set_content("ok", "text/plain");
  6860. });
  6861. // Server read timeout must be longer than the client read timeout for the
  6862. // bug to reproduce, probably to force the server to process a request
  6863. // without a trailing blank line.
  6864. const time_t client_read_timeout_sec = 1;
  6865. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6866. bool listen_thread_ok = false;
  6867. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6868. auto se = detail::scope_exit([&] {
  6869. svr.stop();
  6870. t.join();
  6871. ASSERT_FALSE(svr.is_running());
  6872. EXPECT_TRUE(listen_thread_ok);
  6873. });
  6874. svr.wait_until_ready();
  6875. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6876. }
  6877. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6878. // A certain header line causes an exception if the header property is parsed
  6879. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6880. test_raw_request(
  6881. "GET /hi HTTP/1.1\r\n"
  6882. " : "
  6883. " "
  6884. " ");
  6885. }
  6886. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6887. // A certain header line causes an exception if the header property *name* is
  6888. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6889. // greedy matcher and requires backtracking when there are a lot of ":"
  6890. // characters.
  6891. // This occurs with libc++ but not libstdc++.
  6892. test_raw_request(
  6893. "GET /hi HTTP/1.1\r\n"
  6894. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6895. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6896. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6897. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6898. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6899. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6900. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6901. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6902. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6903. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6904. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6905. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6906. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6907. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6908. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6909. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6910. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6911. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6912. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6913. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6914. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6915. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6916. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6917. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6918. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6919. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6920. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6921. "&&&%%%");
  6922. }
  6923. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6924. // Make sure this doesn't crash the server.
  6925. // In a previous version of the header line regex, the "\r" rendered the line
  6926. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6927. // a new position where the leading white space ended and the field value
  6928. // began.
  6929. // The crash occurs with libc++ but not libstdc++.
  6930. test_raw_request("GET /hi HTTP/1.1\r\n"
  6931. "a:" +
  6932. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6933. "\r\n"
  6934. "\r\n");
  6935. }
  6936. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6937. std::string out;
  6938. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6939. "Content-Type: text/plain\r\n"
  6940. "Transfer-Encoding: chunked\r\n"
  6941. "\r\n"
  6942. "nothex\r\n",
  6943. &out);
  6944. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6945. }
  6946. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6947. std::string out;
  6948. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6949. "Content-Type: text/plain\r\n"
  6950. "Transfer-Encoding: chunked\r\n"
  6951. "\r\n"
  6952. "3\r\n"
  6953. "xyz\r\n"
  6954. "NaN\r\n",
  6955. &out);
  6956. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6957. }
  6958. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6959. std::string out;
  6960. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6961. "Content-Type: text/plain\r\n"
  6962. "Transfer-Encoding: chunked\r\n"
  6963. "\r\n"
  6964. // Length is too large for 64 bits.
  6965. "1ffffffffffffffff\r\n"
  6966. "xyz\r\n",
  6967. &out);
  6968. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6969. }
  6970. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6971. test_raw_request("GET /hi HTTP/1.1\r\n"
  6972. "Content-Type: text/plain\r\n\r");
  6973. }
  6974. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6975. std::string out;
  6976. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6977. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6978. }
  6979. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6980. Server svr;
  6981. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6982. EXPECT_TRUE(!req.remote_addr.empty());
  6983. });
  6984. thread t = thread([&] { svr.listen(HOST, PORT); });
  6985. auto se = detail::scope_exit([&] {
  6986. svr.stop();
  6987. t.join();
  6988. ASSERT_FALSE(svr.is_running());
  6989. });
  6990. svr.wait_until_ready();
  6991. // Send an invalid request line to trigger Bad Request
  6992. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6993. std::string out;
  6994. ASSERT_TRUE(send_request(5, bad_req, &out));
  6995. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6996. }
  6997. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6998. std::string out;
  6999. std::string request(
  7000. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7001. test_raw_request(request, &out);
  7002. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7003. }
  7004. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7005. std::string out;
  7006. std::string request(
  7007. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7008. test_raw_request(request, &out);
  7009. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7010. }
  7011. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7012. std::string out;
  7013. std::string request(
  7014. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7015. test_raw_request(request, &out);
  7016. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7017. }
  7018. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7019. std::string out;
  7020. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7021. "Test: \r\n\r\n",
  7022. &out);
  7023. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7024. }
  7025. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7026. Server svr;
  7027. std::string x_custom;
  7028. std::string cookie;
  7029. std::string xff;
  7030. std::string x_unicode;
  7031. std::string x_iis;
  7032. svr.Get("/check", [&](const Request &req, Response &res) {
  7033. x_custom = req.get_header_value("X-Custom");
  7034. cookie = req.get_header_value("Cookie");
  7035. xff = req.get_header_value("X-Forwarded-For");
  7036. x_unicode = req.get_header_value("X-Unicode");
  7037. x_iis = req.get_header_value("X-IIS");
  7038. res.set_content("ok", "text/plain");
  7039. });
  7040. thread t = thread([&] { svr.listen(HOST, PORT); });
  7041. auto se = detail::scope_exit([&] {
  7042. svr.stop();
  7043. t.join();
  7044. ASSERT_FALSE(svr.is_running());
  7045. });
  7046. svr.wait_until_ready();
  7047. const std::string req = "GET /check HTTP/1.1\r\n"
  7048. "Host: localhost\r\n"
  7049. "X-Custom: a%0D%0AInjected: b\r\n"
  7050. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7051. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7052. "X-Unicode: %E3%81%82\r\n"
  7053. "X-IIS: %u00E9\r\n"
  7054. "Connection: close\r\n"
  7055. "\r\n";
  7056. std::string res;
  7057. ASSERT_TRUE(send_request(5, req, &res));
  7058. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7059. // Every value must be returned verbatim (wire form), with no decoding.
  7060. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7061. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7062. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7063. EXPECT_EQ("%E3%81%82", x_unicode);
  7064. EXPECT_EQ("%u00E9", x_iis);
  7065. }
  7066. // Applications that previously relied on automatic percent-decoding can
  7067. // reproduce the old behavior by explicitly calling decode_path_component()
  7068. // or, for RFC 3986 conformance, decode_uri_component().
  7069. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7070. Server svr;
  7071. std::string decoded;
  7072. svr.Get("/check", [&](const Request &req, Response &res) {
  7073. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7074. res.set_content("ok", "text/plain");
  7075. });
  7076. thread t = thread([&] { svr.listen(HOST, PORT); });
  7077. auto se = detail::scope_exit([&] {
  7078. svr.stop();
  7079. t.join();
  7080. ASSERT_FALSE(svr.is_running());
  7081. });
  7082. svr.wait_until_ready();
  7083. const std::string req = "GET /check HTTP/1.1\r\n"
  7084. "Host: localhost\r\n"
  7085. "X-Custom: hello%20world\r\n"
  7086. "Connection: close\r\n"
  7087. "\r\n";
  7088. std::string res;
  7089. ASSERT_TRUE(send_request(5, req, &res));
  7090. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7091. EXPECT_EQ("hello world", decoded);
  7092. }
  7093. // Regression test for #2033. Browsers send Referer values that include
  7094. // percent-encoded characters such as %0A inside the URL. Decoding the
  7095. // header value would either trip the post-decode CR/LF/NUL guard (the
  7096. // original bug, returning 400) or, after that guard was relaxed, silently
  7097. // store a literal LF — both unacceptable. The wire form must round-trip.
  7098. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7099. Server svr;
  7100. std::string referer;
  7101. svr.Get("/check", [&](const Request &req, Response &res) {
  7102. referer = req.get_header_value("Referer");
  7103. res.set_content("ok", "text/plain");
  7104. });
  7105. thread t = thread([&] { svr.listen(HOST, PORT); });
  7106. auto se = detail::scope_exit([&] {
  7107. svr.stop();
  7108. t.join();
  7109. ASSERT_FALSE(svr.is_running());
  7110. });
  7111. svr.wait_until_ready();
  7112. const std::string req = "GET /check HTTP/1.1\r\n"
  7113. "Host: localhost\r\n"
  7114. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7115. "Connection: close\r\n"
  7116. "\r\n";
  7117. std::string res;
  7118. ASSERT_TRUE(send_request(5, req, &res));
  7119. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7120. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7121. }
  7122. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7123. Server svr;
  7124. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7125. res.set_header("Cache-Control", "no-cache");
  7126. res.set_chunked_content_provider(
  7127. "text/event-stream", [](size_t offset, DataSink &sink) {
  7128. std::string s = "data:";
  7129. s += std::to_string(offset);
  7130. s += "\n\n";
  7131. auto ret = sink.write(s.data(), s.size());
  7132. EXPECT_TRUE(ret);
  7133. std::this_thread::sleep_for(std::chrono::seconds(1));
  7134. return true;
  7135. });
  7136. });
  7137. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7138. svr.wait_until_ready();
  7139. Client client(HOST, PORT);
  7140. const Headers headers = {{"Accept", "text/event-stream"}};
  7141. auto get_thread = std::thread([&client, &headers]() {
  7142. auto res = client.Get(
  7143. "/events", headers,
  7144. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7145. });
  7146. auto se = detail::scope_exit([&] {
  7147. svr.stop();
  7148. get_thread.join();
  7149. listen_thread.join();
  7150. ASSERT_FALSE(svr.is_running());
  7151. });
  7152. // Give GET time to get a few messages.
  7153. std::this_thread::sleep_for(std::chrono::seconds(2));
  7154. }
  7155. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7156. httplib::Server svr;
  7157. svr.Post("/hi",
  7158. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7159. res.status = StatusCode::OK_200;
  7160. });
  7161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7162. svr.wait_until_ready();
  7163. Client cli(HOST, PORT);
  7164. auto res = cli.Post("/hi", "data", "text/plain");
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::OK_200, res->status);
  7167. svr.stop();
  7168. thread.join();
  7169. ASSERT_FALSE(svr.is_running());
  7170. res = cli.Post("/hi", "data", "text/plain");
  7171. ASSERT_FALSE(res);
  7172. }
  7173. TEST(ServerStopTest, ListenFailure) {
  7174. Server svr;
  7175. auto t = thread([&]() {
  7176. auto ret = svr.listen("????", PORT);
  7177. EXPECT_FALSE(ret);
  7178. });
  7179. svr.wait_until_ready();
  7180. svr.stop();
  7181. t.join();
  7182. }
  7183. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7184. TEST(ServerStopTest, Decommision) {
  7185. Server svr;
  7186. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7187. for (int i = 0; i < 4; i++) {
  7188. auto is_even = !(i % 2);
  7189. std::thread t{[&] {
  7190. try {
  7191. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7192. if (is_even) {
  7193. throw std::runtime_error("Some thing that happens to go wrong.");
  7194. }
  7195. svr.listen(HOST, PORT);
  7196. } catch (...) { svr.decommission(); }
  7197. }};
  7198. svr.wait_until_ready();
  7199. // Server is up
  7200. {
  7201. Client cli(HOST, PORT);
  7202. auto res = cli.Get("/hi");
  7203. if (is_even) {
  7204. EXPECT_FALSE(res);
  7205. } else {
  7206. EXPECT_TRUE(res);
  7207. EXPECT_EQ("hi...", res->body);
  7208. }
  7209. }
  7210. svr.stop();
  7211. t.join();
  7212. // Server is down...
  7213. {
  7214. Client cli(HOST, PORT);
  7215. auto res = cli.Get("/hi");
  7216. EXPECT_FALSE(res);
  7217. }
  7218. }
  7219. }
  7220. #endif
  7221. // Helper function for string body upload progress tests
  7222. template <typename SetupHandler, typename ClientCall>
  7223. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7224. ClientCall &&client_call,
  7225. const string &body) {
  7226. Server svr;
  7227. setup_handler(svr);
  7228. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7229. auto se = detail::scope_exit([&] {
  7230. svr.stop();
  7231. t.join();
  7232. });
  7233. svr.wait_until_ready();
  7234. Client cli(HOST, PORT);
  7235. vector<uint64_t> progress_values;
  7236. bool progress_called = false;
  7237. auto res =
  7238. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7239. progress_values.push_back(current);
  7240. progress_called = true;
  7241. return true;
  7242. });
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(200, res->status);
  7245. EXPECT_TRUE(progress_called);
  7246. }
  7247. TEST(UploadProgressTest, PostStringBodyBasic) {
  7248. TestStringBodyUploadProgress(
  7249. [](Server &svr) {
  7250. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7251. res.set_content("received", "text/plain");
  7252. });
  7253. },
  7254. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7255. return cli.Post("/test", body, "text/plain", progress_callback);
  7256. },
  7257. "test data for upload progress");
  7258. }
  7259. TEST(UploadProgressTest, PutStringBodyBasic) {
  7260. TestStringBodyUploadProgress(
  7261. [](Server &svr) {
  7262. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7263. res.set_content("put received", "text/plain");
  7264. });
  7265. },
  7266. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7267. return cli.Put("/test", body, "text/plain", progress_callback);
  7268. },
  7269. "put test data for upload progress");
  7270. }
  7271. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7272. TestStringBodyUploadProgress(
  7273. [](Server &svr) {
  7274. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7275. res.set_content("patch received", "text/plain");
  7276. });
  7277. },
  7278. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7279. return cli.Patch("/test", body, "text/plain", progress_callback);
  7280. },
  7281. "patch test data for upload progress");
  7282. }
  7283. // Helper function for content provider upload progress tests
  7284. template <typename SetupHandler, typename ClientCall>
  7285. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7286. ClientCall &&client_call) {
  7287. Server svr;
  7288. setup_handler(svr);
  7289. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7290. auto se = detail::scope_exit([&] {
  7291. svr.stop();
  7292. t.join();
  7293. });
  7294. svr.wait_until_ready();
  7295. Client cli(HOST, PORT);
  7296. vector<uint64_t> progress_values;
  7297. auto res =
  7298. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7299. progress_values.push_back(current);
  7300. return true;
  7301. });
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(200, res->status);
  7304. EXPECT_FALSE(progress_values.empty());
  7305. }
  7306. TEST(UploadProgressTest, PostContentProviderProgress) {
  7307. TestContentProviderUploadProgress(
  7308. [](Server &svr) {
  7309. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7310. res.set_content("provider received", "text/plain");
  7311. });
  7312. },
  7313. [](Client &cli, UploadProgress progress_callback) {
  7314. return cli.Post(
  7315. "/test", 10,
  7316. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7317. sink.os << "test data";
  7318. return true;
  7319. },
  7320. "text/plain", progress_callback);
  7321. });
  7322. }
  7323. // Helper function for multipart upload progress tests
  7324. template <typename SetupHandler, typename ClientCall>
  7325. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7326. ClientCall &&client_call,
  7327. const string &endpoint) {
  7328. Server svr;
  7329. setup_handler(svr);
  7330. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7331. auto se = detail::scope_exit([&] {
  7332. svr.stop();
  7333. t.join();
  7334. });
  7335. svr.wait_until_ready();
  7336. Client cli(HOST, PORT);
  7337. vector<uint64_t> progress_values;
  7338. UploadFormDataItems items = {
  7339. {"field1", "value1", "", ""},
  7340. {"field2", "longer value for progress tracking test", "", ""},
  7341. {"file1", "file content data for upload progress", "test.txt",
  7342. "text/plain"}};
  7343. auto res = client_call(cli, endpoint, items,
  7344. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7345. progress_values.push_back(current);
  7346. return true;
  7347. });
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(200, res->status);
  7350. EXPECT_FALSE(progress_values.empty());
  7351. }
  7352. TEST(UploadProgressTest, PostMultipartProgress) {
  7353. TestMultipartUploadProgress(
  7354. [](Server &svr) {
  7355. svr.Post("/multipart", [](const Request &req, Response &res) {
  7356. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7357. res.set_content("multipart received", "text/plain");
  7358. });
  7359. },
  7360. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7361. UploadProgress progress_callback) {
  7362. return cli.Post(endpoint, items, progress_callback);
  7363. },
  7364. "/multipart");
  7365. }
  7366. // Helper function for basic download progress tests
  7367. template <typename SetupHandler, typename ClientCall>
  7368. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7369. ClientCall &&client_call, const string &endpoint,
  7370. size_t expected_content_size) {
  7371. Server svr;
  7372. setup_handler(svr);
  7373. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7374. auto se = detail::scope_exit([&] {
  7375. svr.stop();
  7376. t.join();
  7377. });
  7378. svr.wait_until_ready();
  7379. Client cli(HOST, PORT);
  7380. vector<uint64_t> progress_values;
  7381. auto res = client_call(cli, endpoint,
  7382. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7383. progress_values.push_back(current);
  7384. return true;
  7385. });
  7386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7387. EXPECT_EQ(200, res->status);
  7388. EXPECT_FALSE(progress_values.empty());
  7389. EXPECT_EQ(expected_content_size, res->body.size());
  7390. }
  7391. TEST(DownloadProgressTest, GetBasic) {
  7392. TestBasicDownloadProgress(
  7393. [](Server &svr) {
  7394. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7395. string content(1000, 'D');
  7396. res.set_content(content, "text/plain");
  7397. });
  7398. },
  7399. [](Client &cli, const string &endpoint,
  7400. DownloadProgress progress_callback) {
  7401. return cli.Get(endpoint, progress_callback);
  7402. },
  7403. "/download", 1000u);
  7404. }
  7405. // Helper function for content receiver download progress tests
  7406. template <typename SetupHandler, typename ClientCall>
  7407. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7408. ClientCall &&client_call,
  7409. const string &endpoint,
  7410. size_t expected_content_size) {
  7411. Server svr;
  7412. setup_handler(svr);
  7413. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7414. auto se = detail::scope_exit([&] {
  7415. svr.stop();
  7416. t.join();
  7417. });
  7418. svr.wait_until_ready();
  7419. Client cli(HOST, PORT);
  7420. vector<uint64_t> progress_values;
  7421. string received_body;
  7422. auto res = client_call(
  7423. cli, endpoint,
  7424. [&](const char *data, size_t data_length) -> bool {
  7425. received_body.append(data, data_length);
  7426. return true;
  7427. },
  7428. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7429. progress_values.push_back(current);
  7430. return true;
  7431. });
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. EXPECT_EQ(200, res->status);
  7434. EXPECT_FALSE(progress_values.empty());
  7435. EXPECT_EQ(expected_content_size, received_body.size());
  7436. EXPECT_TRUE(res->body.empty());
  7437. }
  7438. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7439. TestContentReceiverDownloadProgress(
  7440. [](Server &svr) {
  7441. svr.Get("/download-receiver",
  7442. [](const Request & /*req*/, Response &res) {
  7443. string content(2000, 'R');
  7444. res.set_content(content, "text/plain");
  7445. });
  7446. },
  7447. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7448. DownloadProgress progress_callback) {
  7449. return cli.Get(endpoint, content_receiver, progress_callback);
  7450. },
  7451. "/download-receiver", 2000u);
  7452. }
  7453. TEST(StreamingTest, NoContentLengthStreaming) {
  7454. Server svr;
  7455. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7456. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7457. if (offset < 6) {
  7458. sink.os << (offset < 3 ? "a" : "b");
  7459. } else {
  7460. sink.done();
  7461. }
  7462. return true;
  7463. });
  7464. });
  7465. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7466. auto listen_se = detail::scope_exit([&] {
  7467. svr.stop();
  7468. listen_thread.join();
  7469. ASSERT_FALSE(svr.is_running());
  7470. });
  7471. svr.wait_until_ready();
  7472. Client client(HOST, PORT);
  7473. auto get_thread = std::thread([&client]() {
  7474. std::string s;
  7475. auto res =
  7476. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7477. s += std::string(data, len);
  7478. return true;
  7479. });
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::OK_200, res->status);
  7482. EXPECT_EQ("aaabbb", s);
  7483. });
  7484. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7485. // Give GET time to get a few messages.
  7486. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7487. }
  7488. TEST(MountTest, Unmount) {
  7489. Server svr;
  7490. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7491. auto se = detail::scope_exit([&] {
  7492. svr.stop();
  7493. listen_thread.join();
  7494. ASSERT_FALSE(svr.is_running());
  7495. });
  7496. svr.wait_until_ready();
  7497. Client cli("localhost", PORT);
  7498. svr.set_mount_point("/mount2", "./www2");
  7499. auto res = cli.Get("/");
  7500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7501. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7502. res = cli.Get("/mount2/dir/test.html");
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. svr.set_mount_point("/", "./www");
  7506. res = cli.Get("/dir/");
  7507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. svr.remove_mount_point("/");
  7510. res = cli.Get("/dir/");
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7513. svr.remove_mount_point("/mount2");
  7514. res = cli.Get("/mount2/dir/test.html");
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7517. }
  7518. TEST(MountTest, Redicect) {
  7519. Server svr;
  7520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7521. auto se = detail::scope_exit([&] {
  7522. svr.stop();
  7523. listen_thread.join();
  7524. ASSERT_FALSE(svr.is_running());
  7525. });
  7526. svr.set_mount_point("/", "./www");
  7527. svr.wait_until_ready();
  7528. Client cli("localhost", PORT);
  7529. auto res = cli.Get("/dir/");
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. EXPECT_EQ(StatusCode::OK_200, res->status);
  7532. res = cli.Get("/dir");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7535. res = cli.Get("/file");
  7536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7537. EXPECT_EQ(StatusCode::OK_200, res->status);
  7538. res = cli.Get("/file/");
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7541. cli.set_follow_location(true);
  7542. res = cli.Get("/dir");
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::OK_200, res->status);
  7545. }
  7546. TEST(MountTest, MultibytesPathName) {
  7547. Server svr;
  7548. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7549. auto se = detail::scope_exit([&] {
  7550. svr.stop();
  7551. listen_thread.join();
  7552. ASSERT_FALSE(svr.is_running());
  7553. });
  7554. svr.set_mount_point("/", "./www");
  7555. svr.wait_until_ready();
  7556. Client cli("localhost", PORT);
  7557. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7559. EXPECT_EQ(StatusCode::OK_200, res->status);
  7560. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7561. }
  7562. #ifdef _WIN32
  7563. // Issue #2435: mmap::open() must succeed even when another handle holds
  7564. // the file open for writing (e.g. an active log file).
  7565. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7566. const char *path = "mmap_concurrent_writer_test.txt";
  7567. const char *content = "hello";
  7568. {
  7569. std::ofstream f(path, std::ios::binary);
  7570. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7571. }
  7572. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7573. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7574. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7575. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7576. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7577. detail::mmap m(path);
  7578. ASSERT_TRUE(m.is_open());
  7579. EXPECT_EQ(strlen(content), m.size());
  7580. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7581. }
  7582. #endif
  7583. TEST(KeepAliveTest, ReadTimeout) {
  7584. Server svr;
  7585. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7586. std::this_thread::sleep_for(std::chrono::seconds(2));
  7587. res.set_content("a", "text/plain");
  7588. });
  7589. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7590. res.set_content("b", "text/plain");
  7591. });
  7592. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7593. auto se = detail::scope_exit([&] {
  7594. svr.stop();
  7595. listen_thread.join();
  7596. ASSERT_FALSE(svr.is_running());
  7597. });
  7598. svr.wait_until_ready();
  7599. Client cli("localhost", PORT);
  7600. cli.set_keep_alive(true);
  7601. cli.set_read_timeout(std::chrono::seconds(1));
  7602. auto resa = cli.Get("/a");
  7603. ASSERT_FALSE(resa);
  7604. EXPECT_EQ(Error::Read, resa.error());
  7605. auto resb = cli.Get("/b");
  7606. ASSERT_TRUE(resb);
  7607. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7608. EXPECT_EQ("b", resb->body);
  7609. }
  7610. TEST(KeepAliveTest, MaxCount) {
  7611. size_t keep_alive_max_count = 3;
  7612. Server svr;
  7613. svr.set_keep_alive_max_count(keep_alive_max_count);
  7614. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7615. res.set_content("Hello World!", "text/plain");
  7616. });
  7617. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7618. auto se = detail::scope_exit([&] {
  7619. svr.stop();
  7620. listen_thread.join();
  7621. ASSERT_FALSE(svr.is_running());
  7622. });
  7623. svr.wait_until_ready();
  7624. Client cli(HOST, PORT);
  7625. cli.set_keep_alive(true);
  7626. for (size_t i = 0; i < 5; i++) {
  7627. auto result = cli.Get("/hi");
  7628. ASSERT_TRUE(result);
  7629. EXPECT_EQ(StatusCode::OK_200, result->status);
  7630. if (i == keep_alive_max_count - 1) {
  7631. EXPECT_EQ("close", result->get_header_value("Connection"));
  7632. } else {
  7633. EXPECT_FALSE(result->has_header("Connection"));
  7634. }
  7635. }
  7636. }
  7637. TEST(KeepAliveTest, Issue1041) {
  7638. Server svr;
  7639. svr.set_keep_alive_timeout(3);
  7640. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7641. res.set_content("Hello World!", "text/plain");
  7642. });
  7643. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7644. auto se = detail::scope_exit([&] {
  7645. svr.stop();
  7646. listen_thread.join();
  7647. ASSERT_FALSE(svr.is_running());
  7648. });
  7649. svr.wait_until_ready();
  7650. Client cli(HOST, PORT);
  7651. cli.set_keep_alive(true);
  7652. auto result = cli.Get("/hi");
  7653. ASSERT_TRUE(result);
  7654. EXPECT_EQ(StatusCode::OK_200, result->status);
  7655. std::this_thread::sleep_for(std::chrono::seconds(5));
  7656. result = cli.Get("/hi");
  7657. ASSERT_TRUE(result);
  7658. EXPECT_EQ(StatusCode::OK_200, result->status);
  7659. }
  7660. TEST(KeepAliveTest, Issue1959) {
  7661. Server svr;
  7662. svr.set_keep_alive_timeout(5);
  7663. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7664. res.set_content("a", "text/plain");
  7665. });
  7666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7667. auto se = detail::scope_exit([&] {
  7668. if (!svr.is_running()) return;
  7669. svr.stop();
  7670. listen_thread.join();
  7671. ASSERT_FALSE(svr.is_running());
  7672. });
  7673. svr.wait_until_ready();
  7674. Client cli("localhost", PORT);
  7675. cli.set_keep_alive(true);
  7676. using namespace std::chrono;
  7677. auto start = steady_clock::now();
  7678. cli.Get("/a");
  7679. svr.stop();
  7680. listen_thread.join();
  7681. auto end = steady_clock::now();
  7682. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7683. EXPECT_LT(elapsed, 5000);
  7684. }
  7685. #ifdef CPPHTTPLIB_SSL_ENABLED
  7686. TEST(KeepAliveTest, SSLClientReconnection) {
  7687. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7688. ASSERT_TRUE(svr.is_valid());
  7689. svr.set_keep_alive_timeout(1);
  7690. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7691. res.set_content("Hello World!", "text/plain");
  7692. });
  7693. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7694. auto se = detail::scope_exit([&] {
  7695. svr.stop();
  7696. listen_thread.join();
  7697. ASSERT_FALSE(svr.is_running());
  7698. });
  7699. svr.wait_until_ready();
  7700. SSLClient cli(HOST, PORT);
  7701. cli.enable_server_certificate_verification(false);
  7702. cli.set_keep_alive(true);
  7703. auto result = cli.Get("/hi");
  7704. ASSERT_TRUE(result);
  7705. EXPECT_EQ(StatusCode::OK_200, result->status);
  7706. result = cli.Get("/hi");
  7707. ASSERT_TRUE(result);
  7708. EXPECT_EQ(StatusCode::OK_200, result->status);
  7709. std::this_thread::sleep_for(std::chrono::seconds(2));
  7710. // Recoonect
  7711. result = cli.Get("/hi");
  7712. ASSERT_TRUE(result);
  7713. EXPECT_EQ(StatusCode::OK_200, result->status);
  7714. result = cli.Get("/hi");
  7715. ASSERT_TRUE(result);
  7716. EXPECT_EQ(StatusCode::OK_200, result->status);
  7717. }
  7718. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7720. ASSERT_TRUE(svr.is_valid());
  7721. svr.set_keep_alive_timeout(1);
  7722. std::string content = "reconnect";
  7723. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7724. res.set_content("Hello World!", "text/plain");
  7725. });
  7726. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7727. auto se = detail::scope_exit([&] {
  7728. svr.stop();
  7729. listen_thread.join();
  7730. ASSERT_FALSE(svr.is_running());
  7731. });
  7732. svr.wait_until_ready();
  7733. SSLClient cli(HOST, PORT);
  7734. cli.enable_server_certificate_verification(false);
  7735. cli.set_keep_alive(true);
  7736. auto result = cli.Post(
  7737. "/hi", content.size(),
  7738. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7739. sink.write(content.c_str(), content.size());
  7740. return true;
  7741. },
  7742. "text/plain");
  7743. ASSERT_TRUE(result);
  7744. EXPECT_EQ(200, result->status);
  7745. std::this_thread::sleep_for(std::chrono::seconds(2));
  7746. // Recoonect
  7747. result = cli.Post(
  7748. "/hi", content.size(),
  7749. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7750. sink.write(content.c_str(), content.size());
  7751. return true;
  7752. },
  7753. "text/plain");
  7754. ASSERT_TRUE(result);
  7755. EXPECT_EQ(200, result->status);
  7756. result = cli.Post(
  7757. "/hi", content.size(),
  7758. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7759. sink.write(content.c_str(), content.size());
  7760. return true;
  7761. },
  7762. "text/plain");
  7763. ASSERT_TRUE(result);
  7764. EXPECT_EQ(200, result->status);
  7765. }
  7766. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7767. using namespace httplib::tls;
  7768. {
  7769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7770. ASSERT_TRUE(svr.is_valid());
  7771. svr.Get("/sni", [&](const Request &req, Response &res) {
  7772. std::string expected = req.sni();
  7773. EXPECT_EQ(expected, req.get_param_value("expected"));
  7774. res.set_content("ok", "text/plain");
  7775. });
  7776. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7777. auto se = detail::scope_exit([&] {
  7778. svr.stop();
  7779. listen_thread.join();
  7780. ASSERT_FALSE(svr.is_running());
  7781. });
  7782. svr.wait_until_ready();
  7783. {
  7784. SSLClient cli("localhost", PORT);
  7785. cli.enable_server_certificate_verification(false);
  7786. auto res = cli.Get("/sni?expected=localhost");
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. }
  7789. {
  7790. SSLClient cli("::1", PORT);
  7791. cli.enable_server_certificate_verification(false);
  7792. auto res = cli.Get("/sni?expected=");
  7793. // NOTE: This may fail if the server is listening on IPv4 only
  7794. // (e.g., when localhost resolves to 127.0.0.1 only)
  7795. if (res) {
  7796. EXPECT_EQ(StatusCode::OK_200, res->status);
  7797. } else {
  7798. EXPECT_EQ(Error::Connection, res.error());
  7799. }
  7800. }
  7801. }
  7802. }
  7803. #endif
  7804. TEST(ClientProblemDetectionTest, ContentProvider) {
  7805. Server svr;
  7806. size_t content_length = 1024 * 1024;
  7807. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7808. res.set_content_provider(
  7809. content_length, "text/plain",
  7810. [&](size_t offset, size_t length, DataSink &sink) {
  7811. auto out_len = std::min(length, static_cast<size_t>(1024));
  7812. std::string out(out_len, '@');
  7813. sink.write(out.data(), out_len);
  7814. return offset < 4096;
  7815. },
  7816. [](bool success) { ASSERT_FALSE(success); });
  7817. });
  7818. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7819. res.set_content_provider(
  7820. 0, "text/plain",
  7821. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7822. EXPECT_TRUE(false);
  7823. return true;
  7824. },
  7825. [](bool success) { ASSERT_FALSE(success); });
  7826. });
  7827. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7828. auto se = detail::scope_exit([&] {
  7829. svr.stop();
  7830. listen_thread.join();
  7831. ASSERT_FALSE(svr.is_running());
  7832. });
  7833. svr.wait_until_ready();
  7834. Client cli("localhost", PORT);
  7835. {
  7836. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7837. size_t /*data_length*/) { return false; });
  7838. ASSERT_FALSE(res);
  7839. }
  7840. {
  7841. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7842. size_t /*data_length*/) { return false; });
  7843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7844. }
  7845. }
  7846. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7847. Server svr;
  7848. svr.set_error_handler([](Request const &, Response &res) -> void {
  7849. res.set_chunked_content_provider(
  7850. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7851. sink.os << "hello";
  7852. sink.os << "world";
  7853. sink.done();
  7854. return true;
  7855. });
  7856. });
  7857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7858. auto se = detail::scope_exit([&] {
  7859. svr.stop();
  7860. listen_thread.join();
  7861. ASSERT_FALSE(svr.is_running());
  7862. });
  7863. svr.wait_until_ready();
  7864. Client cli("localhost", PORT);
  7865. auto res = cli.Get("/");
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7868. EXPECT_EQ("helloworld", res->body);
  7869. }
  7870. TEST(LongPollingTest, ClientCloseDetection) {
  7871. Server svr;
  7872. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7873. res.set_chunked_content_provider(
  7874. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7875. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7876. sink.os << "hello";
  7877. auto count = 10;
  7878. while (count > 0 && sink.is_writable()) {
  7879. this_thread::sleep_for(chrono::milliseconds(10));
  7880. count--;
  7881. }
  7882. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7883. return true;
  7884. });
  7885. });
  7886. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7887. auto se = detail::scope_exit([&] {
  7888. svr.stop();
  7889. listen_thread.join();
  7890. ASSERT_FALSE(svr.is_running());
  7891. });
  7892. svr.wait_until_ready();
  7893. Client cli("localhost", PORT);
  7894. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7895. EXPECT_EQ("hello", string(data, data_length));
  7896. return false; // close the socket immediately.
  7897. });
  7898. ASSERT_FALSE(res);
  7899. }
  7900. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7901. Server svr;
  7902. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7903. res.set_chunked_content_provider(
  7904. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7905. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7906. sink.os << "hello";
  7907. EXPECT_TRUE(sink.os.good());
  7908. // Wait for the client to close the connection
  7909. auto count = 10;
  7910. while (count > 0 && sink.is_writable()) {
  7911. this_thread::sleep_for(chrono::milliseconds(10));
  7912. count--;
  7913. }
  7914. // After client disconnect, write repeatedly until the socket
  7915. // write actually fails (small writes may be absorbed by the
  7916. // kernel buffer)
  7917. std::string chunk(1024, 'x');
  7918. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7919. sink.os << chunk;
  7920. }
  7921. EXPECT_TRUE(sink.os.fail());
  7922. return true;
  7923. });
  7924. });
  7925. auto port = svr.bind_to_any_port("localhost");
  7926. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7927. auto se = detail::scope_exit([&] {
  7928. svr.stop();
  7929. listen_thread.join();
  7930. ASSERT_FALSE(svr.is_running());
  7931. });
  7932. svr.wait_until_ready();
  7933. Client cli("localhost", port);
  7934. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7935. EXPECT_EQ("hello", string(data, data_length));
  7936. return false; // close the socket immediately.
  7937. });
  7938. ASSERT_FALSE(res);
  7939. }
  7940. TEST(GetWithParametersTest, GetWithParameters) {
  7941. Server svr;
  7942. svr.Get("/", [&](const Request &req, Response &) {
  7943. EXPECT_EQ("world", req.get_param_value("hello"));
  7944. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7945. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7946. });
  7947. svr.Get("/params", [&](const Request &req, Response &) {
  7948. EXPECT_EQ("world", req.get_param_value("hello"));
  7949. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7950. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7951. });
  7952. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7953. EXPECT_EQ("resource-id", req.matches[1]);
  7954. EXPECT_EQ("foo", req.get_param_value("param1"));
  7955. EXPECT_EQ("bar", req.get_param_value("param2"));
  7956. });
  7957. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7958. EXPECT_EQ("user-id", req.path_params.at("id"));
  7959. EXPECT_EQ("foo", req.get_param_value("param1"));
  7960. EXPECT_EQ("bar", req.get_param_value("param2"));
  7961. });
  7962. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7963. auto se = detail::scope_exit([&] {
  7964. svr.stop();
  7965. listen_thread.join();
  7966. ASSERT_FALSE(svr.is_running());
  7967. });
  7968. svr.wait_until_ready();
  7969. {
  7970. Client cli(HOST, PORT);
  7971. Params params;
  7972. params.emplace("hello", "world");
  7973. params.emplace("hello2", "world2");
  7974. params.emplace("hello3", "world3");
  7975. auto res = cli.Get("/", params, Headers{});
  7976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. }
  7979. {
  7980. Client cli(HOST, PORT);
  7981. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7983. EXPECT_EQ(StatusCode::OK_200, res->status);
  7984. }
  7985. {
  7986. Client cli(HOST, PORT);
  7987. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7989. EXPECT_EQ(StatusCode::OK_200, res->status);
  7990. }
  7991. {
  7992. Client cli(HOST, PORT);
  7993. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. }
  7997. }
  7998. TEST(GetWithParametersTest, GetWithParameters2) {
  7999. Server svr;
  8000. svr.Get("/", [&](const Request &req, Response &res) {
  8001. auto text = req.get_param_value("hello");
  8002. res.set_content(text, "text/plain");
  8003. });
  8004. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8005. auto se = detail::scope_exit([&] {
  8006. svr.stop();
  8007. listen_thread.join();
  8008. ASSERT_FALSE(svr.is_running());
  8009. });
  8010. svr.wait_until_ready();
  8011. Client cli("localhost", PORT);
  8012. Params params;
  8013. params.emplace("hello", "world");
  8014. std::string body;
  8015. auto res = cli.Get("/", params, Headers{},
  8016. [&](const char *data, size_t data_length) {
  8017. body.append(data, data_length);
  8018. return true;
  8019. });
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. EXPECT_EQ("world", body);
  8023. }
  8024. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8025. Server svr;
  8026. svr.Get("/search", [&](const Request &req, Response &res) {
  8027. auto q = req.get_param_value("q");
  8028. res.set_content(q, "text/plain");
  8029. });
  8030. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8031. auto se = detail::scope_exit([&] {
  8032. svr.stop();
  8033. listen_thread.join();
  8034. ASSERT_FALSE(svr.is_running());
  8035. });
  8036. svr.wait_until_ready();
  8037. Client cli("localhost", PORT);
  8038. // Verify that Get(path, params) works without requiring Headers argument
  8039. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::OK_200, res->status);
  8042. EXPECT_EQ("cpp-httplib", res->body);
  8043. }
  8044. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8045. auto host = "httpbingo.org";
  8046. auto path = std::string{"/range/32"};
  8047. #ifdef CPPHTTPLIB_SSL_ENABLED
  8048. SSLClient cli(host);
  8049. #else
  8050. Client cli(host);
  8051. #endif
  8052. cli.set_default_headers({make_range_header({{1, 10}})});
  8053. cli.set_connection_timeout(5);
  8054. {
  8055. auto res = cli.Get(path);
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ("bcdefghijk", res->body);
  8058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8059. }
  8060. {
  8061. auto res = cli.Get(path);
  8062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8063. EXPECT_EQ("bcdefghijk", res->body);
  8064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8065. }
  8066. }
  8067. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8068. Server svr;
  8069. svr.set_default_headers({{"Hello", "World"}});
  8070. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8071. res.set_content("ok", "text/plain");
  8072. });
  8073. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8074. auto se = detail::scope_exit([&] {
  8075. svr.stop();
  8076. listen_thread.join();
  8077. ASSERT_FALSE(svr.is_running());
  8078. });
  8079. svr.wait_until_ready();
  8080. Client cli("localhost", PORT);
  8081. auto res = cli.Get("/");
  8082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. EXPECT_EQ("ok", res->body);
  8085. EXPECT_EQ("World", res->get_header_value("Hello"));
  8086. }
  8087. #ifdef CPPHTTPLIB_SSL_ENABLED
  8088. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8090. ASSERT_TRUE(svr.is_valid());
  8091. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8092. std::this_thread::sleep_for(std::chrono::seconds(2));
  8093. res.set_content("a", "text/plain");
  8094. });
  8095. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8096. res.set_content("b", "text/plain");
  8097. });
  8098. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8099. auto se = detail::scope_exit([&] {
  8100. svr.stop();
  8101. listen_thread.join();
  8102. ASSERT_FALSE(svr.is_running());
  8103. });
  8104. svr.wait_until_ready();
  8105. SSLClient cli("localhost", PORT);
  8106. cli.enable_server_certificate_verification(false);
  8107. cli.set_keep_alive(true);
  8108. cli.set_read_timeout(std::chrono::seconds(1));
  8109. auto resa = cli.Get("/a");
  8110. ASSERT_TRUE(!resa);
  8111. EXPECT_EQ(Error::Read, resa.error());
  8112. auto resb = cli.Get("/b");
  8113. ASSERT_TRUE(resb);
  8114. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8115. EXPECT_EQ("b", resb->body);
  8116. }
  8117. #endif
  8118. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8119. protected:
  8120. ServerTestWithAI_PASSIVE()
  8121. : cli_(HOST, PORT)
  8122. #ifdef CPPHTTPLIB_SSL_ENABLED
  8123. ,
  8124. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8125. #endif
  8126. {
  8127. #ifdef CPPHTTPLIB_SSL_ENABLED
  8128. cli_.enable_server_certificate_verification(false);
  8129. #endif
  8130. }
  8131. virtual void SetUp() {
  8132. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8133. res.set_content("Hello World!", "text/plain");
  8134. });
  8135. t_ = thread(
  8136. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8137. svr_.wait_until_ready();
  8138. }
  8139. virtual void TearDown() {
  8140. svr_.stop();
  8141. t_.join();
  8142. }
  8143. #ifdef CPPHTTPLIB_SSL_ENABLED
  8144. SSLClient cli_;
  8145. SSLServer svr_;
  8146. #else
  8147. Client cli_;
  8148. Server svr_;
  8149. #endif
  8150. thread t_;
  8151. };
  8152. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8153. auto res = cli_.Get("/hi");
  8154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8155. EXPECT_EQ(StatusCode::OK_200, res->status);
  8156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8157. EXPECT_EQ("Hello World!", res->body);
  8158. }
  8159. class ServerUpDownTest : public ::testing::Test {
  8160. protected:
  8161. ServerUpDownTest() : cli_(HOST, PORT) {}
  8162. virtual void SetUp() {
  8163. t_ = thread([&]() {
  8164. svr_.bind_to_any_port(HOST);
  8165. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8166. ASSERT_TRUE(svr_.listen_after_bind());
  8167. });
  8168. svr_.wait_until_ready();
  8169. }
  8170. virtual void TearDown() {
  8171. svr_.stop();
  8172. t_.join();
  8173. }
  8174. Client cli_;
  8175. Server svr_;
  8176. thread t_;
  8177. };
  8178. TEST_F(ServerUpDownTest, QuickStartStop) {
  8179. // Should not crash, especially when run with
  8180. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8181. }
  8182. class PayloadMaxLengthTest : public ::testing::Test {
  8183. protected:
  8184. PayloadMaxLengthTest()
  8185. : cli_(HOST, PORT)
  8186. #ifdef CPPHTTPLIB_SSL_ENABLED
  8187. ,
  8188. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8189. #endif
  8190. {
  8191. #ifdef CPPHTTPLIB_SSL_ENABLED
  8192. cli_.enable_server_certificate_verification(false);
  8193. #endif
  8194. }
  8195. virtual void SetUp() {
  8196. svr_.set_payload_max_length(8);
  8197. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8198. res.set_content("test", "text/plain");
  8199. });
  8200. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8201. svr_.wait_until_ready();
  8202. }
  8203. virtual void TearDown() {
  8204. svr_.stop();
  8205. t_.join();
  8206. }
  8207. #ifdef CPPHTTPLIB_SSL_ENABLED
  8208. SSLClient cli_;
  8209. SSLServer svr_;
  8210. #else
  8211. Client cli_;
  8212. Server svr_;
  8213. #endif
  8214. thread t_;
  8215. };
  8216. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8217. auto res = cli_.Post("/test", "123456789", "text/plain");
  8218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8219. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8220. res = cli_.Post("/test", "12345678", "text/plain");
  8221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8222. EXPECT_EQ(StatusCode::OK_200, res->status);
  8223. }
  8224. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8225. // Test chunked encoding with payload exceeding the 8-byte limit
  8226. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8227. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8229. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8230. }
  8231. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8232. // Test chunked encoding with payload within the 8-byte limit
  8233. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8234. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. }
  8238. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8239. // Test using send_request to send chunked data exceeding payload limit
  8240. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8241. "Host: " +
  8242. std::string(HOST) + ":" + std::to_string(PORT) +
  8243. "\r\n"
  8244. "Transfer-Encoding: chunked\r\n"
  8245. "Connection: close\r\n"
  8246. "\r\n"
  8247. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8248. "0123456789\r\n"
  8249. "0\r\n" // End chunk
  8250. "\r\n";
  8251. std::string response;
  8252. bool result = send_request(1, chunked_request, &response);
  8253. if (!result) {
  8254. // If send_request fails, it might be because the server closed the
  8255. // connection due to payload limit enforcement, which is acceptable
  8256. SUCCEED()
  8257. << "Server rejected oversized chunked request (connection closed)";
  8258. } else {
  8259. // If we got a response, check if it's an error response or connection was
  8260. // closed early Short response length indicates connection was closed due to
  8261. // payload limit
  8262. if (response.length() <= 10) {
  8263. SUCCEED() << "Server closed connection for oversized chunked request";
  8264. } else {
  8265. // Check for error status codes
  8266. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8267. response.find("Payload Too Large") != std::string::npos ||
  8268. response.find("400") != std::string::npos);
  8269. }
  8270. }
  8271. }
  8272. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8273. // Test request without Content-Length header exceeding payload limit
  8274. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8275. "Host: " +
  8276. std::string(HOST) + ":" +
  8277. std::to_string(PORT) +
  8278. "\r\n"
  8279. "Connection: close\r\n"
  8280. "\r\n";
  8281. // Add payload exceeding the 8-byte limit
  8282. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8283. request_without_content_length += large_payload;
  8284. std::string response;
  8285. bool result = send_request(1, request_without_content_length, &response);
  8286. if (!result) {
  8287. // If send_request fails, server likely closed connection due to payload
  8288. // limit
  8289. SUCCEED() << "Server rejected oversized request without Content-Length "
  8290. "(connection closed)";
  8291. } else {
  8292. // Check if server responded with error or closed connection early
  8293. if (response.length() <= 10) {
  8294. SUCCEED() << "Server closed connection for oversized request without "
  8295. "Content-Length";
  8296. } else {
  8297. // Check for error status codes
  8298. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8299. response.find("Payload Too Large") != std::string::npos ||
  8300. response.find("400") != std::string::npos);
  8301. }
  8302. }
  8303. }
  8304. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8305. // Test request without Content-Length header within payload limit
  8306. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8307. "Host: " +
  8308. std::string(HOST) + ":" +
  8309. std::to_string(PORT) +
  8310. "\r\n"
  8311. "Connection: close\r\n"
  8312. "\r\n";
  8313. // Add payload within the 8-byte limit
  8314. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8315. request_without_content_length += small_payload;
  8316. std::string response;
  8317. bool result = send_request(1, request_without_content_length, &response);
  8318. // For requests without Content-Length, the server may have different behavior
  8319. // The key is that it should not reject due to payload limit for small
  8320. // payloads
  8321. if (result) {
  8322. // Check for any HTTP response (success or error, but not connection closed)
  8323. if (response.length() > 10) {
  8324. SUCCEED()
  8325. << "Server processed request without Content-Length within limit";
  8326. } else {
  8327. // Short response might indicate connection closed, which is acceptable
  8328. SUCCEED() << "Server closed connection for request without "
  8329. "Content-Length (acceptable behavior)";
  8330. }
  8331. } else {
  8332. // Connection failure might be due to protocol requirements
  8333. SUCCEED() << "Connection issue with request without Content-Length "
  8334. "(environment-specific)";
  8335. }
  8336. }
  8337. class LargePayloadMaxLengthTest : public ::testing::Test {
  8338. protected:
  8339. LargePayloadMaxLengthTest()
  8340. : cli_(HOST, PORT)
  8341. #ifdef CPPHTTPLIB_SSL_ENABLED
  8342. ,
  8343. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8344. #endif
  8345. {
  8346. #ifdef CPPHTTPLIB_SSL_ENABLED
  8347. cli_.enable_server_certificate_verification(false);
  8348. #endif
  8349. }
  8350. virtual void SetUp() {
  8351. // Set 10MB payload limit
  8352. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8353. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8354. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8355. res.set_content("Large payload test", "text/plain");
  8356. });
  8357. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8358. svr_.wait_until_ready();
  8359. }
  8360. virtual void TearDown() {
  8361. svr_.stop();
  8362. t_.join();
  8363. }
  8364. #ifdef CPPHTTPLIB_SSL_ENABLED
  8365. SSLClient cli_;
  8366. SSLServer svr_;
  8367. #else
  8368. Client cli_;
  8369. Server svr_;
  8370. #endif
  8371. thread t_;
  8372. };
  8373. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8374. // Test chunked encoding with payload within 10MB limit
  8375. std::string medium_payload(5 * 1024 * 1024,
  8376. 'A'); // 5MB payload, within 10MB limit
  8377. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8379. EXPECT_EQ(StatusCode::OK_200, res->status);
  8380. }
  8381. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8382. // Test chunked encoding with payload exceeding 10MB limit
  8383. std::string large_payload(12 * 1024 * 1024,
  8384. 'B'); // 12MB payload, exceeds 10MB limit
  8385. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8386. // Server may either return 413 or close the connection
  8387. if (res) {
  8388. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8389. } else {
  8390. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8391. }
  8392. }
  8393. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8394. // Test request without Content-Length header within 10MB limit
  8395. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8396. "Host: " +
  8397. std::string(HOST) + ":" +
  8398. std::to_string(PORT) +
  8399. "\r\n"
  8400. "Connection: close\r\n"
  8401. "\r\n";
  8402. // Add 1MB payload (within 10MB limit)
  8403. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8404. request_without_content_length += medium_payload;
  8405. std::string response;
  8406. bool result = send_request(5, request_without_content_length, &response);
  8407. if (result) {
  8408. // Should get a proper HTTP response for payloads within limit
  8409. if (response.length() > 10) {
  8410. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8411. "10MB limit";
  8412. } else {
  8413. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8414. "Content-Length)";
  8415. }
  8416. } else {
  8417. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8418. }
  8419. }
  8420. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8421. // Test request without Content-Length header exceeding 10MB limit
  8422. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8423. "Host: " +
  8424. std::string(HOST) + ":" +
  8425. std::to_string(PORT) +
  8426. "\r\n"
  8427. "Connection: close\r\n"
  8428. "\r\n";
  8429. // Add 12MB payload (exceeds 10MB limit)
  8430. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8431. request_without_content_length += large_payload;
  8432. std::string response;
  8433. bool result = send_request(10, request_without_content_length, &response);
  8434. if (!result) {
  8435. // Server should close connection due to payload limit
  8436. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8437. "(connection closed)";
  8438. } else {
  8439. // Check for error response
  8440. if (response.length() <= 10) {
  8441. SUCCEED()
  8442. << "Server closed connection for 12MB request exceeding 10MB limit";
  8443. } else {
  8444. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8445. response.find("Payload Too Large") != std::string::npos ||
  8446. response.find("400") != std::string::npos);
  8447. }
  8448. }
  8449. }
  8450. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8451. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8452. // path.
  8453. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8454. Server svr;
  8455. const size_t LIMIT = 64 * 1024; // 64KB
  8456. svr.set_payload_max_length(LIMIT);
  8457. size_t total = 0;
  8458. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8459. const ContentReader &content_reader) {
  8460. content_reader([&](const char * /*data*/, size_t len) {
  8461. total += len;
  8462. return true;
  8463. });
  8464. res.status = 200;
  8465. res.set_content("stream_ok", "text/plain");
  8466. });
  8467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8468. auto se = detail::scope_exit([&] {
  8469. svr.stop();
  8470. thread.join();
  8471. ASSERT_FALSE(svr.is_running());
  8472. });
  8473. svr.wait_until_ready();
  8474. // Prepare 256KB raw data and gzip-compress it
  8475. std::string raw(256 * 1024, 'A');
  8476. std::string gz;
  8477. {
  8478. z_stream zs{};
  8479. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8480. Z_DEFAULT_STRATEGY);
  8481. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8482. zs.avail_in = static_cast<uInt>(raw.size());
  8483. char outbuf[4096];
  8484. int ret;
  8485. do {
  8486. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8487. zs.avail_out = sizeof(outbuf);
  8488. ret = deflate(&zs, Z_FINISH);
  8489. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8490. } while (ret != Z_STREAM_END);
  8491. deflateEnd(&zs);
  8492. }
  8493. Client cli(HOST, PORT);
  8494. cli.set_connection_timeout(std::chrono::seconds(5));
  8495. Headers headers = {{"Content-Encoding", "gzip"}};
  8496. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8497. "application/octet-stream");
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. // Server must reject oversized decompressed payloads with 413.
  8500. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8501. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8502. EXPECT_LE(total, LIMIT);
  8503. }
  8504. #endif
  8505. // Regression test for DoS vulnerability: a malicious server sending a response
  8506. // without Content-Length header must not cause unbounded memory consumption on
  8507. // the client side. The client should stop reading after a reasonable limit,
  8508. // similar to the server-side set_payload_max_length protection.
  8509. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8510. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8511. #ifndef _WIN32
  8512. signal(SIGPIPE, SIG_IGN);
  8513. #endif
  8514. auto server_thread = std::thread([] {
  8515. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8516. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8517. default_socket_options(srv);
  8518. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8519. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8520. sockaddr_in addr{};
  8521. addr.sin_family = AF_INET;
  8522. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8523. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8524. int opt = 1;
  8525. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8526. #ifdef _WIN32
  8527. reinterpret_cast<const char *>(&opt),
  8528. #else
  8529. &opt,
  8530. #endif
  8531. sizeof(opt));
  8532. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8533. ::listen(srv, 1);
  8534. sockaddr_in cli_addr{};
  8535. socklen_t cli_len = sizeof(cli_addr);
  8536. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8537. if (cli != INVALID_SOCKET) {
  8538. char buf[4096];
  8539. ::recv(cli, buf, sizeof(buf), 0);
  8540. // Malicious response: no Content-Length, no chunked encoding
  8541. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8542. "Connection: close\r\n"
  8543. "\r\n";
  8544. ::send(cli,
  8545. #ifdef _WIN32
  8546. static_cast<const char *>(response_header.c_str()),
  8547. static_cast<int>(response_header.size()),
  8548. #else
  8549. response_header.c_str(), response_header.size(),
  8550. #endif
  8551. 0);
  8552. // Send 10MB of data
  8553. std::string chunk(64 * 1024, 'A');
  8554. size_t total_sent = 0;
  8555. while (total_sent < MALICIOUS_DATA_SIZE) {
  8556. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8557. auto sent = ::send(cli,
  8558. #ifdef _WIN32
  8559. static_cast<const char *>(chunk.c_str()),
  8560. static_cast<int>(to_send),
  8561. #else
  8562. chunk.c_str(), to_send,
  8563. #endif
  8564. 0);
  8565. if (sent <= 0) break;
  8566. total_sent += static_cast<size_t>(sent);
  8567. }
  8568. detail::close_socket(cli);
  8569. }
  8570. detail::close_socket(srv);
  8571. });
  8572. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8573. size_t total_read = 0;
  8574. {
  8575. Client cli("127.0.0.1", PORT + 2);
  8576. cli.set_read_timeout(5, 0);
  8577. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8578. auto stream = cli.open_stream("GET", "/malicious");
  8579. ASSERT_TRUE(stream.is_valid());
  8580. char buffer[64 * 1024];
  8581. ssize_t n;
  8582. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8583. total_read += static_cast<size_t>(n);
  8584. }
  8585. } // StreamHandle and Client destroyed here, closing the socket
  8586. server_thread.join();
  8587. // With set_payload_max_length, the client must stop reading before consuming
  8588. // all 10MB. The read loop should be cut off at or near the configured limit.
  8589. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8590. << "Client read " << total_read << " bytes, exceeding the configured "
  8591. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8592. }
  8593. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8594. // the entire response body without truncation.
  8595. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8596. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8597. #ifndef _WIN32
  8598. signal(SIGPIPE, SIG_IGN);
  8599. #endif
  8600. auto server_thread = std::thread([] {
  8601. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8602. default_socket_options(srv);
  8603. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8604. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8605. sockaddr_in addr{};
  8606. addr.sin_family = AF_INET;
  8607. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8608. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8609. int opt = 1;
  8610. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8611. #ifdef _WIN32
  8612. reinterpret_cast<const char *>(&opt),
  8613. #else
  8614. &opt,
  8615. #endif
  8616. sizeof(opt));
  8617. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8618. ::listen(srv, 1);
  8619. sockaddr_in cli_addr{};
  8620. socklen_t cli_len = sizeof(cli_addr);
  8621. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8622. if (cli != INVALID_SOCKET) {
  8623. char buf[4096];
  8624. ::recv(cli, buf, sizeof(buf), 0);
  8625. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8626. "Connection: close\r\n"
  8627. "\r\n";
  8628. ::send(cli,
  8629. #ifdef _WIN32
  8630. static_cast<const char *>(response_header.c_str()),
  8631. static_cast<int>(response_header.size()),
  8632. #else
  8633. response_header.c_str(), response_header.size(),
  8634. #endif
  8635. 0);
  8636. std::string chunk(64 * 1024, 'A');
  8637. size_t total_sent = 0;
  8638. while (total_sent < DATA_SIZE) {
  8639. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8640. auto sent = ::send(cli,
  8641. #ifdef _WIN32
  8642. static_cast<const char *>(chunk.c_str()),
  8643. static_cast<int>(to_send),
  8644. #else
  8645. chunk.c_str(), to_send,
  8646. #endif
  8647. 0);
  8648. if (sent <= 0) break;
  8649. total_sent += static_cast<size_t>(sent);
  8650. }
  8651. #ifdef _WIN32
  8652. ::shutdown(cli, SD_SEND);
  8653. #else
  8654. ::shutdown(cli, SHUT_WR);
  8655. #endif
  8656. // Drain until the client closes its end, ensuring all data is delivered
  8657. char drain[1024];
  8658. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8659. detail::close_socket(cli);
  8660. }
  8661. detail::close_socket(srv);
  8662. });
  8663. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8664. size_t total_read = 0;
  8665. {
  8666. Client cli("127.0.0.1", PORT + 2);
  8667. cli.set_read_timeout(5, 0);
  8668. cli.set_payload_max_length(0); // 0 means no limit
  8669. auto stream = cli.open_stream("GET", "/data");
  8670. ASSERT_TRUE(stream.is_valid());
  8671. char buffer[64 * 1024];
  8672. ssize_t n;
  8673. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8674. total_read += static_cast<size_t>(n);
  8675. }
  8676. }
  8677. server_thread.join();
  8678. EXPECT_EQ(total_read, DATA_SIZE)
  8679. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8680. << " bytes without truncation, but only read " << total_read << " bytes.";
  8681. }
  8682. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8683. // enormous Content-Length must not cause the client to pre-allocate a huge
  8684. // response body buffer. The reservation is capped at payload_max_length_, and
  8685. // the read itself fails when the body exceeds the limit.
  8686. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8687. #ifndef _WIN32
  8688. signal(SIGPIPE, SIG_IGN);
  8689. #endif
  8690. auto server_thread = std::thread([] {
  8691. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8692. default_socket_options(srv);
  8693. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8694. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8695. sockaddr_in addr{};
  8696. addr.sin_family = AF_INET;
  8697. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8698. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8699. int opt = 1;
  8700. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8701. #ifdef _WIN32
  8702. reinterpret_cast<const char *>(&opt),
  8703. #else
  8704. &opt,
  8705. #endif
  8706. sizeof(opt));
  8707. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8708. ::listen(srv, 1);
  8709. sockaddr_in cli_addr{};
  8710. socklen_t cli_len = sizeof(cli_addr);
  8711. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8712. if (cli != INVALID_SOCKET) {
  8713. char buf[4096];
  8714. ::recv(cli, buf, sizeof(buf), 0);
  8715. // Malicious response: claim a 20GB body but send only a tiny payload.
  8716. std::string response = "HTTP/1.1 200 OK\r\n"
  8717. "Content-Length: 20000000000\r\n"
  8718. "\r\n"
  8719. "abc";
  8720. ::send(cli,
  8721. #ifdef _WIN32
  8722. static_cast<const char *>(response.c_str()),
  8723. static_cast<int>(response.size()),
  8724. #else
  8725. response.c_str(), response.size(),
  8726. #endif
  8727. 0);
  8728. detail::close_socket(cli);
  8729. }
  8730. detail::close_socket(srv);
  8731. });
  8732. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8733. {
  8734. Client cli("127.0.0.1", PORT + 2);
  8735. cli.set_read_timeout(5, 0);
  8736. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8737. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8738. // (server claims more bytes than payload_max_length permits), but it must
  8739. // not exhaust memory before getting there.
  8740. auto res = cli.Get("/malicious");
  8741. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8742. }
  8743. server_thread.join();
  8744. }
  8745. // Verify that content_receiver bypasses the default payload_max_length,
  8746. // allowing streaming downloads larger than 100MB without requiring an explicit
  8747. // set_payload_max_length call.
  8748. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8749. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8750. #ifndef _WIN32
  8751. signal(SIGPIPE, SIG_IGN);
  8752. #endif
  8753. auto server_thread = std::thread([] {
  8754. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8755. default_socket_options(srv);
  8756. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8757. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8758. sockaddr_in addr{};
  8759. addr.sin_family = AF_INET;
  8760. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8761. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8762. int opt = 1;
  8763. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8764. #ifdef _WIN32
  8765. reinterpret_cast<const char *>(&opt),
  8766. #else
  8767. &opt,
  8768. #endif
  8769. sizeof(opt));
  8770. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8771. ::listen(srv, 1);
  8772. sockaddr_in cli_addr{};
  8773. socklen_t cli_len = sizeof(cli_addr);
  8774. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8775. if (cli != INVALID_SOCKET) {
  8776. char buf[4096];
  8777. ::recv(cli, buf, sizeof(buf), 0);
  8778. // Response with Content-Length larger than default 100MB limit
  8779. auto content_length = std::to_string(DATA_SIZE);
  8780. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8781. "Content-Length: " +
  8782. content_length +
  8783. "\r\n"
  8784. "Connection: close\r\n"
  8785. "\r\n";
  8786. ::send(cli,
  8787. #ifdef _WIN32
  8788. static_cast<const char *>(response_header.c_str()),
  8789. static_cast<int>(response_header.size()),
  8790. #else
  8791. response_header.c_str(), response_header.size(),
  8792. #endif
  8793. 0);
  8794. std::string chunk(64 * 1024, 'A');
  8795. size_t total_sent = 0;
  8796. while (total_sent < DATA_SIZE) {
  8797. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8798. auto sent = ::send(cli,
  8799. #ifdef _WIN32
  8800. static_cast<const char *>(chunk.c_str()),
  8801. static_cast<int>(to_send),
  8802. #else
  8803. chunk.c_str(), to_send,
  8804. #endif
  8805. 0);
  8806. if (sent <= 0) break;
  8807. total_sent += static_cast<size_t>(sent);
  8808. }
  8809. detail::close_socket(cli);
  8810. }
  8811. detail::close_socket(srv);
  8812. });
  8813. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8814. size_t total_received = 0;
  8815. {
  8816. Client cli("127.0.0.1", PORT + 2);
  8817. cli.set_read_timeout(10, 0);
  8818. // Do NOT call set_payload_max_length — use the default 100MB limit
  8819. auto res =
  8820. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8821. total_received += data_length;
  8822. return true;
  8823. });
  8824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8825. EXPECT_EQ(StatusCode::OK_200, res->status);
  8826. }
  8827. server_thread.join();
  8828. EXPECT_EQ(total_received, DATA_SIZE)
  8829. << "With content_receiver, the client should read all " << DATA_SIZE
  8830. << " bytes despite the default 100MB payload_max_length, but only read "
  8831. << total_received << " bytes.";
  8832. }
  8833. // Verify that an explicit set_payload_max_length smaller than the response is
  8834. // enforced even when a content_receiver is used.
  8835. TEST(ClientVulnerabilityTest,
  8836. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8837. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8838. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8839. #ifndef _WIN32
  8840. signal(SIGPIPE, SIG_IGN);
  8841. #endif
  8842. auto server_thread = std::thread([] {
  8843. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8844. default_socket_options(srv);
  8845. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8846. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8847. sockaddr_in addr{};
  8848. addr.sin_family = AF_INET;
  8849. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8850. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8851. int opt = 1;
  8852. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8853. #ifdef _WIN32
  8854. reinterpret_cast<const char *>(&opt),
  8855. #else
  8856. &opt,
  8857. #endif
  8858. sizeof(opt));
  8859. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8860. ::listen(srv, 1);
  8861. sockaddr_in cli_addr{};
  8862. socklen_t cli_len = sizeof(cli_addr);
  8863. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8864. if (cli != INVALID_SOCKET) {
  8865. char buf[4096];
  8866. ::recv(cli, buf, sizeof(buf), 0);
  8867. auto content_length = std::to_string(DATA_SIZE);
  8868. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8869. "Content-Length: " +
  8870. content_length +
  8871. "\r\n"
  8872. "Connection: close\r\n"
  8873. "\r\n";
  8874. ::send(cli,
  8875. #ifdef _WIN32
  8876. static_cast<const char *>(response_header.c_str()),
  8877. static_cast<int>(response_header.size()),
  8878. #else
  8879. response_header.c_str(), response_header.size(),
  8880. #endif
  8881. 0);
  8882. std::string chunk(64 * 1024, 'A');
  8883. size_t total_sent = 0;
  8884. while (total_sent < DATA_SIZE) {
  8885. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8886. auto sent = ::send(cli,
  8887. #ifdef _WIN32
  8888. static_cast<const char *>(chunk.c_str()),
  8889. static_cast<int>(to_send),
  8890. #else
  8891. chunk.c_str(), to_send,
  8892. #endif
  8893. 0);
  8894. if (sent <= 0) break;
  8895. total_sent += static_cast<size_t>(sent);
  8896. }
  8897. detail::close_socket(cli);
  8898. }
  8899. detail::close_socket(srv);
  8900. });
  8901. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8902. size_t total_received = 0;
  8903. {
  8904. Client cli("127.0.0.1", PORT + 2);
  8905. cli.set_read_timeout(10, 0);
  8906. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8907. auto res =
  8908. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8909. total_received += data_length;
  8910. return true;
  8911. });
  8912. // Should fail because 200MB exceeds the explicit 150MB limit
  8913. EXPECT_FALSE(res);
  8914. }
  8915. server_thread.join();
  8916. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8917. << "Client with content_receiver should respect the explicit "
  8918. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8919. << total_received << " bytes.";
  8920. }
  8921. // Verify that an explicit set_payload_max_length larger than the response
  8922. // allows the content_receiver to read all data successfully.
  8923. TEST(ClientVulnerabilityTest,
  8924. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8925. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8926. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8927. #ifndef _WIN32
  8928. signal(SIGPIPE, SIG_IGN);
  8929. #endif
  8930. auto server_thread = std::thread([] {
  8931. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8932. default_socket_options(srv);
  8933. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8934. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8935. sockaddr_in addr{};
  8936. addr.sin_family = AF_INET;
  8937. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8938. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8939. int opt = 1;
  8940. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8941. #ifdef _WIN32
  8942. reinterpret_cast<const char *>(&opt),
  8943. #else
  8944. &opt,
  8945. #endif
  8946. sizeof(opt));
  8947. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8948. ::listen(srv, 1);
  8949. sockaddr_in cli_addr{};
  8950. socklen_t cli_len = sizeof(cli_addr);
  8951. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8952. if (cli != INVALID_SOCKET) {
  8953. char buf[4096];
  8954. ::recv(cli, buf, sizeof(buf), 0);
  8955. auto content_length = std::to_string(DATA_SIZE);
  8956. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8957. "Content-Length: " +
  8958. content_length +
  8959. "\r\n"
  8960. "Connection: close\r\n"
  8961. "\r\n";
  8962. ::send(cli,
  8963. #ifdef _WIN32
  8964. static_cast<const char *>(response_header.c_str()),
  8965. static_cast<int>(response_header.size()),
  8966. #else
  8967. response_header.c_str(), response_header.size(),
  8968. #endif
  8969. 0);
  8970. std::string chunk(64 * 1024, 'A');
  8971. size_t total_sent = 0;
  8972. while (total_sent < DATA_SIZE) {
  8973. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8974. auto sent = ::send(cli,
  8975. #ifdef _WIN32
  8976. static_cast<const char *>(chunk.c_str()),
  8977. static_cast<int>(to_send),
  8978. #else
  8979. chunk.c_str(), to_send,
  8980. #endif
  8981. 0);
  8982. if (sent <= 0) break;
  8983. total_sent += static_cast<size_t>(sent);
  8984. }
  8985. #ifdef _WIN32
  8986. ::shutdown(cli, SD_SEND);
  8987. #else
  8988. ::shutdown(cli, SHUT_WR);
  8989. #endif
  8990. char drain[1024];
  8991. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8992. detail::close_socket(cli);
  8993. }
  8994. detail::close_socket(srv);
  8995. });
  8996. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8997. size_t total_received = 0;
  8998. {
  8999. Client cli("127.0.0.1", PORT + 2);
  9000. cli.set_read_timeout(10, 0);
  9001. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9002. auto res =
  9003. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9004. total_received += data_length;
  9005. return true;
  9006. });
  9007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::OK_200, res->status);
  9009. }
  9010. server_thread.join();
  9011. EXPECT_EQ(total_received, DATA_SIZE)
  9012. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9013. << " bytes (larger than " << DATA_SIZE
  9014. << " bytes response), content_receiver should read all data, but only "
  9015. "read "
  9016. << total_received << " bytes.";
  9017. }
  9018. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9019. // Regression test for "zip bomb" attack on the client side: a malicious server
  9020. // sends a small gzip-compressed response that decompresses to a huge payload.
  9021. // The client must enforce payload_max_length on the decompressed size.
  9022. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9023. constexpr size_t DECOMPRESSED_SIZE =
  9024. 10 * 1024 * 1024; // 10MB after decompression
  9025. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9026. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9027. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9028. std::string compressed;
  9029. {
  9030. httplib::detail::gzip_compressor compressor;
  9031. bool ok =
  9032. compressor.compress(uncompressed.data(), uncompressed.size(),
  9033. /*last=*/true, [&](const char *buf, size_t len) {
  9034. compressed.append(buf, len);
  9035. return true;
  9036. });
  9037. ASSERT_TRUE(ok);
  9038. }
  9039. // Sanity: compressed data should be much smaller than the decompressed size
  9040. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9041. #ifndef _WIN32
  9042. signal(SIGPIPE, SIG_IGN);
  9043. #endif
  9044. // Set up the listening socket in the main thread so the server is guaranteed
  9045. // to be ready before the client connects (eliminates race condition).
  9046. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9047. default_socket_options(srv);
  9048. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9049. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9050. sockaddr_in addr{};
  9051. addr.sin_family = AF_INET;
  9052. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9053. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9054. int opt = 1;
  9055. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9056. #ifdef _WIN32
  9057. reinterpret_cast<const char *>(&opt),
  9058. #else
  9059. &opt,
  9060. #endif
  9061. sizeof(opt));
  9062. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9063. ASSERT_EQ(0, ::listen(srv, 1));
  9064. auto server_thread = std::thread([&compressed, srv] {
  9065. sockaddr_in cli_addr{};
  9066. socklen_t cli_len = sizeof(cli_addr);
  9067. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9068. if (cli != INVALID_SOCKET) {
  9069. // Read the full HTTP request (until \r\n\r\n)
  9070. char buf[4096];
  9071. size_t total = 0;
  9072. while (total < sizeof(buf)) {
  9073. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9074. if (n <= 0) break;
  9075. total += static_cast<size_t>(n);
  9076. // Check for end of headers
  9077. if (total >= 4) {
  9078. std::string req(buf, total);
  9079. if (req.find("\r\n\r\n") != std::string::npos) break;
  9080. }
  9081. }
  9082. // Malicious response: gzip-compressed body, no Content-Length
  9083. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9084. "Content-Encoding: gzip\r\n"
  9085. "Connection: close\r\n"
  9086. "\r\n";
  9087. ::send(cli,
  9088. #ifdef _WIN32
  9089. static_cast<const char *>(response_header.c_str()),
  9090. static_cast<int>(response_header.size()),
  9091. #else
  9092. response_header.c_str(), response_header.size(),
  9093. #endif
  9094. 0);
  9095. // Send the compressed payload (small on the wire, huge when decompressed)
  9096. size_t total_sent = 0;
  9097. while (total_sent < compressed.size()) {
  9098. auto to_send = std::min(compressed.size() - total_sent,
  9099. static_cast<size_t>(64 * 1024));
  9100. auto sent =
  9101. ::send(cli,
  9102. #ifdef _WIN32
  9103. static_cast<const char *>(compressed.c_str() + total_sent),
  9104. static_cast<int>(to_send),
  9105. #else
  9106. compressed.c_str() + total_sent, to_send,
  9107. #endif
  9108. 0);
  9109. if (sent <= 0) break;
  9110. total_sent += static_cast<size_t>(sent);
  9111. }
  9112. detail::close_socket(cli);
  9113. }
  9114. });
  9115. auto se = detail::scope_exit([&] {
  9116. detail::close_socket(srv);
  9117. server_thread.join();
  9118. });
  9119. size_t total_decompressed = 0;
  9120. {
  9121. Client cli("127.0.0.1", PORT + 3);
  9122. cli.set_read_timeout(5, 0);
  9123. cli.set_decompress(true);
  9124. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9125. auto stream = cli.open_stream("GET", "/zipbomb");
  9126. ASSERT_TRUE(stream.is_valid());
  9127. char buffer[64 * 1024];
  9128. ssize_t n;
  9129. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9130. total_decompressed += static_cast<size_t>(n);
  9131. }
  9132. }
  9133. // The decompressed size must be capped by payload_max_length. Without
  9134. // protection, the client would decompress the full 10MB from a tiny
  9135. // compressed payload, enabling a zip bomb DoS attack.
  9136. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9137. << "Client decompressed " << total_decompressed
  9138. << " bytes from a gzip response. The decompressed size should be "
  9139. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9140. }
  9141. #endif
  9142. TEST(HostAndPortPropertiesTest, NoSSL) {
  9143. httplib::Client cli("www.google.com", 1234);
  9144. ASSERT_EQ("www.google.com", cli.host());
  9145. ASSERT_EQ(1234, cli.port());
  9146. }
  9147. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9148. httplib::Client cli("www.google.com:1234");
  9149. ASSERT_EQ("www.google.com", cli.host());
  9150. ASSERT_EQ(1234, cli.port());
  9151. }
  9152. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9153. // Port number that overflows int — should not crash, client becomes invalid
  9154. httplib::Client cli("http://www.google.com:99999999999999999999");
  9155. ASSERT_FALSE(cli.is_valid());
  9156. }
  9157. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9158. // Port 99999 exceeds valid range (1-65535) — should not crash
  9159. httplib::Client cli("http://www.google.com:99999");
  9160. ASSERT_FALSE(cli.is_valid());
  9161. }
  9162. #ifdef CPPHTTPLIB_SSL_ENABLED
  9163. TEST(HostAndPortPropertiesTest, SSL) {
  9164. httplib::SSLClient cli("www.google.com");
  9165. ASSERT_EQ("www.google.com", cli.host());
  9166. ASSERT_EQ(443, cli.port());
  9167. }
  9168. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9169. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9170. std::string cert;
  9171. read_file(CA_CERT_FILE, cert);
  9172. httplib::SSLClient httplib_client("www.google.com");
  9173. // Load CA store first time
  9174. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9175. // Load CA store second time (update)
  9176. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9177. // Verify client is still valid and can make connections
  9178. httplib_client.enable_server_certificate_verification(true);
  9179. auto res = httplib_client.Get("/");
  9180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9181. // Google may return 200 or 301 depending on various factors
  9182. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9183. res->status == StatusCode::MovedPermanently_301);
  9184. }
  9185. TEST(SSLClientTest, ServerNameIndication_Online) {
  9186. auto host = "httpbingo.org";
  9187. auto path = std::string{"/get"};
  9188. SSLClient cli(host, 443);
  9189. auto res = cli.Get(path);
  9190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9191. ASSERT_EQ(StatusCode::OK_200, res->status);
  9192. }
  9193. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9194. // Use a site that will cause SSL verification failure due to self-signed cert
  9195. SSLClient cli("self-signed.badssl.com", 443);
  9196. cli.enable_server_certificate_verification(true);
  9197. auto res = cli.Get("/");
  9198. ASSERT_TRUE(!res);
  9199. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9200. // Verify backend error is captured for SSLServerVerification
  9201. // This occurs when certificate verification fails
  9202. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9203. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9204. EXPECT_NE(0UL, res.ssl_backend_error());
  9205. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9206. // For OpenSSL, ssl_error is 0 for verification errors
  9207. EXPECT_EQ(0, res.ssl_error());
  9208. #if !defined(_WIN32) || \
  9209. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9210. // On non-Windows or when Windows Schannel is disabled, the error comes
  9211. // from OpenSSL's verification
  9212. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9213. res.ssl_backend_error());
  9214. #endif
  9215. #endif
  9216. }
  9217. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9218. // Use a site where hostname doesn't match the certificate
  9219. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9220. SSLClient cli("wrong.host.badssl.com", 443);
  9221. cli.enable_server_certificate_verification(true);
  9222. cli.enable_server_hostname_verification(true);
  9223. auto res = cli.Get("/");
  9224. ASSERT_TRUE(!res);
  9225. // The error type depends on when hostname verification occurs:
  9226. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9227. // - Mbed TLS: SSLServerVerification (during handshake)
  9228. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9229. res.error() == Error::SSLServerVerification);
  9230. // Verify backend error is captured for hostname verification failure
  9231. EXPECT_NE(0UL, res.ssl_backend_error());
  9232. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9233. // For OpenSSL, ssl_error is 0 for verification errors
  9234. EXPECT_EQ(0, res.ssl_error());
  9235. #if !defined(_WIN32) || \
  9236. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9237. // On non-Windows or when Windows Schannel is disabled, the error comes
  9238. // from OpenSSL's hostname verification
  9239. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9240. res.ssl_backend_error());
  9241. #endif
  9242. #endif
  9243. }
  9244. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9245. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9246. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9247. SSLClient cli("www.google.com", 443);
  9248. cli.enable_server_certificate_verification(true);
  9249. auto res = cli.Get("/");
  9250. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9251. }
  9252. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9253. SSLClient cli("www.google.com", 443);
  9254. cli.enable_server_certificate_verification(true);
  9255. cli.enable_windows_certificate_verification(false);
  9256. auto res = cli.Get("/");
  9257. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9258. }
  9259. #endif
  9260. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9261. Client cli("https://google.com");
  9262. auto res = cli.Get("/");
  9263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9264. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9265. }
  9266. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9267. SSLClient cli("google.com");
  9268. cli.set_ca_cert_path(CA_CERT_FILE);
  9269. auto res = cli.Get("/");
  9270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9271. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9272. }
  9273. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9274. SSLClient cli("google.com");
  9275. cli.enable_server_certificate_verification(true);
  9276. cli.set_ca_cert_path("hello");
  9277. auto res = cli.Get("/");
  9278. ASSERT_TRUE(!res);
  9279. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9280. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9281. // should be set
  9282. EXPECT_EQ(0, res.ssl_error());
  9283. // Verify backend error is captured for SSLLoadingCerts
  9284. // This error occurs when loading CA certificates fails
  9285. EXPECT_NE(0UL, res.ssl_backend_error());
  9286. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9287. // OpenSSL specific error codes:
  9288. // > openssl errstr 0x80000002
  9289. // error:80000002:system library::No such file or directory
  9290. // > openssl errstr 0xA000126
  9291. // error:0A000126:SSL routines::unexpected eof while reading
  9292. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9293. res.ssl_backend_error() == 0xA000126);
  9294. #endif
  9295. }
  9296. TEST(SSLClientTest, ServerCertificateVerification4) {
  9297. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9298. ASSERT_TRUE(svr.is_valid());
  9299. svr.Get("/test", [&](const Request &, Response &res) {
  9300. res.set_content("test", "text/plain");
  9301. svr.stop();
  9302. ASSERT_TRUE(true);
  9303. });
  9304. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9305. auto se = detail::scope_exit([&] {
  9306. t.join();
  9307. ASSERT_FALSE(svr.is_running());
  9308. });
  9309. svr.wait_until_ready();
  9310. SSLClient cli("127.0.0.1", PORT);
  9311. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9312. cli.enable_server_certificate_verification(true);
  9313. cli.set_connection_timeout(30);
  9314. auto res = cli.Get("/test");
  9315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9316. ASSERT_EQ(StatusCode::OK_200, res->status);
  9317. }
  9318. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9319. std::string cert;
  9320. read_file(CA_CERT_FILE, cert);
  9321. SSLClient cli("google.com");
  9322. cli.load_ca_cert_store(cert.data(), cert.size());
  9323. const auto res = cli.Get("/");
  9324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9325. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9326. }
  9327. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9328. // clang-format off
  9329. static constexpr char cert[] =
  9330. "GlobalSign Root CA\n"
  9331. "==================\n"
  9332. "-----BEGIN CERTIFICATE-----\n"
  9333. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9334. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9335. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9336. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9337. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9338. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9339. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9340. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9341. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9342. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9343. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9344. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9345. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9346. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9347. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9348. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9349. "-----END CERTIFICATE-----\n";
  9350. // clang-format on
  9351. SSLClient cli("google.com");
  9352. cli.load_ca_cert_store(cert, sizeof(cert));
  9353. const auto res = cli.Get("/");
  9354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9355. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9356. }
  9357. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9358. SSLClient cli("www.youtube.com");
  9359. cli.set_ca_cert_path(CA_CERT_FILE);
  9360. cli.enable_server_certificate_verification(true);
  9361. cli.set_follow_location(true);
  9362. auto res = cli.Get("/");
  9363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9364. ASSERT_EQ(StatusCode::OK_200, res->status);
  9365. }
  9366. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9367. SSLClient cli("wWw.YouTube.Com");
  9368. cli.set_ca_cert_path(CA_CERT_FILE);
  9369. cli.enable_server_certificate_verification(true);
  9370. cli.enable_server_hostname_verification(true);
  9371. cli.set_follow_location(true);
  9372. auto res = cli.Get("/");
  9373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9374. ASSERT_EQ(StatusCode::OK_200, res->status);
  9375. }
  9376. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9377. SSLClient cli("gOoGlE.COm");
  9378. cli.enable_server_certificate_verification(true);
  9379. cli.enable_server_hostname_verification(true);
  9380. cli.set_follow_location(true);
  9381. auto res = cli.Get("/");
  9382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9383. ASSERT_EQ(StatusCode::OK_200, res->status);
  9384. }
  9385. TEST(SSLClientTest, Issue2004_Online) {
  9386. Client client("https://google.com");
  9387. client.set_follow_location(true);
  9388. auto res = client.Get("/");
  9389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9390. ASSERT_EQ(StatusCode::OK_200, res->status);
  9391. auto body = res->body;
  9392. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9393. }
  9394. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9395. // Create SSLClient with invalid cert/key to make is_valid() return false
  9396. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9397. "nonexistent_key.pem");
  9398. // is_valid() should be false due to cert loading failure
  9399. ASSERT_FALSE(cli.is_valid());
  9400. auto res = cli.Get("/");
  9401. ASSERT_FALSE(res);
  9402. EXPECT_EQ(Error::SSLConnection, res.error());
  9403. }
  9404. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9405. // Test for Issue #2251: SSL error not properly reported when client cert
  9406. // and key paths are swapped or mismatched
  9407. // This simulates the scenario where user accidentally swaps the cert and key
  9408. // files
  9409. // Using client cert file as private key and vice versa (completely wrong)
  9410. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9411. // Should fail validation due to cert/key mismatch
  9412. ASSERT_FALSE(cli.is_valid());
  9413. // Attempt to make a request should fail with proper error
  9414. auto res = cli.Get("/");
  9415. ASSERT_FALSE(res);
  9416. EXPECT_EQ(Error::SSLConnection, res.error());
  9417. // SSL error should be recorded in the Result object (this is the key fix for
  9418. // Issue #2251)
  9419. auto backend_error = res.ssl_backend_error();
  9420. EXPECT_NE(0u, backend_error);
  9421. }
  9422. // Tests cert/key mismatch detection at the TLS context level
  9423. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9424. // Test that using mismatched cert/key causes connection failure.
  9425. // We verify this at the SSLClient level rather than through internal
  9426. // TLS API functions.
  9427. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9428. cli.enable_server_certificate_verification(false);
  9429. cli.set_connection_timeout(2);
  9430. // The mismatch should cause a connection or handshake error
  9431. auto res = cli.Get("/test");
  9432. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9433. // Either way, the request should fail
  9434. EXPECT_FALSE(res);
  9435. }
  9436. #endif
  9437. #if 0
  9438. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9439. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9440. ASSERT_TRUE(cli != nullptr);
  9441. cli->set_address_family(AF_INET6);
  9442. cli->set_interface("en0");
  9443. auto res = cli->Get("/get");
  9444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9445. ASSERT_EQ(StatusCode::OK_200, res->status);
  9446. }
  9447. #endif
  9448. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9449. #ifdef CPPHTTPLIB_SSL_ENABLED
  9450. void ClientCertPresent(
  9451. const std::string &client_cert_file,
  9452. const std::string &client_private_key_file,
  9453. const std::string &client_encrypted_private_key_pass = std::string()) {
  9454. using namespace httplib::tls;
  9455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9456. CLIENT_CA_CERT_DIR);
  9457. ASSERT_TRUE(svr.is_valid());
  9458. svr.Get("/test", [&](const Request &req, Response &res) {
  9459. res.set_content("test", "text/plain");
  9460. auto cert = req.peer_cert();
  9461. ASSERT_TRUE(static_cast<bool>(cert));
  9462. std::string common_name = cert.subject_cn();
  9463. EXPECT_EQ("Common Name", common_name);
  9464. });
  9465. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9466. auto se = detail::scope_exit([&] {
  9467. svr.stop();
  9468. t.join();
  9469. ASSERT_FALSE(svr.is_running());
  9470. });
  9471. svr.wait_until_ready();
  9472. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9473. client_encrypted_private_key_pass);
  9474. cli.enable_server_certificate_verification(false);
  9475. cli.set_connection_timeout(30);
  9476. auto res = cli.Get("/test");
  9477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9478. ASSERT_EQ(StatusCode::OK_200, res->status);
  9479. }
  9480. TEST(SSLClientServerTest, ClientCertPresent) {
  9481. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9482. }
  9483. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9484. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9485. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9486. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9487. }
  9488. // PEM memory-based constructor tests (works with all TLS backends)
  9489. void PemMemoryClientCertPresent(
  9490. const std::string &client_cert_file,
  9491. const std::string &client_private_key_file,
  9492. const std::string &client_encrypted_private_key_pass = std::string()) {
  9493. // Read PEM files into memory
  9494. std::string server_cert_pem, server_key_pem;
  9495. std::string client_ca_pem;
  9496. std::string client_cert_pem, client_key_pem;
  9497. read_file(SERVER_CERT_FILE, server_cert_pem);
  9498. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9499. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9500. read_file(client_cert_file, client_cert_pem);
  9501. read_file(client_private_key_file, client_key_pem);
  9502. // Create server with PEM memory
  9503. SSLServer::PemMemory server_pem = {
  9504. server_cert_pem.c_str(),
  9505. server_cert_pem.size(),
  9506. server_key_pem.c_str(),
  9507. server_key_pem.size(),
  9508. client_ca_pem.c_str(),
  9509. client_ca_pem.size(),
  9510. nullptr // no password for server key
  9511. };
  9512. SSLServer svr(server_pem);
  9513. ASSERT_TRUE(svr.is_valid());
  9514. svr.Get("/test", [&](const Request &, Response &res) {
  9515. res.set_content("test", "text/plain");
  9516. });
  9517. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9518. auto se = detail::scope_exit([&] {
  9519. svr.stop();
  9520. t.join();
  9521. ASSERT_FALSE(svr.is_running());
  9522. });
  9523. svr.wait_until_ready();
  9524. // Create client with PEM memory
  9525. const char *password = client_encrypted_private_key_pass.empty()
  9526. ? nullptr
  9527. : client_encrypted_private_key_pass.c_str();
  9528. SSLClient::PemMemory client_pem = {
  9529. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9530. client_key_pem.size(), password};
  9531. SSLClient cli(HOST, PORT, client_pem);
  9532. cli.enable_server_certificate_verification(false);
  9533. cli.set_connection_timeout(30);
  9534. auto res = cli.Get("/test");
  9535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9536. ASSERT_EQ(StatusCode::OK_200, res->status);
  9537. }
  9538. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9539. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9540. }
  9541. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9542. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9543. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9544. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9545. }
  9546. TEST(SSLClientServerTest, ClientCertMissing) {
  9547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9548. CLIENT_CA_CERT_DIR);
  9549. ASSERT_TRUE(svr.is_valid());
  9550. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9551. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9552. auto se = detail::scope_exit([&] {
  9553. svr.stop();
  9554. t.join();
  9555. ASSERT_FALSE(svr.is_running());
  9556. });
  9557. svr.wait_until_ready();
  9558. SSLClient cli(HOST, PORT);
  9559. cli.set_connection_timeout(30);
  9560. auto res = cli.Get("/test");
  9561. ASSERT_TRUE(!res);
  9562. // When client cert is missing and server requires it, connection fails
  9563. // Error type depends on backend implementation
  9564. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9565. res.error() == Error::SSLConnection);
  9566. // Verify backend error is captured
  9567. // Note: This test may have different error codes depending on the exact
  9568. // verification failure
  9569. EXPECT_NE(0UL, res.ssl_backend_error());
  9570. }
  9571. TEST(SSLClientServerTest, TrustDirOptional) {
  9572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9573. ASSERT_TRUE(svr.is_valid());
  9574. svr.Get("/test", [&](const Request &, Response &res) {
  9575. res.set_content("test", "text/plain");
  9576. });
  9577. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9578. auto se = detail::scope_exit([&] {
  9579. svr.stop();
  9580. t.join();
  9581. ASSERT_FALSE(svr.is_running());
  9582. });
  9583. svr.wait_until_ready();
  9584. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9585. cli.enable_server_certificate_verification(false);
  9586. cli.set_connection_timeout(30);
  9587. auto res = cli.Get("/test");
  9588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9589. ASSERT_EQ(StatusCode::OK_200, res->status);
  9590. }
  9591. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9592. class NoListenSSLServer : public SSLServer {
  9593. public:
  9594. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9595. const char *client_ca_cert_file_path,
  9596. const char *client_ca_cert_dir_path = nullptr)
  9597. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9598. client_ca_cert_dir_path),
  9599. stop_(false) {}
  9600. std::atomic_bool stop_;
  9601. private:
  9602. bool process_and_close_socket(socket_t /*sock*/) override {
  9603. // Don't create SSL context
  9604. while (!stop_.load()) {
  9605. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9606. }
  9607. return true;
  9608. }
  9609. };
  9610. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9611. CLIENT_CA_CERT_FILE);
  9612. ASSERT_TRUE(svr.is_valid());
  9613. svr.Get("/test", [&](const Request &, Response &res) {
  9614. res.set_content("test", "text/plain");
  9615. });
  9616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9617. auto se = detail::scope_exit([&] {
  9618. svr.stop_ = true;
  9619. svr.stop();
  9620. t.join();
  9621. ASSERT_FALSE(svr.is_running());
  9622. });
  9623. svr.wait_until_ready();
  9624. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9625. cli.enable_server_certificate_verification(false);
  9626. cli.set_connection_timeout(1);
  9627. auto res = cli.Get("/test");
  9628. ASSERT_TRUE(!res);
  9629. EXPECT_EQ(Error::SSLConnection, res.error());
  9630. // Timeout results in WantRead error code (maps to backend-specific value)
  9631. EXPECT_NE(0, res.ssl_error());
  9632. }
  9633. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9634. // Test SSLServer with client certificate verification using the standard
  9635. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9637. CLIENT_CA_CERT_DIR);
  9638. ASSERT_TRUE(svr.is_valid());
  9639. svr.Get("/test", [&](const Request &req, Response &res) {
  9640. res.set_content("test", "text/plain");
  9641. auto cert = req.peer_cert();
  9642. ASSERT_TRUE(static_cast<bool>(cert));
  9643. auto common_name = cert.subject_cn();
  9644. EXPECT_EQ("Common Name", common_name);
  9645. });
  9646. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9647. auto se = detail::scope_exit([&] {
  9648. svr.stop();
  9649. t.join();
  9650. ASSERT_FALSE(svr.is_running());
  9651. });
  9652. svr.wait_until_ready();
  9653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9654. cli.enable_server_certificate_verification(false);
  9655. cli.set_connection_timeout(30);
  9656. auto res = cli.Get("/test");
  9657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9658. ASSERT_EQ(StatusCode::OK_200, res->status);
  9659. }
  9660. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9661. // Verifies that wildcard matching and exact matching work consistently
  9662. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9663. using namespace httplib::tls;
  9664. // We need a running server to test against
  9665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9666. ASSERT_TRUE(svr.is_valid());
  9667. svr.Get("/test", [](const Request &, Response &res) {
  9668. res.set_content("ok", "text/plain");
  9669. });
  9670. thread t([&]() { svr.listen(HOST, PORT); });
  9671. auto se = detail::scope_exit([&] {
  9672. svr.stop();
  9673. t.join();
  9674. });
  9675. svr.wait_until_ready();
  9676. bool verify_callback_called = false;
  9677. bool verify_result_wrong = false;
  9678. SSLClient cli(HOST, PORT);
  9679. cli.enable_server_certificate_verification(true);
  9680. cli.set_ca_cert_path(CA_CERT_FILE);
  9681. cli.set_connection_timeout(5);
  9682. // Note: Test certificate has CN="Common Name", not "localhost"
  9683. bool verify_result_cn = false;
  9684. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9685. verify_callback_called = true;
  9686. if (!ctx.cert) return false;
  9687. // Test 1: "Common Name" should match (our test server cert CN)
  9688. verify_result_cn = ctx.check_hostname("Common Name");
  9689. // Test 2: wrong hostname should not match
  9690. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9691. return true; // Accept for the purpose of this test
  9692. });
  9693. auto res = cli.Get("/test");
  9694. // The request may succeed or fail depending on cert configuration
  9695. // but the callback should have been called
  9696. ASSERT_TRUE(verify_callback_called)
  9697. << "Verify callback should have been called";
  9698. // CN="Common Name" should match our test certificate
  9699. //
  9700. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9701. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9702. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9703. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9704. // <openssl/base.h>, which is included transitively when
  9705. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9706. #if defined(OPENSSL_IS_BORINGSSL)
  9707. EXPECT_FALSE(verify_result_cn)
  9708. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9709. #else
  9710. EXPECT_TRUE(verify_result_cn)
  9711. << "verify_hostname should match 'Common Name' (certificate CN)";
  9712. #endif
  9713. // Wrong hostname should not match
  9714. EXPECT_FALSE(verify_result_wrong)
  9715. << "verify_hostname should not match 'wronghost.example.com'";
  9716. }
  9717. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9718. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9719. // X509_check_ip behavior and must hold for every backend.
  9720. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9721. using namespace httplib::tls;
  9722. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9723. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9724. ASSERT_TRUE(svr.is_valid());
  9725. svr.Get("/test", [](const Request &, Response &res) {
  9726. res.set_content("ok", "text/plain");
  9727. });
  9728. thread t([&]() { svr.listen(HOST, PORT); });
  9729. auto se = detail::scope_exit([&] {
  9730. svr.stop();
  9731. t.join();
  9732. });
  9733. svr.wait_until_ready();
  9734. bool verify_callback_called = false;
  9735. bool ip_matched_via_cn = true;
  9736. SSLClient cli(HOST, PORT);
  9737. cli.enable_server_certificate_verification(true);
  9738. cli.set_ca_cert_path(CA_CERT_FILE);
  9739. cli.set_connection_timeout(5);
  9740. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9741. verify_callback_called = true;
  9742. if (!ctx.cert) return false;
  9743. // The IP appears only in the CN, so it must NOT be accepted.
  9744. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9745. return true; // Accept for the purpose of this test
  9746. });
  9747. cli.Get("/test");
  9748. ASSERT_TRUE(verify_callback_called)
  9749. << "Verify callback should have been called";
  9750. EXPECT_FALSE(ip_matched_via_cn)
  9751. << "An IP host must not be authenticated via the certificate CN";
  9752. }
  9753. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9754. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9755. using namespace httplib::tls;
  9756. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  9757. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  9758. ASSERT_TRUE(svr.is_valid());
  9759. svr.Get("/test", [](const Request &, Response &res) {
  9760. res.set_content("ok", "text/plain");
  9761. });
  9762. thread t([&]() { svr.listen(HOST, PORT); });
  9763. auto se = detail::scope_exit([&] {
  9764. svr.stop();
  9765. t.join();
  9766. });
  9767. svr.wait_until_ready();
  9768. bool verify_callback_called = false;
  9769. bool san_matched = false;
  9770. bool wrong_ipv6_matched = true;
  9771. bool cn_ipv6_matched = true;
  9772. SSLClient cli(HOST, PORT);
  9773. cli.enable_server_certificate_verification(true);
  9774. cli.set_ca_cert_path(CA_CERT_FILE);
  9775. cli.set_connection_timeout(5);
  9776. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9777. verify_callback_called = true;
  9778. if (!ctx.cert) return false;
  9779. // Matches the IPv6 iPAddress SAN.
  9780. san_matched = ctx.check_hostname("2001:db8::1");
  9781. // A different IPv6 address must not match.
  9782. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  9783. // "::1" lives only in the CN, so it must not be accepted.
  9784. cn_ipv6_matched = ctx.check_hostname("::1");
  9785. return true; // Accept for the purpose of this test
  9786. });
  9787. cli.Get("/test");
  9788. ASSERT_TRUE(verify_callback_called)
  9789. << "Verify callback should have been called";
  9790. EXPECT_TRUE(san_matched)
  9791. << "verify_hostname should match an IPv6 iPAddress SAN";
  9792. EXPECT_FALSE(wrong_ipv6_matched)
  9793. << "verify_hostname should not match a non-matching IPv6 address";
  9794. EXPECT_FALSE(cn_ipv6_matched)
  9795. << "An IPv6 host must not be authenticated via the certificate CN";
  9796. }
  9797. #endif
  9798. // mbedTLS-specific callback constructor test
  9799. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9800. #ifdef CPPHTTPLIB_SSL_ENABLED
  9801. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9802. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9803. ASSERT_TRUE(svr.is_valid());
  9804. // Set up a handler to verify client certificate is present
  9805. bool client_cert_verified = false;
  9806. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9807. // Verify that client certificate was provided
  9808. client_cert_verified = true;
  9809. res.set_content("success", "text/plain");
  9810. });
  9811. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9812. auto se = detail::scope_exit([&] {
  9813. svr.stop();
  9814. t.join();
  9815. ASSERT_FALSE(svr.is_running());
  9816. });
  9817. svr.wait_until_ready();
  9818. // Client with certificate
  9819. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9820. cli.enable_server_certificate_verification(false);
  9821. cli.set_connection_timeout(30);
  9822. auto res = cli.Get("/test");
  9823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9824. ASSERT_EQ(StatusCode::OK_200, res->status);
  9825. ASSERT_TRUE(client_cert_verified);
  9826. EXPECT_EQ("success", res->body);
  9827. }
  9828. #endif
  9829. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9830. // backends
  9831. #ifdef CPPHTTPLIB_SSL_ENABLED
  9832. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9833. using namespace httplib::tls;
  9834. // Test that when client CA cert file is provided,
  9835. // the server properly requests and validates client certificates
  9836. // Create a server with client authentication
  9837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9838. ASSERT_TRUE(svr.is_valid());
  9839. bool handler_called = false;
  9840. svr.Get("/test", [&](const Request &req, Response &res) {
  9841. handler_called = true;
  9842. // Verify that a client certificate was provided
  9843. auto cert = req.peer_cert();
  9844. ASSERT_TRUE(static_cast<bool>(cert));
  9845. // Get the issuer name
  9846. std::string issuer_str = cert.issuer_name();
  9847. ASSERT_FALSE(issuer_str.empty());
  9848. // The client certificate should be issued by our test CA
  9849. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9850. res.set_content("authenticated", "text/plain");
  9851. });
  9852. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9853. auto se = detail::scope_exit([&] {
  9854. svr.stop();
  9855. t.join();
  9856. ASSERT_FALSE(svr.is_running());
  9857. });
  9858. svr.wait_until_ready();
  9859. // Connect with a client certificate issued by the CA
  9860. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9861. cli.enable_server_certificate_verification(false);
  9862. cli.set_connection_timeout(30);
  9863. auto res = cli.Get("/test");
  9864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9865. ASSERT_EQ(StatusCode::OK_200, res->status);
  9866. ASSERT_TRUE(handler_called);
  9867. EXPECT_EQ("authenticated", res->body);
  9868. }
  9869. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9870. using namespace httplib::tls;
  9871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9872. ASSERT_TRUE(svr.is_valid());
  9873. svr.Get("/test", [](const Request &, Response &res) {
  9874. res.set_content("ok", "text/plain");
  9875. });
  9876. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9877. auto se = detail::scope_exit([&] {
  9878. svr.stop();
  9879. t.join();
  9880. });
  9881. svr.wait_until_ready();
  9882. SSLClient cli(HOST, PORT);
  9883. cli.enable_server_certificate_verification(false);
  9884. cli.set_connection_timeout(30);
  9885. bool cert_checked = false;
  9886. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9887. if (ctx.cert) {
  9888. auto sans = ctx.sans();
  9889. // Test certificate may or may not have SANs - just verify the API
  9890. // works If SANs exist, verify the types are valid
  9891. for (const auto &san : sans) {
  9892. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9893. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9894. san.type == SanType::OTHER);
  9895. EXPECT_FALSE(san.value.empty());
  9896. }
  9897. cert_checked = true;
  9898. }
  9899. return true;
  9900. });
  9901. auto res = cli.Get("/test");
  9902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9903. EXPECT_TRUE(cert_checked);
  9904. }
  9905. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9906. using namespace httplib::tls;
  9907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9908. ASSERT_TRUE(svr.is_valid());
  9909. svr.Get("/test", [](const Request &, Response &res) {
  9910. res.set_content("ok", "text/plain");
  9911. });
  9912. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9913. auto se = detail::scope_exit([&] {
  9914. svr.stop();
  9915. t.join();
  9916. });
  9917. svr.wait_until_ready();
  9918. SSLClient cli(HOST, PORT);
  9919. cli.enable_server_certificate_verification(false);
  9920. cli.set_connection_timeout(30);
  9921. bool validity_checked = false;
  9922. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9923. if (ctx.cert) {
  9924. time_t not_before = 0, not_after = 0;
  9925. bool result = ctx.validity(not_before, not_after);
  9926. EXPECT_TRUE(result);
  9927. // Verify that not_before < now < not_after for a valid cert
  9928. time_t now = time(nullptr);
  9929. EXPECT_LT(not_before, now);
  9930. EXPECT_GT(not_after, now);
  9931. validity_checked = true;
  9932. }
  9933. return true;
  9934. });
  9935. auto res = cli.Get("/test");
  9936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9937. EXPECT_TRUE(validity_checked);
  9938. }
  9939. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9940. using namespace httplib::tls;
  9941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9942. ASSERT_TRUE(svr.is_valid());
  9943. svr.Get("/test", [](const Request &, Response &res) {
  9944. res.set_content("ok", "text/plain");
  9945. });
  9946. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9947. auto se = detail::scope_exit([&] {
  9948. svr.stop();
  9949. t.join();
  9950. });
  9951. svr.wait_until_ready();
  9952. SSLClient cli(HOST, PORT);
  9953. cli.enable_server_certificate_verification(false);
  9954. cli.set_connection_timeout(30);
  9955. bool serial_checked = false;
  9956. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9957. if (ctx.cert) {
  9958. std::string serial = ctx.serial();
  9959. EXPECT_FALSE(serial.empty());
  9960. // Serial should be a hex string
  9961. for (char c : serial) {
  9962. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9963. (c >= 'a' && c <= 'f'));
  9964. }
  9965. serial_checked = true;
  9966. }
  9967. return true;
  9968. });
  9969. auto res = cli.Get("/test");
  9970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9971. EXPECT_TRUE(serial_checked);
  9972. }
  9973. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9974. // Test 1: Valid CA file - no error should be recorded
  9975. {
  9976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9977. CLIENT_CA_CERT_FILE);
  9978. ASSERT_TRUE(svr.is_valid());
  9979. // With valid setup, last_ssl_error should be 0
  9980. EXPECT_EQ(0, svr.ssl_last_error());
  9981. }
  9982. // Test 2: Invalid CA file content
  9983. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9984. {
  9985. // Create a temporary file with completely invalid content
  9986. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9987. {
  9988. std::ofstream ofs(temp_invalid_ca);
  9989. ofs << "This is not a certificate file at all\n";
  9990. ofs << "Just plain text content\n";
  9991. }
  9992. // Create server with invalid CA file
  9993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9994. // Clean up temporary file
  9995. std::remove(temp_invalid_ca);
  9996. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9997. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9998. // Note: SSL_CTX_load_verify_locations typically fails first,
  9999. // but our error handling code path is still exercised
  10000. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10001. }
  10002. }
  10003. TEST(VerifyCallbackTest, VerifyContextFields) {
  10004. using namespace httplib::tls;
  10005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10006. ASSERT_TRUE(svr.is_valid());
  10007. svr.Get("/test", [](const Request &, Response &res) {
  10008. res.set_content("ok", "text/plain");
  10009. });
  10010. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. t.join();
  10014. });
  10015. svr.wait_until_ready();
  10016. SSLClient cli(HOST, PORT);
  10017. cli.enable_server_certificate_verification(false);
  10018. cli.set_connection_timeout(30);
  10019. int callback_count = 0;
  10020. bool saw_leaf_cert = false;
  10021. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10022. if (ctx.cert) {
  10023. callback_count++;
  10024. // We should see at least one certificate (the leaf)
  10025. std::string cn = ctx.subject_cn();
  10026. if (!cn.empty()) { saw_leaf_cert = true; }
  10027. // Verify context fields are populated
  10028. EXPECT_NE(ctx.session, nullptr);
  10029. EXPECT_GE(ctx.depth, 0);
  10030. }
  10031. return true;
  10032. });
  10033. auto res = cli.Get("/test");
  10034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10035. EXPECT_GT(callback_count, 0);
  10036. EXPECT_TRUE(saw_leaf_cert);
  10037. }
  10038. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10039. using httplib::tls::TlsError;
  10040. // Test that verify_error_to_string returns empty for success
  10041. std::string success_str = TlsError::verify_error_to_string(0);
  10042. EXPECT_TRUE(success_str.empty());
  10043. // Test that verify_error_to_string returns non-empty for error codes
  10044. // Using a common error code (certificate expired)
  10045. std::string error_str =
  10046. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10047. EXPECT_FALSE(error_str.empty());
  10048. }
  10049. TEST(SessionVerifierTest, CertificateAccepted) {
  10050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10051. ASSERT_TRUE(svr.is_valid());
  10052. svr.Get("/test", [](const Request &, Response &res) {
  10053. res.set_content("ok", "text/plain");
  10054. });
  10055. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10056. auto se = detail::scope_exit([&] {
  10057. svr.stop();
  10058. t.join();
  10059. });
  10060. svr.wait_until_ready();
  10061. SSLClient cli(HOST, PORT);
  10062. cli.enable_server_certificate_verification(false);
  10063. cli.set_connection_timeout(30);
  10064. bool callback_called = false;
  10065. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10066. EXPECT_NE(session, nullptr);
  10067. callback_called = true;
  10068. return SSLVerifierResponse::CertificateAccepted;
  10069. });
  10070. auto res = cli.Get("/test");
  10071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10072. EXPECT_EQ(200, res->status);
  10073. EXPECT_TRUE(callback_called);
  10074. }
  10075. TEST(SessionVerifierTest, CertificateRejected) {
  10076. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10077. ASSERT_TRUE(svr.is_valid());
  10078. svr.Get("/test", [](const Request &, Response &res) {
  10079. res.set_content("ok", "text/plain");
  10080. });
  10081. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10082. auto se = detail::scope_exit([&] {
  10083. svr.stop();
  10084. t.join();
  10085. });
  10086. svr.wait_until_ready();
  10087. SSLClient cli(HOST, PORT);
  10088. cli.enable_server_certificate_verification(false);
  10089. cli.set_connection_timeout(30);
  10090. bool callback_called = false;
  10091. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10092. EXPECT_NE(session, nullptr);
  10093. callback_called = true;
  10094. return SSLVerifierResponse::CertificateRejected;
  10095. });
  10096. auto res = cli.Get("/test");
  10097. EXPECT_FALSE(res);
  10098. EXPECT_TRUE(callback_called);
  10099. }
  10100. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10102. ASSERT_TRUE(svr.is_valid());
  10103. svr.Get("/test", [](const Request &, Response &res) {
  10104. res.set_content("ok", "text/plain");
  10105. });
  10106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10107. auto se = detail::scope_exit([&] {
  10108. svr.stop();
  10109. t.join();
  10110. });
  10111. svr.wait_until_ready();
  10112. // NoDecisionMade with verification disabled should succeed (no default check)
  10113. SSLClient cli(HOST, PORT);
  10114. cli.enable_server_certificate_verification(false);
  10115. cli.set_connection_timeout(30);
  10116. bool callback_called = false;
  10117. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10118. EXPECT_NE(session, nullptr);
  10119. callback_called = true;
  10120. return SSLVerifierResponse::NoDecisionMade;
  10121. });
  10122. auto res = cli.Get("/test");
  10123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10124. EXPECT_EQ(200, res->status);
  10125. EXPECT_TRUE(callback_called);
  10126. }
  10127. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10129. ASSERT_TRUE(svr.is_valid());
  10130. svr.Get("/test", [](const Request &, Response &res) {
  10131. res.set_content("ok", "text/plain");
  10132. });
  10133. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10134. auto se = detail::scope_exit([&] {
  10135. svr.stop();
  10136. t.join();
  10137. });
  10138. svr.wait_until_ready();
  10139. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10140. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10141. // so we only check that the request fails, not whether the callback was
  10142. // called.
  10143. SSLClient cli(HOST, PORT);
  10144. cli.enable_server_certificate_verification(true);
  10145. cli.set_connection_timeout(30);
  10146. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10147. EXPECT_NE(session, nullptr);
  10148. return SSLVerifierResponse::NoDecisionMade;
  10149. });
  10150. auto res = cli.Get("/test");
  10151. EXPECT_FALSE(res);
  10152. }
  10153. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10154. // Test SSL server using PemMemory constructor with client CA certificates
  10155. // Read PEM files
  10156. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10157. read_file(SERVER_CERT_FILE, server_cert_pem);
  10158. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10159. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10160. // Create SSLServer with PemMemory constructor including client CA
  10161. SSLServer::PemMemory server_pem = {
  10162. server_cert_pem.c_str(),
  10163. server_cert_pem.size(),
  10164. server_key_pem.c_str(),
  10165. server_key_pem.size(),
  10166. client_ca_pem.c_str(),
  10167. client_ca_pem.size(),
  10168. nullptr // no password for server key
  10169. };
  10170. SSLServer svr(server_pem);
  10171. ASSERT_TRUE(svr.is_valid());
  10172. // No SSL error should be recorded for valid setup
  10173. EXPECT_EQ(0, svr.ssl_last_error());
  10174. // Set up server endpoints
  10175. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10176. res.set_content("ok", "text/plain");
  10177. });
  10178. // Start server in a thread
  10179. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10180. svr.wait_until_ready();
  10181. // Connect with client certificate (using constructor with paths)
  10182. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10183. cli.enable_server_certificate_verification(false);
  10184. auto res = cli.Get("/test-pem-ca");
  10185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10186. EXPECT_EQ(200, res->status);
  10187. EXPECT_EQ("ok", res->body);
  10188. svr.stop();
  10189. server_thread.join();
  10190. }
  10191. #endif
  10192. #ifdef _WIN32
  10193. TEST(CleanupTest, WSACleanup) {
  10194. int ret = WSACleanup();
  10195. ASSERT_EQ(0, ret);
  10196. }
  10197. #endif
  10198. #ifndef CPPHTTPLIB_SSL_ENABLED
  10199. TEST(NoSSLSupport, SimpleInterface) {
  10200. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10201. }
  10202. #endif
  10203. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10204. TEST(InvalidScheme, SimpleInterface) {
  10205. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10206. }
  10207. #endif
  10208. TEST(NoScheme, SimpleInterface) {
  10209. Client cli("yahoo.com:80");
  10210. ASSERT_TRUE(cli.is_valid());
  10211. }
  10212. TEST(SendAPI, SimpleInterface_Online) {
  10213. Client cli("http://yahoo.com");
  10214. Request req;
  10215. req.method = "GET";
  10216. req.path = "/";
  10217. auto res = cli.send(req);
  10218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10219. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10220. }
  10221. TEST(SendAPI, WithParamsInRequest) {
  10222. Server svr;
  10223. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10224. EXPECT_TRUE(req.has_param("test"));
  10225. EXPECT_EQ("test_value", req.get_param_value("test"));
  10226. });
  10227. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. svr.stop();
  10230. t.join();
  10231. ASSERT_FALSE(svr.is_running());
  10232. });
  10233. svr.wait_until_ready();
  10234. Client cli(HOST, PORT);
  10235. {
  10236. Request req;
  10237. req.method = "GET";
  10238. req.path = "/";
  10239. req.params.emplace("test", "test_value");
  10240. auto res = cli.send(req);
  10241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10242. }
  10243. {
  10244. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10246. }
  10247. }
  10248. TEST(ClientImplMethods, GetSocketTest) {
  10249. httplib::Server svr;
  10250. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10251. res.status = StatusCode::OK_200;
  10252. });
  10253. auto port = svr.bind_to_any_port("127.0.0.1");
  10254. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. thread.join();
  10258. ASSERT_FALSE(svr.is_running());
  10259. });
  10260. svr.wait_until_ready();
  10261. {
  10262. httplib::Client cli("127.0.0.1", port);
  10263. cli.set_keep_alive(true);
  10264. // Use the behavior of cpp-httplib of opening the connection
  10265. // only when the first request happens. If that changes,
  10266. // this test would be obsolete.
  10267. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10268. // This also implicitly tests the server. But other tests would fail much
  10269. // earlier than this one to be considered.
  10270. auto res = cli.Get("/");
  10271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10272. EXPECT_EQ(StatusCode::OK_200, res->status);
  10273. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10274. }
  10275. }
  10276. #ifdef CPPHTTPLIB_SSL_ENABLED
  10277. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10278. Client cli("http://yahoo.com");
  10279. auto res = cli.Get("/");
  10280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10281. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10282. cli.set_follow_location(true);
  10283. res = cli.Get("/");
  10284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10287. }
  10288. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10289. Client cli("https://yahoo.com");
  10290. auto res = cli.Get("/");
  10291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10292. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10293. cli.set_follow_location(true);
  10294. res = cli.Get("/");
  10295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10296. EXPECT_EQ(StatusCode::OK_200, res->status);
  10297. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10298. }
  10299. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10300. Client cli("https://yahoo.com");
  10301. auto res = cli.Get("/");
  10302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10303. ASSERT_FALSE(!res);
  10304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10305. ASSERT_FALSE(res == nullptr);
  10306. ASSERT_TRUE(res != nullptr);
  10307. EXPECT_EQ(Error::Success, res.error());
  10308. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10309. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10310. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10311. cli.set_follow_location(true);
  10312. res = cli.Get("/");
  10313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10314. EXPECT_EQ(Error::Success, res.error());
  10315. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10316. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10317. EXPECT_EQ(StatusCode::OK_200, res->status);
  10318. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10319. }
  10320. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10321. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10322. Client cli("https://cdnjs.cloudflare.com");
  10323. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10324. Headers{{"Accept-Encoding", "br"}});
  10325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10326. EXPECT_EQ(StatusCode::OK_200, res->status);
  10327. EXPECT_EQ(287630U, res->body.size());
  10328. EXPECT_EQ("application/javascript; charset=utf-8",
  10329. res->get_header_value("Content-Type"));
  10330. }
  10331. #endif
  10332. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10333. #undef REDIR_HOST // Silence compiler warning
  10334. #define REDIR_HOST "https://httpbingo.org"
  10335. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10336. Client cli(REDIR_HOST);
  10337. cli.set_follow_location(true);
  10338. auto res =
  10339. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10341. EXPECT_EQ(StatusCode::OK_200, res->status);
  10342. }
  10343. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10344. Client cli(REDIR_HOST);
  10345. cli.set_follow_location(true);
  10346. Params params;
  10347. params.emplace("url", "http://example.com");
  10348. params.emplace("status_code", "302");
  10349. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10351. EXPECT_EQ(StatusCode::OK_200, res->status);
  10352. }
  10353. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10354. Client cli(REDIR_HOST);
  10355. cli.set_follow_location(true);
  10356. Params params;
  10357. params.emplace("url", "http://example.com");
  10358. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10360. EXPECT_EQ(StatusCode::OK_200, res->status);
  10361. }
  10362. TEST(HttpToHttpsRedirectTest, CertFile) {
  10363. auto ssl_port = PORT + 1;
  10364. Server svr;
  10365. ASSERT_TRUE(svr.is_valid());
  10366. svr.Get("/index", [&](const Request &, Response &res) {
  10367. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10368. "/index");
  10369. svr.stop();
  10370. });
  10371. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10372. ASSERT_TRUE(ssl_svr.is_valid());
  10373. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10374. res.set_content("test", "text/plain");
  10375. ssl_svr.stop();
  10376. });
  10377. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10378. thread t2 =
  10379. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10380. auto se = detail::scope_exit([&] {
  10381. t2.join();
  10382. t.join();
  10383. ASSERT_FALSE(svr.is_running());
  10384. });
  10385. svr.wait_until_ready();
  10386. ssl_svr.wait_until_ready();
  10387. Client cli("127.0.0.1", PORT);
  10388. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10389. cli.enable_server_certificate_verification(true);
  10390. cli.set_follow_location(true);
  10391. cli.set_connection_timeout(30);
  10392. auto res = cli.Get("/index");
  10393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10394. ASSERT_EQ(StatusCode::OK_200, res->status);
  10395. }
  10396. TEST(SSLClientRedirectTest, CertFile) {
  10397. auto ssl_port = PORT + 1;
  10398. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10399. ASSERT_TRUE(ssl_svr1.is_valid());
  10400. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10401. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10402. "/index");
  10403. ssl_svr1.stop();
  10404. });
  10405. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10406. ASSERT_TRUE(ssl_svr2.is_valid());
  10407. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10408. res.set_content("test", "text/plain");
  10409. ssl_svr2.stop();
  10410. });
  10411. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10412. thread t2 =
  10413. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10414. auto se = detail::scope_exit([&] {
  10415. t2.join();
  10416. t.join();
  10417. ASSERT_FALSE(ssl_svr1.is_running());
  10418. });
  10419. ssl_svr1.wait_until_ready();
  10420. ssl_svr2.wait_until_ready();
  10421. SSLClient cli("127.0.0.1", PORT);
  10422. std::string cert;
  10423. read_file(SERVER_CERT2_FILE, cert);
  10424. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10425. cli.enable_server_certificate_verification(true);
  10426. cli.set_follow_location(true);
  10427. cli.set_connection_timeout(30);
  10428. auto res = cli.Get("/index");
  10429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10430. ASSERT_EQ(StatusCode::OK_200, res->status);
  10431. }
  10432. #endif
  10433. #ifdef CPPHTTPLIB_SSL_ENABLED
  10434. // Test that set_ca_cert_store() skips system certs (consistent with
  10435. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10436. // should be trusted - system certs should NOT be loaded.
  10437. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10438. // Load a specific cert that is NOT a system CA cert
  10439. std::string cert;
  10440. read_file(SERVER_CERT2_FILE, cert);
  10441. SSLClient cli("google.com");
  10442. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10443. cli.enable_server_certificate_verification(true);
  10444. // This should FAIL because:
  10445. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10446. // 2. System certs should NOT be loaded when custom store is set
  10447. // If system certs WERE loaded, this would succeed
  10448. auto res = cli.Get("/");
  10449. ASSERT_FALSE(res);
  10450. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10451. }
  10452. // Same as above, but through the native store handle path. Regression test:
  10453. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10454. // merged system certs into the user-provided store.
  10455. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10456. std::string cert;
  10457. read_file(SERVER_CERT2_FILE, cert);
  10458. SSLClient cli("google.com");
  10459. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10460. cli.enable_server_certificate_verification(true);
  10461. auto res = cli.Get("/");
  10462. ASSERT_FALSE(res);
  10463. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10464. }
  10465. // A custom store set via the native handle must still verify a server whose
  10466. // cert it does contain.
  10467. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10468. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10469. ASSERT_TRUE(svr.is_valid());
  10470. svr.Get("/test", [&](const Request &, Response &res) {
  10471. res.set_content("test", "text/plain");
  10472. });
  10473. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10474. auto se = detail::scope_exit([&] {
  10475. svr.stop();
  10476. t.join();
  10477. ASSERT_FALSE(svr.is_running());
  10478. });
  10479. svr.wait_until_ready();
  10480. SSLClient cli("127.0.0.1", PORT);
  10481. std::string cert;
  10482. read_file(SERVER_CERT2_FILE, cert);
  10483. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10484. cli.enable_server_certificate_verification(true);
  10485. cli.set_connection_timeout(30);
  10486. auto res = cli.Get("/test");
  10487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10488. ASSERT_EQ(StatusCode::OK_200, res->status);
  10489. }
  10490. // CA certs loaded through the universal Client must be transferred to the
  10491. // client created internally for following an HTTPS redirect. Regression test:
  10492. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10493. // the CA data for redirect transfer.
  10494. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10495. auto ssl_port = PORT + 1;
  10496. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10497. ASSERT_TRUE(ssl_svr1.is_valid());
  10498. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10499. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10500. "/index");
  10501. });
  10502. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10503. ASSERT_TRUE(ssl_svr2.is_valid());
  10504. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10505. res.set_content("test", "text/plain");
  10506. });
  10507. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10508. thread t2 =
  10509. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10510. auto se = detail::scope_exit([&] {
  10511. ssl_svr2.stop();
  10512. ssl_svr1.stop();
  10513. t2.join();
  10514. t.join();
  10515. ASSERT_FALSE(ssl_svr1.is_running());
  10516. });
  10517. ssl_svr1.wait_until_ready();
  10518. ssl_svr2.wait_until_ready();
  10519. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10520. std::string cert;
  10521. read_file(SERVER_CERT2_FILE, cert);
  10522. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10523. cli.enable_server_certificate_verification(true);
  10524. cli.set_follow_location(true);
  10525. cli.set_connection_timeout(30);
  10526. auto res = cli.Get("/index");
  10527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10528. ASSERT_EQ(StatusCode::OK_200, res->status);
  10529. }
  10530. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10531. // so a host signed by a system CA verifies even though a custom CA is set
  10532. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10533. std::string cert;
  10534. read_file(SERVER_CERT2_FILE, cert);
  10535. SSLClient cli("google.com");
  10536. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10537. cli.enable_system_ca(true);
  10538. cli.enable_server_certificate_verification(true);
  10539. auto res = cli.Get("/");
  10540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10541. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10542. }
  10543. // The custom CA remains effective when combined with the system CA
  10544. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10545. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10546. ASSERT_TRUE(svr.is_valid());
  10547. svr.Get("/test", [&](const Request &, Response &res) {
  10548. res.set_content("test", "text/plain");
  10549. });
  10550. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10551. auto se = detail::scope_exit([&] {
  10552. svr.stop();
  10553. t.join();
  10554. ASSERT_FALSE(svr.is_running());
  10555. });
  10556. svr.wait_until_ready();
  10557. SSLClient cli("127.0.0.1", PORT);
  10558. std::string cert;
  10559. read_file(SERVER_CERT2_FILE, cert);
  10560. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10561. cli.enable_system_ca(true);
  10562. cli.enable_server_certificate_verification(true);
  10563. cli.set_connection_timeout(30);
  10564. auto res = cli.Get("/test");
  10565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10566. ASSERT_EQ(StatusCode::OK_200, res->status);
  10567. }
  10568. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10569. // skip chain verification entirely (only the certificate identity was
  10570. // checked), so a server presenting an untrusted certificate with a matching
  10571. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10572. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10573. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10574. ASSERT_TRUE(svr.is_valid());
  10575. svr.Get("/test", [&](const Request &, Response &res) {
  10576. res.set_content("test", "text/plain");
  10577. });
  10578. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10579. auto se = detail::scope_exit([&] {
  10580. svr.stop();
  10581. t.join();
  10582. ASSERT_FALSE(svr.is_running());
  10583. });
  10584. svr.wait_until_ready();
  10585. SSLClient cli("127.0.0.1", PORT);
  10586. std::string cert;
  10587. // A trusted CA that did not sign the server certificate. The server cert
  10588. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10589. // this connection.
  10590. read_file(CLIENT_CA_CERT_FILE, cert);
  10591. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10592. cli.enable_server_certificate_verification(true);
  10593. cli.set_connection_timeout(30);
  10594. auto res = cli.Get("/test");
  10595. ASSERT_FALSE(res);
  10596. }
  10597. // enable_system_ca(false) prevents system CA loading entirely
  10598. TEST(SSLClientTest, DisableSystemCa_Online) {
  10599. SSLClient cli("google.com");
  10600. cli.enable_system_ca(false);
  10601. cli.enable_server_certificate_verification(true);
  10602. auto res = cli.Get("/");
  10603. ASSERT_FALSE(res);
  10604. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10605. // itself when the CA chain is empty
  10606. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10607. res.error() == Error::SSLConnection);
  10608. }
  10609. // The universal Client forwards enable_system_ca()
  10610. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10611. std::string cert;
  10612. read_file(SERVER_CERT2_FILE, cert);
  10613. Client cli("https://google.com");
  10614. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10615. cli.enable_system_ca(true);
  10616. cli.enable_server_certificate_verification(true);
  10617. auto res = cli.Get("/");
  10618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10619. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10620. }
  10621. // The system CA policy must carry over to the client created internally for
  10622. // following a cross-host HTTPS redirect
  10623. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10624. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10625. ASSERT_TRUE(svr.is_valid());
  10626. svr.Get("/index", [&](const Request &, Response &res) {
  10627. res.set_redirect("https://www.google.com/");
  10628. });
  10629. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10630. auto se = detail::scope_exit([&] {
  10631. svr.stop();
  10632. t.join();
  10633. ASSERT_FALSE(svr.is_running());
  10634. });
  10635. svr.wait_until_ready();
  10636. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10637. std::string cert;
  10638. read_file(SERVER_CERT2_FILE, cert);
  10639. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10640. cli.enable_system_ca(true);
  10641. cli.enable_server_certificate_verification(true);
  10642. cli.set_follow_location(true);
  10643. cli.set_connection_timeout(30);
  10644. // Receiving any response proves the redirect client completed the TLS
  10645. // handshake with a system-CA-signed host
  10646. auto res = cli.Get("/index");
  10647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10648. }
  10649. TEST(MultipartFormDataTest, LargeData) {
  10650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10651. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10652. const ContentReader &content_reader) {
  10653. if (req.is_multipart_form_data()) {
  10654. std::vector<FormData> items;
  10655. content_reader(
  10656. [&](const FormData &file) {
  10657. items.push_back(file);
  10658. return true;
  10659. },
  10660. [&](const char *data, size_t data_length) {
  10661. items.back().content.append(data, data_length);
  10662. return true;
  10663. });
  10664. EXPECT_TRUE(std::string(items[0].name) == "document");
  10665. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10666. EXPECT_TRUE(items[0].filename == "2MB_data");
  10667. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10668. EXPECT_TRUE(items[1].name == "hello");
  10669. EXPECT_TRUE(items[1].content == "world");
  10670. EXPECT_TRUE(items[1].filename == "");
  10671. EXPECT_TRUE(items[1].content_type == "");
  10672. } else {
  10673. std::string body;
  10674. content_reader([&](const char *data, size_t data_length) {
  10675. body.append(data, data_length);
  10676. return true;
  10677. });
  10678. }
  10679. });
  10680. auto port = svr.bind_to_any_port(HOST);
  10681. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10682. auto se = detail::scope_exit([&] {
  10683. svr.stop();
  10684. t.join();
  10685. ASSERT_FALSE(svr.is_running());
  10686. });
  10687. svr.wait_until_ready();
  10688. {
  10689. std::string data(1024 * 1024 * 2, '.');
  10690. std::stringstream buffer;
  10691. buffer << data;
  10692. SSLClient cli(HOST, port);
  10693. cli.enable_server_certificate_verification(false);
  10694. UploadFormDataItems items{
  10695. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10696. {"hello", "world", "", ""},
  10697. };
  10698. auto res = cli.Post("/post", items);
  10699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10700. ASSERT_EQ(StatusCode::OK_200, res->status);
  10701. }
  10702. }
  10703. TEST(MultipartFormDataTest, DataProviderItems) {
  10704. std::random_device seed_gen;
  10705. std::mt19937 random(seed_gen());
  10706. std::string rand1;
  10707. rand1.resize(1000);
  10708. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10709. std::string rand2;
  10710. rand2.resize(3000);
  10711. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10713. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10714. const ContentReader &content_reader) {
  10715. ASSERT_FALSE(req.is_multipart_form_data());
  10716. std::string body;
  10717. content_reader([&](const char *data, size_t data_length) {
  10718. body.append(data, data_length);
  10719. return true;
  10720. });
  10721. EXPECT_EQ(body, "");
  10722. });
  10723. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10724. const ContentReader &content_reader) {
  10725. ASSERT_TRUE(req.is_multipart_form_data());
  10726. std::vector<FormData> items;
  10727. content_reader(
  10728. [&](const FormData &file) {
  10729. items.push_back(file);
  10730. return true;
  10731. },
  10732. [&](const char *data, size_t data_length) {
  10733. items.back().content.append(data, data_length);
  10734. return true;
  10735. });
  10736. ASSERT_TRUE(items.size() == 2);
  10737. EXPECT_EQ(std::string(items[0].name), "name1");
  10738. EXPECT_EQ(items[0].content, "Testing123");
  10739. EXPECT_EQ(items[0].filename, "filename1");
  10740. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10741. EXPECT_EQ(items[1].name, "name2");
  10742. EXPECT_EQ(items[1].content, "Testing456");
  10743. EXPECT_EQ(items[1].filename, "");
  10744. EXPECT_EQ(items[1].content_type, "");
  10745. });
  10746. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10747. const ContentReader &content_reader) {
  10748. ASSERT_TRUE(req.is_multipart_form_data());
  10749. std::vector<FormData> items;
  10750. content_reader(
  10751. [&](const FormData &file) {
  10752. items.push_back(file);
  10753. return true;
  10754. },
  10755. [&](const char *data, size_t data_length) {
  10756. items.back().content.append(data, data_length);
  10757. return true;
  10758. });
  10759. ASSERT_TRUE(items.size() == 2);
  10760. EXPECT_EQ(items[0].name, "name3");
  10761. EXPECT_EQ(items[0].content, rand1);
  10762. EXPECT_EQ(items[0].filename, "filename3");
  10763. EXPECT_EQ(items[0].content_type, "");
  10764. EXPECT_EQ(items[1].name, "name4");
  10765. EXPECT_EQ(items[1].content, rand2);
  10766. EXPECT_EQ(items[1].filename, "filename4");
  10767. EXPECT_EQ(items[1].content_type, "");
  10768. });
  10769. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  10770. const ContentReader &content_reader) {
  10771. ASSERT_TRUE(req.is_multipart_form_data());
  10772. std::vector<FormData> items;
  10773. content_reader(
  10774. [&](const FormData &file) {
  10775. items.push_back(file);
  10776. return true;
  10777. },
  10778. [&](const char *data, size_t data_length) {
  10779. items.back().content.append(data, data_length);
  10780. return true;
  10781. });
  10782. ASSERT_TRUE(items.size() == 4);
  10783. EXPECT_EQ(std::string(items[0].name), "name1");
  10784. EXPECT_EQ(items[0].content, "Testing123");
  10785. EXPECT_EQ(items[0].filename, "filename1");
  10786. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10787. EXPECT_EQ(items[1].name, "name2");
  10788. EXPECT_EQ(items[1].content, "Testing456");
  10789. EXPECT_EQ(items[1].filename, "");
  10790. EXPECT_EQ(items[1].content_type, "");
  10791. EXPECT_EQ(items[2].name, "name3");
  10792. EXPECT_EQ(items[2].content, rand1);
  10793. EXPECT_EQ(items[2].filename, "filename3");
  10794. EXPECT_EQ(items[2].content_type, "");
  10795. EXPECT_EQ(items[3].name, "name4");
  10796. EXPECT_EQ(items[3].content, rand2);
  10797. EXPECT_EQ(items[3].filename, "filename4");
  10798. EXPECT_EQ(items[3].content_type, "");
  10799. });
  10800. auto port = svr.bind_to_any_port("localhost");
  10801. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10802. auto se = detail::scope_exit([&] {
  10803. svr.stop();
  10804. t.join();
  10805. ASSERT_FALSE(svr.is_running());
  10806. });
  10807. svr.wait_until_ready();
  10808. {
  10809. SSLClient cli("localhost", port);
  10810. cli.enable_server_certificate_verification(false);
  10811. UploadFormDataItems items{
  10812. {"name1", "Testing123", "filename1", "application/octet-stream"},
  10813. {"name2", "Testing456", "", ""}, // not a file
  10814. };
  10815. {
  10816. auto res = cli.Post("/post-none", {}, {}, {});
  10817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10818. ASSERT_EQ(StatusCode::OK_200, res->status);
  10819. }
  10820. FormDataProviderItems providers;
  10821. {
  10822. auto res =
  10823. cli.Post("/post-items", {}, items, providers); // empty providers
  10824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10825. ASSERT_EQ(StatusCode::OK_200, res->status);
  10826. }
  10827. providers.push_back({"name3",
  10828. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10829. // test the offset is given correctly at each step
  10830. if (!offset)
  10831. sink.os.write(rand1.data(), 30);
  10832. else if (offset == 30)
  10833. sink.os.write(rand1.data() + 30, 300);
  10834. else if (offset == 330)
  10835. sink.os.write(rand1.data() + 330, 670);
  10836. else if (offset == rand1.size())
  10837. sink.done();
  10838. return true;
  10839. },
  10840. "filename3",
  10841. {}});
  10842. providers.push_back({"name4",
  10843. [&](size_t offset, httplib::DataSink &sink) -> bool {
  10844. // test the offset is given correctly at each step
  10845. if (!offset)
  10846. sink.os.write(rand2.data(), 2000);
  10847. else if (offset == 2000)
  10848. sink.os.write(rand2.data() + 2000, 1);
  10849. else if (offset == 2001)
  10850. sink.os.write(rand2.data() + 2001, 999);
  10851. else if (offset == rand2.size())
  10852. sink.done();
  10853. return true;
  10854. },
  10855. "filename4",
  10856. {}});
  10857. {
  10858. auto res = cli.Post("/post-providers", {}, {}, providers);
  10859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10860. ASSERT_EQ(StatusCode::OK_200, res->status);
  10861. }
  10862. {
  10863. auto res = cli.Post("/post-both", {}, items, providers);
  10864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10865. ASSERT_EQ(StatusCode::OK_200, res->status);
  10866. }
  10867. }
  10868. }
  10869. TEST(MultipartFormDataTest, BadHeader) {
  10870. Server svr;
  10871. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10872. res.set_content("ok", "text/plain");
  10873. });
  10874. thread t = thread([&] { svr.listen(HOST, PORT); });
  10875. auto se = detail::scope_exit([&] {
  10876. svr.stop();
  10877. t.join();
  10878. ASSERT_FALSE(svr.is_running());
  10879. });
  10880. svr.wait_until_ready();
  10881. const std::string body =
  10882. "This is the preamble. It is to be ignored, though it\r\n"
  10883. "is a handy place for composition agents to include an\r\n"
  10884. "explanatory note to non-MIME conformant readers.\r\n"
  10885. "\r\n"
  10886. "\r\n"
  10887. "--simple boundary\r\n"
  10888. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10889. ": BAD...\r\n"
  10890. "\r\n"
  10891. "value1\r\n"
  10892. "--simple boundary\r\n"
  10893. "Content-Disposition: form-data; name=\"field2\"; "
  10894. "filename=\"example.txt\"\r\n"
  10895. "\r\n"
  10896. "value2\r\n"
  10897. "--simple boundary--\r\n"
  10898. "This is the epilogue. It is also to be ignored.\r\n";
  10899. std::string content_type =
  10900. R"(multipart/form-data; boundary="simple boundary")";
  10901. Client cli(HOST, PORT);
  10902. auto res = cli.Post("/post", body, content_type.c_str());
  10903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10904. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  10905. }
  10906. TEST(MultipartFormDataTest, WithPreamble) {
  10907. Server svr;
  10908. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  10909. res.set_content("ok", "text/plain");
  10910. });
  10911. thread t = thread([&] { svr.listen(HOST, PORT); });
  10912. auto se = detail::scope_exit([&] {
  10913. svr.stop();
  10914. t.join();
  10915. ASSERT_FALSE(svr.is_running());
  10916. });
  10917. svr.wait_until_ready();
  10918. const std::string body =
  10919. "This is the preamble. It is to be ignored, though it\r\n"
  10920. "is a handy place for composition agents to include an\r\n"
  10921. "explanatory note to non-MIME conformant readers.\r\n"
  10922. "\r\n"
  10923. "\r\n"
  10924. "--simple boundary\r\n"
  10925. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10926. "\r\n"
  10927. "value1\r\n"
  10928. "--simple boundary\r\n"
  10929. "Content-Disposition: form-data; name=\"field2\"; "
  10930. "filename=\"example.txt\"\r\n"
  10931. "\r\n"
  10932. "value2\r\n"
  10933. "--simple boundary--\r\n"
  10934. "This is the epilogue. It is also to be ignored.\r\n";
  10935. std::string content_type =
  10936. R"(multipart/form-data; boundary="simple boundary")";
  10937. Client cli(HOST, PORT);
  10938. auto res = cli.Post("/post", body, content_type.c_str());
  10939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10940. EXPECT_EQ(StatusCode::OK_200, res->status);
  10941. }
  10942. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10944. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10945. const ContentReader &content_reader) {
  10946. if (req.is_multipart_form_data()) {
  10947. std::vector<FormData> items;
  10948. content_reader(
  10949. [&](const FormData &file) {
  10950. items.push_back(file);
  10951. return true;
  10952. },
  10953. [&](const char *data, size_t data_length) {
  10954. items.back().content.append(data, data_length);
  10955. return true;
  10956. });
  10957. EXPECT_TRUE(std::string(items[0].name) == "document");
  10958. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10959. EXPECT_TRUE(items[0].filename == "2MB_data");
  10960. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10961. EXPECT_TRUE(items[1].name == "hello");
  10962. EXPECT_TRUE(items[1].content == "world");
  10963. EXPECT_TRUE(items[1].filename == "");
  10964. EXPECT_TRUE(items[1].content_type == "");
  10965. } else {
  10966. std::string body;
  10967. content_reader([&](const char *data, size_t data_length) {
  10968. body.append(data, data_length);
  10969. return true;
  10970. });
  10971. }
  10972. });
  10973. auto port = svr.bind_to_any_port("localhost");
  10974. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10975. auto se = detail::scope_exit([&] {
  10976. svr.stop();
  10977. t.join();
  10978. ASSERT_FALSE(svr.is_running());
  10979. });
  10980. svr.wait_until_ready();
  10981. {
  10982. std::string data(1024 * 1024 * 2, '.');
  10983. std::stringstream buffer;
  10984. buffer << data;
  10985. SSLClient cli("localhost", port);
  10986. cli.enable_server_certificate_verification(false);
  10987. UploadFormDataItems items{
  10988. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10989. {"hello", "world", "", ""},
  10990. };
  10991. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10993. ASSERT_EQ(StatusCode::OK_200, res->status);
  10994. }
  10995. }
  10996. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10997. std::string data(1024 * 1024 * 2, '&');
  10998. std::stringstream buffer;
  10999. buffer << data;
  11000. Client cli("https://localhost:8080");
  11001. UploadFormDataItems items{
  11002. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11003. {"hello", "world", "", ""},
  11004. };
  11005. for (const char &c : " \t\r\n") {
  11006. auto res =
  11007. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11008. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11009. ASSERT_FALSE(res);
  11010. }
  11011. }
  11012. TEST(MultipartFormDataTest, PutFormData) {
  11013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11014. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11015. const ContentReader &content_reader) {
  11016. if (req.is_multipart_form_data()) {
  11017. std::vector<FormData> items;
  11018. content_reader(
  11019. [&](const FormData &file) {
  11020. items.push_back(file);
  11021. return true;
  11022. },
  11023. [&](const char *data, size_t data_length) {
  11024. items.back().content.append(data, data_length);
  11025. return true;
  11026. });
  11027. EXPECT_TRUE(std::string(items[0].name) == "document");
  11028. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11029. EXPECT_TRUE(items[0].filename == "2MB_data");
  11030. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11031. EXPECT_TRUE(items[1].name == "hello");
  11032. EXPECT_TRUE(items[1].content == "world");
  11033. EXPECT_TRUE(items[1].filename == "");
  11034. EXPECT_TRUE(items[1].content_type == "");
  11035. } else {
  11036. std::string body;
  11037. content_reader([&](const char *data, size_t data_length) {
  11038. body.append(data, data_length);
  11039. return true;
  11040. });
  11041. }
  11042. });
  11043. auto port = svr.bind_to_any_port("localhost");
  11044. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11045. auto se = detail::scope_exit([&] {
  11046. svr.stop();
  11047. t.join();
  11048. ASSERT_FALSE(svr.is_running());
  11049. });
  11050. svr.wait_until_ready();
  11051. {
  11052. std::string data(1024 * 1024 * 2, '&');
  11053. std::stringstream buffer;
  11054. buffer << data;
  11055. SSLClient cli("localhost", port);
  11056. cli.enable_server_certificate_verification(false);
  11057. UploadFormDataItems items{
  11058. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11059. {"hello", "world", "", ""},
  11060. };
  11061. auto res = cli.Put("/put", items);
  11062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11063. ASSERT_EQ(StatusCode::OK_200, res->status);
  11064. }
  11065. }
  11066. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11068. svr.Put("/put_customboundary",
  11069. [&](const Request &req, const Response & /*res*/,
  11070. const ContentReader &content_reader) {
  11071. if (req.is_multipart_form_data()) {
  11072. std::vector<FormData> items;
  11073. content_reader(
  11074. [&](const FormData &file) {
  11075. items.push_back(file);
  11076. return true;
  11077. },
  11078. [&](const char *data, size_t data_length) {
  11079. items.back().content.append(data, data_length);
  11080. return true;
  11081. });
  11082. EXPECT_TRUE(std::string(items[0].name) == "document");
  11083. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11084. EXPECT_TRUE(items[0].filename == "2MB_data");
  11085. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11086. EXPECT_TRUE(items[1].name == "hello");
  11087. EXPECT_TRUE(items[1].content == "world");
  11088. EXPECT_TRUE(items[1].filename == "");
  11089. EXPECT_TRUE(items[1].content_type == "");
  11090. } else {
  11091. std::string body;
  11092. content_reader([&](const char *data, size_t data_length) {
  11093. body.append(data, data_length);
  11094. return true;
  11095. });
  11096. }
  11097. });
  11098. auto port = svr.bind_to_any_port("localhost");
  11099. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11100. auto se = detail::scope_exit([&] {
  11101. svr.stop();
  11102. t.join();
  11103. ASSERT_FALSE(svr.is_running());
  11104. });
  11105. svr.wait_until_ready();
  11106. {
  11107. std::string data(1024 * 1024 * 2, '&');
  11108. std::stringstream buffer;
  11109. buffer << data;
  11110. SSLClient cli("localhost", port);
  11111. cli.enable_server_certificate_verification(false);
  11112. UploadFormDataItems items{
  11113. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11114. {"hello", "world", "", ""},
  11115. };
  11116. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11118. ASSERT_EQ(StatusCode::OK_200, res->status);
  11119. }
  11120. }
  11121. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11122. std::string data(1024 * 1024 * 2, '&');
  11123. std::stringstream buffer;
  11124. buffer << data;
  11125. Client cli("https://localhost:8080");
  11126. cli.enable_server_certificate_verification(false);
  11127. UploadFormDataItems items{
  11128. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11129. {"hello", "world", "", ""},
  11130. };
  11131. for (const char &c : " \t\r\n") {
  11132. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11133. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11134. ASSERT_FALSE(res);
  11135. }
  11136. }
  11137. TEST(MultipartFormDataTest, AlternateFilename) {
  11138. auto handled = false;
  11139. Server svr;
  11140. svr.Post("/test", [&](const Request &req, Response &res) {
  11141. ASSERT_EQ(2u, req.form.files.size());
  11142. ASSERT_EQ(1u, req.form.fields.size());
  11143. // Test files
  11144. const auto &file1 = req.form.get_file("file1");
  11145. ASSERT_EQ("file1", file1.name);
  11146. ASSERT_EQ("A.txt", file1.filename);
  11147. ASSERT_EQ("text/plain", file1.content_type);
  11148. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11149. const auto &file2 = req.form.get_file("file2");
  11150. ASSERT_EQ("file2", file2.name);
  11151. ASSERT_EQ("a.html", file2.filename);
  11152. ASSERT_EQ("text/html", file2.content_type);
  11153. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11154. file2.content);
  11155. // Test text field
  11156. const auto &text = req.form.get_field("text");
  11157. ASSERT_EQ("text default", text);
  11158. res.set_content("ok", "text/plain");
  11159. handled = true;
  11160. });
  11161. thread t = thread([&] { svr.listen(HOST, PORT); });
  11162. auto se = detail::scope_exit([&] {
  11163. svr.stop();
  11164. t.join();
  11165. ASSERT_FALSE(svr.is_running());
  11166. ASSERT_TRUE(handled);
  11167. });
  11168. svr.wait_until_ready();
  11169. auto req = "POST /test HTTP/1.1\r\n"
  11170. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11171. "Content-Length: 399\r\n"
  11172. "\r\n"
  11173. "----------\r\n"
  11174. "Content-Disposition: form-data; name=\"text\"\r\n"
  11175. "\r\n"
  11176. "text default\r\n"
  11177. "----------\r\n"
  11178. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11179. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11180. "Content-Type: text/plain\r\n"
  11181. "\r\n"
  11182. "Content of a.txt.\r\n"
  11183. "\r\n"
  11184. "----------\r\n"
  11185. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11186. "\"a.html\"\r\n"
  11187. "Content-Type: text/html\r\n"
  11188. "\r\n"
  11189. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11190. "\r\n"
  11191. "------------\r\n";
  11192. ASSERT_TRUE(send_request(1, req));
  11193. }
  11194. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11195. auto handled = false;
  11196. Server svr;
  11197. svr.Post("/test", [&](const Request &req, Response &res) {
  11198. // Case-insensitive "utf-8''" prefix with a long value
  11199. const auto &file = req.form.get_file("file1");
  11200. ASSERT_EQ("file1", file.name);
  11201. // 8000 chars exercises both the Content-Disposition parser and the
  11202. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11203. // Prior to the fix, std::regex_match on this header would cause O(N)
  11204. // stack recursion in libstdc++, leading to SIGSEGV.
  11205. std::string expected_filename(8000, 'A');
  11206. ASSERT_EQ(expected_filename, file.filename);
  11207. res.set_content("ok", "text/plain");
  11208. handled = true;
  11209. });
  11210. thread t = thread([&] { svr.listen(HOST, PORT); });
  11211. auto se = detail::scope_exit([&] {
  11212. svr.stop();
  11213. t.join();
  11214. ASSERT_FALSE(svr.is_running());
  11215. ASSERT_TRUE(handled);
  11216. });
  11217. svr.wait_until_ready();
  11218. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11219. // Regression test for GHSA-qq6v-r583-3h69
  11220. std::string long_filename(8000, 'A');
  11221. std::string body = "----------\r\n"
  11222. "Content-Disposition: form-data; name=\"file1\"; "
  11223. "filename*=\"Utf-8''" +
  11224. long_filename +
  11225. "\"\r\n"
  11226. "\r\n"
  11227. "hello\r\n"
  11228. "------------\r\n";
  11229. auto req = "POST /test HTTP/1.1\r\n"
  11230. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11231. "Content-Length: " +
  11232. std::to_string(body.size()) + "\r\n\r\n" + body;
  11233. ASSERT_TRUE(send_request(1, req));
  11234. }
  11235. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11236. auto handled = false;
  11237. Server svr;
  11238. svr.Post("/test", [&](const Request &req, Response &) {
  11239. ASSERT_EQ(2u, req.form.fields.size());
  11240. const auto &text1 = req.form.get_field("text1");
  11241. ASSERT_EQ("text1", text1);
  11242. const auto &text2 = req.form.get_field("text2");
  11243. ASSERT_EQ("text2", text2);
  11244. handled = true;
  11245. });
  11246. thread t = thread([&] { svr.listen(HOST, PORT); });
  11247. auto se = detail::scope_exit([&] {
  11248. svr.stop();
  11249. t.join();
  11250. ASSERT_FALSE(svr.is_running());
  11251. ASSERT_TRUE(handled);
  11252. });
  11253. svr.wait_until_ready();
  11254. auto req = "POST /test HTTP/1.1\r\n"
  11255. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11256. "Content-Length: 146\r\n"
  11257. "\r\n----------\r\n"
  11258. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11259. "\r\n"
  11260. "text1"
  11261. "\r\n----------\r\n"
  11262. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11263. "\r\n"
  11264. "text2"
  11265. "\r\n------------";
  11266. std::string response;
  11267. ASSERT_TRUE(send_request(1, req, &response));
  11268. ASSERT_EQ("200", response.substr(9, 3));
  11269. }
  11270. TEST(MultipartFormDataTest, ContentLength) {
  11271. auto handled = false;
  11272. Server svr;
  11273. svr.Post("/test", [&](const Request &req, Response &) {
  11274. ASSERT_EQ(2u, req.form.fields.size());
  11275. const auto &text1 = req.form.get_field("text1");
  11276. ASSERT_EQ("text1", text1);
  11277. const auto &text2 = req.form.get_field("text2");
  11278. ASSERT_EQ("text2", text2);
  11279. handled = true;
  11280. });
  11281. thread t = thread([&] { svr.listen(HOST, PORT); });
  11282. auto se = detail::scope_exit([&] {
  11283. svr.stop();
  11284. t.join();
  11285. ASSERT_FALSE(svr.is_running());
  11286. ASSERT_TRUE(handled);
  11287. });
  11288. svr.wait_until_ready();
  11289. auto req = "POST /test HTTP/1.1\r\n"
  11290. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11291. "Content-Length: 167\r\n"
  11292. "\r\n----------\r\n"
  11293. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11294. "Content-Length: 5\r\n"
  11295. "\r\n"
  11296. "text1"
  11297. "\r\n----------\r\n"
  11298. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11299. "\r\n"
  11300. "text2"
  11301. "\r\n------------\r\n";
  11302. std::string response;
  11303. ASSERT_TRUE(send_request(1, req, &response));
  11304. ASSERT_EQ("200", response.substr(9, 3));
  11305. }
  11306. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11307. auto handled = false;
  11308. Server svr;
  11309. svr.Post("/test", [&](const Request &req, Response &) {
  11310. ASSERT_EQ(2u, req.form.fields.size());
  11311. const auto &text1 = req.form.get_field("text1");
  11312. ASSERT_EQ("text1", text1);
  11313. // TODO: Add header access for text fields if needed
  11314. const auto &text2 = req.form.get_field("text2");
  11315. ASSERT_EQ("text2", text2);
  11316. // TODO: Header access for text fields needs to be implemented
  11317. // auto &headers = it->second.headers;
  11318. // ASSERT_EQ(3U, headers.size());
  11319. // auto custom_header = headers.find("x-whatever");
  11320. // ASSERT_TRUE(custom_header != headers.end());
  11321. // ASSERT_NE("customvalue", custom_header->second);
  11322. // ASSERT_EQ("CustomValue", custom_header->second);
  11323. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11324. handled = true;
  11325. });
  11326. thread t = thread([&] { svr.listen(HOST, PORT); });
  11327. auto se = detail::scope_exit([&] {
  11328. svr.stop();
  11329. t.join();
  11330. ASSERT_FALSE(svr.is_running());
  11331. ASSERT_TRUE(handled);
  11332. });
  11333. svr.wait_until_ready();
  11334. auto req = "POST /test HTTP/1.1\r\n"
  11335. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11336. "Content-Length: 232\r\n"
  11337. "\r\n----------\r\n"
  11338. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11339. "Content-Length: 5\r\n"
  11340. "X-Test: 1\r\n"
  11341. "\r\n"
  11342. "text1"
  11343. "\r\n----------\r\n"
  11344. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11345. "Content-Type: text/plain\r\n"
  11346. "X-Whatever: CustomValue\r\n"
  11347. "\r\n"
  11348. "text2"
  11349. "\r\n------------\r\n"
  11350. "That should be disregarded. Not even read";
  11351. std::string response;
  11352. ASSERT_TRUE(send_request(1, req, &response));
  11353. ASSERT_EQ("200", response.substr(9, 3));
  11354. }
  11355. TEST(MultipartFormDataTest, LargeHeader) {
  11356. auto handled = false;
  11357. Server svr;
  11358. svr.Post("/test", [&](const Request &req, Response &) {
  11359. ASSERT_EQ(1u, req.form.fields.size());
  11360. const auto &text = req.form.get_field("name1");
  11361. ASSERT_EQ("text1", text);
  11362. handled = true;
  11363. });
  11364. thread t = thread([&] { svr.listen(HOST, PORT); });
  11365. auto se = detail::scope_exit([&] {
  11366. svr.stop();
  11367. t.join();
  11368. ASSERT_FALSE(svr.is_running());
  11369. ASSERT_TRUE(handled);
  11370. });
  11371. svr.wait_until_ready();
  11372. auto boundary = std::string("cpp-httplib-multipart-data");
  11373. std::string content = "--" + boundary +
  11374. "\r\n"
  11375. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11376. "\r\n"
  11377. "text1\r\n"
  11378. "--" +
  11379. boundary + "--\r\n";
  11380. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11381. "Content-Type: multipart/form-data;boundary=" +
  11382. boundary +
  11383. "\r\n"
  11384. "Content-Length: " +
  11385. std::to_string(content.size()) +
  11386. "\r\n"
  11387. "Dummy-Header: ";
  11388. std::string header_suffix = "\r\n"
  11389. "\r\n";
  11390. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11391. size_t header_dummy_size =
  11392. read_buff_size -
  11393. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11394. auto header_dummy = std::string(header_dummy_size, '@');
  11395. auto req = header_prefix + header_dummy + header_suffix + content;
  11396. std::string response;
  11397. ASSERT_TRUE(send_request(1, req, &response));
  11398. ASSERT_EQ("200", response.substr(9, 3));
  11399. }
  11400. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11401. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11402. // (not chunked Transfer-Encoding) after the streaming refactor.
  11403. auto handled = false;
  11404. Server svr;
  11405. svr.Post("/upload", [&](const Request &req, Response &res) {
  11406. auto cl_it = req.headers.find("Content-Length");
  11407. EXPECT_TRUE(cl_it != req.headers.end());
  11408. auto te_it = req.headers.find("Transfer-Encoding");
  11409. EXPECT_TRUE(te_it == req.headers.end());
  11410. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11411. res.set_content("ok", "text/plain");
  11412. handled = true;
  11413. });
  11414. auto port = svr.bind_to_any_port(HOST);
  11415. auto t = thread([&] { svr.listen_after_bind(); });
  11416. auto se = detail::scope_exit([&] {
  11417. svr.stop();
  11418. t.join();
  11419. ASSERT_FALSE(svr.is_running());
  11420. ASSERT_TRUE(handled);
  11421. });
  11422. svr.wait_until_ready();
  11423. UploadFormDataItems items = {
  11424. {"field1", "hello", "", "text/plain"},
  11425. {"file1", "world", "test.txt", "application/octet-stream"},
  11426. };
  11427. Client cli(HOST, port);
  11428. auto res = cli.Post("/upload", {}, items);
  11429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11430. EXPECT_EQ(StatusCode::OK_200, res->status);
  11431. }
  11432. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11433. // Verify that make_multipart_content_provider coalesces many small segments
  11434. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11435. constexpr size_t kItemCount = 1000;
  11436. UploadFormDataItems items;
  11437. items.reserve(kItemCount);
  11438. for (size_t i = 0; i < kItemCount; i++) {
  11439. items.push_back(
  11440. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11441. }
  11442. const std::string boundary = "----test-boundary";
  11443. auto content_length = detail::get_multipart_content_length(items, boundary);
  11444. auto provider = detail::make_multipart_content_provider(items, boundary);
  11445. // Drive the provider the same way write_content_with_progress does
  11446. size_t write_count = 0;
  11447. size_t total_bytes = 0;
  11448. DataSink sink;
  11449. size_t offset = 0;
  11450. sink.write = [&](const char *d, size_t l) -> bool {
  11451. (void)d;
  11452. write_count++;
  11453. total_bytes += l;
  11454. offset += l;
  11455. return true;
  11456. };
  11457. sink.is_writable = []() -> bool { return true; };
  11458. while (offset < content_length) {
  11459. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11460. }
  11461. EXPECT_EQ(content_length, total_bytes);
  11462. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11463. // With buffering into 64KB blocks, write_count should be much smaller.
  11464. auto segment_count = 3 * kItemCount + 1;
  11465. EXPECT_LT(write_count, segment_count / 10);
  11466. }
  11467. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11468. // Integration test: send many UploadFormDataItems and verify the server
  11469. // receives all of them correctly (#2410).
  11470. constexpr size_t kItemCount = 500;
  11471. auto handled = false;
  11472. Server svr;
  11473. svr.Post("/upload", [&](const Request &req, Response &res) {
  11474. EXPECT_EQ(kItemCount, req.form.fields.size());
  11475. for (size_t i = 0; i < kItemCount; i++) {
  11476. auto key = "field" + std::to_string(i);
  11477. auto val = "value" + std::to_string(i);
  11478. auto it = req.form.fields.find(key);
  11479. if (it != req.form.fields.end()) {
  11480. EXPECT_EQ(val, it->second.content);
  11481. } else {
  11482. ADD_FAILURE() << "Missing field: " << key;
  11483. }
  11484. }
  11485. res.set_content("ok", "text/plain");
  11486. handled = true;
  11487. });
  11488. auto port = svr.bind_to_any_port(HOST);
  11489. auto t = thread([&] { svr.listen_after_bind(); });
  11490. auto se = detail::scope_exit([&] {
  11491. svr.stop();
  11492. t.join();
  11493. ASSERT_FALSE(svr.is_running());
  11494. ASSERT_TRUE(handled);
  11495. });
  11496. svr.wait_until_ready();
  11497. UploadFormDataItems items;
  11498. items.reserve(kItemCount);
  11499. for (size_t i = 0; i < kItemCount; i++) {
  11500. items.push_back(
  11501. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11502. }
  11503. Client cli(HOST, port);
  11504. auto res = cli.Post("/upload", items);
  11505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11506. EXPECT_EQ(StatusCode::OK_200, res->status);
  11507. }
  11508. TEST(MultipartFormDataTest, MakeFileProvider) {
  11509. // Verify make_file_provider sends a file's contents correctly.
  11510. const std::string file_content(4096, 'Z');
  11511. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11512. {
  11513. std::ofstream ofs(tmp_path, std::ios::binary);
  11514. ofs.write(file_content.data(),
  11515. static_cast<std::streamsize>(file_content.size()));
  11516. }
  11517. auto handled = false;
  11518. Server svr;
  11519. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11520. const ContentReader &content_reader) {
  11521. ASSERT_TRUE(req.is_multipart_form_data());
  11522. std::vector<FormData> items;
  11523. content_reader(
  11524. [&](const FormData &file) {
  11525. items.push_back(file);
  11526. return true;
  11527. },
  11528. [&](const char *data, size_t data_length) {
  11529. items.back().content.append(data, data_length);
  11530. return true;
  11531. });
  11532. ASSERT_EQ(1u, items.size());
  11533. EXPECT_EQ("myfile", items[0].name);
  11534. EXPECT_EQ("data.bin", items[0].filename);
  11535. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11536. EXPECT_EQ(file_content, items[0].content);
  11537. handled = true;
  11538. });
  11539. auto port = svr.bind_to_any_port(HOST);
  11540. auto t = thread([&] { svr.listen_after_bind(); });
  11541. auto se = detail::scope_exit([&] {
  11542. svr.stop();
  11543. t.join();
  11544. ASSERT_FALSE(svr.is_running());
  11545. ASSERT_TRUE(handled);
  11546. std::remove(tmp_path.c_str());
  11547. });
  11548. svr.wait_until_ready();
  11549. FormDataProviderItems providers;
  11550. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11551. "application/octet-stream"));
  11552. Client cli(HOST, port);
  11553. auto res = cli.Post("/upload", {}, {}, providers);
  11554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11555. EXPECT_EQ(StatusCode::OK_200, res->status);
  11556. }
  11557. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11558. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11559. // (100) headers is rejected with a 400 Bad Request response.
  11560. Server svr;
  11561. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11562. res.set_content("ok", "text/plain");
  11563. });
  11564. thread t = thread([&] { svr.listen(HOST, PORT); });
  11565. auto se = detail::scope_exit([&] {
  11566. svr.stop();
  11567. t.join();
  11568. ASSERT_FALSE(svr.is_running());
  11569. });
  11570. svr.wait_until_ready();
  11571. // Build a multipart part with 101 custom headers (exceeding
  11572. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11573. std::stringstream body;
  11574. body << "--simpleboundary\r\n"
  11575. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11576. for (int i = 0; i < 101; i++) {
  11577. body << "X-Custom-Header-" << i << ": value\r\n";
  11578. }
  11579. body << "\r\n"
  11580. << "value1\r\n"
  11581. << "--simpleboundary--\r\n";
  11582. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11583. Client cli(HOST, PORT);
  11584. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11586. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11587. }
  11588. TEST(MakeFileBodyTest, Basic) {
  11589. const std::string file_content(4096, 'Z');
  11590. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11591. {
  11592. std::ofstream ofs(tmp_path, std::ios::binary);
  11593. ofs.write(file_content.data(),
  11594. static_cast<std::streamsize>(file_content.size()));
  11595. }
  11596. auto handled = false;
  11597. Server svr;
  11598. svr.Post("/upload", [&](const Request &req, Response &res) {
  11599. EXPECT_EQ(file_content, req.body);
  11600. handled = true;
  11601. res.status = StatusCode::OK_200;
  11602. });
  11603. auto port = svr.bind_to_any_port(HOST);
  11604. auto t = thread([&] { svr.listen_after_bind(); });
  11605. auto se = detail::scope_exit([&] {
  11606. svr.stop();
  11607. t.join();
  11608. ASSERT_FALSE(svr.is_running());
  11609. ASSERT_TRUE(handled);
  11610. std::remove(tmp_path.c_str());
  11611. });
  11612. svr.wait_until_ready();
  11613. auto fb = make_file_body(tmp_path);
  11614. ASSERT_GT(fb.first, 0u);
  11615. Client cli(HOST, port);
  11616. auto res =
  11617. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11619. EXPECT_EQ(StatusCode::OK_200, res->status);
  11620. }
  11621. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11622. static constexpr unsigned int number_of_tasks{1000000};
  11623. std::atomic_uint count{0};
  11624. std::unique_ptr<TaskQueue> task_queue{
  11625. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11626. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11627. auto queued = task_queue->enqueue(
  11628. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11629. EXPECT_TRUE(queued);
  11630. }
  11631. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11632. task_queue->shutdown();
  11633. #else
  11634. EXPECT_NO_THROW(task_queue->shutdown());
  11635. #endif
  11636. EXPECT_EQ(number_of_tasks, count.load());
  11637. }
  11638. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11639. static constexpr unsigned int number_of_tasks{1000000};
  11640. static constexpr unsigned int qlimit{2};
  11641. unsigned int queued_count{0};
  11642. std::atomic_uint count{0};
  11643. std::unique_ptr<TaskQueue> task_queue{
  11644. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11645. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11646. if (task_queue->enqueue(
  11647. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11648. queued_count++;
  11649. }
  11650. }
  11651. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11652. task_queue->shutdown();
  11653. #else
  11654. EXPECT_NO_THROW(task_queue->shutdown());
  11655. #endif
  11656. EXPECT_EQ(queued_count, count.load());
  11657. EXPECT_TRUE(queued_count <= number_of_tasks);
  11658. EXPECT_TRUE(queued_count >= qlimit);
  11659. }
  11660. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11661. // Use a short idle timeout so a dynamic thread spawns, times out and
  11662. // exits during the test, and the pool keeps working afterwards.
  11663. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11664. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11665. /*idle_timeout_sec=*/1}};
  11666. std::atomic_uint count{0};
  11667. std::condition_variable cv;
  11668. std::mutex mtx;
  11669. bool release = false;
  11670. // Block the base thread so the second task spawns a dynamic thread.
  11671. EXPECT_TRUE(task_queue->enqueue([&] {
  11672. std::unique_lock<std::mutex> lock(mtx);
  11673. while (!release) {
  11674. cv.wait(lock);
  11675. }
  11676. count++;
  11677. }));
  11678. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11679. // Let the dynamic thread finish its task and exceed the idle timeout.
  11680. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11681. {
  11682. std::unique_lock<std::mutex> lock(mtx);
  11683. release = true;
  11684. }
  11685. cv.notify_all();
  11686. // The pool must still accept and run tasks after the dynamic thread exited.
  11687. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11688. task_queue->shutdown();
  11689. EXPECT_EQ(3u, count.load());
  11690. }
  11691. TEST(TaskQueueTest, MaxQueuedRequests) {
  11692. static constexpr unsigned int qlimit{3};
  11693. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11694. std::condition_variable sem_cv;
  11695. std::mutex sem_mtx;
  11696. int credits = 0;
  11697. bool queued;
  11698. /* Fill up the queue with tasks that will block until we give them credits to
  11699. * complete. */
  11700. for (unsigned int n = 0; n <= qlimit;) {
  11701. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11702. std::unique_lock<std::mutex> lock(sem_mtx);
  11703. while (credits <= 0) {
  11704. sem_cv.wait(lock);
  11705. }
  11706. /* Consume the credit and signal the test code if they are all gone. */
  11707. if (--credits == 0) { sem_cv.notify_one(); }
  11708. });
  11709. if (n < qlimit) {
  11710. /* The first qlimit enqueues must succeed. */
  11711. EXPECT_TRUE(queued);
  11712. } else {
  11713. /* The last one will succeed only when the worker thread
  11714. * starts and dequeues the first blocking task. Although
  11715. * not necessary for the correctness of this test, we sleep for
  11716. * a short while to avoid busy waiting. */
  11717. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11718. }
  11719. if (queued) { n++; }
  11720. }
  11721. /* Further enqueues must fail since the queue is full. */
  11722. for (auto i = 0; i < 4; i++) {
  11723. queued = task_queue->enqueue([] {});
  11724. EXPECT_FALSE(queued);
  11725. }
  11726. /* Give the credits to allow the previous tasks to complete. */
  11727. {
  11728. std::unique_lock<std::mutex> lock(sem_mtx);
  11729. credits += qlimit + 1;
  11730. }
  11731. sem_cv.notify_all();
  11732. /* Wait for all the credits to be consumed. */
  11733. {
  11734. std::unique_lock<std::mutex> lock(sem_mtx);
  11735. while (credits > 0) {
  11736. sem_cv.wait(lock);
  11737. }
  11738. }
  11739. /* Check that we are able again to enqueue at least qlimit tasks. */
  11740. for (unsigned int i = 0; i < qlimit; i++) {
  11741. queued = task_queue->enqueue([] {});
  11742. EXPECT_TRUE(queued);
  11743. }
  11744. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11745. task_queue->shutdown();
  11746. #else
  11747. EXPECT_NO_THROW(task_queue->shutdown());
  11748. #endif
  11749. }
  11750. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11751. Server svr;
  11752. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11753. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11754. });
  11755. svr.Get("/hello", [](const Request &req, Response &res) {
  11756. res.set_content(req.get_param_value("key"), "text/plain");
  11757. });
  11758. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11759. auto se = detail::scope_exit([&] {
  11760. svr.stop();
  11761. thread.join();
  11762. ASSERT_FALSE(svr.is_running());
  11763. });
  11764. svr.wait_until_ready();
  11765. {
  11766. Client cli(HOST, PORT);
  11767. cli.set_follow_location(true);
  11768. auto res = cli.Get("/");
  11769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11770. EXPECT_EQ(StatusCode::OK_200, res->status);
  11771. EXPECT_EQ("val&key2=val2", res->body);
  11772. }
  11773. }
  11774. #endif
  11775. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  11776. Server svr;
  11777. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11778. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  11779. });
  11780. svr.Get("/hello", [](const Request &req, Response &res) {
  11781. res.set_content(req.get_param_value("key"), "text/plain");
  11782. });
  11783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11784. auto se = detail::scope_exit([&] {
  11785. svr.stop();
  11786. thread.join();
  11787. ASSERT_FALSE(svr.is_running());
  11788. });
  11789. svr.wait_until_ready();
  11790. {
  11791. Client cli(HOST, PORT);
  11792. cli.set_follow_location(true);
  11793. auto res = cli.Get("/");
  11794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11795. EXPECT_EQ(StatusCode::OK_200, res->status);
  11796. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  11797. }
  11798. }
  11799. TEST(RedirectTest, RedirectWithPlusInPath) {
  11800. Server svr;
  11801. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11802. res.set_redirect("/a+b");
  11803. });
  11804. // Route pattern uses regex; escape + as \\+
  11805. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  11806. res.set_content(req.path, "text/plain");
  11807. });
  11808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. thread.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. {
  11816. Client cli(HOST, PORT);
  11817. cli.set_follow_location(true);
  11818. auto res = cli.Get("/");
  11819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11820. EXPECT_EQ(StatusCode::OK_200, res->status);
  11821. EXPECT_EQ("/a+b", res->body);
  11822. }
  11823. }
  11824. #ifdef CPPHTTPLIB_SSL_ENABLED
  11825. TEST(RedirectTest, Issue2185_Online) {
  11826. SSLClient client("github.com");
  11827. client.set_follow_location(true);
  11828. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  11829. "Coollab-Windows.zip");
  11830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11831. EXPECT_EQ(StatusCode::OK_200, res->status);
  11832. EXPECT_EQ(9920427U, res->body.size());
  11833. }
  11834. #endif
  11835. TEST(VulnerabilityTest, CRLFInjection) {
  11836. Server svr;
  11837. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  11838. res.set_content("Hello 1", "text/plain");
  11839. });
  11840. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  11841. res.set_content("Hello 2", "text/plain");
  11842. });
  11843. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  11844. res.set_content("Hello 3", "text/plain");
  11845. });
  11846. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  11847. res.set_content("Hello 4", "text/plain");
  11848. });
  11849. svr.set_logger([](const Request &req, const Response & /*res*/) {
  11850. for (const auto &x : req.headers) {
  11851. auto key = x.first;
  11852. EXPECT_STRNE("evil", key.c_str());
  11853. }
  11854. });
  11855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11856. auto se = detail::scope_exit([&] {
  11857. svr.stop();
  11858. thread.join();
  11859. ASSERT_FALSE(svr.is_running());
  11860. });
  11861. svr.wait_until_ready();
  11862. {
  11863. Client cli(HOST, PORT);
  11864. cli.Post("/test1", "A=B",
  11865. "application/x-www-form-urlencoded\r\nevil: hello1");
  11866. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  11867. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  11868. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  11869. }
  11870. }
  11871. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  11872. auto server_thread = std::thread([] {
  11873. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11874. default_socket_options(srv);
  11875. sockaddr_in addr{};
  11876. addr.sin_family = AF_INET;
  11877. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  11878. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11879. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11880. ::listen(srv, 1);
  11881. sockaddr_in cli_addr{};
  11882. socklen_t cli_len = sizeof(cli_addr);
  11883. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11884. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  11885. std::string buf_all;
  11886. char buf[2048];
  11887. ssize_t n;
  11888. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  11889. buf_all.append(buf, static_cast<size_t>(n));
  11890. size_t pos;
  11891. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  11892. auto request_block = buf_all.substr(0, pos + 4); // include separator
  11893. auto e = request_block.find("\r\n");
  11894. if (e != std::string::npos) {
  11895. auto request_line = request_block.substr(0, e);
  11896. std::string msg =
  11897. "CRLF injection detected in request line: '" + request_line + "'";
  11898. EXPECT_FALSE(true) << msg;
  11899. }
  11900. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  11901. ::send(cli,
  11902. #ifdef _WIN32
  11903. static_cast<const char *>(resp.c_str()),
  11904. static_cast<int>(resp.size()),
  11905. #else
  11906. resp.c_str(), resp.size(),
  11907. #endif
  11908. 0);
  11909. buf_all.erase(0, pos + 4);
  11910. }
  11911. }
  11912. detail::close_socket(cli);
  11913. detail::close_socket(srv);
  11914. });
  11915. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11916. auto cli = Client("127.0.0.1", PORT + 1);
  11917. auto headers = Headers{
  11918. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  11919. {"Connection", "keep-alive"}};
  11920. auto res = cli.Get("/hi", headers);
  11921. EXPECT_FALSE(res);
  11922. EXPECT_EQ(Error::InvalidHeaders, res.error());
  11923. server_thread.join();
  11924. }
  11925. TEST(PathParamsTest, StaticMatch) {
  11926. const auto pattern = "/users/all";
  11927. detail::PathParamsMatcher matcher(pattern);
  11928. Request request;
  11929. request.path = "/users/all";
  11930. ASSERT_TRUE(matcher.match(request));
  11931. std::unordered_map<std::string, std::string> expected_params = {};
  11932. EXPECT_EQ(request.path_params, expected_params);
  11933. }
  11934. TEST(PathParamsTest, StaticMismatch) {
  11935. const auto pattern = "/users/all";
  11936. detail::PathParamsMatcher matcher(pattern);
  11937. Request request;
  11938. request.path = "/users/1";
  11939. ASSERT_FALSE(matcher.match(request));
  11940. }
  11941. TEST(PathParamsTest, SingleParamInTheMiddle) {
  11942. const auto pattern = "/users/:id/subscriptions";
  11943. detail::PathParamsMatcher matcher(pattern);
  11944. Request request;
  11945. request.path = "/users/42/subscriptions";
  11946. ASSERT_TRUE(matcher.match(request));
  11947. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11948. EXPECT_EQ(request.path_params, expected_params);
  11949. }
  11950. TEST(PathParamsTest, SingleParamInTheEnd) {
  11951. const auto pattern = "/users/:id";
  11952. detail::PathParamsMatcher matcher(pattern);
  11953. Request request;
  11954. request.path = "/users/24";
  11955. ASSERT_TRUE(matcher.match(request));
  11956. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  11957. EXPECT_EQ(request.path_params, expected_params);
  11958. }
  11959. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  11960. const auto pattern = "/users/:id/";
  11961. detail::PathParamsMatcher matcher(pattern);
  11962. Request request;
  11963. request.path = "/users/42/";
  11964. ASSERT_TRUE(matcher.match(request));
  11965. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  11966. EXPECT_EQ(request.path_params, expected_params);
  11967. }
  11968. TEST(PathParamsTest, EmptyParam) {
  11969. const auto pattern = "/users/:id/";
  11970. detail::PathParamsMatcher matcher(pattern);
  11971. Request request;
  11972. request.path = "/users//";
  11973. ASSERT_TRUE(matcher.match(request));
  11974. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  11975. EXPECT_EQ(request.path_params, expected_params);
  11976. }
  11977. TEST(PathParamsTest, FragmentMismatch) {
  11978. const auto pattern = "/users/:id/";
  11979. detail::PathParamsMatcher matcher(pattern);
  11980. Request request;
  11981. request.path = "/admins/24/";
  11982. ASSERT_FALSE(matcher.match(request));
  11983. }
  11984. TEST(PathParamsTest, ExtraFragments) {
  11985. const auto pattern = "/users/:id";
  11986. detail::PathParamsMatcher matcher(pattern);
  11987. Request request;
  11988. request.path = "/users/42/subscriptions";
  11989. ASSERT_FALSE(matcher.match(request));
  11990. }
  11991. TEST(PathParamsTest, MissingTrailingParam) {
  11992. const auto pattern = "/users/:id";
  11993. detail::PathParamsMatcher matcher(pattern);
  11994. Request request;
  11995. request.path = "/users";
  11996. ASSERT_FALSE(matcher.match(request));
  11997. }
  11998. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11999. const auto pattern = "/users/:id/subscriptions";
  12000. detail::PathParamsMatcher matcher(pattern);
  12001. Request request;
  12002. request.path = "/users/subscriptions";
  12003. ASSERT_FALSE(matcher.match(request));
  12004. }
  12005. TEST(PathParamsTest, MultipleParams) {
  12006. const auto pattern = "/users/:userid/subscriptions/:subid";
  12007. detail::PathParamsMatcher matcher(pattern);
  12008. Request request;
  12009. request.path = "/users/42/subscriptions/2";
  12010. ASSERT_TRUE(matcher.match(request));
  12011. std::unordered_map<std::string, std::string> expected_params = {
  12012. {"userid", "42"}, {"subid", "2"}};
  12013. EXPECT_EQ(request.path_params, expected_params);
  12014. }
  12015. TEST(PathParamsTest, SequenceOfParams) {
  12016. const auto pattern = "/values/:x/:y/:z";
  12017. detail::PathParamsMatcher matcher(pattern);
  12018. Request request;
  12019. request.path = "/values/1/2/3";
  12020. ASSERT_TRUE(matcher.match(request));
  12021. std::unordered_map<std::string, std::string> expected_params = {
  12022. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12023. EXPECT_EQ(request.path_params, expected_params);
  12024. }
  12025. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12026. const auto pattern = "/prefix:suffix";
  12027. detail::PathParamsMatcher matcher(pattern);
  12028. Request request;
  12029. request.path = "/prefix:suffix";
  12030. ASSERT_TRUE(matcher.match(request));
  12031. const std::unordered_map<std::string, std::string> expected_params = {};
  12032. EXPECT_EQ(request.path_params, expected_params);
  12033. }
  12034. TEST(ParseUrlTest, VariousPatterns) {
  12035. {
  12036. detail::UrlComponents uc;
  12037. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12038. EXPECT_EQ("http", uc.scheme);
  12039. EXPECT_EQ("example.com", uc.host);
  12040. EXPECT_EQ("8080", uc.port);
  12041. EXPECT_EQ("/path", uc.path);
  12042. EXPECT_EQ("?q=1", uc.query);
  12043. }
  12044. {
  12045. detail::UrlComponents uc;
  12046. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12047. EXPECT_EQ("https", uc.scheme);
  12048. EXPECT_EQ("example.com", uc.host);
  12049. EXPECT_TRUE(uc.port.empty());
  12050. EXPECT_EQ("/path", uc.path);
  12051. }
  12052. {
  12053. detail::UrlComponents uc;
  12054. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12055. EXPECT_EQ("::1", uc.host);
  12056. EXPECT_EQ("8080", uc.port);
  12057. EXPECT_EQ("/path", uc.path);
  12058. }
  12059. {
  12060. detail::UrlComponents uc;
  12061. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12062. }
  12063. {
  12064. detail::UrlComponents uc;
  12065. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12066. EXPECT_TRUE(uc.scheme.empty());
  12067. EXPECT_EQ("example.com", uc.host);
  12068. EXPECT_EQ("/path", uc.path);
  12069. EXPECT_EQ("?q=1", uc.query);
  12070. }
  12071. {
  12072. detail::UrlComponents uc;
  12073. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12074. EXPECT_TRUE(uc.host.empty());
  12075. EXPECT_EQ("/path", uc.path);
  12076. EXPECT_EQ("?q=1", uc.query);
  12077. }
  12078. {
  12079. detail::UrlComponents uc;
  12080. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12081. EXPECT_EQ("example.com", uc.host);
  12082. EXPECT_EQ("8080", uc.port);
  12083. }
  12084. {
  12085. // Unix socket path — must not be parsed as host
  12086. detail::UrlComponents uc;
  12087. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12088. EXPECT_TRUE(uc.host.empty());
  12089. }
  12090. {
  12091. detail::UrlComponents uc;
  12092. ASSERT_TRUE(detail::parse_url("", uc));
  12093. EXPECT_TRUE(uc.host.empty());
  12094. EXPECT_TRUE(uc.path.empty());
  12095. }
  12096. {
  12097. detail::UrlComponents uc;
  12098. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12099. }
  12100. {
  12101. detail::UrlComponents uc;
  12102. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12103. }
  12104. {
  12105. // Accepted by parse_url; callers restrict to http/https
  12106. detail::UrlComponents uc;
  12107. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12108. EXPECT_EQ("ftp", uc.scheme);
  12109. }
  12110. {
  12111. detail::UrlComponents uc;
  12112. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12113. }
  12114. {
  12115. detail::UrlComponents uc;
  12116. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12117. }
  12118. }
  12119. TEST(ParseUrlTest, FragmentHandling) {
  12120. {
  12121. detail::UrlComponents uc;
  12122. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12123. EXPECT_EQ("/path", uc.path);
  12124. EXPECT_TRUE(uc.query.empty());
  12125. }
  12126. {
  12127. detail::UrlComponents uc;
  12128. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12129. EXPECT_TRUE(uc.path.empty());
  12130. EXPECT_TRUE(uc.query.empty());
  12131. }
  12132. }
  12133. TEST(ParseUrlTest, UserinfoHandling) {
  12134. // Userinfo with @ but no colon — host includes @
  12135. detail::UrlComponents uc;
  12136. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12137. EXPECT_EQ("user@host.com", uc.host);
  12138. EXPECT_EQ("/path", uc.path);
  12139. }
  12140. TEST(ParseUrlTest, IPv6EdgeCases) {
  12141. {
  12142. detail::UrlComponents uc;
  12143. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12144. EXPECT_TRUE(uc.scheme.empty());
  12145. EXPECT_EQ("::1", uc.host);
  12146. EXPECT_EQ("8080", uc.port);
  12147. }
  12148. {
  12149. // Zone ID '%25' is not in [a-fA-F0-9:]
  12150. detail::UrlComponents uc;
  12151. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12152. }
  12153. }
  12154. TEST(ParseUrlTest, SchemeEdgeCases) {
  12155. {
  12156. detail::UrlComponents uc;
  12157. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12158. }
  12159. {
  12160. detail::UrlComponents uc;
  12161. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12162. }
  12163. {
  12164. detail::UrlComponents uc;
  12165. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12166. }
  12167. }
  12168. TEST(ParseUrlTest, PortEdgeCases) {
  12169. {
  12170. detail::UrlComponents uc;
  12171. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12172. EXPECT_TRUE(uc.port.empty());
  12173. EXPECT_EQ("/path", uc.path);
  12174. }
  12175. {
  12176. // parse_url accepts any port string; validation is done by parse_port
  12177. detail::UrlComponents uc;
  12178. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12179. EXPECT_EQ("abc", uc.port);
  12180. }
  12181. }
  12182. TEST(ParseUrlTest, WebSocketPatterns) {
  12183. {
  12184. detail::UrlComponents uc;
  12185. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12186. EXPECT_EQ("ws", uc.scheme);
  12187. EXPECT_EQ("echo.example.com", uc.host);
  12188. EXPECT_EQ("8080", uc.port);
  12189. EXPECT_EQ("/ws", uc.path);
  12190. }
  12191. {
  12192. detail::UrlComponents uc;
  12193. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12194. EXPECT_EQ("wss", uc.scheme);
  12195. EXPECT_EQ("echo.example.com", uc.host);
  12196. EXPECT_TRUE(uc.port.empty());
  12197. EXPECT_EQ("/ws", uc.path);
  12198. }
  12199. }
  12200. TEST(ParseUrlTest, QueryOnly) {
  12201. detail::UrlComponents uc;
  12202. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12203. EXPECT_TRUE(uc.host.empty());
  12204. EXPECT_TRUE(uc.path.empty());
  12205. EXPECT_EQ("?q=1&r=2", uc.query);
  12206. }
  12207. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12208. detail::UrlComponents uc;
  12209. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12210. EXPECT_TRUE(uc.scheme.empty());
  12211. EXPECT_EQ("example.com", uc.host);
  12212. EXPECT_EQ("443", uc.port);
  12213. EXPECT_EQ("/path", uc.path);
  12214. }
  12215. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12216. // If ipv6 regex working, regex match codepath is taken.
  12217. // else port will default to 80 in Client impl
  12218. int clientImplMagicPort = 80;
  12219. int port = 4321;
  12220. // above ports must be different to avoid false negative
  12221. EXPECT_NE(clientImplMagicPort, port);
  12222. std::string ipV6TestURL = "http://[ff06::c3]";
  12223. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12224. CLIENT_PRIVATE_KEY_FILE);
  12225. EXPECT_EQ(cli.port(), port);
  12226. }
  12227. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12228. auto file_path = "./www/dir/index.html";
  12229. auto dir_path = "./www/dir";
  12230. detail::FileStat stat_file(file_path);
  12231. EXPECT_TRUE(stat_file.is_file());
  12232. EXPECT_FALSE(stat_file.is_dir());
  12233. detail::FileStat stat_dir(dir_path);
  12234. EXPECT_FALSE(stat_dir.is_file());
  12235. EXPECT_TRUE(stat_dir.is_dir());
  12236. }
  12237. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12238. // IPv4 with default HTTP port (80)
  12239. EXPECT_EQ("example.com",
  12240. detail::make_host_and_port_string("example.com", 80, false));
  12241. // IPv4 with default HTTPS port (443)
  12242. EXPECT_EQ("example.com",
  12243. detail::make_host_and_port_string("example.com", 443, true));
  12244. // IPv4 with non-default HTTP port
  12245. EXPECT_EQ("example.com:8080",
  12246. detail::make_host_and_port_string("example.com", 8080, false));
  12247. // IPv4 with non-default HTTPS port
  12248. EXPECT_EQ("example.com:8443",
  12249. detail::make_host_and_port_string("example.com", 8443, true));
  12250. // IPv6 with default HTTP port (80)
  12251. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12252. // IPv6 with default HTTPS port (443)
  12253. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12254. // IPv6 with non-default HTTP port
  12255. EXPECT_EQ("[::1]:8080",
  12256. detail::make_host_and_port_string("::1", 8080, false));
  12257. // IPv6 with non-default HTTPS port
  12258. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12259. // IPv6 full address with default port
  12260. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12261. detail::make_host_and_port_string(
  12262. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12263. // IPv6 full address with non-default port
  12264. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12265. detail::make_host_and_port_string(
  12266. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12267. // IPv6 localhost with non-default port
  12268. EXPECT_EQ("[::1]:3000",
  12269. detail::make_host_and_port_string("::1", 3000, false));
  12270. // IPv6 with zone ID (link-local address) with default port
  12271. EXPECT_EQ("[fe80::1%eth0]",
  12272. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12273. // IPv6 with zone ID (link-local address) with non-default port
  12274. EXPECT_EQ("[fe80::1%eth0]:8080",
  12275. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12276. // Edge case: Port 443 with is_ssl=false (should add port)
  12277. EXPECT_EQ("example.com:443",
  12278. detail::make_host_and_port_string("example.com", 443, false));
  12279. // Edge case: Port 80 with is_ssl=true (should add port)
  12280. EXPECT_EQ("example.com:80",
  12281. detail::make_host_and_port_string("example.com", 80, true));
  12282. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12283. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12284. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12285. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12286. // Security fix: Already bracketed IPv6 should not get double brackets
  12287. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12288. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12289. EXPECT_EQ("[::1]:8080",
  12290. detail::make_host_and_port_string("[::1]", 8080, false));
  12291. EXPECT_EQ("[2001:db8::1]:8080",
  12292. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12293. EXPECT_EQ("[fe80::1%eth0]",
  12294. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12295. EXPECT_EQ("[fe80::1%eth0]:8080",
  12296. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12297. // Edge case: Empty host (should return as-is)
  12298. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12299. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12300. // This is a known limitation but shouldn't crash
  12301. EXPECT_EQ("[host:name]",
  12302. detail::make_host_and_port_string("host:name", 80, false));
  12303. // Port number edge cases (no validation, but should not crash)
  12304. EXPECT_EQ("example.com:0",
  12305. detail::make_host_and_port_string("example.com", 0, false));
  12306. EXPECT_EQ("example.com:-1",
  12307. detail::make_host_and_port_string("example.com", -1, false));
  12308. EXPECT_EQ("example.com:65535",
  12309. detail::make_host_and_port_string("example.com", 65535, false));
  12310. EXPECT_EQ("example.com:65536",
  12311. detail::make_host_and_port_string("example.com", 65536, false));
  12312. }
  12313. #ifdef CPPHTTPLIB_SSL_ENABLED
  12314. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12315. httplib::SSLClient cli("roblox.com", 443);
  12316. cli.set_follow_location(true);
  12317. auto res = cli.Get("/");
  12318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12319. EXPECT_EQ(StatusCode::OK_200, res->status);
  12320. }
  12321. #endif
  12322. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12323. Server svr;
  12324. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12325. EXPECT_EQ(res.status, 400);
  12326. });
  12327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12328. auto se = detail::scope_exit([&] {
  12329. svr.stop();
  12330. thread.join();
  12331. ASSERT_FALSE(svr.is_running());
  12332. });
  12333. svr.wait_until_ready();
  12334. Client cli(HOST, PORT);
  12335. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12336. }
  12337. TEST(InvalidHeaderCharsTest, is_field_name) {
  12338. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12339. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12340. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12341. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12342. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12343. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12344. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12345. EXPECT_FALSE(detail::fields::is_field_name(""));
  12346. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12347. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12348. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12349. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12350. }
  12351. TEST(InvalidHeaderCharsTest, is_field_value) {
  12352. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12353. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12354. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12355. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12356. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12357. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12358. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12359. EXPECT_TRUE(detail::fields::is_field_value(""));
  12360. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12361. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12362. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12363. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12364. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12365. }
  12366. TEST(InvalidHeaderCharsTest, OnServer) {
  12367. Server svr;
  12368. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12369. std::string header = "Not Set";
  12370. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12371. res.set_header(header, "value");
  12372. res.set_content("Page Content Page Content", "text/plain");
  12373. });
  12374. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12375. std::string header = "Not Set";
  12376. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12377. res.set_header("X-Test", header);
  12378. res.set_content("Page Content Page Content", "text/plain");
  12379. });
  12380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. thread.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. });
  12386. svr.wait_until_ready();
  12387. Client cli(HOST, PORT);
  12388. {
  12389. auto res = cli.Get(
  12390. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12392. EXPECT_EQ("Page Content Page Content", res->body);
  12393. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12394. }
  12395. {
  12396. auto res = cli.Get(
  12397. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12399. EXPECT_EQ("Page Content Page Content", res->body);
  12400. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12401. }
  12402. }
  12403. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12404. auto handled = false;
  12405. Server svr;
  12406. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12407. thread t = thread([&] { svr.listen(HOST, PORT); });
  12408. auto se = detail::scope_exit([&] {
  12409. svr.stop();
  12410. t.join();
  12411. ASSERT_FALSE(svr.is_running());
  12412. ASSERT_FALSE(handled);
  12413. });
  12414. svr.wait_until_ready();
  12415. auto req = "POST /test HTTP/1.1\r\n"
  12416. "Content-Length: x\r\n"
  12417. "\r\n";
  12418. std::string response;
  12419. ASSERT_TRUE(send_request(1, req, &response));
  12420. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12421. response.substr(0, response.find("\r\n")));
  12422. }
  12423. #ifndef _WIN32
  12424. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12425. static constexpr char reject[] = "Unauthorized";
  12426. static constexpr char accept[] = "Upload accepted";
  12427. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12428. Server svr;
  12429. svr.set_expect_100_continue_handler(
  12430. [](const Request & /*req*/, Response &res) {
  12431. res.status = StatusCode::Unauthorized_401;
  12432. res.set_content(reject, "text/plain");
  12433. return res.status;
  12434. });
  12435. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12436. res.set_content(accept, "text/plain");
  12437. });
  12438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12439. auto se = detail::scope_exit([&] {
  12440. svr.stop();
  12441. thread.join();
  12442. ASSERT_FALSE(svr.is_running());
  12443. });
  12444. svr.wait_until_ready();
  12445. {
  12446. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12447. curl_easy_init(), &curl_easy_cleanup};
  12448. ASSERT_NE(curl, nullptr);
  12449. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12450. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12451. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12452. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12453. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12454. &curl_slist_free_all};
  12455. ASSERT_NE(list, nullptr);
  12456. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12457. struct read_data {
  12458. size_t read_size;
  12459. size_t total_size;
  12460. } data = {0, total_size};
  12461. using read_callback_t =
  12462. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12463. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12464. void *userdata) -> size_t {
  12465. read_data *d = (read_data *)userdata;
  12466. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12467. std::fill_n(ptr, size * nmemb, 'A');
  12468. d->read_size += size * nmemb;
  12469. return size * nmemb;
  12470. };
  12471. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12472. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12473. std::vector<char> buffer;
  12474. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12475. using write_callback_t =
  12476. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12477. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12478. void *userdata) -> size_t {
  12479. std::vector<char> *buf = (std::vector<char> *)userdata;
  12480. buf->reserve(buf->size() + size * nmemb + 1);
  12481. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12482. return size * nmemb;
  12483. };
  12484. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12485. {
  12486. const auto res = curl_easy_perform(curl.get());
  12487. ASSERT_EQ(res, CURLE_OK);
  12488. }
  12489. {
  12490. auto response_code = long{};
  12491. const auto res =
  12492. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12493. ASSERT_EQ(res, CURLE_OK);
  12494. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12495. }
  12496. {
  12497. auto dl = curl_off_t{};
  12498. const auto res =
  12499. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12500. ASSERT_EQ(res, CURLE_OK);
  12501. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12502. }
  12503. {
  12504. buffer.push_back('\0');
  12505. ASSERT_STRCASEEQ(buffer.data(), reject);
  12506. }
  12507. }
  12508. }
  12509. #endif
  12510. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12511. // Regression test for #2458.
  12512. //
  12513. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12514. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12515. // ticket can make the client socket spuriously readable during the
  12516. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12517. // the client withholds the body and then blocks reading a response that never
  12518. // comes, failing with `Failed to read connection`.
  12519. //
  12520. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12521. // within the timeout. This raw OpenSSL server deliberately never sends
  12522. // `100 Continue`; the client must still deliver the body and receive 200.
  12523. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12524. signal(SIGPIPE, SIG_IGN);
  12525. const auto port = PORT + 4;
  12526. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12527. ASSERT_NE(srv, INVALID_SOCKET);
  12528. int opt = 1;
  12529. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12530. sockaddr_in addr{};
  12531. addr.sin_family = AF_INET;
  12532. addr.sin_port = htons(static_cast<uint16_t>(port));
  12533. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12534. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12535. ASSERT_EQ(0, ::listen(srv, 1));
  12536. std::atomic<size_t> server_body_bytes{0};
  12537. auto server_thread = std::thread([&] {
  12538. sockaddr_in cli_addr{};
  12539. socklen_t cli_len = sizeof(cli_addr);
  12540. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12541. if (cli == INVALID_SOCKET) { return; }
  12542. // Bound the lifetime of the server side so a buggy client (which never
  12543. // sends the body) cannot make this thread block forever on join.
  12544. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12545. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12546. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12547. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12548. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12549. SSL *ssl = SSL_new(ctx);
  12550. SSL_set_fd(ssl, static_cast<int>(cli));
  12551. if (SSL_accept(ssl) > 0) {
  12552. // Read the request headers. Reading here also flushes the TLS 1.3
  12553. // session tickets to the client. Deliberately do NOT send
  12554. // `100 Continue`.
  12555. std::string buf;
  12556. char tmp[1024];
  12557. while (buf.find("\r\n\r\n") == std::string::npos) {
  12558. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12559. if (n <= 0) { break; }
  12560. buf.append(tmp, static_cast<size_t>(n));
  12561. }
  12562. // A correct client sends the body now; count what arrives.
  12563. auto pos = buf.find("\r\n\r\n");
  12564. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12565. while (body < 4096) {
  12566. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12567. if (n <= 0) { break; }
  12568. body += static_cast<size_t>(n);
  12569. }
  12570. server_body_bytes = body;
  12571. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12572. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12573. SSL_shutdown(ssl);
  12574. }
  12575. SSL_free(ssl);
  12576. detail::close_socket(cli);
  12577. SSL_CTX_free(ctx);
  12578. });
  12579. auto se = detail::scope_exit([&] {
  12580. server_thread.join();
  12581. detail::close_socket(srv);
  12582. });
  12583. SSLClient cli("127.0.0.1", port);
  12584. cli.enable_server_certificate_verification(false);
  12585. cli.set_connection_timeout(5, 0);
  12586. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12587. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12588. std::string body(4096, 'A');
  12589. auto res = cli.Put("/api/test", body, "application/json");
  12590. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12591. EXPECT_EQ(StatusCode::OK_200, res->status);
  12592. EXPECT_EQ(body.size(), server_body_bytes.load());
  12593. }
  12594. #endif
  12595. template <typename S, typename C>
  12596. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12597. svr.Get("/stream", [&](const Request &, Response &res) {
  12598. auto data = new std::string("01234567890123456789");
  12599. res.set_content_provider(
  12600. data->size(), "text/plain",
  12601. [&, data](size_t offset, size_t length, DataSink &sink) {
  12602. const size_t DATA_CHUNK_SIZE = 4;
  12603. const auto &d = *data;
  12604. std::this_thread::sleep_for(std::chrono::seconds(1));
  12605. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12606. return true;
  12607. },
  12608. [data](bool success) {
  12609. EXPECT_FALSE(success);
  12610. delete data;
  12611. });
  12612. });
  12613. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12614. auto i = new size_t(0);
  12615. res.set_content_provider(
  12616. "text/plain",
  12617. [i](size_t, DataSink &sink) {
  12618. if (*i < 5) {
  12619. std::this_thread::sleep_for(std::chrono::seconds(1));
  12620. sink.write("abcd", 4);
  12621. (*i)++;
  12622. } else {
  12623. sink.done();
  12624. }
  12625. return true;
  12626. },
  12627. [i](bool success) {
  12628. EXPECT_FALSE(success);
  12629. delete i;
  12630. });
  12631. });
  12632. svr.Get("/chunked", [&](const Request &, Response &res) {
  12633. auto i = new size_t(0);
  12634. res.set_chunked_content_provider(
  12635. "text/plain",
  12636. [i](size_t, DataSink &sink) {
  12637. if (*i < 5) {
  12638. std::this_thread::sleep_for(std::chrono::seconds(1));
  12639. sink.os << "abcd";
  12640. (*i)++;
  12641. } else {
  12642. sink.done();
  12643. }
  12644. return true;
  12645. },
  12646. [i](bool success) {
  12647. EXPECT_FALSE(success);
  12648. delete i;
  12649. });
  12650. });
  12651. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12652. auto se = detail::scope_exit([&] {
  12653. svr.stop();
  12654. listen_thread.join();
  12655. ASSERT_FALSE(svr.is_running());
  12656. });
  12657. svr.wait_until_ready();
  12658. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12659. {
  12660. auto start = std::chrono::steady_clock::now();
  12661. auto res = cli.Get("/stream");
  12662. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12663. std::chrono::steady_clock::now() - start)
  12664. .count();
  12665. ASSERT_FALSE(res);
  12666. EXPECT_EQ(Error::Read, res.error());
  12667. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12668. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12669. }
  12670. {
  12671. auto start = std::chrono::steady_clock::now();
  12672. auto res = cli.Get("/stream_without_length");
  12673. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12674. std::chrono::steady_clock::now() - start)
  12675. .count();
  12676. ASSERT_FALSE(res);
  12677. EXPECT_EQ(Error::Read, res.error());
  12678. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12679. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12680. }
  12681. {
  12682. auto start = std::chrono::steady_clock::now();
  12683. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12684. EXPECT_EQ("abcd", string(data, data_length));
  12685. return true;
  12686. });
  12687. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12688. std::chrono::steady_clock::now() - start)
  12689. .count();
  12690. ASSERT_FALSE(res);
  12691. EXPECT_EQ(Error::Read, res.error());
  12692. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12693. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12694. }
  12695. }
  12696. TEST(MaxTimeoutTest, ContentStream) {
  12697. time_t timeout = 2000;
  12698. time_t threshold = 200;
  12699. Server svr;
  12700. Client cli("localhost", PORT);
  12701. max_timeout_test(svr, cli, timeout, threshold);
  12702. }
  12703. #ifdef CPPHTTPLIB_SSL_ENABLED
  12704. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12705. time_t timeout = 2000;
  12706. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12708. SSLClient cli("localhost", PORT);
  12709. cli.enable_server_certificate_verification(false);
  12710. max_timeout_test(svr, cli, timeout, threshold);
  12711. }
  12712. #endif
  12713. class EventDispatcher {
  12714. public:
  12715. EventDispatcher() {}
  12716. bool wait_event(DataSink *sink) {
  12717. unique_lock<mutex> lk(m_);
  12718. int id = id_;
  12719. // Wait with timeout to prevent hanging if client disconnects
  12720. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12721. [&] { return cid_ == id; })) {
  12722. return false; // Timeout occurred
  12723. }
  12724. sink->write(message_.data(), message_.size());
  12725. return true;
  12726. }
  12727. void send_event(const string &message) {
  12728. lock_guard<mutex> lk(m_);
  12729. cid_ = id_++;
  12730. message_ = message;
  12731. cv_.notify_all();
  12732. }
  12733. private:
  12734. mutex m_;
  12735. condition_variable cv_;
  12736. atomic_int id_{0};
  12737. atomic_int cid_{-1};
  12738. string message_;
  12739. };
  12740. TEST(ClientInThreadTest, Issue2068) {
  12741. EventDispatcher ed;
  12742. Server svr;
  12743. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12744. res.set_chunked_content_provider("text/event-stream",
  12745. [&](size_t /*offset*/, DataSink &sink) {
  12746. return ed.wait_event(&sink);
  12747. });
  12748. });
  12749. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12750. svr.wait_until_ready();
  12751. thread event_thread([&] {
  12752. int id = 0;
  12753. while (svr.is_running()) {
  12754. this_thread::sleep_for(chrono::milliseconds(500));
  12755. std::stringstream ss;
  12756. ss << "data: " << id << "\n\n";
  12757. ed.send_event(ss.str());
  12758. id++;
  12759. }
  12760. });
  12761. auto se = detail::scope_exit([&] {
  12762. svr.stop();
  12763. listen_thread.join();
  12764. event_thread.join();
  12765. ASSERT_FALSE(svr.is_running());
  12766. });
  12767. {
  12768. auto client = detail::make_unique<Client>(HOST, PORT);
  12769. client->set_read_timeout(std::chrono::minutes(10));
  12770. std::atomic<bool> stop{false};
  12771. std::thread t([&] {
  12772. client->Get("/event1",
  12773. [&](const char *, size_t) -> bool { return !stop; });
  12774. });
  12775. std::this_thread::sleep_for(std::chrono::seconds(2));
  12776. stop = true;
  12777. client->stop();
  12778. t.join();
  12779. // Reset client after thread has finished
  12780. client.reset();
  12781. }
  12782. }
  12783. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  12784. auto handled = false;
  12785. Server svr;
  12786. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12787. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12788. auto se = detail::scope_exit([&] {
  12789. svr.stop();
  12790. t.join();
  12791. ASSERT_FALSE(svr.is_running());
  12792. ASSERT_FALSE(handled);
  12793. });
  12794. svr.wait_until_ready();
  12795. // Two Content-Length headers with different values — must be rejected
  12796. auto req = "POST /test HTTP/1.1\r\n"
  12797. "Content-Length: 5\r\n"
  12798. "Content-Length: 10\r\n"
  12799. "\r\n"
  12800. "hello";
  12801. std::string response;
  12802. ASSERT_TRUE(send_request(1, req, &response));
  12803. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12804. response.substr(0, response.find("\r\n")));
  12805. }
  12806. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  12807. auto handled = false;
  12808. Server svr;
  12809. svr.Post("/test", [&](const Request &, Response &res) {
  12810. handled = true;
  12811. res.set_content("ok", "text/plain");
  12812. });
  12813. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop();
  12816. t.join();
  12817. ASSERT_FALSE(svr.is_running());
  12818. ASSERT_TRUE(handled);
  12819. });
  12820. svr.wait_until_ready();
  12821. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  12822. auto req = "POST /test HTTP/1.1\r\n"
  12823. "Content-Length: 5\r\n"
  12824. "Content-Length: 5\r\n"
  12825. "\r\n"
  12826. "hello";
  12827. std::string response;
  12828. ASSERT_TRUE(send_request(1, req, &response));
  12829. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  12830. }
  12831. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  12832. Server svr;
  12833. svr.Get("/", [](const Request &req, Response &res) {
  12834. EXPECT_EQ(2U, req.trailers.size());
  12835. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  12836. // Denied
  12837. EXPECT_FALSE(req.has_trailer("Content-Length"));
  12838. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  12839. // Accepted
  12840. EXPECT_TRUE(req.has_trailer("X-Hello"));
  12841. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  12842. EXPECT_TRUE(req.has_trailer("X-World"));
  12843. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  12844. res.set_content("ok", "text/plain");
  12845. });
  12846. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12847. auto se = detail::scope_exit([&] {
  12848. svr.stop();
  12849. t.join();
  12850. ASSERT_FALSE(svr.is_running());
  12851. });
  12852. svr.wait_until_ready();
  12853. const std::string req = "GET / HTTP/1.1\r\n"
  12854. "Transfer-Encoding: chunked\r\n"
  12855. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  12856. "\r\n"
  12857. "0\r\n"
  12858. "Content-Length: 10\r\n"
  12859. "Host: internal.local\r\n"
  12860. "Content-Type: malicious/content\r\n"
  12861. "Cookie: any\r\n"
  12862. "Set-Cookie: any\r\n"
  12863. "X-Forwarded-For: attacker.com\r\n"
  12864. "X-Real-Ip: 1.1.1.1\r\n"
  12865. "X-Hello: hello\r\n"
  12866. "X-World: world\r\n"
  12867. "\r\n";
  12868. std::string res;
  12869. ASSERT_TRUE(send_request(1, req, &res));
  12870. }
  12871. // A direct client that is not listed in trusted_proxies must not be able to
  12872. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  12873. // the peer address on the actual TCP connection determines whether the
  12874. // header is honored.
  12875. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  12876. Server svr;
  12877. // Deliberately does NOT include the loopback address the test client
  12878. // actually connects from, so the direct connection is not a trusted proxy.
  12879. svr.set_trusted_proxies({"203.0.113.66"});
  12880. std::string observed_remote_addr;
  12881. svr.Get("/ip", [&](const Request &req, Response &res) {
  12882. observed_remote_addr = req.remote_addr;
  12883. res.set_content("ok", "text/plain");
  12884. });
  12885. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12886. auto se = detail::scope_exit([&] {
  12887. svr.stop();
  12888. t.join();
  12889. ASSERT_FALSE(svr.is_running());
  12890. });
  12891. svr.wait_until_ready();
  12892. Client cli(HOST, PORT);
  12893. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  12894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12895. EXPECT_EQ(StatusCode::OK_200, res->status);
  12896. // The connecting peer is not a trusted proxy, so the spoofed header must be
  12897. // ignored entirely and the real connection-level address retained.
  12898. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12899. observed_remote_addr == "127.0.0.1");
  12900. }
  12901. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  12902. Server svr;
  12903. std::string observed_remote_addr;
  12904. std::string observed_xff;
  12905. svr.Get("/ip", [&](const Request &req, Response &res) {
  12906. observed_remote_addr = req.remote_addr;
  12907. observed_xff = req.get_header_value("X-Forwarded-For");
  12908. res.set_content("ok", "text/plain");
  12909. });
  12910. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12911. auto se = detail::scope_exit([&] {
  12912. svr.stop();
  12913. t.join();
  12914. ASSERT_FALSE(svr.is_running());
  12915. });
  12916. svr.wait_until_ready();
  12917. Client cli(HOST, PORT);
  12918. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  12919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12920. EXPECT_EQ(StatusCode::OK_200, res->status);
  12921. EXPECT_EQ(observed_xff, "203.0.113.66");
  12922. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12923. observed_remote_addr == "127.0.0.1");
  12924. }
  12925. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  12926. Server svr;
  12927. svr.set_trusted_proxies({"203.0.113.66"});
  12928. std::string observed_remote_addr;
  12929. std::string observed_xff;
  12930. svr.Get("/ip", [&](const Request &req, Response &res) {
  12931. observed_remote_addr = req.remote_addr;
  12932. observed_xff = req.get_header_value("X-Forwarded-For");
  12933. res.set_content("ok", "text/plain");
  12934. });
  12935. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12936. auto se = detail::scope_exit([&] {
  12937. svr.stop();
  12938. t.join();
  12939. ASSERT_FALSE(svr.is_running());
  12940. });
  12941. svr.wait_until_ready();
  12942. Client cli(HOST, PORT);
  12943. auto res = cli.Get("/ip");
  12944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12945. EXPECT_EQ(StatusCode::OK_200, res->status);
  12946. EXPECT_EQ(observed_xff, "");
  12947. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12948. observed_remote_addr == "127.0.0.1");
  12949. }
  12950. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  12951. Server svr;
  12952. // Include the loopback address the test client actually connects from, so
  12953. // the direct connection itself is recognized as the trusted proxy hop.
  12954. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  12955. std::string observed_remote_addr;
  12956. std::string observed_xff;
  12957. svr.Get("/ip", [&](const Request &req, Response &res) {
  12958. observed_remote_addr = req.remote_addr;
  12959. observed_xff = req.get_header_value("X-Forwarded-For");
  12960. res.set_content("ok", "text/plain");
  12961. });
  12962. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12963. auto se = detail::scope_exit([&] {
  12964. svr.stop();
  12965. t.join();
  12966. ASSERT_FALSE(svr.is_running());
  12967. });
  12968. svr.wait_until_ready();
  12969. Client cli(HOST, PORT);
  12970. auto res = cli.Get(
  12971. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  12972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12973. EXPECT_EQ(StatusCode::OK_200, res->status);
  12974. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  12975. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12976. }
  12977. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  12978. Server svr;
  12979. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  12980. std::string observed_remote_addr;
  12981. std::string observed_xff;
  12982. svr.Get("/ip", [&](const Request &req, Response &res) {
  12983. observed_remote_addr = req.remote_addr;
  12984. observed_xff = req.get_header_value("X-Forwarded-For");
  12985. res.set_content("ok", "text/plain");
  12986. });
  12987. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12988. auto se = detail::scope_exit([&] {
  12989. svr.stop();
  12990. t.join();
  12991. ASSERT_FALSE(svr.is_running());
  12992. });
  12993. svr.wait_until_ready();
  12994. Client cli(HOST, PORT);
  12995. auto res = cli.Get(
  12996. "/ip",
  12997. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12999. EXPECT_EQ(StatusCode::OK_200, res->status);
  13000. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13001. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13002. }
  13003. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13004. Server svr;
  13005. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13006. std::string observed_remote_addr;
  13007. std::string observed_xff;
  13008. svr.Get("/ip", [&](const Request &req, Response &res) {
  13009. observed_remote_addr = req.remote_addr;
  13010. observed_xff = req.get_header_value("X-Forwarded-For");
  13011. res.set_content("ok", "text/plain");
  13012. });
  13013. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13014. auto se = detail::scope_exit([&] {
  13015. svr.stop();
  13016. t.join();
  13017. ASSERT_FALSE(svr.is_running());
  13018. });
  13019. svr.wait_until_ready();
  13020. Client cli(HOST, PORT);
  13021. auto res = cli.Get(
  13022. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13024. EXPECT_EQ(StatusCode::OK_200, res->status);
  13025. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13026. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13027. // and must not be selected.
  13028. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13029. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13030. }
  13031. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13032. Server svr;
  13033. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13034. std::string observed_remote_addr;
  13035. svr.Get("/ip", [&](const Request &req, Response &res) {
  13036. observed_remote_addr = req.remote_addr;
  13037. res.set_content("ok", "text/plain");
  13038. });
  13039. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13040. auto se = detail::scope_exit([&] {
  13041. svr.stop();
  13042. t.join();
  13043. ASSERT_FALSE(svr.is_running());
  13044. });
  13045. svr.wait_until_ready();
  13046. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13047. // a forged address and the trusted proxy's own address; the forged value must
  13048. // not win over the address the trusted proxy actually recorded.
  13049. Client cli(HOST, PORT);
  13050. auto res = cli.Get(
  13051. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13053. EXPECT_EQ(StatusCode::OK_200, res->status);
  13054. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13055. }
  13056. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13057. Server svr;
  13058. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13059. std::string observed_remote_addr;
  13060. std::string observed_xff;
  13061. svr.Get("/ip", [&](const Request &req, Response &res) {
  13062. observed_remote_addr = req.remote_addr;
  13063. observed_xff = req.get_header_value("X-Forwarded-For");
  13064. res.set_content("ok", "text/plain");
  13065. });
  13066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13067. auto se = detail::scope_exit([&] {
  13068. svr.stop();
  13069. t.join();
  13070. ASSERT_FALSE(svr.is_running());
  13071. });
  13072. svr.wait_until_ready();
  13073. Client cli(HOST, PORT);
  13074. auto res = cli.Get(
  13075. "/ip",
  13076. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13078. EXPECT_EQ(StatusCode::OK_200, res->status);
  13079. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13080. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13081. }
  13082. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13083. Server svr;
  13084. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13085. std::string observed_remote_addr;
  13086. std::string observed_xff;
  13087. svr.Get("/ip", [&](const Request &req, Response &res) {
  13088. observed_remote_addr = req.remote_addr;
  13089. observed_xff = req.get_header_value("X-Forwarded-For");
  13090. res.set_content("ok", "text/plain");
  13091. });
  13092. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13093. auto se = detail::scope_exit([&] {
  13094. svr.stop();
  13095. t.join();
  13096. ASSERT_FALSE(svr.is_running());
  13097. });
  13098. svr.wait_until_ready();
  13099. std::string raw_req =
  13100. "GET /ip HTTP/1.1\r\n"
  13101. "Host: localhost\r\n"
  13102. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13103. "Connection: close\r\n"
  13104. "\r\n";
  13105. std::string out;
  13106. ASSERT_TRUE(send_request(5, raw_req, &out));
  13107. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13108. // Header parser trims surrounding whitespace of the header value
  13109. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13110. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13111. }
  13112. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13113. // crash the server (it used to call front() on an empty vector inside
  13114. // get_client_ip). The connection-level remote address must be retained instead.
  13115. static void run_malformed_xff_test(const std::string &xff_value) {
  13116. Server svr;
  13117. svr.set_trusted_proxies({"192.0.2.45"});
  13118. std::string observed_remote_addr;
  13119. svr.Get("/ip", [&](const Request &req, Response &res) {
  13120. observed_remote_addr = req.remote_addr;
  13121. res.set_content("ok", "text/plain");
  13122. });
  13123. int port = 0;
  13124. thread t = thread([&]() {
  13125. port = svr.bind_to_any_port(HOST);
  13126. svr.listen_after_bind();
  13127. });
  13128. auto se = detail::scope_exit([&] {
  13129. svr.stop();
  13130. t.join();
  13131. ASSERT_FALSE(svr.is_running());
  13132. });
  13133. svr.wait_until_ready();
  13134. Client cli(HOST, port);
  13135. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13137. EXPECT_EQ(StatusCode::OK_200, res->status);
  13138. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13139. observed_remote_addr == "127.0.0.1");
  13140. }
  13141. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13142. run_malformed_xff_test("");
  13143. }
  13144. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13145. run_malformed_xff_test(",");
  13146. }
  13147. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13148. run_malformed_xff_test(", , ,");
  13149. }
  13150. #ifndef _WIN32
  13151. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13152. Server svr;
  13153. svr.Post("/post", [&](const Request &req, Response &res) {
  13154. res.set_content(req.body, "text/plain");
  13155. });
  13156. svr.Put("/put", [&](const Request &req, Response &res) {
  13157. res.set_content(req.body, "text/plain");
  13158. });
  13159. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13160. res.set_content(req.body, "text/plain");
  13161. });
  13162. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13163. res.set_content(req.body, "text/plain");
  13164. });
  13165. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13166. auto se = detail::scope_exit([&] {
  13167. svr.stop();
  13168. t.join();
  13169. ASSERT_FALSE(svr.is_running());
  13170. });
  13171. svr.wait_until_ready();
  13172. std::string resp;
  13173. // POST without Content-Length
  13174. ASSERT_TRUE(send_request(5,
  13175. "POST /post HTTP/1.1\r\n"
  13176. "Host: localhost\r\n"
  13177. "Connection: close\r\n"
  13178. "\r\n",
  13179. &resp));
  13180. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13181. // PUT without Content-Length
  13182. resp.clear();
  13183. ASSERT_TRUE(send_request(5,
  13184. "PUT /put HTTP/1.1\r\n"
  13185. "Host: localhost\r\n"
  13186. "Connection: close\r\n"
  13187. "\r\n",
  13188. &resp));
  13189. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13190. // PATCH without Content-Length
  13191. resp.clear();
  13192. ASSERT_TRUE(send_request(5,
  13193. "PATCH /patch HTTP/1.1\r\n"
  13194. "Host: localhost\r\n"
  13195. "Connection: close\r\n"
  13196. "\r\n",
  13197. &resp));
  13198. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13199. // DELETE without Content-Length
  13200. resp.clear();
  13201. ASSERT_TRUE(send_request(5,
  13202. "DELETE /delete HTTP/1.1\r\n"
  13203. "Host: localhost\r\n"
  13204. "Connection: close\r\n"
  13205. "\r\n",
  13206. &resp));
  13207. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13208. }
  13209. #endif
  13210. //==============================================================================
  13211. // open_stream() Tests
  13212. //==============================================================================
  13213. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13214. std::string result;
  13215. char buf[8192];
  13216. ssize_t n;
  13217. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13218. result.append(buf, static_cast<size_t>(n));
  13219. }
  13220. return result;
  13221. }
  13222. // Mock stream for unit tests
  13223. class MockStream : public Stream {
  13224. public:
  13225. std::string data;
  13226. size_t pos = 0;
  13227. ssize_t error_after = -1; // -1 = no error
  13228. explicit MockStream(const std::string &d, ssize_t err = -1)
  13229. : data(d), error_after(err) {}
  13230. bool is_readable() const override { return true; }
  13231. bool wait_readable() const override { return true; }
  13232. bool wait_writable() const override { return true; }
  13233. ssize_t read(char *ptr, size_t size) override {
  13234. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13235. if (pos >= data.size()) return 0;
  13236. size_t limit =
  13237. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13238. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13239. std::memcpy(ptr, data.data() + pos, to_read);
  13240. pos += to_read;
  13241. return static_cast<ssize_t>(to_read);
  13242. }
  13243. ssize_t write(const char *, size_t) override { return -1; }
  13244. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13245. ip = "127.0.0.1";
  13246. port = 0;
  13247. }
  13248. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13249. ip = "127.0.0.1";
  13250. port = 0;
  13251. }
  13252. socket_t socket() const override { return INVALID_SOCKET; }
  13253. time_t duration() const override { return 0; }
  13254. };
  13255. TEST(StreamHandleTest, Basic) {
  13256. ClientImpl::StreamHandle handle;
  13257. EXPECT_FALSE(handle.is_valid());
  13258. handle.response = detail::make_unique<Response>();
  13259. handle.error = Error::Connection;
  13260. EXPECT_FALSE(handle.is_valid());
  13261. handle.error = Error::Success;
  13262. EXPECT_TRUE(handle.is_valid());
  13263. }
  13264. TEST(BodyReaderTest, Basic) {
  13265. MockStream stream("Hello, World!");
  13266. detail::BodyReader reader;
  13267. reader.stream = &stream;
  13268. reader.content_length = 13;
  13269. char buf[32];
  13270. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13271. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13272. EXPECT_TRUE(reader.eof);
  13273. }
  13274. TEST(BodyReaderTest, NoStream) {
  13275. detail::BodyReader reader;
  13276. char buf[32];
  13277. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13278. EXPECT_EQ(Error::Connection, reader.last_error);
  13279. }
  13280. TEST(BodyReaderTest, Error) {
  13281. MockStream stream("Hello, World!", 5);
  13282. detail::BodyReader reader;
  13283. reader.stream = &stream;
  13284. reader.content_length = 13;
  13285. char buf[32];
  13286. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13287. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13288. EXPECT_EQ(Error::Read, reader.last_error);
  13289. }
  13290. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13291. // Mock-based StreamHandle tests relying on private internals are removed.
  13292. class OpenStreamTest : public ::testing::Test {
  13293. protected:
  13294. void SetUp() override {
  13295. svr_.Get("/hello", [](const Request &, Response &res) {
  13296. res.set_content("Hello World!", "text/plain");
  13297. });
  13298. svr_.Get("/large", [](const Request &, Response &res) {
  13299. res.set_content(std::string(10000, 'X'), "text/plain");
  13300. });
  13301. svr_.Get("/chunked", [](const Request &, Response &res) {
  13302. res.set_chunked_content_provider("text/plain",
  13303. [](size_t offset, DataSink &sink) {
  13304. if (offset < 15) {
  13305. sink.write("chunk", 5);
  13306. return true;
  13307. }
  13308. sink.done();
  13309. return true;
  13310. });
  13311. });
  13312. svr_.Get("/compressible", [](const Request &, Response &res) {
  13313. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13314. DataSink &sink) {
  13315. if (offset < 100 * 1024) {
  13316. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13317. sink.write(chunk.data(), chunk.size());
  13318. return true;
  13319. }
  13320. sink.done();
  13321. return true;
  13322. });
  13323. });
  13324. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13325. [](const Request & /*req*/, Response &res) {
  13326. auto i = new int(0);
  13327. res.set_header("Trailer", "Content-Length, X-Allowed");
  13328. res.set_chunked_content_provider(
  13329. "text/plain",
  13330. [i](size_t /*offset*/, DataSink &sink) {
  13331. switch (*i) {
  13332. case 0: sink.os << "123"; break;
  13333. case 1: sink.os << "456"; break;
  13334. case 2: sink.os << "789"; break;
  13335. case 3: {
  13336. sink.done_with_trailer(
  13337. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13338. } break;
  13339. }
  13340. (*i)++;
  13341. return true;
  13342. },
  13343. [i](bool success) {
  13344. EXPECT_TRUE(success);
  13345. delete i;
  13346. });
  13347. });
  13348. // Echo headers endpoint for header-related tests
  13349. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13350. std::string body;
  13351. for (const auto &h : req.headers) {
  13352. body.append(h.first);
  13353. body.push_back(':');
  13354. body.append(h.second);
  13355. body.push_back('\n');
  13356. }
  13357. res.set_content(body, "text/plain");
  13358. });
  13359. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13360. std::string body;
  13361. for (const auto &h : req.headers) {
  13362. body.append(h.first);
  13363. body.push_back(':');
  13364. body.append(h.second);
  13365. body.push_back('\n');
  13366. }
  13367. res.set_content(body, "text/plain");
  13368. });
  13369. port_ = svr_.bind_to_any_port("127.0.0.1");
  13370. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13371. svr_.wait_until_ready();
  13372. }
  13373. void TearDown() override {
  13374. svr_.stop();
  13375. if (thread_.joinable()) thread_.join();
  13376. }
  13377. Server svr_;
  13378. std::thread thread_;
  13379. int port_ = 0;
  13380. };
  13381. TEST_F(OpenStreamTest, Basic) {
  13382. Client cli("127.0.0.1", port_);
  13383. auto handle = cli.open_stream("GET", "/hello");
  13384. EXPECT_TRUE(handle.is_valid());
  13385. EXPECT_EQ("Hello World!", read_all(handle));
  13386. }
  13387. TEST_F(OpenStreamTest, SmallBuffer) {
  13388. Client cli("127.0.0.1", port_);
  13389. auto handle = cli.open_stream("GET", "/hello");
  13390. std::string result;
  13391. char buf[4];
  13392. ssize_t n;
  13393. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13394. result.append(buf, static_cast<size_t>(n));
  13395. EXPECT_EQ("Hello World!", result);
  13396. }
  13397. TEST_F(OpenStreamTest, DefaultHeaders) {
  13398. Client cli("127.0.0.1", port_);
  13399. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13400. {
  13401. auto handle = cli.open_stream("GET", "/echo-headers");
  13402. ASSERT_TRUE(handle.is_valid());
  13403. auto body = read_all(handle);
  13404. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13405. std::string::npos);
  13406. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13407. std::string::npos);
  13408. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13409. }
  13410. // open_stream POST with body and no explicit content_type should NOT add
  13411. // text/plain Content-Type (behavior differs from non-streaming path), but
  13412. // should include Content-Length
  13413. {
  13414. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13415. ASSERT_TRUE(handle.is_valid());
  13416. auto body = read_all(handle);
  13417. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13418. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13419. }
  13420. // open_stream POST with explicit Content-Type should preserve it
  13421. {
  13422. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13423. {{"Content-Type", "application/custom"}},
  13424. "{}", "application/custom");
  13425. ASSERT_TRUE(handle.is_valid());
  13426. auto body = read_all(handle);
  13427. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13428. }
  13429. // User-specified User-Agent must not be overwritten for stream API
  13430. {
  13431. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13432. {{"User-Agent", "MyAgent/1.2"}});
  13433. ASSERT_TRUE(handle.is_valid());
  13434. auto body = read_all(handle);
  13435. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13436. }
  13437. }
  13438. TEST_F(OpenStreamTest, Large) {
  13439. Client cli("127.0.0.1", port_);
  13440. auto handle = cli.open_stream("GET", "/large");
  13441. EXPECT_EQ(10000u, read_all(handle).size());
  13442. }
  13443. TEST_F(OpenStreamTest, ConnectionError) {
  13444. Client cli("127.0.0.1", 9999);
  13445. auto handle = cli.open_stream("GET", "/hello");
  13446. EXPECT_FALSE(handle.is_valid());
  13447. }
  13448. TEST_F(OpenStreamTest, Chunked) {
  13449. Client cli("127.0.0.1", port_);
  13450. auto handle = cli.open_stream("GET", "/chunked");
  13451. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13452. "Transfer-Encoding") == "chunked");
  13453. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13454. }
  13455. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13456. Client cli("127.0.0.1", port_);
  13457. auto handle =
  13458. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13459. ASSERT_TRUE(handle.is_valid());
  13460. // Consume body to allow trailers to be received/parsed
  13461. auto body = read_all(handle);
  13462. // Explicitly parse trailers (ensure trailers are available for assertion)
  13463. handle.parse_trailers_if_needed();
  13464. EXPECT_EQ(std::string("123456789"), body);
  13465. // The response should include a Trailer header declaring both names
  13466. ASSERT_TRUE(handle.response);
  13467. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13468. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13469. handle.response->get_header_value("Trailer"));
  13470. // Prohibited trailer must not be present
  13471. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13472. // Allowed trailer should be present
  13473. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13474. EXPECT_EQ(std::string("yes"),
  13475. handle.response->get_trailer_value("X-Allowed"));
  13476. // Verify trailers are NOT present as regular headers
  13477. EXPECT_EQ(std::string(""),
  13478. handle.response->get_header_value("Content-Length"));
  13479. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13480. }
  13481. static std::thread serve_single_response(std::promise<int> &port_promise,
  13482. const std::string &response) {
  13483. return std::thread([&port_promise, response] {
  13484. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13485. default_socket_options(srv);
  13486. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13487. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13488. sockaddr_in addr{};
  13489. addr.sin_family = AF_INET;
  13490. addr.sin_port = htons(0); // Let OS assign a free port
  13491. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13492. int opt = 1;
  13493. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13494. #ifdef _WIN32
  13495. reinterpret_cast<const char *>(&opt),
  13496. #else
  13497. &opt,
  13498. #endif
  13499. sizeof(opt));
  13500. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13501. ::listen(srv, 1) != 0) {
  13502. port_promise.set_value(-1);
  13503. detail::close_socket(srv);
  13504. return;
  13505. }
  13506. socklen_t addr_len = sizeof(addr);
  13507. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13508. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13509. sockaddr_in cli_addr{};
  13510. socklen_t cli_len = sizeof(cli_addr);
  13511. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13512. if (cli != INVALID_SOCKET) {
  13513. // Read the complete HTTP request (until the blank line that terminates
  13514. // headers) before sending the response. If the server closes the socket
  13515. // while the client's request data is still unread in the kernel receive
  13516. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13517. // connection on both sides: it discards the client's receive buffer
  13518. // (which already holds our response) and causes any in-progress write on
  13519. // the client to fail with ECONNRESET. Reading all request data first
  13520. // ensures close() emits a graceful FIN.
  13521. {
  13522. char rbuf[256];
  13523. std::string req;
  13524. while (req.find("\r\n\r\n") == std::string::npos) {
  13525. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13526. if (n <= 0) { break; }
  13527. req.append(rbuf, static_cast<size_t>(n));
  13528. }
  13529. }
  13530. ::send(cli,
  13531. #ifdef _WIN32
  13532. static_cast<const char *>(response.c_str()),
  13533. static_cast<int>(response.size()),
  13534. #else
  13535. response.c_str(), response.size(),
  13536. #endif
  13537. 0);
  13538. detail::close_socket(cli);
  13539. }
  13540. detail::close_socket(srv);
  13541. });
  13542. }
  13543. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13544. #ifndef _WIN32
  13545. signal(SIGPIPE, SIG_IGN);
  13546. #endif
  13547. std::promise<int> port_promise;
  13548. auto port_future = port_promise.get_future();
  13549. auto server_thread =
  13550. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13551. "Content-Type: text/plain\r\n"
  13552. "Content-Length: not-a-number\r\n"
  13553. "Connection: close\r\n"
  13554. "\r\n"
  13555. "hello");
  13556. auto port = port_future.get();
  13557. ASSERT_GT(port, 0);
  13558. Client cli("127.0.0.1", port);
  13559. auto handle = cli.open_stream("GET", "/");
  13560. EXPECT_FALSE(handle.is_valid());
  13561. server_thread.join();
  13562. }
  13563. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13564. #ifndef _WIN32
  13565. signal(SIGPIPE, SIG_IGN);
  13566. #endif
  13567. std::promise<int> port_promise;
  13568. auto port_future = port_promise.get_future();
  13569. auto server_thread = serve_single_response(
  13570. port_promise, "HTTP/1.1 200 OK\r\n"
  13571. "Content-Type: text/plain\r\n"
  13572. "Content-Length: 99999999999999999999999999\r\n"
  13573. "Connection: close\r\n"
  13574. "\r\n"
  13575. "hello");
  13576. auto port = port_future.get();
  13577. ASSERT_GT(port, 0);
  13578. // Historically std::stoull would throw std::out_of_range here and crash
  13579. // the process, then parsing silently clamped to a bogus framing length and
  13580. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13581. // so the stream fails to open, matching the not-a-number case above. The
  13582. // process still must NOT terminate.
  13583. Client cli("127.0.0.1", port);
  13584. auto handle = cli.open_stream("GET", "/");
  13585. EXPECT_FALSE(handle.is_valid());
  13586. server_thread.join();
  13587. }
  13588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13589. TEST_F(OpenStreamTest, Gzip) {
  13590. Client cli("127.0.0.1", port_);
  13591. auto handle = cli.open_stream("GET", "/compressible", {},
  13592. {{"Accept-Encoding", "gzip"}});
  13593. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13594. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13595. }
  13596. #endif
  13597. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13598. TEST_F(OpenStreamTest, Brotli) {
  13599. Client cli("127.0.0.1", port_);
  13600. auto handle =
  13601. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13602. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13603. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13604. }
  13605. #endif
  13606. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13607. TEST_F(OpenStreamTest, Zstd) {
  13608. Client cli("127.0.0.1", port_);
  13609. auto handle = cli.open_stream("GET", "/compressible", {},
  13610. {{"Accept-Encoding", "zstd"}});
  13611. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13612. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13613. }
  13614. #endif
  13615. #ifdef CPPHTTPLIB_SSL_ENABLED
  13616. class SSLOpenStreamTest : public ::testing::Test {
  13617. protected:
  13618. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13619. void SetUp() override {
  13620. svr_.Get("/hello", [](const Request &, Response &res) {
  13621. res.set_content("Hello SSL World!", "text/plain");
  13622. });
  13623. svr_.Get("/chunked", [](const Request &, Response &res) {
  13624. res.set_chunked_content_provider("text/plain",
  13625. [](size_t offset, DataSink &sink) {
  13626. if (offset < 15) {
  13627. sink.write("chunk", 5);
  13628. return true;
  13629. }
  13630. sink.done();
  13631. return true;
  13632. });
  13633. });
  13634. svr_.Post("/echo", [](const Request &req, Response &res) {
  13635. res.set_content(req.body, req.get_header_value("Content-Type"));
  13636. });
  13637. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13638. std::string body = req.body;
  13639. res.set_chunked_content_provider(
  13640. "text/plain", [body](size_t offset, DataSink &sink) {
  13641. if (offset < body.size()) {
  13642. sink.write(body.data() + offset, body.size() - offset);
  13643. }
  13644. sink.done();
  13645. return true;
  13646. });
  13647. });
  13648. port_ = svr_.bind_to_any_port("127.0.0.1");
  13649. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13650. svr_.wait_until_ready();
  13651. }
  13652. void TearDown() override {
  13653. svr_.stop();
  13654. if (thread_.joinable()) thread_.join();
  13655. }
  13656. SSLServer svr_;
  13657. std::thread thread_;
  13658. int port_ = 0;
  13659. };
  13660. TEST_F(SSLOpenStreamTest, Basic) {
  13661. SSLClient cli("127.0.0.1", port_);
  13662. cli.enable_server_certificate_verification(false);
  13663. auto handle = cli.open_stream("GET", "/hello");
  13664. ASSERT_TRUE(handle.is_valid());
  13665. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13666. }
  13667. TEST_F(SSLOpenStreamTest, Chunked) {
  13668. SSLClient cli("127.0.0.1", port_);
  13669. cli.enable_server_certificate_verification(false);
  13670. auto handle = cli.open_stream("GET", "/chunked");
  13671. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13672. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13673. "Transfer-Encoding") == "chunked");
  13674. auto body = read_all(handle);
  13675. EXPECT_EQ("chunkchunkchunk", body);
  13676. }
  13677. TEST_F(SSLOpenStreamTest, Post) {
  13678. SSLClient cli("127.0.0.1", port_);
  13679. cli.enable_server_certificate_verification(false);
  13680. auto handle =
  13681. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13682. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13683. EXPECT_EQ(200, handle.response->status);
  13684. auto body = read_all(handle);
  13685. EXPECT_EQ("Hello SSL POST", body);
  13686. }
  13687. TEST_F(SSLOpenStreamTest, PostChunked) {
  13688. SSLClient cli("127.0.0.1", port_);
  13689. cli.enable_server_certificate_verification(false);
  13690. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13691. "Chunked SSL Data", "text/plain");
  13692. ASSERT_TRUE(handle.is_valid());
  13693. EXPECT_EQ(200, handle.response->status);
  13694. auto body = read_all(handle);
  13695. EXPECT_EQ("Chunked SSL Data", body);
  13696. }
  13697. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13698. // Content-Length is terminated by the server closing the connection. When the
  13699. // SSL peer sends a close_notify after the body, the client must treat it as a
  13700. // clean EOF and return a successful response rather than an error.
  13701. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13703. ASSERT_TRUE(svr.is_valid());
  13704. svr.set_keep_alive_max_count(1);
  13705. const std::string expected_body = "Hello from connection-close response!";
  13706. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13707. res.set_content_provider("text/plain",
  13708. [&](size_t offset, DataSink &sink) -> bool {
  13709. if (offset < expected_body.size()) {
  13710. sink.write(expected_body.data() + offset,
  13711. expected_body.size() - offset);
  13712. }
  13713. sink.done();
  13714. return true;
  13715. });
  13716. });
  13717. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13718. auto se = detail::scope_exit([&] {
  13719. svr.stop();
  13720. listen_thread.join();
  13721. ASSERT_FALSE(svr.is_running());
  13722. });
  13723. svr.wait_until_ready();
  13724. SSLClient cli(HOST, PORT);
  13725. cli.enable_server_certificate_verification(false);
  13726. auto res = cli.Get("/no-content-length");
  13727. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13728. EXPECT_EQ(StatusCode::OK_200, res->status);
  13729. EXPECT_EQ(expected_body, res->body);
  13730. }
  13731. #endif // CPPHTTPLIB_SSL_ENABLED
  13732. //==============================================================================
  13733. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13734. // results for various scenarios.
  13735. //==============================================================================
  13736. TEST(ParityTest, GetVsOpenStream) {
  13737. Server svr;
  13738. const std::string path = "/parity";
  13739. const std::string content = "Parity test content: hello world";
  13740. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13741. res.set_content(content, "text/plain");
  13742. });
  13743. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13744. auto se = detail::scope_exit([&] {
  13745. svr.stop();
  13746. t.join();
  13747. ASSERT_FALSE(svr.is_running());
  13748. });
  13749. svr.wait_until_ready();
  13750. Client cli(HOST, PORT);
  13751. // Non-stream path
  13752. auto r1 = cli.Get(path);
  13753. ASSERT_TRUE(r1);
  13754. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13755. // Stream path
  13756. auto h = cli.open_stream("GET", path);
  13757. ASSERT_TRUE(h.is_valid());
  13758. EXPECT_EQ(r1->body, read_all(h));
  13759. }
  13760. // Helper to compress data with provided compressor type T
  13761. template <typename Compressor>
  13762. static std::string compress_payload_for_parity(const std::string &in) {
  13763. std::string out;
  13764. Compressor compressor;
  13765. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  13766. [&](const char *data, size_t n) {
  13767. out.append(data, n);
  13768. return true;
  13769. });
  13770. EXPECT_TRUE(ok);
  13771. return out;
  13772. }
  13773. // Helper function for compression parity tests
  13774. template <typename Compressor>
  13775. static void test_compression_parity(const std::string &original,
  13776. const std::string &path,
  13777. const std::string &encoding) {
  13778. const std::string compressed =
  13779. compress_payload_for_parity<Compressor>(original);
  13780. Server svr;
  13781. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13782. res.set_content(compressed, "application/octet-stream");
  13783. res.set_header("Content-Encoding", encoding);
  13784. });
  13785. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  13786. auto se = detail::scope_exit([&] {
  13787. svr.stop();
  13788. t.join();
  13789. ASSERT_FALSE(svr.is_running());
  13790. });
  13791. svr.wait_until_ready();
  13792. Client cli(HOST, PORT);
  13793. // Non-streaming
  13794. {
  13795. auto res = cli.Get(path);
  13796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13797. EXPECT_EQ(StatusCode::OK_200, res->status);
  13798. EXPECT_EQ(original, res->body);
  13799. }
  13800. // Streaming
  13801. {
  13802. auto h = cli.open_stream("GET", path);
  13803. ASSERT_TRUE(h.is_valid());
  13804. EXPECT_EQ(original, read_all(h));
  13805. }
  13806. }
  13807. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13808. TEST(ParityTest, Gzip) {
  13809. test_compression_parity<detail::gzip_compressor>(
  13810. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  13811. }
  13812. #endif
  13813. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13814. TEST(ParityTest, Brotli) {
  13815. test_compression_parity<detail::brotli_compressor>(
  13816. "Hello, brotli parity test payload", "/parity-br", "br");
  13817. }
  13818. #endif
  13819. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13820. TEST(ParityTest, Zstd) {
  13821. test_compression_parity<detail::zstd_compressor>(
  13822. "Zstandard parity test payload", "/parity-zstd", "zstd");
  13823. }
  13824. #endif
  13825. //==============================================================================
  13826. // New Stream API Tests
  13827. //==============================================================================
  13828. inline std::string read_body(httplib::stream::Result &result) {
  13829. std::string body;
  13830. while (result.next()) {
  13831. body.append(result.data(), result.size());
  13832. }
  13833. return body;
  13834. }
  13835. TEST(ClientConnectionTest, Basic) {
  13836. httplib::ClientConnection conn;
  13837. EXPECT_FALSE(conn.is_open());
  13838. conn.sock = 1;
  13839. EXPECT_TRUE(conn.is_open());
  13840. httplib::ClientConnection conn2(std::move(conn));
  13841. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  13842. conn2.sock = INVALID_SOCKET;
  13843. }
  13844. // Unified test server for all stream::* tests
  13845. class StreamApiTest : public ::testing::Test {
  13846. protected:
  13847. void SetUp() override {
  13848. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  13849. res.set_content("Hello World!", "text/plain");
  13850. });
  13851. svr_.Get("/echo-params",
  13852. [](const httplib::Request &req, httplib::Response &res) {
  13853. std::string r;
  13854. for (const auto &p : req.params) {
  13855. if (!r.empty()) r += "&";
  13856. r += p.first + "=" + p.second;
  13857. }
  13858. res.set_content(r, "text/plain");
  13859. });
  13860. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13861. res.set_content(req.body, req.get_header_value("Content-Type"));
  13862. });
  13863. svr_.Post("/echo-headers",
  13864. [](const httplib::Request &req, httplib::Response &res) {
  13865. std::string r;
  13866. for (const auto &h : req.headers)
  13867. r += h.first + ": " + h.second + "\n";
  13868. res.set_content(r, "text/plain");
  13869. });
  13870. svr_.Post("/echo-params",
  13871. [](const httplib::Request &req, httplib::Response &res) {
  13872. std::string r = "params:";
  13873. for (const auto &p : req.params)
  13874. r += p.first + "=" + p.second + ";";
  13875. res.set_content(r + " body:" + req.body, "text/plain");
  13876. });
  13877. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  13878. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  13879. });
  13880. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  13881. res.set_content("PUT:" + req.body, "text/plain");
  13882. });
  13883. svr_.Patch("/echo",
  13884. [](const httplib::Request &req, httplib::Response &res) {
  13885. res.set_content("PATCH:" + req.body, "text/plain");
  13886. });
  13887. svr_.Delete(
  13888. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  13889. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  13890. "text/plain");
  13891. });
  13892. svr_.Get("/head-test",
  13893. [](const httplib::Request &, httplib::Response &res) {
  13894. res.set_content("body for HEAD", "text/plain");
  13895. });
  13896. svr_.Options("/options",
  13897. [](const httplib::Request &, httplib::Response &res) {
  13898. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  13899. });
  13900. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  13901. svr_.wait_until_ready();
  13902. }
  13903. void TearDown() override {
  13904. svr_.stop();
  13905. if (thread_.joinable()) thread_.join();
  13906. }
  13907. httplib::Server svr_;
  13908. std::thread thread_;
  13909. };
  13910. // stream::Get tests
  13911. TEST_F(StreamApiTest, GetBasic) {
  13912. httplib::Client cli(HOST, PORT);
  13913. auto result = httplib::stream::Get(cli, "/hello");
  13914. ASSERT_TRUE(result.is_valid());
  13915. EXPECT_EQ(200, result.status());
  13916. EXPECT_EQ("Hello World!", read_body(result));
  13917. }
  13918. TEST_F(StreamApiTest, GetWithParams) {
  13919. httplib::Client cli(HOST, PORT);
  13920. httplib::Params params{{"foo", "bar"}};
  13921. auto result = httplib::stream::Get(cli, "/echo-params", params);
  13922. ASSERT_TRUE(result.is_valid());
  13923. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  13924. }
  13925. TEST_F(StreamApiTest, GetConnectionError) {
  13926. httplib::Client cli(HOST, 9999);
  13927. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  13928. }
  13929. TEST_F(StreamApiTest, Get404) {
  13930. httplib::Client cli(HOST, PORT);
  13931. auto result = httplib::stream::Get(cli, "/nonexistent");
  13932. EXPECT_TRUE(result.is_valid());
  13933. EXPECT_EQ(404, result.status());
  13934. }
  13935. // stream::Post tests
  13936. TEST_F(StreamApiTest, PostBasic) {
  13937. httplib::Client cli(HOST, PORT);
  13938. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  13939. "application/json");
  13940. ASSERT_TRUE(result.is_valid());
  13941. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  13942. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  13943. }
  13944. TEST_F(StreamApiTest, PostWithHeaders) {
  13945. httplib::Client cli(HOST, PORT);
  13946. httplib::Headers headers{{"X-Custom", "value"}};
  13947. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  13948. "text/plain");
  13949. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  13950. }
  13951. TEST_F(StreamApiTest, PostWithParams) {
  13952. httplib::Client cli(HOST, PORT);
  13953. httplib::Params params{{"k", "v"}};
  13954. auto result =
  13955. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  13956. auto body = read_body(result);
  13957. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  13958. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  13959. }
  13960. TEST_F(StreamApiTest, PostLarge) {
  13961. httplib::Client cli(HOST, PORT);
  13962. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  13963. size_t total = 0;
  13964. while (result.next()) {
  13965. total += result.size();
  13966. }
  13967. EXPECT_EQ(100u * 1024u, total);
  13968. }
  13969. // stream::Put/Patch tests
  13970. TEST_F(StreamApiTest, PutAndPatch) {
  13971. httplib::Client cli(HOST, PORT);
  13972. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  13973. EXPECT_EQ("PUT:test", read_body(put));
  13974. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  13975. EXPECT_EQ("PATCH:test", read_body(patch));
  13976. }
  13977. // stream::Delete tests
  13978. TEST_F(StreamApiTest, Delete) {
  13979. httplib::Client cli(HOST, PORT);
  13980. auto del1 = httplib::stream::Delete(cli, "/resource");
  13981. EXPECT_EQ("Deleted", read_body(del1));
  13982. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  13983. EXPECT_EQ("Deleted:data", read_body(del2));
  13984. }
  13985. // stream::Head/Options tests
  13986. TEST_F(StreamApiTest, HeadAndOptions) {
  13987. httplib::Client cli(HOST, PORT);
  13988. auto head = httplib::stream::Head(cli, "/head-test");
  13989. EXPECT_TRUE(head.is_valid());
  13990. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  13991. auto opts = httplib::stream::Options(cli, "/options");
  13992. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  13993. }
  13994. // SSL stream::* tests
  13995. #ifdef CPPHTTPLIB_SSL_ENABLED
  13996. class SSLStreamApiTest : public ::testing::Test {
  13997. protected:
  13998. void SetUp() override {
  13999. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14000. res.set_content("Hello SSL!", "text/plain");
  14001. });
  14002. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14003. res.set_content(req.body, "text/plain");
  14004. });
  14005. port_ = svr_.bind_to_any_port("127.0.0.1");
  14006. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14007. svr_.wait_until_ready();
  14008. }
  14009. void TearDown() override {
  14010. svr_.stop();
  14011. if (thread_.joinable()) thread_.join();
  14012. }
  14013. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14014. std::thread thread_;
  14015. int port_ = 0;
  14016. };
  14017. TEST_F(SSLStreamApiTest, GetAndPost) {
  14018. httplib::SSLClient cli("127.0.0.1", port_);
  14019. cli.enable_server_certificate_verification(false);
  14020. auto get = httplib::stream::Get(cli, "/hello");
  14021. EXPECT_EQ("Hello SSL!", read_body(get));
  14022. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14023. EXPECT_EQ("test", read_body(post));
  14024. }
  14025. #endif
  14026. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14027. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14028. // BodyReader
  14029. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14030. // Test that read timeout during streaming is detected
  14031. // Use a large content-length response where server delays mid-stream
  14032. Server svr;
  14033. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14034. // Send a large response with delay in the middle
  14035. res.set_content_provider(
  14036. 1000, // content_length
  14037. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14038. if (offset < 100) {
  14039. // Send first 100 bytes immediately
  14040. std::string data(100, 'A');
  14041. sink.write(data.c_str(), data.size());
  14042. return true;
  14043. }
  14044. // Then delay longer than client timeout
  14045. std::this_thread::sleep_for(std::chrono::seconds(3));
  14046. std::string data(900, 'B');
  14047. sink.write(data.c_str(), data.size());
  14048. return true;
  14049. });
  14050. });
  14051. auto port = 8091;
  14052. std::thread t([&]() { svr.listen("localhost", port); });
  14053. svr.wait_until_ready();
  14054. Client cli("localhost", port);
  14055. cli.set_read_timeout(1, 0); // 1 second timeout
  14056. auto handle = cli.open_stream("GET", "/slow-stream");
  14057. ASSERT_TRUE(handle.is_valid());
  14058. char buf[256];
  14059. ssize_t total = 0;
  14060. ssize_t n;
  14061. bool got_error = false;
  14062. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14063. total += n;
  14064. }
  14065. if (n < 0) {
  14066. got_error = true;
  14067. // Should be timeout or read error
  14068. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14069. handle.get_read_error() == Error::Read)
  14070. << "Actual error: " << to_string(handle.get_read_error());
  14071. }
  14072. // Either we got an error, or we got less data than expected
  14073. EXPECT_TRUE(got_error || total < 1000)
  14074. << "Expected timeout but got all " << total << " bytes";
  14075. svr.stop();
  14076. t.join();
  14077. }
  14078. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14079. // Test connection closed detection via BodyReader
  14080. Server svr;
  14081. std::atomic<bool> close_now{false};
  14082. svr.Get("/will-close", [&](const Request &, Response &res) {
  14083. res.set_content_provider(
  14084. 10000, // Large content_length that we won't fully send
  14085. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14086. if (offset < 100) {
  14087. std::string data(100, 'X');
  14088. sink.write(data.c_str(), data.size());
  14089. return true;
  14090. }
  14091. // Wait for signal then abort
  14092. while (!close_now) {
  14093. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14094. }
  14095. return false; // Abort - server will close connection
  14096. });
  14097. });
  14098. auto port = 8092;
  14099. std::thread t([&]() { svr.listen("localhost", port); });
  14100. svr.wait_until_ready();
  14101. Client cli("localhost", port);
  14102. auto handle = cli.open_stream("GET", "/will-close");
  14103. ASSERT_TRUE(handle.is_valid());
  14104. char buf[256];
  14105. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14106. EXPECT_GT(n, 0) << "First read should succeed";
  14107. // Signal server to close
  14108. close_now = true;
  14109. // Keep reading until error or EOF
  14110. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14111. // Keep reading
  14112. }
  14113. // Should get an error since content_length wasn't satisfied
  14114. if (n < 0) {
  14115. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14116. handle.get_read_error() == Error::Read)
  14117. << "Actual error: " << to_string(handle.get_read_error());
  14118. }
  14119. svr.stop();
  14120. t.join();
  14121. }
  14122. #ifdef CPPHTTPLIB_SSL_ENABLED
  14123. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14124. // Test that read timeout during SSL streaming is detected
  14125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14126. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14127. res.set_content_provider(
  14128. 1000, "text/plain",
  14129. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14130. if (offset < 100) {
  14131. std::string data(100, 'A');
  14132. sink.write(data.c_str(), data.size());
  14133. return true;
  14134. }
  14135. std::this_thread::sleep_for(std::chrono::seconds(3));
  14136. std::string data(900, 'B');
  14137. sink.write(data.c_str(), data.size());
  14138. return true;
  14139. });
  14140. });
  14141. auto port = 8093;
  14142. std::thread t([&]() { svr.listen("localhost", port); });
  14143. svr.wait_until_ready();
  14144. SSLClient cli("localhost", port);
  14145. cli.enable_server_certificate_verification(false);
  14146. cli.set_read_timeout(1, 0); // 1 second timeout
  14147. auto handle = cli.open_stream("GET", "/slow-stream");
  14148. ASSERT_TRUE(handle.is_valid());
  14149. char buf[256];
  14150. ssize_t total = 0;
  14151. ssize_t n;
  14152. bool got_error = false;
  14153. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14154. total += n;
  14155. }
  14156. if (n < 0) {
  14157. got_error = true;
  14158. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14159. handle.get_read_error() == Error::Read)
  14160. << "Actual error: " << to_string(handle.get_read_error());
  14161. }
  14162. EXPECT_TRUE(got_error || total < 1000)
  14163. << "Expected timeout but got all " << total << " bytes";
  14164. svr.stop();
  14165. t.join();
  14166. }
  14167. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14168. // Test SSL connection closed detection
  14169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14170. std::atomic<bool> close_now{false};
  14171. svr.Get("/will-close", [&](const Request &, Response &res) {
  14172. res.set_content_provider(
  14173. 10000, "text/plain",
  14174. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14175. if (offset < 100) {
  14176. std::string data(100, 'X');
  14177. sink.write(data.c_str(), data.size());
  14178. return true;
  14179. }
  14180. while (!close_now) {
  14181. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14182. }
  14183. return false;
  14184. });
  14185. });
  14186. auto port = 8094;
  14187. std::thread t([&]() { svr.listen("localhost", port); });
  14188. svr.wait_until_ready();
  14189. SSLClient cli("localhost", port);
  14190. cli.enable_server_certificate_verification(false);
  14191. auto handle = cli.open_stream("GET", "/will-close");
  14192. ASSERT_TRUE(handle.is_valid());
  14193. char buf[256];
  14194. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14195. EXPECT_GT(n, 0);
  14196. // Signal server to close
  14197. close_now = true;
  14198. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14199. // Keep reading
  14200. }
  14201. if (n < 0) {
  14202. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14203. handle.get_read_error() == Error::Read)
  14204. << "Actual error: " << to_string(handle.get_read_error());
  14205. }
  14206. svr.stop();
  14207. t.join();
  14208. }
  14209. #endif
  14210. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14211. using namespace httplib;
  14212. // Create a test file
  14213. const char *fname = "etag_testfile.txt";
  14214. const char *content = "etag-content";
  14215. {
  14216. std::ofstream ofs(fname);
  14217. ofs << content;
  14218. ASSERT_TRUE(ofs.good());
  14219. }
  14220. Server svr;
  14221. svr.set_mount_point("/static", ".");
  14222. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14223. svr.wait_until_ready();
  14224. Client cli(HOST, PORT);
  14225. // First request: should get 200 with ETag header
  14226. auto res1 = cli.Get("/static/etag_testfile.txt");
  14227. ASSERT_TRUE(res1);
  14228. ASSERT_EQ(200, res1->status);
  14229. ASSERT_TRUE(res1->has_header("ETag"));
  14230. std::string etag = res1->get_header_value("ETag");
  14231. EXPECT_FALSE(etag.empty());
  14232. // Verify ETag format: W/"hex-hex"
  14233. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14234. EXPECT_EQ('W', etag[0]);
  14235. EXPECT_EQ('/', etag[1]);
  14236. EXPECT_EQ('"', etag[2]);
  14237. EXPECT_EQ('"', etag.back());
  14238. // Exact match: expect 304 Not Modified
  14239. Headers h2 = {{"If-None-Match", etag}};
  14240. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14241. ASSERT_TRUE(res2);
  14242. EXPECT_EQ(304, res2->status);
  14243. // Wildcard match: expect 304 Not Modified
  14244. Headers h3 = {{"If-None-Match", "*"}};
  14245. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14246. ASSERT_TRUE(res3);
  14247. EXPECT_EQ(304, res3->status);
  14248. // Non-matching ETag: expect 200
  14249. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14250. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14251. ASSERT_TRUE(res4);
  14252. EXPECT_EQ(200, res4->status);
  14253. // Multiple ETags with one matching: expect 304
  14254. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14255. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14256. ASSERT_TRUE(res5);
  14257. EXPECT_EQ(304, res5->status);
  14258. svr.stop();
  14259. t.join();
  14260. std::remove(fname);
  14261. }
  14262. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14263. using namespace httplib;
  14264. Server svr;
  14265. svr.set_mount_point("/static", ".");
  14266. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14267. svr.wait_until_ready();
  14268. Client cli(HOST, PORT);
  14269. // Send If-None-Match: * to a non-existent file
  14270. Headers h = {{"If-None-Match", "*"}};
  14271. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14273. EXPECT_EQ(404, res->status);
  14274. svr.stop();
  14275. t.join();
  14276. }
  14277. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14278. using namespace httplib;
  14279. // Create a test file
  14280. const char *fname = "etag_boundary_testfile.txt";
  14281. const char *content = "boundary-test";
  14282. {
  14283. std::ofstream ofs(fname);
  14284. ofs << content;
  14285. ASSERT_TRUE(ofs.good());
  14286. }
  14287. Server svr;
  14288. svr.set_mount_point("/static", ".");
  14289. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14290. svr.wait_until_ready();
  14291. Client cli(HOST, PORT);
  14292. // Get the actual ETag
  14293. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14294. ASSERT_TRUE(res1);
  14295. ASSERT_EQ(200, res1->status);
  14296. ASSERT_TRUE(res1->has_header("ETag"));
  14297. std::string etag = res1->get_header_value("ETag");
  14298. // Test 1: Very long ETag value (longer than actual ETag)
  14299. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14300. Headers h1 = {{"If-None-Match", "W/"
  14301. "\"very-long-etag-value-that-is-much-longer-"
  14302. "than-the-actual-etag-value\""}};
  14303. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14304. ASSERT_TRUE(res2);
  14305. EXPECT_EQ(200, res2->status); // Should not match
  14306. // Test 2: Long string followed by wildcard
  14307. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14308. // string)
  14309. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14310. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14311. ASSERT_TRUE(res3);
  14312. EXPECT_EQ(304, res3->status); // Should match on "*"
  14313. // Test 3: Wildcard followed by long string
  14314. // Should match on "*" immediately and return 304
  14315. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14316. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14317. ASSERT_TRUE(res4);
  14318. EXPECT_EQ(304, res4->status); // Should match on "*"
  14319. // Test 4: Multiple long non-matching values
  14320. // Should NOT match and return 200 (test that all comparisons are safe)
  14321. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14322. "W/\"second-long-non-matching-value\", "
  14323. "W/\"third-long-non-matching-value\""}};
  14324. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14325. ASSERT_TRUE(res5);
  14326. EXPECT_EQ(200, res5->status); // Should not match
  14327. // Test 5: Single character that is not "*" (edge case)
  14328. Headers h5 = {{"If-None-Match", "X"}};
  14329. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14330. ASSERT_TRUE(res6);
  14331. EXPECT_EQ(200, res6->status); // Should not match
  14332. svr.stop();
  14333. t.join();
  14334. std::remove(fname);
  14335. }
  14336. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14337. using namespace httplib;
  14338. // Create a test file
  14339. const char *fname = "ims_testfile.txt";
  14340. const char *content = "if-modified-since-test";
  14341. {
  14342. std::ofstream ofs(fname);
  14343. ofs << content;
  14344. ASSERT_TRUE(ofs.good());
  14345. }
  14346. Server svr;
  14347. svr.set_mount_point("/static", ".");
  14348. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14349. svr.wait_until_ready();
  14350. Client cli(HOST, PORT);
  14351. // First request: should get 200 with Last-Modified header
  14352. auto res1 = cli.Get("/static/ims_testfile.txt");
  14353. ASSERT_TRUE(res1);
  14354. ASSERT_EQ(200, res1->status);
  14355. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14356. std::string last_modified = res1->get_header_value("Last-Modified");
  14357. EXPECT_FALSE(last_modified.empty());
  14358. // If-Modified-Since with same time: expect 304
  14359. Headers h2 = {{"If-Modified-Since", last_modified}};
  14360. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14361. ASSERT_TRUE(res2);
  14362. EXPECT_EQ(304, res2->status);
  14363. // If-Modified-Since with future time: expect 304
  14364. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14365. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14366. ASSERT_TRUE(res3);
  14367. EXPECT_EQ(304, res3->status);
  14368. // If-Modified-Since with past time: expect 200
  14369. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14370. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14371. ASSERT_TRUE(res4);
  14372. EXPECT_EQ(200, res4->status);
  14373. // If-None-Match takes precedence over If-Modified-Since
  14374. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14375. ASSERT_TRUE(res1->has_header("ETag"));
  14376. std::string etag = res1->get_header_value("ETag");
  14377. Headers h5 = {{"If-None-Match", etag},
  14378. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14379. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14380. ASSERT_TRUE(res5);
  14381. EXPECT_EQ(304, res5->status);
  14382. svr.stop();
  14383. t.join();
  14384. std::remove(fname);
  14385. }
  14386. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14387. using namespace httplib;
  14388. Server svr;
  14389. // Endpoint that returns compressible content
  14390. svr.Get("/compressible", [](const Request &, Response &res) {
  14391. // Return a large enough body to trigger compression
  14392. std::string body(1000, 'a');
  14393. res.set_content(body, "text/plain");
  14394. });
  14395. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14396. svr.wait_until_ready();
  14397. Client cli(HOST, PORT);
  14398. // Request with gzip support: should get Vary header when compressed
  14399. cli.set_compress(true);
  14400. auto res1 = cli.Get("/compressible");
  14401. ASSERT_TRUE(res1);
  14402. EXPECT_EQ(200, res1->status);
  14403. // If Content-Encoding is set, Vary should also be set
  14404. if (res1->has_header("Content-Encoding")) {
  14405. EXPECT_TRUE(res1->has_header("Vary"));
  14406. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14407. }
  14408. // Request without Accept-Encoding header: should not have compression
  14409. Headers h_no_compress;
  14410. auto res2 = cli.Get("/compressible", h_no_compress);
  14411. ASSERT_TRUE(res2);
  14412. EXPECT_EQ(200, res2->status);
  14413. // Verify Vary header is present when compression is applied
  14414. // (the exact behavior depends on server configuration)
  14415. svr.stop();
  14416. t.join();
  14417. }
  14418. TEST(ETagTest, IfRangeWithETag) {
  14419. using namespace httplib;
  14420. // Create a test file with known content
  14421. const char *fname = "if_range_testfile.txt";
  14422. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14423. {
  14424. std::ofstream ofs(fname);
  14425. ofs << content;
  14426. ASSERT_TRUE(ofs.good());
  14427. }
  14428. Server svr;
  14429. svr.set_mount_point("/static", ".");
  14430. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14431. svr.wait_until_ready();
  14432. Client cli(HOST, PORT);
  14433. // First request: get ETag
  14434. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14435. ASSERT_TRUE(res1);
  14436. ASSERT_EQ(200, res1->status);
  14437. ASSERT_TRUE(res1->has_header("ETag"));
  14438. std::string etag = res1->get_header_value("ETag");
  14439. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14440. // Since our server generates weak ETags (W/"..."), If-Range with our
  14441. // ETag should NOT result in partial content - it should return full content.
  14442. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14443. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14444. ASSERT_TRUE(res2);
  14445. // Weak ETag in If-Range -> full content (200), not partial (206)
  14446. EXPECT_EQ(200, res2->status);
  14447. EXPECT_EQ(content, res2->body);
  14448. EXPECT_FALSE(res2->has_header("Content-Range"));
  14449. // Range request with non-matching If-Range (ETag): should get 200 (full
  14450. // content)
  14451. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14452. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14453. ASSERT_TRUE(res3);
  14454. EXPECT_EQ(200, res3->status);
  14455. EXPECT_EQ(content, res3->body);
  14456. EXPECT_FALSE(res3->has_header("Content-Range"));
  14457. // Range request with strong ETag (hypothetical - our server doesn't generate
  14458. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14459. // should return full content)
  14460. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14461. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14462. ASSERT_TRUE(res4);
  14463. EXPECT_EQ(200, res4->status);
  14464. EXPECT_EQ(content, res4->body);
  14465. EXPECT_FALSE(res4->has_header("Content-Range"));
  14466. svr.stop();
  14467. t.join();
  14468. std::remove(fname);
  14469. }
  14470. TEST(ETagTest, IfRangeWithDate) {
  14471. using namespace httplib;
  14472. // Create a test file
  14473. const char *fname = "if_range_date_testfile.txt";
  14474. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14475. {
  14476. std::ofstream ofs(fname);
  14477. ofs << content;
  14478. ASSERT_TRUE(ofs.good());
  14479. }
  14480. Server svr;
  14481. svr.set_mount_point("/static", ".");
  14482. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14483. svr.wait_until_ready();
  14484. Client cli(HOST, PORT);
  14485. // First request: get Last-Modified
  14486. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14487. ASSERT_TRUE(res1);
  14488. ASSERT_EQ(200, res1->status);
  14489. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14490. std::string last_modified = res1->get_header_value("Last-Modified");
  14491. // Range request with matching If-Range (date): should get 206
  14492. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14493. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14494. ASSERT_TRUE(res2);
  14495. EXPECT_EQ(206, res2->status);
  14496. EXPECT_EQ("FGHIJ", res2->body);
  14497. // Range request with old If-Range date: should get 200 (full content)
  14498. Headers h3 = {{"Range", "bytes=5-9"},
  14499. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14500. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14501. ASSERT_TRUE(res3);
  14502. EXPECT_EQ(200, res3->status);
  14503. EXPECT_EQ(content, res3->body);
  14504. // Range request with future If-Range date: should get 206
  14505. Headers h4 = {{"Range", "bytes=0-4"},
  14506. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14507. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14508. ASSERT_TRUE(res4);
  14509. EXPECT_EQ(206, res4->status);
  14510. EXPECT_EQ("ABCDE", res4->body);
  14511. svr.stop();
  14512. t.join();
  14513. std::remove(fname);
  14514. }
  14515. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14516. using namespace httplib;
  14517. const char *fname = "etag_malformed.txt";
  14518. const char *content = "malformed-etag";
  14519. {
  14520. std::ofstream ofs(fname);
  14521. ofs << content;
  14522. ASSERT_TRUE(ofs.good());
  14523. }
  14524. Server svr;
  14525. svr.set_mount_point("/static", ".");
  14526. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14527. svr.wait_until_ready();
  14528. Client cli(HOST, PORT);
  14529. // baseline: should get 200 and an ETag
  14530. auto res1 = cli.Get("/static/etag_malformed.txt");
  14531. ASSERT_TRUE(res1);
  14532. ASSERT_EQ(200, res1->status);
  14533. ASSERT_TRUE(res1->has_header("ETag"));
  14534. // Malformed ETag value (missing quotes) should be treated as non-matching
  14535. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14536. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14537. ASSERT_TRUE(res_bad);
  14538. EXPECT_EQ(200, res_bad->status);
  14539. // Whitespace-only header value should be considered invalid / non-matching
  14540. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14541. "Host: localhost\r\n"
  14542. "If-None-Match: \r\n"
  14543. "Connection: close\r\n"
  14544. "\r\n";
  14545. std::string out;
  14546. ASSERT_TRUE(send_request(5, raw_req, &out));
  14547. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14548. svr.stop();
  14549. t.join();
  14550. std::remove(fname);
  14551. }
  14552. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14553. using namespace httplib;
  14554. const char *fname = "ims_invalid_format.txt";
  14555. const char *content = "ims-bad-format";
  14556. {
  14557. std::ofstream ofs(fname);
  14558. ofs << content;
  14559. ASSERT_TRUE(ofs.good());
  14560. }
  14561. Server svr;
  14562. svr.set_mount_point("/static", ".");
  14563. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14564. svr.wait_until_ready();
  14565. Client cli(HOST, PORT);
  14566. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14567. ASSERT_TRUE(res1);
  14568. ASSERT_EQ(200, res1->status);
  14569. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14570. // If-Modified-Since with invalid format should not result in 304
  14571. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14572. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14573. ASSERT_TRUE(res_bad);
  14574. EXPECT_EQ(200, res_bad->status);
  14575. // If-Range with invalid date format should be treated as mismatch -> full
  14576. // content (200)
  14577. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14578. {"If-Range", "invalid-date"}};
  14579. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14580. ASSERT_TRUE(res_ifrange);
  14581. EXPECT_EQ(200, res_ifrange->status);
  14582. svr.stop();
  14583. t.join();
  14584. std::remove(fname);
  14585. }
  14586. TEST(ETagTest, IfRangeWithMalformedETag) {
  14587. using namespace httplib;
  14588. const char *fname = "ifrange_malformed.txt";
  14589. const std::string content = "0123456789";
  14590. {
  14591. std::ofstream ofs(fname);
  14592. ofs << content;
  14593. ASSERT_TRUE(ofs.good());
  14594. }
  14595. Server svr;
  14596. svr.set_mount_point("/static", ".");
  14597. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14598. svr.wait_until_ready();
  14599. Client cli(HOST, PORT);
  14600. // First request: get ETag
  14601. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14602. ASSERT_TRUE(res1);
  14603. ASSERT_EQ(200, res1->status);
  14604. ASSERT_TRUE(res1->has_header("ETag"));
  14605. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14606. // full content (200)
  14607. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14608. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14609. ASSERT_TRUE(res2);
  14610. EXPECT_EQ(200, res2->status);
  14611. EXPECT_EQ(content, res2->body);
  14612. svr.stop();
  14613. t.join();
  14614. std::remove(fname);
  14615. }
  14616. TEST(ETagTest, ExtremeLargeDateValues) {
  14617. using namespace httplib;
  14618. const char *fname = "ims_extreme_date.txt";
  14619. const char *content = "ims-extreme-date";
  14620. {
  14621. std::ofstream ofs(fname);
  14622. ofs << content;
  14623. ASSERT_TRUE(ofs.good());
  14624. }
  14625. Server svr;
  14626. svr.set_mount_point("/static", ".");
  14627. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14628. svr.wait_until_ready();
  14629. Client cli(HOST, PORT);
  14630. auto res1 = cli.Get(std::string("/static/") + fname);
  14631. ASSERT_TRUE(res1);
  14632. ASSERT_EQ(200, res1->status);
  14633. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14634. // Extremely large year that may overflow date parsing routines.
  14635. Headers h_large_date = {
  14636. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14637. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14638. ASSERT_TRUE(res_bad);
  14639. // Expect server to treat this as invalid/mismatch and return full content
  14640. EXPECT_EQ(200, res_bad->status);
  14641. // If-Range with extremely large date should be treated as mismatch -> full
  14642. // content (200)
  14643. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14644. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14645. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14646. ASSERT_TRUE(res_ifrange);
  14647. EXPECT_EQ(200, res_ifrange->status);
  14648. svr.stop();
  14649. t.join();
  14650. std::remove(fname);
  14651. }
  14652. TEST(ETagTest, NegativeFileModificationTime) {
  14653. using namespace httplib;
  14654. const char *fname = "ims_negative_mtime.txt";
  14655. const std::string content = "negative-mtime";
  14656. {
  14657. std::ofstream ofs(fname);
  14658. ofs << content;
  14659. ASSERT_TRUE(ofs.good());
  14660. }
  14661. // Try to set file mtime to a negative value. This may fail on some
  14662. // platforms/filesystems; if it fails, the test will still verify server
  14663. // behaves safely by performing a regular conditional request.
  14664. #if defined(__APPLE__) || defined(__linux__)
  14665. bool set_negative = false;
  14666. do {
  14667. struct timeval times[2];
  14668. // access time: now
  14669. times[0].tv_sec = time(nullptr);
  14670. times[0].tv_usec = 0;
  14671. // modification time: negative (e.g., -1)
  14672. times[1].tv_sec = -1;
  14673. times[1].tv_usec = 0;
  14674. if (utimes(fname, times) == 0) { set_negative = true; }
  14675. } while (0);
  14676. #else
  14677. bool set_negative = false;
  14678. #endif
  14679. Server svr;
  14680. svr.set_mount_point("/static", ".");
  14681. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14682. svr.wait_until_ready();
  14683. Client cli(HOST, PORT);
  14684. auto res1 = cli.Get(std::string("/static/") + fname);
  14685. ASSERT_TRUE(res1);
  14686. ASSERT_EQ(200, res1->status);
  14687. bool has_last_modified = res1->has_header("Last-Modified");
  14688. std::string last_modified;
  14689. if (has_last_modified) {
  14690. last_modified = res1->get_header_value("Last-Modified");
  14691. }
  14692. if (set_negative) {
  14693. // If we successfully set a negative mtime, ensure server returns a
  14694. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14695. // with an old date and ensure server handles it without crash.
  14696. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14697. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14698. ASSERT_TRUE(res2);
  14699. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14700. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14701. } else {
  14702. // Could not set negative mtime on this platform; fall back to verifying
  14703. // that normal invalid/malformed dates are treated safely (non-304).
  14704. Headers h_bad_date = {
  14705. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14706. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14707. ASSERT_TRUE(res_bad);
  14708. EXPECT_EQ(200, res_bad->status);
  14709. }
  14710. svr.stop();
  14711. t.join();
  14712. std::remove(fname);
  14713. }
  14714. //==============================================================================
  14715. // SSE Parsing Tests
  14716. //==============================================================================
  14717. class SSEParsingTest : public ::testing::Test {
  14718. protected:
  14719. // Test helper that mimics SSE parsing behavior
  14720. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14721. int &retry_ms) {
  14722. // Blank line signals end of event
  14723. if (line.empty() || line == "\r") { return true; }
  14724. // Lines starting with ':' are comments (ignored)
  14725. if (!line.empty() && line[0] == ':') { return false; }
  14726. // Find the colon separator
  14727. auto colon_pos = line.find(':');
  14728. if (colon_pos == std::string::npos) {
  14729. // Line with no colon is treated as field name with empty value
  14730. return false;
  14731. }
  14732. std::string field = line.substr(0, colon_pos);
  14733. std::string value;
  14734. // Value starts after colon, skip optional single space
  14735. if (colon_pos + 1 < line.size()) {
  14736. size_t value_start = colon_pos + 1;
  14737. if (line[value_start] == ' ') { value_start++; }
  14738. value = line.substr(value_start);
  14739. // Remove trailing \r if present
  14740. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14741. }
  14742. // Handle known fields
  14743. if (field == "event") {
  14744. msg.event = value;
  14745. } else if (field == "data") {
  14746. // Multiple data lines are concatenated with newlines
  14747. if (!msg.data.empty()) { msg.data += "\n"; }
  14748. msg.data += value;
  14749. } else if (field == "id") {
  14750. // Empty id is valid (clears the last event ID)
  14751. msg.id = value;
  14752. } else if (field == "retry") {
  14753. // Parse retry interval in milliseconds
  14754. {
  14755. int v = 0;
  14756. auto res =
  14757. detail::from_chars(value.data(), value.data() + value.size(), v);
  14758. if (res.ec == std::errc{}) { retry_ms = v; }
  14759. }
  14760. }
  14761. // Unknown fields are ignored per SSE spec
  14762. return false;
  14763. }
  14764. };
  14765. // Test: Single-line data
  14766. TEST_F(SSEParsingTest, SingleLineData) {
  14767. sse::SSEMessage msg;
  14768. int retry_ms = 3000;
  14769. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  14770. EXPECT_EQ(msg.data, "hello");
  14771. EXPECT_EQ(msg.event, "message");
  14772. // Blank line ends event
  14773. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14774. }
  14775. // Test: Multi-line data
  14776. TEST_F(SSEParsingTest, MultiLineData) {
  14777. sse::SSEMessage msg;
  14778. int retry_ms = 3000;
  14779. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  14780. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  14781. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  14782. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  14783. }
  14784. // Test: Custom event types
  14785. TEST_F(SSEParsingTest, CustomEventType) {
  14786. sse::SSEMessage msg;
  14787. int retry_ms = 3000;
  14788. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  14789. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  14790. EXPECT_EQ(msg.event, "update");
  14791. EXPECT_EQ(msg.data, "payload");
  14792. }
  14793. // Test: Event ID handling
  14794. TEST_F(SSEParsingTest, EventIdHandling) {
  14795. sse::SSEMessage msg;
  14796. int retry_ms = 3000;
  14797. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  14798. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  14799. EXPECT_EQ(msg.id, "12345");
  14800. }
  14801. // Test: Empty event ID (clears last event ID)
  14802. TEST_F(SSEParsingTest, EmptyEventId) {
  14803. sse::SSEMessage msg;
  14804. msg.id = "previous";
  14805. int retry_ms = 3000;
  14806. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  14807. EXPECT_EQ(msg.id, "");
  14808. }
  14809. // Test: Retry field parsing
  14810. TEST_F(SSEParsingTest, RetryFieldParsing) {
  14811. sse::SSEMessage msg;
  14812. int retry_ms = 3000;
  14813. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  14814. EXPECT_EQ(retry_ms, 5000);
  14815. }
  14816. // Test: Invalid retry value
  14817. TEST_F(SSEParsingTest, InvalidRetryValue) {
  14818. sse::SSEMessage msg;
  14819. int retry_ms = 3000;
  14820. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  14821. EXPECT_EQ(retry_ms, 3000); // Unchanged
  14822. }
  14823. // Test: Comments (lines starting with :)
  14824. TEST_F(SSEParsingTest, CommentsIgnored) {
  14825. sse::SSEMessage msg;
  14826. int retry_ms = 3000;
  14827. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  14828. EXPECT_EQ(msg.data, "");
  14829. EXPECT_EQ(msg.event, "message");
  14830. }
  14831. // Test: Colon in value
  14832. TEST_F(SSEParsingTest, ColonInValue) {
  14833. sse::SSEMessage msg;
  14834. int retry_ms = 3000;
  14835. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  14836. EXPECT_EQ(msg.data, "hello:world:test");
  14837. }
  14838. // Test: Line with no colon (field name only)
  14839. TEST_F(SSEParsingTest, FieldNameOnly) {
  14840. sse::SSEMessage msg;
  14841. int retry_ms = 3000;
  14842. // According to SSE spec, this is treated as field name with empty value
  14843. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  14844. // Since we don't recognize "data" without colon, data should be empty
  14845. EXPECT_EQ(msg.data, "");
  14846. }
  14847. // Test: Trailing \r handling
  14848. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  14849. sse::SSEMessage msg;
  14850. int retry_ms = 3000;
  14851. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  14852. EXPECT_EQ(msg.data, "hello");
  14853. }
  14854. // Test: Unknown fields ignored
  14855. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  14856. sse::SSEMessage msg;
  14857. int retry_ms = 3000;
  14858. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  14859. EXPECT_EQ(msg.data, "");
  14860. EXPECT_EQ(msg.event, "message");
  14861. }
  14862. // Test: Space after colon is optional
  14863. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  14864. sse::SSEMessage msg1, msg2;
  14865. int retry_ms = 3000;
  14866. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  14867. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  14868. EXPECT_EQ(msg1.data, "hello");
  14869. EXPECT_EQ(msg2.data, "hello");
  14870. }
  14871. // Test: SSEMessage clear
  14872. TEST_F(SSEParsingTest, MessageClear) {
  14873. sse::SSEMessage msg;
  14874. msg.event = "custom";
  14875. msg.data = "some data";
  14876. msg.id = "123";
  14877. msg.clear();
  14878. EXPECT_EQ(msg.event, "message");
  14879. EXPECT_EQ(msg.data, "");
  14880. EXPECT_EQ(msg.id, "");
  14881. }
  14882. // Test: Complete event parsing
  14883. TEST_F(SSEParsingTest, CompleteEventParsing) {
  14884. sse::SSEMessage msg;
  14885. int retry_ms = 3000;
  14886. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  14887. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  14888. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  14889. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  14890. // Blank line ends event
  14891. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  14892. EXPECT_EQ(msg.event, "notification");
  14893. EXPECT_EQ(msg.id, "evt-42");
  14894. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  14895. EXPECT_EQ(retry_ms, 1000);
  14896. }
  14897. //==============================================================================
  14898. // Integration Tests with Server
  14899. //==============================================================================
  14900. class SSEIntegrationTest : public ::testing::Test {
  14901. protected:
  14902. void SetUp() override {
  14903. stop_server_.store(false);
  14904. events_.clear();
  14905. server_ = httplib::detail::make_unique<Server>();
  14906. setup_server();
  14907. start_server();
  14908. }
  14909. void TearDown() override {
  14910. stop_server_.store(true);
  14911. event_cv_.notify_all();
  14912. server_->stop();
  14913. if (server_thread_.joinable()) { server_thread_.join(); }
  14914. }
  14915. void setup_server() {
  14916. // Simple SSE endpoint
  14917. server_->Get("/events", [this](const Request &req, Response &res) {
  14918. auto last_id = req.get_header_value("Last-Event-ID");
  14919. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  14920. res.set_chunked_content_provider(
  14921. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  14922. std::unique_lock<std::mutex> lock(event_mutex_);
  14923. if (event_cv_.wait_for(
  14924. lock, std::chrono::milliseconds(200), [this] {
  14925. return !events_.empty() || stop_server_.load();
  14926. })) {
  14927. if (stop_server_.load()) { return false; }
  14928. if (!events_.empty()) {
  14929. std::string event = events_.front();
  14930. events_.erase(events_.begin());
  14931. sink.write(event.data(), event.size());
  14932. return true;
  14933. }
  14934. }
  14935. return !stop_server_.load();
  14936. });
  14937. });
  14938. // Endpoint that returns error
  14939. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  14940. res.status = 500;
  14941. res.set_content("Internal Server Error", "text/plain");
  14942. });
  14943. // Endpoint for custom event types
  14944. server_->Get("/custom-events", [](const Request &, Response &res) {
  14945. res.set_chunked_content_provider(
  14946. "text/event-stream", [](size_t offset, DataSink &sink) {
  14947. if (offset == 0) {
  14948. std::string event = "event: update\ndata: updated\n\n"
  14949. "event: delete\ndata: deleted\n\n";
  14950. sink.write(event.data(), event.size());
  14951. }
  14952. return false; // End stream after sending
  14953. });
  14954. });
  14955. }
  14956. void start_server() {
  14957. port_ = server_->bind_to_any_port(HOST);
  14958. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14959. // Wait for server to start
  14960. while (!server_->is_running()) {
  14961. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14962. }
  14963. }
  14964. int get_port() const { return port_; }
  14965. void send_event(const std::string &event) {
  14966. std::lock_guard<std::mutex> lock(event_mutex_);
  14967. events_.push_back(event);
  14968. event_cv_.notify_all();
  14969. }
  14970. std::unique_ptr<Server> server_;
  14971. std::thread server_thread_;
  14972. std::mutex event_mutex_;
  14973. std::condition_variable event_cv_;
  14974. std::vector<std::string> events_;
  14975. std::atomic<bool> stop_server_{false};
  14976. std::string last_received_event_id_;
  14977. int port_ = 0;
  14978. };
  14979. // Test: Successful connection and on_open callback
  14980. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  14981. // Add a simple endpoint that sends one event and closes
  14982. server_->Get("/simple-event", [](const Request &, Response &res) {
  14983. res.set_chunked_content_provider(
  14984. "text/event-stream", [](size_t offset, DataSink &sink) {
  14985. if (offset == 0) {
  14986. std::string event = "data: hello\n\n";
  14987. sink.write(event.data(), event.size());
  14988. }
  14989. return false; // Close stream after sending
  14990. });
  14991. });
  14992. Client client("localhost", get_port());
  14993. sse::SSEClient sse(client, "/simple-event");
  14994. std::atomic<bool> open_called{false};
  14995. std::atomic<bool> message_received{false};
  14996. sse.on_open([&open_called]() { open_called.store(true); });
  14997. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  14998. if (msg.data == "hello") { message_received.store(true); }
  14999. });
  15000. sse.set_reconnect_interval(100);
  15001. sse.set_max_reconnect_attempts(1);
  15002. // Start async
  15003. sse.start_async();
  15004. // Wait for message to be processed
  15005. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15006. sse.stop();
  15007. EXPECT_TRUE(open_called.load());
  15008. EXPECT_TRUE(message_received.load());
  15009. }
  15010. // Test: on_message callback
  15011. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15012. // Endpoint that sends multiple events then closes
  15013. server_->Get("/multi-event", [](const Request &, Response &res) {
  15014. res.set_chunked_content_provider(
  15015. "text/event-stream", [](size_t offset, DataSink &sink) {
  15016. if (offset == 0) {
  15017. std::string events = "data: message1\n\ndata: message2\n\n";
  15018. sink.write(events.data(), events.size());
  15019. }
  15020. return false;
  15021. });
  15022. });
  15023. Client client("localhost", get_port());
  15024. sse::SSEClient sse(client, "/multi-event");
  15025. std::vector<std::string> received_messages;
  15026. std::mutex messages_mutex;
  15027. sse.on_message([&](const sse::SSEMessage &msg) {
  15028. std::lock_guard<std::mutex> lock(messages_mutex);
  15029. received_messages.push_back(msg.data);
  15030. });
  15031. sse.set_reconnect_interval(100);
  15032. sse.set_max_reconnect_attempts(1);
  15033. sse.start_async();
  15034. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15035. sse.stop();
  15036. std::lock_guard<std::mutex> lock(messages_mutex);
  15037. EXPECT_GE(received_messages.size(), 2u);
  15038. if (received_messages.size() >= 2) {
  15039. EXPECT_EQ(received_messages[0], "message1");
  15040. EXPECT_EQ(received_messages[1], "message2");
  15041. }
  15042. }
  15043. // Test: on_event for specific types
  15044. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15045. Client client("localhost", get_port());
  15046. sse::SSEClient sse(client, "/custom-events");
  15047. std::atomic<bool> update_received{false};
  15048. std::atomic<bool> delete_received{false};
  15049. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15050. if (msg.data == "updated") { update_received.store(true); }
  15051. });
  15052. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15053. if (msg.data == "deleted") { delete_received.store(true); }
  15054. });
  15055. sse.set_max_reconnect_attempts(1);
  15056. sse.start_async();
  15057. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15058. sse.stop();
  15059. EXPECT_TRUE(update_received.load());
  15060. EXPECT_TRUE(delete_received.load());
  15061. }
  15062. // Test: on_error callback on connection failure
  15063. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15064. // Connect to a non-existent port
  15065. Client client("localhost", 59999);
  15066. sse::SSEClient sse(client, "/events");
  15067. std::atomic<bool> error_called{false};
  15068. Error received_error = Error::Success;
  15069. sse.on_error([&](Error err) {
  15070. error_called.store(true);
  15071. received_error = err;
  15072. });
  15073. sse.set_reconnect_interval(50);
  15074. sse.set_max_reconnect_attempts(1);
  15075. sse.start_async();
  15076. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15077. sse.stop();
  15078. EXPECT_TRUE(error_called.load());
  15079. EXPECT_NE(received_error, Error::Success);
  15080. }
  15081. // Test: Last-Event-ID header sent on reconnect
  15082. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15083. // Endpoint that sends event with ID
  15084. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15085. res.set_chunked_content_provider(
  15086. "text/event-stream", [](size_t offset, DataSink &sink) {
  15087. if (offset == 0) {
  15088. std::string event = "id: evt-123\ndata: test\n\n";
  15089. sink.write(event.data(), event.size());
  15090. }
  15091. return false;
  15092. });
  15093. });
  15094. Client client("localhost", get_port());
  15095. sse::SSEClient sse(client, "/event-with-id");
  15096. std::atomic<bool> id_received{false};
  15097. sse.on_message([&](const sse::SSEMessage &msg) {
  15098. if (!msg.id.empty()) { id_received.store(true); }
  15099. });
  15100. sse.set_reconnect_interval(100);
  15101. sse.set_max_reconnect_attempts(1);
  15102. sse.start_async();
  15103. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15104. sse.stop();
  15105. EXPECT_TRUE(id_received.load());
  15106. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15107. }
  15108. // Test: Manual stop
  15109. TEST_F(SSEIntegrationTest, ManualStop) {
  15110. // Endpoint that sends one event and stays open briefly
  15111. std::atomic<bool> handler_running{true};
  15112. server_->Get("/stay-open", [&handler_running](const Request &,
  15113. Response &res) {
  15114. res.set_chunked_content_provider(
  15115. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15116. if (offset == 0) {
  15117. std::string event = "data: connected\n\n";
  15118. sink.write(event.data(), event.size());
  15119. }
  15120. // Keep connection open while handler_running is true
  15121. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15122. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15123. }
  15124. return false;
  15125. });
  15126. });
  15127. Client client("localhost", get_port());
  15128. sse::SSEClient sse(client, "/stay-open");
  15129. std::atomic<bool> connected{false};
  15130. sse.on_open([&connected]() { connected.store(true); });
  15131. sse.set_reconnect_interval(100);
  15132. sse.set_max_reconnect_attempts(1);
  15133. sse.start_async();
  15134. // Wait for connection to establish
  15135. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15136. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15137. }
  15138. EXPECT_TRUE(connected.load());
  15139. EXPECT_TRUE(sse.is_connected());
  15140. // Signal handler to stop
  15141. handler_running.store(false);
  15142. // Stop SSE client
  15143. sse.stop();
  15144. EXPECT_FALSE(sse.is_connected());
  15145. }
  15146. // Test: SSEClient with custom headers
  15147. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15148. // Setup a server endpoint that checks for custom header
  15149. std::atomic<bool> header_received{false};
  15150. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15151. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15152. header_received.store(true);
  15153. }
  15154. res.set_chunked_content_provider("text/event-stream",
  15155. [](size_t, DataSink &) { return false; });
  15156. });
  15157. Client client("localhost", get_port());
  15158. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15159. sse::SSEClient sse(client, "/header-check", headers);
  15160. sse.set_max_reconnect_attempts(1);
  15161. sse.start_async();
  15162. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15163. sse.stop();
  15164. EXPECT_TRUE(header_received.load());
  15165. }
  15166. // Test: Reconnect interval configuration
  15167. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15168. Client client("localhost", get_port());
  15169. sse::SSEClient sse(client, "/events");
  15170. auto &result = sse.set_reconnect_interval(500);
  15171. // Builder pattern should return reference to self
  15172. EXPECT_EQ(&result, &sse);
  15173. }
  15174. // Test: Max reconnect attempts
  15175. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15176. // Connect to non-existent port to force reconnects
  15177. Client client("localhost", 59998);
  15178. sse::SSEClient sse(client, "/events");
  15179. std::atomic<int> error_count{0};
  15180. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15181. sse.set_reconnect_interval(50);
  15182. sse.set_max_reconnect_attempts(2);
  15183. auto start = std::chrono::steady_clock::now();
  15184. sse.start(); // Blocking call
  15185. auto end = std::chrono::steady_clock::now();
  15186. // Should have stopped after 2 failed attempts
  15187. EXPECT_GE(error_count.load(), 2);
  15188. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15189. auto duration =
  15190. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15191. #ifdef _WIN32
  15192. // Windows is much slower for socket connection failures
  15193. EXPECT_LT(duration.count(), 7000);
  15194. #else
  15195. EXPECT_LT(duration.count(), 1000);
  15196. #endif
  15197. }
  15198. // Test: Multi-line data in integration
  15199. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15200. // Endpoint with multi-line data
  15201. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15202. res.set_chunked_content_provider(
  15203. "text/event-stream", [](size_t offset, DataSink &sink) {
  15204. if (offset == 0) {
  15205. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15206. sink.write(event.data(), event.size());
  15207. }
  15208. return false;
  15209. });
  15210. });
  15211. Client client("localhost", get_port());
  15212. sse::SSEClient sse(client, "/multiline-data");
  15213. std::string received_data;
  15214. std::mutex data_mutex;
  15215. sse.on_message([&](const sse::SSEMessage &msg) {
  15216. std::lock_guard<std::mutex> lock(data_mutex);
  15217. received_data = msg.data;
  15218. });
  15219. sse.set_reconnect_interval(100);
  15220. sse.set_max_reconnect_attempts(1);
  15221. sse.start_async();
  15222. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15223. sse.stop();
  15224. std::lock_guard<std::mutex> lock(data_mutex);
  15225. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15226. }
  15227. // Test: Auto-reconnect after server disconnection
  15228. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15229. std::atomic<int> connection_count{0};
  15230. std::atomic<int> message_count{0};
  15231. // Endpoint that sends one event and closes, forcing reconnect
  15232. server_->Get("/reconnect-test",
  15233. [&connection_count](const Request &, Response &res) {
  15234. connection_count.fetch_add(1);
  15235. res.set_chunked_content_provider(
  15236. "text/event-stream", [](size_t offset, DataSink &sink) {
  15237. if (offset == 0) {
  15238. std::string event = "data: hello\n\n";
  15239. sink.write(event.data(), event.size());
  15240. }
  15241. return false; // Close connection after sending
  15242. });
  15243. });
  15244. Client client("localhost", get_port());
  15245. sse::SSEClient sse(client, "/reconnect-test");
  15246. sse.on_message([&message_count](const sse::SSEMessage &) {
  15247. message_count.fetch_add(1);
  15248. });
  15249. sse.set_reconnect_interval(100);
  15250. sse.set_max_reconnect_attempts(3);
  15251. sse.start_async();
  15252. // Wait long enough for multiple reconnects
  15253. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15254. sse.stop();
  15255. // Should have connected multiple times (initial + reconnects)
  15256. EXPECT_GE(connection_count.load(), 2);
  15257. // Should have received messages from multiple connections
  15258. EXPECT_GE(message_count.load(), 2);
  15259. }
  15260. // Test: Last-Event-ID sent on reconnect
  15261. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15262. std::atomic<int> connection_count{0};
  15263. std::vector<std::string> received_last_event_ids;
  15264. std::mutex id_mutex;
  15265. // Endpoint that checks Last-Event-ID header and sends event with ID
  15266. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15267. int conn = connection_count.fetch_add(1);
  15268. // Capture the Last-Event-ID header from each connection
  15269. {
  15270. std::lock_guard<std::mutex> lock(id_mutex);
  15271. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15272. }
  15273. res.set_chunked_content_provider(
  15274. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15275. if (offset == 0) {
  15276. std::string event =
  15277. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15278. sink.write(event.data(), event.size());
  15279. }
  15280. return false;
  15281. });
  15282. });
  15283. Client client("localhost", get_port());
  15284. sse::SSEClient sse(client, "/reconnect-with-id");
  15285. sse.set_reconnect_interval(100);
  15286. sse.set_max_reconnect_attempts(3);
  15287. sse.start_async();
  15288. // Wait for at least 2 connections
  15289. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15290. sse.stop();
  15291. // Verify behavior
  15292. std::lock_guard<std::mutex> lock(id_mutex);
  15293. EXPECT_GE(received_last_event_ids.size(), 2u);
  15294. // First connection should have no Last-Event-ID
  15295. if (!received_last_event_ids.empty()) {
  15296. EXPECT_EQ(received_last_event_ids[0], "");
  15297. }
  15298. // Second connection should have Last-Event-ID from first connection
  15299. if (received_last_event_ids.size() >= 2) {
  15300. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15301. }
  15302. }
  15303. // Test: set_headers updates headers used on reconnect
  15304. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15305. std::vector<std::string> received_tokens;
  15306. std::mutex token_mutex;
  15307. // Endpoint that captures Authorization header
  15308. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15309. {
  15310. std::lock_guard<std::mutex> lock(token_mutex);
  15311. received_tokens.push_back(req.get_header_value("Authorization"));
  15312. }
  15313. res.set_chunked_content_provider(
  15314. "text/event-stream", [](size_t offset, DataSink &sink) {
  15315. if (offset == 0) {
  15316. std::string event = "data: hello\n\n";
  15317. sink.write(event.data(), event.size());
  15318. }
  15319. return false; // Close connection to trigger reconnect
  15320. });
  15321. });
  15322. Client client("localhost", get_port());
  15323. Headers headers = {{"Authorization", "Bearer old-token"}};
  15324. sse::SSEClient sse(client, "/auth-check", headers);
  15325. // Update headers on each successful connection
  15326. sse.on_open(
  15327. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15328. sse.set_reconnect_interval(100);
  15329. sse.set_max_reconnect_attempts(3);
  15330. sse.start_async();
  15331. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15332. sse.stop();
  15333. std::lock_guard<std::mutex> lock(token_mutex);
  15334. ASSERT_GE(received_tokens.size(), 2u);
  15335. // First connection uses original header
  15336. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15337. // Second connection uses updated header from set_headers
  15338. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15339. }
  15340. // Test: 401 allows reconnection (so on_error can refresh headers)
  15341. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15342. std::atomic<int> connection_count{0};
  15343. // Endpoint: returns 401 on first attempt, 200 on second
  15344. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15345. int conn = connection_count.fetch_add(1);
  15346. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15347. res.status = StatusCode::Unauthorized_401;
  15348. res.set_content("Unauthorized", "text/plain");
  15349. return;
  15350. }
  15351. res.set_chunked_content_provider(
  15352. "text/event-stream", [](size_t offset, DataSink &sink) {
  15353. if (offset == 0) {
  15354. std::string event = "data: authenticated\n\n";
  15355. sink.write(event.data(), event.size());
  15356. }
  15357. return false;
  15358. });
  15359. });
  15360. Client client("localhost", get_port());
  15361. Headers headers = {{"Authorization", "Bearer expired"}};
  15362. sse::SSEClient sse(client, "/auth-retry", headers);
  15363. std::atomic<bool> message_received{false};
  15364. // Refresh token on error
  15365. sse.on_error(
  15366. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15367. sse.on_message([&](const sse::SSEMessage &msg) {
  15368. if (msg.data == "authenticated") { message_received.store(true); }
  15369. });
  15370. sse.set_reconnect_interval(100);
  15371. sse.set_max_reconnect_attempts(3);
  15372. sse.start_async();
  15373. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15374. sse.stop();
  15375. // Should have reconnected after 401 and succeeded with new token
  15376. EXPECT_GE(connection_count.load(), 2);
  15377. EXPECT_TRUE(message_received.load());
  15378. }
  15379. TEST(Issue2318Test, EmptyHostString) {
  15380. {
  15381. httplib::Client cli_empty("", PORT);
  15382. auto res = cli_empty.Get("/");
  15383. ASSERT_FALSE(res);
  15384. EXPECT_EQ(httplib::Error::Connection, res.error());
  15385. }
  15386. {
  15387. httplib::Client cli(" ", PORT);
  15388. auto res = cli.Get("/");
  15389. ASSERT_FALSE(res);
  15390. EXPECT_EQ(httplib::Error::Connection, res.error());
  15391. }
  15392. }
  15393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15394. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15395. Server svr;
  15396. // Set a small payload limit (1KB)
  15397. svr.set_payload_max_length(1024);
  15398. svr.Post("/test", [&](const Request &req, Response &res) {
  15399. res.set_content("Body size: " + std::to_string(req.body.size()),
  15400. "text/plain");
  15401. });
  15402. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15403. auto se = detail::scope_exit([&] {
  15404. svr.stop();
  15405. listen_thread.join();
  15406. });
  15407. svr.wait_until_ready();
  15408. // Create data that compresses well but exceeds limit when decompressed
  15409. // 8KB of repeated null bytes compresses to a very small size
  15410. std::string original_data(8 * 1024, '\0');
  15411. // Compress the data using gzip
  15412. std::string compressed_data;
  15413. detail::gzip_compressor compressor;
  15414. compressor.compress(original_data.data(), original_data.size(), true,
  15415. [&](const char *data, size_t size) {
  15416. compressed_data.append(data, size);
  15417. return true;
  15418. });
  15419. // Verify compression worked (compressed should be much smaller)
  15420. ASSERT_LT(compressed_data.size(), original_data.size());
  15421. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15422. // Send compressed data with Content-Encoding: gzip
  15423. Client cli(HOST, PORT);
  15424. Headers headers = {{"Content-Encoding", "gzip"}};
  15425. auto res =
  15426. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15427. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15429. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15430. }
  15431. #endif
  15432. // ============================================================================
  15433. // OpenSSL-Specific Tests
  15434. // ============================================================================
  15435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15436. X509 *readCertificate(const std::string &strFileName) {
  15437. std::ifstream inStream(strFileName);
  15438. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15439. std::istreambuf_iterator<char>());
  15440. if (strCertPEM.empty()) return (nullptr);
  15441. BIO *pbCert = BIO_new(BIO_s_mem());
  15442. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15443. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15444. BIO_free(pbCert);
  15445. return (pCert);
  15446. }
  15447. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15448. std::ifstream inStream(strFileName);
  15449. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15450. std::istreambuf_iterator<char>());
  15451. if (strPrivateKeyPEM.empty()) return (nullptr);
  15452. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15453. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15454. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15455. BIO_free(pbPrivKey);
  15456. return (pPrivateKey);
  15457. }
  15458. TEST(BindServerTest, UpdateCerts) {
  15459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15460. int port = svr.bind_to_any_port("0.0.0.0");
  15461. ASSERT_TRUE(svr.is_valid());
  15462. ASSERT_TRUE(port > 0);
  15463. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15464. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15465. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15466. ASSERT_TRUE(cert != nullptr);
  15467. ASSERT_TRUE(ca_cert != nullptr);
  15468. ASSERT_TRUE(key != nullptr);
  15469. X509_STORE *cert_store = X509_STORE_new();
  15470. X509_STORE_add_cert(cert_store, ca_cert);
  15471. // svr.update_certs(cert, key, cert_store); // deprecated
  15472. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15473. CLIENT_CA_CERT_FILE);
  15474. ASSERT_TRUE(svr.is_valid());
  15475. svr.stop();
  15476. X509_STORE_free(cert_store);
  15477. X509_free(cert);
  15478. X509_free(ca_cert);
  15479. EVP_PKEY_free(key);
  15480. }
  15481. // Test that update_certs() updates client CA list correctly
  15482. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15483. // Start with file-based constructor
  15484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15485. ASSERT_TRUE(svr.is_valid());
  15486. // Initially no client CA list should be set
  15487. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15488. ASSERT_TRUE(ssl_ctx != nullptr);
  15489. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15490. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15491. EXPECT_EQ(0, count_before);
  15492. // Now update with client CA (PEM string)
  15493. std::string cert_pem, key_pem, ca_pem;
  15494. read_file(SERVER_CERT_FILE, cert_pem);
  15495. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15496. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15497. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15498. ASSERT_TRUE(svr.is_valid());
  15499. // Now client CA list should be set
  15500. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15501. ASSERT_TRUE(ca_list_after != nullptr);
  15502. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15503. }
  15504. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15505. // Test that the file-path SSLServer constructor properly sets the client CA
  15506. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15508. ASSERT_TRUE(svr.is_valid());
  15509. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15510. ASSERT_TRUE(ssl_ctx != nullptr);
  15511. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15512. ASSERT_TRUE(ca_list != nullptr);
  15513. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15514. }
  15515. #endif
  15516. // ============================================================================
  15517. // MbedTLS-Specific Tests
  15518. // ============================================================================
  15519. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15520. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15521. using namespace httplib::tls;
  15522. // Track if callback was invoked
  15523. bool callback_invoked = false;
  15524. // The callback receives void* ctx which is actually MbedTlsContext*
  15525. // We can access the mbedtls_ssl_config via the context
  15526. auto setup_callback = [&callback_invoked](void *ctx) {
  15527. callback_invoked = true;
  15528. // Cast to MbedTlsContext* to access the ssl config
  15529. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15530. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15531. // Use static variables to hold certificate data (simplified for test)
  15532. static mbedtls_x509_crt own_cert;
  15533. static mbedtls_pk_context own_key;
  15534. static mbedtls_x509_crt ca_chain;
  15535. static bool initialized = false;
  15536. if (!initialized) {
  15537. mbedtls_x509_crt_init(&own_cert);
  15538. mbedtls_pk_init(&own_key);
  15539. mbedtls_x509_crt_init(&ca_chain);
  15540. // Load server certificate
  15541. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15542. return false;
  15543. }
  15544. // Load server private key.
  15545. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15546. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15547. #if MBEDTLS_VERSION_MAJOR == 3
  15548. ,
  15549. mbedtls_ctr_drbg_random, nullptr
  15550. #endif
  15551. ) != 0) {
  15552. return false;
  15553. }
  15554. // Load CA chain for client verification
  15555. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15556. return false;
  15557. }
  15558. initialized = true;
  15559. }
  15560. // Configure the SSL config
  15561. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15562. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15563. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15564. // Set minimum TLS version using mbedTLS native API
  15565. #if MBEDTLS_VERSION_MAJOR >= 3
  15566. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15567. #else
  15568. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15569. MBEDTLS_SSL_MINOR_VERSION_3);
  15570. #endif
  15571. return true;
  15572. };
  15573. SSLServer svr(setup_callback);
  15574. ASSERT_TRUE(svr.is_valid());
  15575. ASSERT_TRUE(callback_invoked);
  15576. svr.Get("/test", [&](const Request &req, Response &res) {
  15577. res.set_content("test", "text/plain");
  15578. auto cert = req.peer_cert();
  15579. ASSERT_TRUE(static_cast<bool>(cert));
  15580. auto common_name = cert.subject_cn();
  15581. EXPECT_EQ("Common Name", common_name);
  15582. });
  15583. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15584. auto se = detail::scope_exit([&] {
  15585. svr.stop();
  15586. t.join();
  15587. ASSERT_FALSE(svr.is_running());
  15588. });
  15589. svr.wait_until_ready();
  15590. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15591. cli.enable_server_certificate_verification(false);
  15592. cli.set_connection_timeout(30);
  15593. auto res = cli.Get("/test");
  15594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15595. ASSERT_EQ(StatusCode::OK_200, res->status);
  15596. }
  15597. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15598. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15599. // keep-alive SSL session, which reads through that config in
  15600. // mbedtls_ssl_close_notify.
  15601. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15603. ASSERT_TRUE(svr.is_valid());
  15604. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15605. res.set_content("test", "text/plain");
  15606. });
  15607. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15608. auto se = detail::scope_exit([&] {
  15609. svr.stop();
  15610. t.join();
  15611. ASSERT_FALSE(svr.is_running());
  15612. });
  15613. svr.wait_until_ready();
  15614. {
  15615. SSLClient cli(HOST, PORT);
  15616. cli.enable_server_certificate_verification(false);
  15617. cli.set_keep_alive(true);
  15618. auto res = cli.Get("/test");
  15619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15620. ASSERT_EQ(StatusCode::OK_200, res->status);
  15621. // cli is destructed here with the keep-alive SSL session still open.
  15622. }
  15623. }
  15624. #endif
  15625. // WebSocket Tests
  15626. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15627. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15628. // defining the meaning of these bits has been negotiated.
  15629. auto make_frame = [](uint8_t first_byte) {
  15630. std::string frame;
  15631. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15632. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15633. frame += "Hello";
  15634. return frame;
  15635. };
  15636. // RSV1 set (0x40)
  15637. {
  15638. detail::BufferStream strm;
  15639. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15640. ws::Opcode opcode;
  15641. std::string payload;
  15642. bool fin;
  15643. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15644. false, 1024));
  15645. }
  15646. // RSV2 set (0x20)
  15647. {
  15648. detail::BufferStream strm;
  15649. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15650. ws::Opcode opcode;
  15651. std::string payload;
  15652. bool fin;
  15653. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15654. false, 1024));
  15655. }
  15656. // RSV3 set (0x10)
  15657. {
  15658. detail::BufferStream strm;
  15659. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15660. ws::Opcode opcode;
  15661. std::string payload;
  15662. bool fin;
  15663. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15664. false, 1024));
  15665. }
  15666. // No RSV bits set - should succeed
  15667. {
  15668. detail::BufferStream strm;
  15669. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15670. ws::Opcode opcode;
  15671. std::string payload;
  15672. bool fin;
  15673. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15674. false, 1024));
  15675. EXPECT_EQ(ws::Opcode::Text, opcode);
  15676. EXPECT_EQ("Hello", payload);
  15677. EXPECT_TRUE(fin);
  15678. }
  15679. }
  15680. TEST(WebSocketTest, ControlFrameValidation) {
  15681. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15682. // payload length <= 125.
  15683. // Ping with FIN=0 - must be rejected
  15684. {
  15685. detail::BufferStream strm;
  15686. std::string frame;
  15687. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15688. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15689. strm.write(frame.data(), frame.size());
  15690. ws::Opcode opcode;
  15691. std::string payload;
  15692. bool fin;
  15693. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15694. false, 1024));
  15695. }
  15696. // Close with FIN=0 - must be rejected
  15697. {
  15698. detail::BufferStream strm;
  15699. std::string frame;
  15700. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15701. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15702. strm.write(frame.data(), frame.size());
  15703. ws::Opcode opcode;
  15704. std::string payload;
  15705. bool fin;
  15706. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15707. false, 1024));
  15708. }
  15709. // Ping with payload_len=126 (extended length) - must be rejected
  15710. {
  15711. detail::BufferStream strm;
  15712. std::string frame;
  15713. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15714. frame += static_cast<char>(126); // payload_len=126 (>125)
  15715. frame += static_cast<char>(0x00); // extended length high byte
  15716. frame += static_cast<char>(126); // extended length low byte
  15717. frame += std::string(126, 'x');
  15718. strm.write(frame.data(), frame.size());
  15719. ws::Opcode opcode;
  15720. std::string payload;
  15721. bool fin;
  15722. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15723. false, 1024));
  15724. }
  15725. // Ping with FIN=1 and payload_len=125 - should succeed
  15726. {
  15727. detail::BufferStream strm;
  15728. std::string frame;
  15729. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15730. frame += static_cast<char>(125); // payload_len=125
  15731. frame += std::string(125, 'x');
  15732. strm.write(frame.data(), frame.size());
  15733. ws::Opcode opcode;
  15734. std::string payload;
  15735. bool fin;
  15736. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15737. false, 1024));
  15738. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15739. EXPECT_EQ(125u, payload.size());
  15740. EXPECT_TRUE(fin);
  15741. }
  15742. }
  15743. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15744. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15745. // length MUST be 0.
  15746. // MSB set - must be rejected
  15747. {
  15748. detail::BufferStream strm;
  15749. std::string frame;
  15750. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15751. frame += static_cast<char>(127); // 64-bit extended length
  15752. frame += static_cast<char>(0x80); // MSB set (invalid)
  15753. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15754. strm.write(frame.data(), frame.size());
  15755. ws::Opcode opcode;
  15756. std::string payload;
  15757. bool fin;
  15758. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15759. false, 1024));
  15760. }
  15761. // MSB clear - should pass length parsing (will be rejected by max_len,
  15762. // but that's a different check; use a small length to verify)
  15763. {
  15764. detail::BufferStream strm;
  15765. std::string frame;
  15766. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15767. frame += static_cast<char>(127); // 64-bit extended length
  15768. frame += std::string(7, '\0'); // high bytes = 0
  15769. frame += static_cast<char>(0x03); // length = 3
  15770. frame += "abc";
  15771. strm.write(frame.data(), frame.size());
  15772. ws::Opcode opcode;
  15773. std::string payload;
  15774. bool fin;
  15775. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15776. false, 1024));
  15777. EXPECT_EQ(ws::Opcode::Text, opcode);
  15778. EXPECT_EQ("abc", payload);
  15779. }
  15780. }
  15781. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  15782. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  15783. // Valid UTF-8
  15784. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  15785. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  15786. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  15787. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  15788. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  15789. // Invalid UTF-8
  15790. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  15791. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  15792. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  15793. EXPECT_FALSE(
  15794. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  15795. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  15796. }
  15797. TEST(WebSocketTest, ConnectAndDisconnect) {
  15798. Server svr;
  15799. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15800. std::string msg;
  15801. while (ws.read(msg)) {}
  15802. });
  15803. auto port = svr.bind_to_any_port(HOST);
  15804. std::thread t([&]() { svr.listen_after_bind(); });
  15805. svr.wait_until_ready();
  15806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15807. ASSERT_TRUE(client.connect());
  15808. EXPECT_TRUE(client.is_open());
  15809. client.close();
  15810. EXPECT_FALSE(client.is_open());
  15811. svr.stop();
  15812. t.join();
  15813. }
  15814. TEST(WebSocketTest, ValidURL) {
  15815. ws::WebSocketClient ws1("ws://localhost:8080/path");
  15816. EXPECT_TRUE(ws1.is_valid());
  15817. ws::WebSocketClient ws2("ws://example.com/path");
  15818. EXPECT_TRUE(ws2.is_valid());
  15819. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  15820. EXPECT_TRUE(ws3.is_valid());
  15821. #ifdef CPPHTTPLIB_SSL_ENABLED
  15822. ws::WebSocketClient wss1("wss://example.com/path");
  15823. EXPECT_TRUE(wss1.is_valid());
  15824. ws::WebSocketClient wss2("wss://example.com:443/path");
  15825. EXPECT_TRUE(wss2.is_valid());
  15826. #endif
  15827. }
  15828. TEST(WebSocketTest, InvalidURL) {
  15829. // No scheme
  15830. ws::WebSocketClient ws1("localhost:8080/path");
  15831. EXPECT_FALSE(ws1.is_valid());
  15832. // No path
  15833. ws::WebSocketClient ws2("ws://localhost:8080");
  15834. EXPECT_FALSE(ws2.is_valid());
  15835. // Empty string
  15836. ws::WebSocketClient ws3("");
  15837. EXPECT_FALSE(ws3.is_valid());
  15838. // Missing host
  15839. ws::WebSocketClient ws4("ws://:8080/path");
  15840. EXPECT_FALSE(ws4.is_valid());
  15841. // Port number overflow — should not crash
  15842. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  15843. EXPECT_FALSE(ws5.is_valid());
  15844. // Port out of range
  15845. ws::WebSocketClient ws6("ws://localhost:99999/path");
  15846. EXPECT_FALSE(ws6.is_valid());
  15847. }
  15848. TEST(WebSocketTest, UnsupportedScheme) {
  15849. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15850. ws::WebSocketClient ws1("http://localhost:8080/path");
  15851. EXPECT_FALSE(ws1.is_valid());
  15852. ws::WebSocketClient ws2("https://localhost:8080/path");
  15853. EXPECT_FALSE(ws2.is_valid());
  15854. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  15855. EXPECT_FALSE(ws3.is_valid());
  15856. #else
  15857. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  15858. std::invalid_argument);
  15859. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  15860. std::invalid_argument);
  15861. #endif
  15862. }
  15863. TEST(WebSocketTest, ConnectWhenInvalid) {
  15864. ws::WebSocketClient ws("not a valid url");
  15865. EXPECT_FALSE(ws.is_valid());
  15866. EXPECT_FALSE(ws.connect());
  15867. }
  15868. TEST(WebSocketTest, DefaultPort) {
  15869. ws::WebSocketClient ws1("ws://example.com/path");
  15870. EXPECT_TRUE(ws1.is_valid());
  15871. // ws:// defaults to port 80 (verified by successful parse)
  15872. #ifdef CPPHTTPLIB_SSL_ENABLED
  15873. ws::WebSocketClient ws2("wss://example.com/path");
  15874. EXPECT_TRUE(ws2.is_valid());
  15875. // wss:// defaults to port 443 (verified by successful parse)
  15876. #endif
  15877. }
  15878. TEST(WebSocketTest, IPv6LiteralAddress) {
  15879. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  15880. EXPECT_TRUE(ws1.is_valid());
  15881. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  15882. EXPECT_TRUE(ws2.is_valid());
  15883. }
  15884. TEST(WebSocketTest, ComplexPath) {
  15885. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  15886. EXPECT_TRUE(ws1.is_valid());
  15887. ws::WebSocketClient ws2("ws://localhost:8080/");
  15888. EXPECT_TRUE(ws2.is_valid());
  15889. }
  15890. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  15891. Server svr;
  15892. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15893. std::string msg;
  15894. while (ws.read(msg)) {}
  15895. });
  15896. auto port = svr.bind_to_any_port(HOST);
  15897. std::thread t([&]() { svr.listen_after_bind(); });
  15898. svr.wait_until_ready();
  15899. auto another_host = "example.com";
  15900. auto wrong_ip = "192.0.2.1";
  15901. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15902. client.set_hostname_addr_map({{another_host, wrong_ip}});
  15903. ASSERT_TRUE(client.connect());
  15904. EXPECT_TRUE(client.is_open());
  15905. client.close();
  15906. svr.stop();
  15907. t.join();
  15908. }
  15909. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  15910. Server svr;
  15911. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15912. std::string msg;
  15913. while (ws.read(msg)) {}
  15914. });
  15915. auto port = svr.bind_to_any_port(HOST);
  15916. std::thread t([&]() { svr.listen_after_bind(); });
  15917. svr.wait_until_ready();
  15918. auto wrong_ip = "192.0.2.1";
  15919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  15920. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  15921. client.set_connection_timeout(1);
  15922. client.set_read_timeout(1);
  15923. client.set_write_timeout(1);
  15924. EXPECT_FALSE(client.connect());
  15925. EXPECT_FALSE(client.is_open());
  15926. svr.stop();
  15927. t.join();
  15928. }
  15929. class WebSocketIntegrationTest : public ::testing::Test {
  15930. protected:
  15931. void SetUp() override {
  15932. server_ = httplib::detail::make_unique<Server>();
  15933. setup_server();
  15934. start_server();
  15935. }
  15936. void TearDown() override {
  15937. server_->stop();
  15938. if (server_thread_.joinable()) { server_thread_.join(); }
  15939. }
  15940. void setup_server() {
  15941. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15942. std::string msg;
  15943. ws::ReadResult ret;
  15944. while ((ret = ws.read(msg))) {
  15945. if (ret == ws::Binary) {
  15946. ws.send(msg.data(), msg.size());
  15947. } else {
  15948. ws.send(msg);
  15949. }
  15950. }
  15951. });
  15952. server_->WebSocket("/ws-echo-string",
  15953. [](const Request &, ws::WebSocket &ws) {
  15954. std::string msg;
  15955. while (ws.read(msg)) {
  15956. ws.send("echo: " + msg);
  15957. }
  15958. });
  15959. server_->WebSocket(
  15960. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  15961. // Echo back request metadata
  15962. ws.send("path:" + req.path);
  15963. ws.send("header:" + req.get_header_value("X-Test-Header"));
  15964. std::string msg;
  15965. while (ws.read(msg)) {}
  15966. });
  15967. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  15968. std::string msg;
  15969. ws.read(msg); // wait for a message
  15970. ws.close();
  15971. });
  15972. server_->WebSocket("/ws-close-status",
  15973. [](const Request &, ws::WebSocket &ws) {
  15974. std::string msg;
  15975. ws.read(msg); // wait for a message
  15976. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  15977. });
  15978. server_->WebSocket(
  15979. "/ws-subprotocol",
  15980. [](const Request &, ws::WebSocket &ws) {
  15981. std::string msg;
  15982. while (ws.read(msg)) {
  15983. ws.send(msg);
  15984. }
  15985. },
  15986. [](const std::vector<std::string> &protocols) -> std::string {
  15987. for (const auto &p : protocols) {
  15988. if (p == "graphql-ws") { return p; }
  15989. }
  15990. return "";
  15991. });
  15992. }
  15993. void start_server() {
  15994. port_ = server_->bind_to_any_port(HOST);
  15995. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15996. server_->wait_until_ready();
  15997. }
  15998. std::unique_ptr<Server> server_;
  15999. std::thread server_thread_;
  16000. int port_ = 0;
  16001. };
  16002. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16004. "/ws-echo");
  16005. ASSERT_TRUE(client.connect());
  16006. ASSERT_TRUE(client.is_open());
  16007. ASSERT_TRUE(client.send("Hello WebSocket"));
  16008. std::string msg;
  16009. EXPECT_EQ(ws::Text, client.read(msg));
  16010. EXPECT_EQ("Hello WebSocket", msg);
  16011. client.close();
  16012. }
  16013. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16014. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16015. "/ws-echo");
  16016. ASSERT_TRUE(client.connect());
  16017. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16018. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16019. std::string msg;
  16020. EXPECT_EQ(ws::Binary, client.read(msg));
  16021. EXPECT_EQ(binary_data, msg);
  16022. client.close();
  16023. }
  16024. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16026. "/ws-echo");
  16027. ASSERT_TRUE(client.connect());
  16028. for (int i = 0; i < 10; i++) {
  16029. auto text = "message " + std::to_string(i);
  16030. ASSERT_TRUE(client.send(text));
  16031. std::string msg;
  16032. ASSERT_TRUE(client.read(msg));
  16033. EXPECT_EQ(text, msg);
  16034. }
  16035. client.close();
  16036. }
  16037. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16039. "/ws-close");
  16040. ASSERT_TRUE(client.connect());
  16041. // Send a message to trigger the server to close
  16042. ASSERT_TRUE(client.send("trigger close"));
  16043. // The server will close, so read should return false
  16044. std::string msg;
  16045. EXPECT_FALSE(client.read(msg));
  16046. EXPECT_FALSE(client.is_open());
  16047. }
  16048. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16050. "/ws-echo");
  16051. ASSERT_TRUE(client.connect());
  16052. // 128KB message
  16053. std::string large_data(128 * 1024, 'X');
  16054. ASSERT_TRUE(client.send(large_data));
  16055. std::string msg;
  16056. ASSERT_TRUE(client.read(msg));
  16057. EXPECT_EQ(large_data, msg);
  16058. client.close();
  16059. }
  16060. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16062. "/ws-echo");
  16063. ASSERT_TRUE(client.connect());
  16064. const int num_threads = 4;
  16065. std::vector<std::thread> threads;
  16066. std::atomic<int> send_count{0};
  16067. for (int t = 0; t < num_threads; t++) {
  16068. threads.emplace_back([&client, &send_count, t]() {
  16069. for (int i = 0; i < 5; i++) {
  16070. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16071. if (client.send(text)) { send_count++; }
  16072. }
  16073. });
  16074. }
  16075. for (auto &th : threads) {
  16076. th.join();
  16077. }
  16078. int received = 0;
  16079. std::string msg;
  16080. while (received < send_count.load()) {
  16081. if (!client.read(msg)) { break; }
  16082. received++;
  16083. }
  16084. EXPECT_EQ(send_count.load(), received);
  16085. client.close();
  16086. }
  16087. TEST_F(WebSocketIntegrationTest, ReadString) {
  16088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16089. "/ws-echo-string");
  16090. ASSERT_TRUE(client.connect());
  16091. ASSERT_TRUE(client.send("hello"));
  16092. std::string msg;
  16093. ASSERT_TRUE(client.read(msg));
  16094. EXPECT_EQ("echo: hello", msg);
  16095. ASSERT_TRUE(client.send("world"));
  16096. ASSERT_TRUE(client.read(msg));
  16097. EXPECT_EQ("echo: world", msg);
  16098. client.close();
  16099. }
  16100. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16101. Headers headers = {{"X-Test-Header", "test-value"}};
  16102. ws::WebSocketClient client(
  16103. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16104. ASSERT_TRUE(client.connect());
  16105. std::string msg;
  16106. ASSERT_TRUE(client.read(msg));
  16107. EXPECT_EQ("path:/ws-request-info", msg);
  16108. ASSERT_TRUE(client.read(msg));
  16109. EXPECT_EQ("header:test-value", msg);
  16110. client.close();
  16111. }
  16112. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16113. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16114. "/ws-echo");
  16115. client.set_read_timeout(1, 0); // 1 second
  16116. ASSERT_TRUE(client.connect());
  16117. // Don't send anything — server echo handler waits for a message,
  16118. // so read() should time out and return false.
  16119. std::string msg;
  16120. EXPECT_FALSE(client.read(msg));
  16121. }
  16122. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16123. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16124. "/ws-echo");
  16125. client.set_read_timeout(5, 0);
  16126. ASSERT_TRUE(client.connect());
  16127. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16128. // The server should reject it and close the connection.
  16129. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16130. client.send(oversized);
  16131. // The server's read() should have failed due to payload limit,
  16132. // so our read() should return false (connection closed).
  16133. std::string msg;
  16134. EXPECT_FALSE(client.read(msg));
  16135. }
  16136. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16137. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16138. "/ws-echo");
  16139. client.set_read_timeout(10, 0);
  16140. ASSERT_TRUE(client.connect());
  16141. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16142. // This should succeed.
  16143. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16144. ASSERT_TRUE(client.send(at_limit));
  16145. std::string msg;
  16146. ASSERT_TRUE(client.read(msg));
  16147. EXPECT_EQ(at_limit.size(), msg.size());
  16148. client.close();
  16149. }
  16150. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16151. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16152. "/nonexistent");
  16153. EXPECT_FALSE(client.connect());
  16154. EXPECT_FALSE(client.is_open());
  16155. }
  16156. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16158. "/ws-echo");
  16159. ASSERT_TRUE(client.connect());
  16160. ASSERT_TRUE(client.send(""));
  16161. std::string msg;
  16162. EXPECT_EQ(ws::Text, client.read(msg));
  16163. EXPECT_EQ("", msg);
  16164. client.close();
  16165. }
  16166. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16168. "/ws-echo");
  16169. // First connection
  16170. ASSERT_TRUE(client.connect());
  16171. ASSERT_TRUE(client.send("first"));
  16172. std::string msg;
  16173. ASSERT_TRUE(client.read(msg));
  16174. EXPECT_EQ("first", msg);
  16175. client.close();
  16176. EXPECT_FALSE(client.is_open());
  16177. // Reconnect using the same client object
  16178. ASSERT_TRUE(client.connect());
  16179. ASSERT_TRUE(client.is_open());
  16180. ASSERT_TRUE(client.send("second"));
  16181. ASSERT_TRUE(client.read(msg));
  16182. EXPECT_EQ("second", msg);
  16183. client.close();
  16184. }
  16185. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16187. "/ws-close-status");
  16188. ASSERT_TRUE(client.connect());
  16189. // Trigger the server to close with GoingAway status
  16190. ASSERT_TRUE(client.send("trigger"));
  16191. // read() should return false after receiving the close frame
  16192. std::string msg;
  16193. EXPECT_FALSE(client.read(msg));
  16194. EXPECT_FALSE(client.is_open());
  16195. }
  16196. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16198. "/ws-echo");
  16199. ASSERT_TRUE(client.connect());
  16200. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16201. EXPECT_FALSE(client.is_open());
  16202. }
  16203. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16204. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16205. ws::WebSocketClient client(
  16206. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16207. ASSERT_TRUE(client.connect());
  16208. // Server should have selected graphql-ws
  16209. EXPECT_EQ("graphql-ws", client.subprotocol());
  16210. client.close();
  16211. }
  16212. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16213. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16214. ws::WebSocketClient client(
  16215. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16216. ASSERT_TRUE(client.connect());
  16217. // Server should not have selected any subprotocol
  16218. EXPECT_TRUE(client.subprotocol().empty());
  16219. client.close();
  16220. }
  16221. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16222. // Connect without requesting any subprotocol
  16223. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16224. "/ws-subprotocol");
  16225. ASSERT_TRUE(client.connect());
  16226. EXPECT_TRUE(client.subprotocol().empty());
  16227. client.close();
  16228. }
  16229. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16231. "/ws-echo");
  16232. client.set_tcp_nodelay(true);
  16233. client.set_connection_timeout(3, 0);
  16234. bool socket_options_called = false;
  16235. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16236. ASSERT_TRUE(client.connect());
  16237. ASSERT_TRUE(client.is_open());
  16238. EXPECT_TRUE(socket_options_called);
  16239. ASSERT_TRUE(client.send("hello"));
  16240. std::string msg;
  16241. auto result = client.read(msg);
  16242. EXPECT_EQ(result, ws::ReadResult::Text);
  16243. EXPECT_EQ(msg, "hello");
  16244. client.close();
  16245. }
  16246. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16247. Server svr;
  16248. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16249. if (!req.has_header("Authorization")) {
  16250. res.status = StatusCode::Unauthorized_401;
  16251. res.set_content("Unauthorized", "text/plain");
  16252. return Server::HandlerResponse::Handled;
  16253. }
  16254. return Server::HandlerResponse::Unhandled;
  16255. });
  16256. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16257. std::string msg;
  16258. while (ws.read(msg)) {
  16259. ws.send(msg);
  16260. }
  16261. });
  16262. auto port = svr.bind_to_any_port("localhost");
  16263. std::thread t([&]() { svr.listen_after_bind(); });
  16264. svr.wait_until_ready();
  16265. // Without Authorization header - should be rejected before upgrade
  16266. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16267. EXPECT_FALSE(client1.connect());
  16268. // With Authorization header - should succeed
  16269. Headers headers = {{"Authorization", "Bearer token123"}};
  16270. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16271. headers);
  16272. ASSERT_TRUE(client2.connect());
  16273. ASSERT_TRUE(client2.send("hello"));
  16274. std::string msg;
  16275. ASSERT_TRUE(client2.read(msg));
  16276. EXPECT_EQ("hello", msg);
  16277. client2.close();
  16278. svr.stop();
  16279. t.join();
  16280. }
  16281. TEST(WebSocketTest, QueryStringInHandshake) {
  16282. Server svr;
  16283. std::mutex mtx;
  16284. std::string received_target;
  16285. std::string received_token;
  16286. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16287. {
  16288. std::lock_guard<std::mutex> lock(mtx);
  16289. received_target = req.target;
  16290. if (req.has_param("token")) {
  16291. received_token = req.get_param_value("token");
  16292. }
  16293. }
  16294. std::string msg;
  16295. while (ws.read(msg)) {
  16296. ws.send(msg);
  16297. }
  16298. });
  16299. auto port = svr.bind_to_any_port("localhost");
  16300. std::thread t([&]() { svr.listen_after_bind(); });
  16301. svr.wait_until_ready();
  16302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16303. "/ws?token=ABC&session=123");
  16304. ASSERT_TRUE(client.connect());
  16305. // Round-trip ensures the handler has run and captured the request.
  16306. ASSERT_TRUE(client.send("hello"));
  16307. std::string msg;
  16308. ASSERT_TRUE(client.read(msg));
  16309. EXPECT_EQ("hello", msg);
  16310. client.close();
  16311. {
  16312. std::lock_guard<std::mutex> lock(mtx);
  16313. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16314. EXPECT_EQ("ABC", received_token);
  16315. }
  16316. svr.stop();
  16317. t.join();
  16318. }
  16319. TEST(WebSocketTest, HostHeaderInHandshake) {
  16320. Server svr;
  16321. std::mutex mtx;
  16322. std::string received_host;
  16323. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16324. {
  16325. std::lock_guard<std::mutex> lock(mtx);
  16326. received_host = req.get_header_value("Host");
  16327. }
  16328. std::string msg;
  16329. while (ws.read(msg)) {
  16330. ws.send(msg);
  16331. }
  16332. });
  16333. auto port = svr.bind_to_any_port("localhost");
  16334. std::thread t([&]() { svr.listen_after_bind(); });
  16335. svr.wait_until_ready();
  16336. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16337. ASSERT_TRUE(client.connect());
  16338. // Round-trip ensures the handler has run and captured the request.
  16339. ASSERT_TRUE(client.send("hello"));
  16340. std::string msg;
  16341. ASSERT_TRUE(client.read(msg));
  16342. client.close();
  16343. {
  16344. std::lock_guard<std::mutex> lock(mtx);
  16345. // Non-default port must be present in the Host header. Default ports
  16346. // (80/443) are omitted; that logic is covered by
  16347. // MakeHostAndPortStringTest.
  16348. EXPECT_EQ("localhost:" + std::to_string(port), received_host);
  16349. }
  16350. svr.stop();
  16351. t.join();
  16352. }
  16353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16354. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16355. protected:
  16356. void SetUp() override {
  16357. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16358. SERVER_PRIVATE_KEY_FILE);
  16359. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16360. std::string msg;
  16361. ws::ReadResult ret;
  16362. while ((ret = ws.read(msg))) {
  16363. if (ret == ws::Binary) {
  16364. ws.send(msg.data(), msg.size());
  16365. } else {
  16366. ws.send(msg);
  16367. }
  16368. }
  16369. });
  16370. port_ = server_->bind_to_any_port(HOST);
  16371. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16372. server_->wait_until_ready();
  16373. }
  16374. void TearDown() override {
  16375. server_->stop();
  16376. if (server_thread_.joinable()) { server_thread_.join(); }
  16377. }
  16378. std::unique_ptr<SSLServer> server_;
  16379. std::thread server_thread_;
  16380. int port_ = 0;
  16381. };
  16382. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16383. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16384. "/ws-echo");
  16385. client.enable_server_certificate_verification(false);
  16386. ASSERT_TRUE(client.connect());
  16387. ASSERT_TRUE(client.is_open());
  16388. ASSERT_TRUE(client.send("Hello WSS"));
  16389. std::string msg;
  16390. EXPECT_EQ(ws::Text, client.read(msg));
  16391. EXPECT_EQ("Hello WSS", msg);
  16392. client.close();
  16393. }
  16394. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16395. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16396. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16397. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16398. // client (without calling close() first) is the only path that runs
  16399. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16400. // bug exactly.
  16401. //
  16402. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16403. // when linked against an instrumented libssl; run under Valgrind to catch it
  16404. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16405. // suite (the freed session otherwise stalls on the close handshake) — this test
  16406. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16407. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16408. {
  16409. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16410. "/ws-echo");
  16411. client.enable_server_certificate_verification(false);
  16412. client.set_read_timeout(2, 0);
  16413. client.set_write_timeout(2, 0);
  16414. ASSERT_TRUE(client.connect());
  16415. ASSERT_TRUE(client.is_open());
  16416. ASSERT_TRUE(client.send("still open"));
  16417. // Intentionally do NOT call client.close(): leaving scope runs
  16418. // shutdown_and_close() with the WebSocket still open, which must send the
  16419. // close frame while the TLS session is still alive.
  16420. }
  16421. }
  16422. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16423. // shutdown_and_close() at the start of connect(), reproducing the same
  16424. // use-after-free within the test body rather than at scope exit. The second
  16425. // connect must succeed and echo, proving the close handshake ran over a live
  16426. // session. See the note above about memory-tool requirements.
  16427. TEST_F(WebSocketSSLIntegrationTest,
  16428. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16429. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16430. "/ws-echo");
  16431. client.enable_server_certificate_verification(false);
  16432. client.set_read_timeout(2, 0);
  16433. client.set_write_timeout(2, 0);
  16434. ASSERT_TRUE(client.connect());
  16435. ASSERT_TRUE(client.is_open());
  16436. ASSERT_TRUE(client.send("still open"));
  16437. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16438. // the still-open connection, which must not touch a freed TLS session.
  16439. ASSERT_TRUE(client.connect());
  16440. ASSERT_TRUE(client.is_open());
  16441. ASSERT_TRUE(client.send("after reconnect"));
  16442. std::string msg;
  16443. EXPECT_EQ(ws::Text, client.read(msg));
  16444. EXPECT_EQ("after reconnect", msg);
  16445. client.close();
  16446. }
  16447. #endif
  16448. #ifdef CPPHTTPLIB_SSL_ENABLED
  16449. class WebSocketSSLCATest : public ::testing::Test {
  16450. protected:
  16451. void SetUp() override {
  16452. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16453. SERVER_PRIVATE_KEY_FILE);
  16454. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16455. std::string msg;
  16456. while (ws.read(msg)) {
  16457. ws.send(msg);
  16458. }
  16459. });
  16460. port_ = server_->bind_to_any_port("127.0.0.1");
  16461. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16462. server_->wait_until_ready();
  16463. }
  16464. void TearDown() override {
  16465. server_->stop();
  16466. if (server_thread_.joinable()) { server_thread_.join(); }
  16467. }
  16468. std::string url() const {
  16469. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16470. }
  16471. std::unique_ptr<SSLServer> server_;
  16472. std::thread server_thread_;
  16473. int port_ = 0;
  16474. };
  16475. // A custom CA loaded as PEM verifies the server with full certificate
  16476. // verification enabled
  16477. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16478. ws::WebSocketClient client(url());
  16479. std::string cert;
  16480. read_file(SERVER_CERT2_FILE, cert);
  16481. client.load_ca_cert_store(cert.c_str(), cert.size());
  16482. ASSERT_TRUE(client.connect());
  16483. ASSERT_TRUE(client.send("hello"));
  16484. std::string msg;
  16485. EXPECT_EQ(ws::Text, client.read(msg));
  16486. EXPECT_EQ("hello", msg);
  16487. client.close();
  16488. }
  16489. // A custom CA that does not cover the server must fail verification (the
  16490. // custom CA is exclusive; system certs are not loaded alongside it)
  16491. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16492. ws::WebSocketClient client(url());
  16493. std::string cert;
  16494. read_file(CLIENT_CA_CERT_FILE, cert);
  16495. client.load_ca_cert_store(cert.c_str(), cert.size());
  16496. ASSERT_FALSE(client.connect());
  16497. }
  16498. // Regression test: reconnecting with a native custom CA store used to reuse
  16499. // a store handle the previous TLS context had already freed (use-after-free
  16500. // under the OpenSSL backend). The context now lives as long as the client.
  16501. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16502. ws::WebSocketClient client(url());
  16503. std::string cert;
  16504. read_file(SERVER_CERT2_FILE, cert);
  16505. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16506. ASSERT_TRUE(client.connect());
  16507. client.close();
  16508. ASSERT_TRUE(client.connect());
  16509. ASSERT_TRUE(client.send("again"));
  16510. std::string msg;
  16511. EXPECT_EQ(ws::Text, client.read(msg));
  16512. EXPECT_EQ("again", msg);
  16513. client.close();
  16514. }
  16515. // Regression test: a certificate with a trusted chain but no identity match
  16516. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16517. // verification entirely for IP hosts, so this connection succeeded there.
  16518. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16519. // chain verification while the identity check must still fail.
  16520. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16522. ASSERT_TRUE(svr.is_valid());
  16523. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16524. std::string msg;
  16525. while (ws.read(msg)) {
  16526. ws.send(msg);
  16527. }
  16528. });
  16529. auto port = svr.bind_to_any_port("127.0.0.1");
  16530. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16531. auto se = detail::scope_exit([&] {
  16532. svr.stop();
  16533. t.join();
  16534. });
  16535. svr.wait_until_ready();
  16536. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16537. "/echo");
  16538. std::string cert;
  16539. read_file(SERVER_CERT_FILE, cert);
  16540. client.load_ca_cert_store(cert.c_str(), cert.size());
  16541. ASSERT_FALSE(client.connect());
  16542. }
  16543. #endif
  16544. #if !defined(_WIN32)
  16545. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16546. auto secret_dir = std::string("./symlink_test_secret");
  16547. auto served_dir = std::string("./symlink_test_served");
  16548. auto secret_file = secret_dir + "/secret.txt";
  16549. auto symlink_path = served_dir + "/escape";
  16550. // Setup: create directories and files
  16551. mkdir(secret_dir.c_str(), 0755);
  16552. mkdir(served_dir.c_str(), 0755);
  16553. {
  16554. std::ofstream ofs(secret_file);
  16555. ofs << "SECRET_DATA";
  16556. }
  16557. // Create symlink using absolute path so it resolves correctly
  16558. #ifdef PATH_MAX
  16559. char abs_secret[PATH_MAX];
  16560. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16561. #else
  16562. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16563. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16564. ASSERT_NE(nullptr, abs_secret);
  16565. #endif
  16566. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16567. auto se = detail::scope_exit([&] {
  16568. unlink(symlink_path.c_str());
  16569. unlink(secret_file.c_str());
  16570. rmdir(served_dir.c_str());
  16571. rmdir(secret_dir.c_str());
  16572. });
  16573. Server svr;
  16574. svr.set_mount_point("/", served_dir);
  16575. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16576. auto se2 = detail::scope_exit([&] {
  16577. svr.stop();
  16578. listen_thread.join();
  16579. });
  16580. svr.wait_until_ready();
  16581. Client cli("localhost", PORT);
  16582. // Symlink pointing outside base dir should be blocked
  16583. auto res = cli.Get("/escape/secret.txt");
  16584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16585. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16586. }
  16587. #endif
  16588. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16589. // A GET request with Content-Length to a static file handler must have its
  16590. // body drained before the keep-alive connection is reused. Otherwise the
  16591. // unread body bytes are interpreted as the next HTTP request.
  16592. //
  16593. // The body is sent AFTER receiving the first response (as in the original
  16594. // PoC) so that the stream_line_reader cannot buffer it together with the
  16595. // headers of the first request.
  16596. Server svr;
  16597. svr.set_mount_point("/", "./www");
  16598. std::atomic<int> smuggled_count(0);
  16599. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16600. smuggled_count++;
  16601. res.set_content("oops", "text/plain");
  16602. });
  16603. auto port = svr.bind_to_any_port("localhost");
  16604. thread t = thread([&] { svr.listen_after_bind(); });
  16605. auto se = detail::scope_exit([&] {
  16606. svr.stop();
  16607. t.join();
  16608. });
  16609. svr.wait_until_ready();
  16610. auto error = Error::Success;
  16611. auto sock = detail::create_client_socket(
  16612. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16613. /*connection_timeout_sec=*/2, 0,
  16614. /*read_timeout_sec=*/2, 0,
  16615. /*write_timeout_sec=*/2, 0, std::string(), error);
  16616. ASSERT_NE(INVALID_SOCKET, sock);
  16617. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16618. // The "smuggled" request will be sent as the body of the outer GET
  16619. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  16620. "Host: localhost\r\n"
  16621. "Connection: close\r\n"
  16622. "\r\n";
  16623. // Step 1: Send only the outer request headers (no body yet)
  16624. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  16625. "Host: localhost\r\n"
  16626. "Content-Length: " +
  16627. std::to_string(smuggled.size()) +
  16628. "\r\n"
  16629. "\r\n";
  16630. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  16631. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  16632. // Step 2: Read the first response (server serves file without reading body)
  16633. std::string first_response;
  16634. char buf[4096];
  16635. for (;;) {
  16636. auto n = recv(sock, buf, sizeof(buf), 0);
  16637. if (n <= 0) break;
  16638. first_response.append(buf, static_cast<size_t>(n));
  16639. // Stop once we have a complete response (headers + body)
  16640. auto hdr_end = first_response.find("\r\n\r\n");
  16641. if (hdr_end != std::string::npos) {
  16642. // Check for Content-Length to know when the body is complete
  16643. auto cl_pos = first_response.find("Content-Length:");
  16644. if (cl_pos != std::string::npos) {
  16645. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  16646. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  16647. auto cl = std::stoul(
  16648. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  16649. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  16650. } else {
  16651. break; // No Content-Length, assume headers-only response
  16652. }
  16653. }
  16654. }
  16655. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  16656. // Step 3: Now send the body, which looks like a new HTTP request.
  16657. // On a vulnerable server the keep-alive loop reads this as a second request.
  16658. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  16659. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  16660. // Step 4: Try to read a second response (should NOT exist after fix)
  16661. std::string second_response;
  16662. for (;;) {
  16663. auto n = recv(sock, buf, sizeof(buf), 0);
  16664. if (n <= 0) break;
  16665. second_response.append(buf, static_cast<size_t>(n));
  16666. }
  16667. // The smuggled request must NOT have been processed
  16668. EXPECT_EQ(0, smuggled_count.load());
  16669. }
  16670. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  16671. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  16672. // must be rejected with 400 Bad Request.
  16673. Server svr;
  16674. svr.Post("/test", [&](const Request &, Response &res) {
  16675. res.set_content("ok", "text/plain");
  16676. });
  16677. thread t = thread([&] { svr.listen(HOST, PORT); });
  16678. auto se = detail::scope_exit([&] {
  16679. svr.stop();
  16680. t.join();
  16681. ASSERT_FALSE(svr.is_running());
  16682. });
  16683. svr.wait_until_ready();
  16684. // Exact "chunked"
  16685. {
  16686. auto req = "POST /test HTTP/1.1\r\n"
  16687. "Host: localhost\r\n"
  16688. "Content-Length: 5\r\n"
  16689. "Transfer-Encoding: chunked\r\n"
  16690. "Connection: close\r\n"
  16691. "\r\n"
  16692. "hello";
  16693. std::string response;
  16694. ASSERT_TRUE(send_request(1, req, &response));
  16695. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16696. response.substr(0, response.find("\r\n")));
  16697. }
  16698. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  16699. {
  16700. auto req = "POST /test HTTP/1.1\r\n"
  16701. "Host: localhost\r\n"
  16702. "Content-Length: 5\r\n"
  16703. "Transfer-Encoding: gzip, chunked\r\n"
  16704. "Connection: close\r\n"
  16705. "\r\n"
  16706. "hello";
  16707. std::string response;
  16708. ASSERT_TRUE(send_request(1, req, &response));
  16709. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  16710. response.substr(0, response.find("\r\n")));
  16711. }
  16712. }
  16713. // Regression for issue #2450: a DELETE without Content-Length on a
  16714. // keep-alive connection must not let the post-response drain consume the
  16715. // next request's bytes.
  16716. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  16717. Server svr;
  16718. std::atomic<int> delete_count(0);
  16719. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  16720. delete_count++;
  16721. res.status = StatusCode::NoContent_204;
  16722. });
  16723. auto port = svr.bind_to_any_port(HOST);
  16724. thread t = thread([&] { svr.listen_after_bind(); });
  16725. auto se = detail::scope_exit([&] {
  16726. svr.stop();
  16727. t.join();
  16728. });
  16729. svr.wait_until_ready();
  16730. auto error = Error::Success;
  16731. auto sock = detail::create_client_socket(
  16732. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16733. /*connection_timeout_sec=*/2, 0,
  16734. /*read_timeout_sec=*/2, 0,
  16735. /*write_timeout_sec=*/2, 0, std::string(), error);
  16736. ASSERT_NE(INVALID_SOCKET, sock);
  16737. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16738. auto send_request_and_read_response = [&](const std::string &req,
  16739. std::string &out) -> bool {
  16740. auto sent = send(sock, req.data(), req.size(), 0);
  16741. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  16742. char buf[4096];
  16743. for (;;) {
  16744. auto n = recv(sock, buf, sizeof(buf), 0);
  16745. if (n <= 0) { return !out.empty(); }
  16746. out.append(buf, static_cast<size_t>(n));
  16747. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  16748. }
  16749. };
  16750. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  16751. "Host: localhost\r\n"
  16752. "\r\n";
  16753. std::string resp1;
  16754. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  16755. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  16756. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  16757. "Host: localhost\r\n"
  16758. "Connection: close\r\n"
  16759. "\r\n";
  16760. std::string resp2;
  16761. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  16762. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  16763. EXPECT_EQ(2, delete_count.load());
  16764. }
  16765. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  16766. Server svr;
  16767. svr.Post("/ingest", [&](const Request &, Response &res,
  16768. const ContentReader &content_reader) {
  16769. auto consumed = content_reader([](const char *, size_t) { return false; });
  16770. EXPECT_FALSE(consumed);
  16771. res.status = StatusCode::Conflict_409;
  16772. res.set_header("Connection", "close");
  16773. });
  16774. auto port = svr.bind_to_any_port(HOST);
  16775. thread t = thread([&] { svr.listen_after_bind(); });
  16776. auto se = detail::scope_exit([&] {
  16777. svr.stop();
  16778. t.join();
  16779. });
  16780. svr.wait_until_ready();
  16781. auto error = Error::Success;
  16782. auto sock = detail::create_client_socket(
  16783. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16784. /*connection_timeout_sec=*/2, 0,
  16785. /*read_timeout_sec=*/1, 0,
  16786. /*write_timeout_sec=*/2, 0, std::string(), error);
  16787. ASSERT_NE(INVALID_SOCKET, sock);
  16788. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  16789. std::string request = "POST /ingest HTTP/1.1\r\n"
  16790. "Host: localhost\r\n"
  16791. "Transfer-Encoding: chunked\r\n"
  16792. "\r\n"
  16793. "4\r\n"
  16794. "data\r\n";
  16795. auto sent = send(sock, request.data(), request.size(), 0);
  16796. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  16797. std::string response;
  16798. ssize_t received = 0;
  16799. do {
  16800. char buf[4096];
  16801. received = recv(sock, buf, sizeof(buf), 0);
  16802. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  16803. } while (received > 0);
  16804. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  16805. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  16806. EXPECT_EQ(0, received);
  16807. }
  16808. namespace no_proxy_test {
  16809. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  16810. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  16811. // calling listen().
  16812. class ScopedServer {
  16813. public:
  16814. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  16815. ~ScopedServer() {
  16816. svr_.stop();
  16817. if (th_.joinable()) { th_.join(); }
  16818. }
  16819. Server &svr() { return svr_; }
  16820. int port() const { return port_; }
  16821. void listen() {
  16822. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16823. svr_.wait_until_ready();
  16824. }
  16825. private:
  16826. Server svr_;
  16827. std::thread th_;
  16828. int port_ = 0;
  16829. };
  16830. class ProxyAndTargetServers {
  16831. public:
  16832. ProxyAndTargetServers() {
  16833. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  16834. proxy_hits_++;
  16835. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16836. res.set_content("via-proxy", "text/plain");
  16837. });
  16838. target_.Get(".*", [this](const Request &req, Response &res) {
  16839. target_hits_++;
  16840. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  16841. res.set_content("direct", "text/plain");
  16842. });
  16843. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  16844. target_port_ = target_.bind_to_any_port("127.0.0.1");
  16845. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  16846. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  16847. proxy_mock_.wait_until_ready();
  16848. target_.wait_until_ready();
  16849. }
  16850. ~ProxyAndTargetServers() {
  16851. proxy_mock_.stop();
  16852. target_.stop();
  16853. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  16854. if (target_thread_.joinable()) { target_thread_.join(); }
  16855. }
  16856. Server &proxy_mock() { return proxy_mock_; }
  16857. Server &target() { return target_; }
  16858. int proxy_port() const { return proxy_port_; }
  16859. int target_port() const { return target_port_; }
  16860. int proxy_hits() const { return proxy_hits_.load(); }
  16861. int target_hits() const { return target_hits_.load(); }
  16862. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  16863. void reset_counters() {
  16864. proxy_hits_ = 0;
  16865. target_hits_ = 0;
  16866. last_had_proxy_authz_ = false;
  16867. }
  16868. private:
  16869. Server proxy_mock_;
  16870. Server target_;
  16871. std::thread proxy_thread_;
  16872. std::thread target_thread_;
  16873. int proxy_port_ = 0;
  16874. int target_port_ = 0;
  16875. std::atomic<int> proxy_hits_{0};
  16876. std::atomic<int> target_hits_{0};
  16877. std::atomic<bool> last_had_proxy_authz_{false};
  16878. };
  16879. inline std::unique_ptr<Client> make_client(const std::string &host,
  16880. ProxyAndTargetServers &s) {
  16881. auto cli = detail::make_unique<Client>(host, s.target_port());
  16882. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  16883. cli->set_proxy("127.0.0.1", s.proxy_port());
  16884. return cli;
  16885. }
  16886. } // namespace no_proxy_test
  16887. using no_proxy_test::make_client;
  16888. using no_proxy_test::ProxyAndTargetServers;
  16889. TEST(NoProxyTest, ExactHostnameBypasses) {
  16890. ProxyAndTargetServers s;
  16891. auto cli = make_client("example.com", s);
  16892. cli->set_no_proxy({"example.com"});
  16893. auto res = cli->Get("/");
  16894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16895. EXPECT_EQ(0, s.proxy_hits());
  16896. EXPECT_EQ(1, s.target_hits());
  16897. }
  16898. TEST(NoProxyTest, SubdomainBypasses) {
  16899. ProxyAndTargetServers s;
  16900. auto cli = make_client("foo.example.com", s);
  16901. cli->set_no_proxy({"example.com"});
  16902. auto res = cli->Get("/");
  16903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16904. EXPECT_EQ(0, s.proxy_hits());
  16905. EXPECT_EQ(1, s.target_hits());
  16906. }
  16907. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  16908. // Regression guard: "evilexample.com" must not be considered a subdomain
  16909. // of "example.com". Without the dot-boundary rule, a naive endsWith
  16910. // check would let traffic bypass the proxy and leak credentials direct
  16911. // to the attacker host.
  16912. ProxyAndTargetServers s;
  16913. auto cli = make_client("evilexample.com", s);
  16914. cli->set_no_proxy({"example.com"});
  16915. auto res = cli->Get("/");
  16916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16917. EXPECT_GE(s.proxy_hits(), 1);
  16918. EXPECT_EQ(0, s.target_hits());
  16919. }
  16920. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  16921. ProxyAndTargetServers s;
  16922. auto cli = make_client("example.com.evil.com", s);
  16923. cli->set_no_proxy({"example.com"});
  16924. auto res = cli->Get("/");
  16925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16926. EXPECT_GE(s.proxy_hits(), 1);
  16927. EXPECT_EQ(0, s.target_hits());
  16928. }
  16929. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  16930. ProxyAndTargetServers s;
  16931. auto cli = make_client("example.com", s);
  16932. cli->set_no_proxy({".example.com"});
  16933. auto res = cli->Get("/");
  16934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16935. EXPECT_EQ(0, s.proxy_hits());
  16936. EXPECT_EQ(1, s.target_hits());
  16937. }
  16938. TEST(NoProxyTest, CaseInsensitiveHostname) {
  16939. ProxyAndTargetServers s;
  16940. auto cli = make_client("Example.COM", s);
  16941. cli->set_no_proxy({"EXAMPLE.com"});
  16942. auto res = cli->Get("/");
  16943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16944. EXPECT_EQ(0, s.proxy_hits());
  16945. EXPECT_EQ(1, s.target_hits());
  16946. }
  16947. TEST(NoProxyTest, TrailingDotIsNormalized) {
  16948. ProxyAndTargetServers s;
  16949. auto cli = make_client("example.com.", s);
  16950. cli->set_no_proxy({"example.com"});
  16951. auto res = cli->Get("/");
  16952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16953. EXPECT_EQ(0, s.proxy_hits());
  16954. EXPECT_EQ(1, s.target_hits());
  16955. }
  16956. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  16957. // Trailing dots must be normalized on BOTH sides — host and entry.
  16958. // An implementation that only strips the host-side trailing dot would
  16959. // fail to match host "example.com" against entry "example.com." because
  16960. // a literal substring search would compare 11 chars against 12.
  16961. ProxyAndTargetServers s;
  16962. auto cli = make_client("example.com", s);
  16963. cli->set_no_proxy({"example.com."});
  16964. auto res = cli->Get("/");
  16965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16966. EXPECT_EQ(0, s.proxy_hits());
  16967. EXPECT_EQ(1, s.target_hits());
  16968. }
  16969. TEST(NoProxyTest, WildcardBypassesEverything) {
  16970. ProxyAndTargetServers s;
  16971. auto cli = make_client("anything.invalid.test", s);
  16972. cli->set_no_proxy({"*"});
  16973. auto res = cli->Get("/");
  16974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16975. EXPECT_EQ(0, s.proxy_hits());
  16976. EXPECT_EQ(1, s.target_hits());
  16977. }
  16978. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  16979. ProxyAndTargetServers s;
  16980. Client cli("127.0.0.1", s.target_port());
  16981. cli.set_proxy("127.0.0.1", s.proxy_port());
  16982. cli.set_no_proxy({"127.0.0.1"});
  16983. auto res = cli.Get("/");
  16984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16985. EXPECT_EQ(0, s.proxy_hits());
  16986. EXPECT_EQ(1, s.target_hits());
  16987. }
  16988. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  16989. ProxyAndTargetServers s;
  16990. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  16991. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  16992. cli.set_proxy("127.0.0.1", s.proxy_port());
  16993. cli.set_no_proxy({"::1"});
  16994. auto res = cli.Get("/");
  16995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16996. EXPECT_EQ(0, s.proxy_hits());
  16997. EXPECT_EQ(1, s.target_hits());
  16998. }
  16999. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17000. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17001. // must still be recognized as IPv6 for CIDR matching. Implementations
  17002. // that detect IPv6 only when the host begins with '[' would parse the
  17003. // host as a hostname and miss the match.
  17004. ProxyAndTargetServers s;
  17005. Client cli("fe80::1", s.target_port());
  17006. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17007. cli.set_proxy("127.0.0.1", s.proxy_port());
  17008. cli.set_no_proxy({"fe80::/10"});
  17009. auto res = cli.Get("/");
  17010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17011. EXPECT_EQ(0, s.proxy_hits());
  17012. EXPECT_EQ(1, s.target_hits());
  17013. }
  17014. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17015. ProxyAndTargetServers s;
  17016. Client cli("::1", s.target_port());
  17017. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17018. cli.set_proxy("127.0.0.1", s.proxy_port());
  17019. cli.set_no_proxy({"[::1]"});
  17020. auto res = cli.Get("/");
  17021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17022. EXPECT_EQ(0, s.proxy_hits());
  17023. EXPECT_EQ(1, s.target_hits());
  17024. }
  17025. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17026. ProxyAndTargetServers s;
  17027. Client cli("fe80::1", s.target_port());
  17028. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17029. cli.set_proxy("127.0.0.1", s.proxy_port());
  17030. cli.set_no_proxy({"[fe80::]/10"});
  17031. auto res = cli.Get("/");
  17032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17033. EXPECT_EQ(0, s.proxy_hits());
  17034. EXPECT_EQ(1, s.target_hits());
  17035. }
  17036. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17037. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17038. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17039. // tricks via address-family conversion.
  17040. ProxyAndTargetServers s;
  17041. Client cli("::ffff:127.0.0.1", s.target_port());
  17042. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17043. cli.set_proxy("127.0.0.1", s.proxy_port());
  17044. cli.set_no_proxy({"127.0.0.1"});
  17045. auto res = cli.Get("/");
  17046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17047. EXPECT_GE(s.proxy_hits(), 1);
  17048. EXPECT_EQ(0, s.target_hits());
  17049. }
  17050. TEST(NoProxyTest, IPv4CidrMatch) {
  17051. ProxyAndTargetServers s;
  17052. Client cli("127.0.0.1", s.target_port());
  17053. cli.set_proxy("127.0.0.1", s.proxy_port());
  17054. cli.set_no_proxy({"127.0.0.0/8"});
  17055. auto res = cli.Get("/");
  17056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17057. EXPECT_EQ(0, s.proxy_hits());
  17058. EXPECT_EQ(1, s.target_hits());
  17059. }
  17060. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17061. ProxyAndTargetServers s;
  17062. Client cli("127.0.0.1", s.target_port());
  17063. cli.set_proxy("127.0.0.1", s.proxy_port());
  17064. cli.set_no_proxy({"10.0.0.0/8"});
  17065. auto res = cli.Get("/");
  17066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17067. EXPECT_GE(s.proxy_hits(), 1);
  17068. EXPECT_EQ(0, s.target_hits());
  17069. }
  17070. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17071. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17072. // IPv4 target matches.
  17073. ProxyAndTargetServers s;
  17074. Client cli("127.0.0.1", s.target_port());
  17075. cli.set_proxy("127.0.0.1", s.proxy_port());
  17076. cli.set_no_proxy({"0.0.0.0/0"});
  17077. auto res = cli.Get("/");
  17078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17079. EXPECT_EQ(0, s.proxy_hits());
  17080. EXPECT_EQ(1, s.target_hits());
  17081. }
  17082. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17083. ProxyAndTargetServers s;
  17084. Client cli("127.0.0.1", s.target_port());
  17085. cli.set_proxy("127.0.0.1", s.proxy_port());
  17086. cli.set_no_proxy({"127.0.0.1"});
  17087. auto res = cli.Get("/");
  17088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17089. EXPECT_EQ(0, s.proxy_hits());
  17090. EXPECT_EQ(1, s.target_hits());
  17091. }
  17092. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17093. ProxyAndTargetServers s;
  17094. Client cli("127.0.0.1", s.target_port());
  17095. cli.set_proxy("127.0.0.1", s.proxy_port());
  17096. cli.set_no_proxy({"127.0.0.0/33"});
  17097. auto res = cli.Get("/");
  17098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17099. EXPECT_GE(s.proxy_hits(), 1);
  17100. EXPECT_EQ(0, s.target_hits());
  17101. }
  17102. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17103. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17104. ProxyAndTargetServers s;
  17105. Client cli("127.0.0.1", s.target_port());
  17106. cli.set_proxy("127.0.0.1", s.proxy_port());
  17107. cli.set_no_proxy({"127.0.0.1/"});
  17108. auto res = cli.Get("/");
  17109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17110. EXPECT_GE(s.proxy_hits(), 1);
  17111. EXPECT_EQ(0, s.target_hits());
  17112. }
  17113. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17114. ProxyAndTargetServers s;
  17115. auto cli = make_client("internal.corp", s);
  17116. cli->set_proxy_basic_auth("u", "p");
  17117. cli->set_no_proxy({"internal.corp"});
  17118. auto res = cli->Get("/");
  17119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17120. EXPECT_EQ(1, s.target_hits());
  17121. EXPECT_EQ(0, s.proxy_hits());
  17122. EXPECT_FALSE(s.last_had_proxy_authz())
  17123. << "Proxy-Authorization must not be sent direct to the target";
  17124. }
  17125. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17126. ProxyAndTargetServers s;
  17127. auto cli = make_client("public.example", s);
  17128. cli->set_proxy_basic_auth("u", "p");
  17129. cli->set_no_proxy({"internal.corp"}); // does not match
  17130. auto res = cli->Get("/");
  17131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17132. EXPECT_GE(s.proxy_hits(), 1);
  17133. EXPECT_TRUE(s.last_had_proxy_authz());
  17134. }
  17135. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17136. ProxyAndTargetServers s;
  17137. auto cli = make_client("anything.test", s);
  17138. auto res = cli->Get("/");
  17139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17140. EXPECT_GE(s.proxy_hits(), 1);
  17141. EXPECT_EQ(0, s.target_hits());
  17142. }
  17143. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17144. ProxyAndTargetServers s;
  17145. auto cli = make_client("example.com", s);
  17146. cli->set_no_proxy({"example.com:8080"});
  17147. auto res = cli->Get("/");
  17148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17149. EXPECT_GE(s.proxy_hits(), 1);
  17150. EXPECT_EQ(0, s.target_hits());
  17151. }
  17152. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17153. ProxyAndTargetServers s;
  17154. auto cli = make_client("anything.test", s);
  17155. cli->set_no_proxy({"", " ", "\t"});
  17156. auto res = cli->Get("/");
  17157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17158. EXPECT_GE(s.proxy_hits(), 1);
  17159. EXPECT_EQ(0, s.target_hits());
  17160. }
  17161. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17162. // An entry with leading/trailing whitespace must still match — env-style
  17163. // values are commonly pasted with stray spaces and an implementation
  17164. // that feeds the raw token directly to inet_pton would fail to match
  17165. // valid CIDRs because of the spaces.
  17166. ProxyAndTargetServers s;
  17167. Client cli("127.0.0.1", s.target_port());
  17168. cli.set_proxy("127.0.0.1", s.proxy_port());
  17169. cli.set_no_proxy({" 127.0.0.0/8 "});
  17170. auto res = cli.Get("/");
  17171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17172. EXPECT_EQ(0, s.proxy_hits());
  17173. EXPECT_EQ(1, s.target_hits());
  17174. }
  17175. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17176. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17177. // go direct and must NOT carry Proxy-Authorization.
  17178. std::atomic<int> proxy_hits{0};
  17179. std::atomic<int> target_hits{0};
  17180. std::atomic<bool> target_saw_authz{false};
  17181. no_proxy_test::ScopedServer proxy_mock, target;
  17182. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17183. proxy_hits++;
  17184. res.status = 302;
  17185. res.set_header("Location", "http://127.0.0.1:" +
  17186. std::to_string(target.port()) + "/landed");
  17187. });
  17188. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17189. target_hits++;
  17190. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17191. res.set_content("direct", "text/plain");
  17192. });
  17193. proxy_mock.listen();
  17194. target.listen();
  17195. Client cli("public.example", target.port());
  17196. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17197. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17198. cli.set_proxy_basic_auth("u", "p");
  17199. cli.set_no_proxy({"127.0.0.1"});
  17200. cli.set_follow_location(true);
  17201. auto res = cli.Get("/redir");
  17202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17203. EXPECT_GE(proxy_hits.load(), 1);
  17204. EXPECT_GE(target_hits.load(), 1);
  17205. EXPECT_FALSE(target_saw_authz.load());
  17206. }
  17207. #ifdef CPPHTTPLIB_SSL_ENABLED
  17208. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17209. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17210. // proxy creds would be sent to the (possibly hostile) origin.
  17211. std::atomic<int> target_hits{0};
  17212. std::atomic<bool> target_saw_proxy_authz{false};
  17213. no_proxy_test::ScopedServer target;
  17214. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17215. target_hits++;
  17216. if (req.has_header("Proxy-Authorization")) {
  17217. target_saw_proxy_authz = true;
  17218. }
  17219. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17220. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17221. "nonce=\"abc\", algorithm=MD5");
  17222. });
  17223. target.listen();
  17224. // The proxy address is set to the target's port: the bypass MUST kick in;
  17225. // if it doesn't, the test still routes "via proxy" to the same server and
  17226. // the Proxy-Authorization assertion below catches the leak.
  17227. Client cli("evil.example", target.port());
  17228. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17229. cli.set_proxy("127.0.0.1", target.port());
  17230. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17231. cli.set_no_proxy({"evil.example"});
  17232. auto res = cli.Get("/x");
  17233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17234. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17235. EXPECT_EQ(1, target_hits.load());
  17236. EXPECT_FALSE(target_saw_proxy_authz.load());
  17237. }
  17238. #endif
  17239. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17240. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17241. std::atomic<int> proxy_hits{0};
  17242. std::atomic<int> bypass_hits{0};
  17243. std::atomic<bool> proxy_saw_c_url{false};
  17244. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17245. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17246. proxy_hits++;
  17247. if (req.path.find("/start") != std::string::npos) {
  17248. res.status = 302;
  17249. res.set_header("Location", "http://127.0.0.1:" +
  17250. std::to_string(bypass_server.port()) +
  17251. "/middle");
  17252. return;
  17253. }
  17254. if (req.path.find("/end") != std::string::npos) {
  17255. proxy_saw_c_url = true;
  17256. res.set_content("c-via-proxy", "text/plain");
  17257. return;
  17258. }
  17259. res.set_content("unexpected", "text/plain");
  17260. });
  17261. // public.example's "advertised" port is arbitrary (the request never lands
  17262. // there — it goes through the proxy), but use a dynamic value to stay
  17263. // friendly with sharded parallel runs.
  17264. int public_port = bypass_server.port();
  17265. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17266. bypass_hits++;
  17267. res.status = 302;
  17268. res.set_header("Location", "http://public.example:" +
  17269. std::to_string(public_port) + "/end");
  17270. });
  17271. proxy_mock.listen();
  17272. bypass_server.listen();
  17273. Client cli("public.example", public_port);
  17274. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17275. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17276. cli.set_no_proxy({"127.0.0.1"});
  17277. cli.set_follow_location(true);
  17278. auto res = cli.Get("/start");
  17279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17280. EXPECT_EQ(StatusCode::OK_200, res->status);
  17281. EXPECT_EQ("c-via-proxy", res->body);
  17282. EXPECT_GE(proxy_hits.load(), 2);
  17283. EXPECT_GE(bypass_hits.load(), 1);
  17284. EXPECT_TRUE(proxy_saw_c_url.load());
  17285. }
  17286. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17287. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17288. // request reconnects to the correct endpoint.
  17289. std::atomic<int> proxy_hits{0};
  17290. std::atomic<int> target_hits{0};
  17291. no_proxy_test::ScopedServer proxy_mock, target;
  17292. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17293. proxy_hits++;
  17294. res.set_content("via-proxy", "text/plain");
  17295. });
  17296. target.svr().Get(".*", [&](const Request &, Response &res) {
  17297. target_hits++;
  17298. res.set_content("direct", "text/plain");
  17299. });
  17300. proxy_mock.listen();
  17301. target.listen();
  17302. Client cli("public.example", target.port());
  17303. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17304. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17305. cli.set_keep_alive(true);
  17306. auto res1 = cli.Get("/a");
  17307. ASSERT_TRUE(res1);
  17308. EXPECT_EQ("via-proxy", res1->body);
  17309. EXPECT_EQ(1, proxy_hits.load());
  17310. EXPECT_EQ(0, target_hits.load());
  17311. cli.set_no_proxy({"public.example"});
  17312. auto res2 = cli.Get("/b");
  17313. ASSERT_TRUE(res2);
  17314. EXPECT_EQ("direct", res2->body);
  17315. EXPECT_EQ(1, proxy_hits.load());
  17316. EXPECT_EQ(1, target_hits.load());
  17317. }
  17318. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17319. namespace proxy_tunnel_test {
  17320. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17321. class ScopedSSLServer {
  17322. public:
  17323. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17324. port_ = svr_.bind_to_any_port("127.0.0.1");
  17325. }
  17326. ~ScopedSSLServer() {
  17327. svr_.stop();
  17328. if (th_.joinable()) { th_.join(); }
  17329. }
  17330. SSLServer &svr() { return svr_; }
  17331. int port() const { return port_; }
  17332. void listen() {
  17333. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17334. svr_.wait_until_ready();
  17335. }
  17336. private:
  17337. SSLServer svr_;
  17338. std::thread th_;
  17339. int port_ = 0;
  17340. };
  17341. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17342. class ScopedConnectProxy {
  17343. public:
  17344. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17345. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17346. if (listen_fd_ < 0) { return; }
  17347. int yes = 1;
  17348. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17349. sockaddr_in a{};
  17350. a.sin_family = AF_INET;
  17351. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17352. a.sin_port = 0;
  17353. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17354. return;
  17355. }
  17356. socklen_t alen = sizeof(a);
  17357. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17358. 0) {
  17359. return;
  17360. }
  17361. port_ = ntohs(a.sin_port);
  17362. if (::listen(listen_fd_, 1) != 0) { return; }
  17363. th_ = std::thread([this] { run(); });
  17364. }
  17365. ~ScopedConnectProxy() {
  17366. stop_ = true;
  17367. if (listen_fd_ >= 0) {
  17368. ::shutdown(listen_fd_, SHUT_RDWR);
  17369. ::close(listen_fd_);
  17370. }
  17371. if (th_.joinable()) { th_.join(); }
  17372. }
  17373. int port() const { return port_; }
  17374. int connect_hits() const { return connect_hits_.load(); }
  17375. private:
  17376. void run() {
  17377. while (!stop_.load()) {
  17378. fd_set rfds;
  17379. FD_ZERO(&rfds);
  17380. FD_SET(listen_fd_, &rfds);
  17381. timeval tv{0, 100 * 1000};
  17382. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17383. if (sel <= 0) { continue; }
  17384. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17385. if (client_fd < 0) { continue; }
  17386. std::string req;
  17387. char buf[2048];
  17388. while (req.find("\r\n\r\n") == std::string::npos) {
  17389. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17390. if (n <= 0) { break; }
  17391. req.append(buf, static_cast<size_t>(n));
  17392. }
  17393. if (req.compare(0, 7, "CONNECT") != 0) {
  17394. ::close(client_fd);
  17395. continue;
  17396. }
  17397. connect_hits_++;
  17398. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17399. ::send(client_fd, ok, std::strlen(ok), 0);
  17400. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17401. sockaddr_in o{};
  17402. o.sin_family = AF_INET;
  17403. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17404. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17405. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17406. 0) {
  17407. ::close(client_fd);
  17408. ::close(origin_fd);
  17409. continue;
  17410. }
  17411. auto forward = [](int from, int to) {
  17412. char b[8192];
  17413. for (;;) {
  17414. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17415. if (n <= 0) { break; }
  17416. ssize_t off = 0;
  17417. while (off < n) {
  17418. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17419. if (s <= 0) {
  17420. off = n;
  17421. break;
  17422. }
  17423. off += s;
  17424. }
  17425. }
  17426. ::shutdown(to, SHUT_WR);
  17427. };
  17428. std::thread t1([&] { forward(client_fd, origin_fd); });
  17429. std::thread t2([&] { forward(origin_fd, client_fd); });
  17430. t1.join();
  17431. t2.join();
  17432. ::close(client_fd);
  17433. ::close(origin_fd);
  17434. }
  17435. }
  17436. int forward_port_ = -1;
  17437. int listen_fd_ = -1;
  17438. int port_ = 0;
  17439. std::thread th_;
  17440. std::atomic<bool> stop_{false};
  17441. std::atomic<int> connect_hits_{0};
  17442. };
  17443. } // namespace proxy_tunnel_test
  17444. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17445. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17446. // retry; otherwise proxy creds would be sent to the origin.
  17447. std::atomic<int> origin_hits{0};
  17448. std::atomic<bool> origin_saw_proxy_authz{false};
  17449. proxy_tunnel_test::ScopedSSLServer origin;
  17450. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17451. origin_hits++;
  17452. if (req.has_header("Proxy-Authorization")) {
  17453. origin_saw_proxy_authz = true;
  17454. }
  17455. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17456. res.set_header("Proxy-Authenticate",
  17457. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17458. "algorithm=MD5");
  17459. });
  17460. origin.listen();
  17461. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17462. ASSERT_NE(0, proxy.port());
  17463. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  17464. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  17465. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  17466. // and answer with its own status, making this test flaky.
  17467. SSLClient cli("127.0.0.1", origin.port());
  17468. cli.enable_server_certificate_verification(false);
  17469. cli.set_proxy("127.0.0.1", proxy.port());
  17470. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17471. auto res = cli.Get("/x");
  17472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17473. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17474. EXPECT_EQ(1, origin_hits.load());
  17475. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17476. EXPECT_EQ(1, proxy.connect_hits());
  17477. }
  17478. #endif