test.cc 680 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  258. ASSERT_EQ(0, listen(s, 1));
  259. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  260. ASSERT_EQ(0, close(s));
  261. }};
  262. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  263. std::thread cli{[&] {
  264. const int s = socket(AF_INET, SOCK_STREAM, 0);
  265. ASSERT_LE(0, s);
  266. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, close(s));
  268. }};
  269. cli.join();
  270. svr.join();
  271. ASSERT_NE(disconnected_svr_sock, -1);
  272. const auto asSocketStream = [&](socket_t fd,
  273. std::function<bool(Stream &)> func) {
  274. return detail::process_client_socket(
  275. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  276. };
  277. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  278. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  279. // wait_writable() returns true because select_write() only checks if the
  280. // send buffer has space. Peer disconnection is detected later by send().
  281. EXPECT_TRUE(ss.wait_writable());
  282. return true;
  283. });
  284. ASSERT_EQ(0, close(disconnected_svr_sock));
  285. }
  286. #endif // #ifndef _WIN32
  287. TEST(SetSocketOptTest, TcpNoDelay) {
  288. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  289. ASSERT_NE(sock, INVALID_SOCKET);
  290. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  291. int val = 0;
  292. socklen_t len = sizeof(val);
  293. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  294. reinterpret_cast<char *>(&val), &len));
  295. EXPECT_NE(val, 0);
  296. detail::close_socket(sock);
  297. }
  298. TEST(ClientTest, MoveConstructible) {
  299. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  300. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  301. }
  302. TEST(ClientTest, MoveAssignable) {
  303. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  304. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  305. }
  306. #ifdef _WIN32
  307. TEST(StartupTest, WSAStartup) {
  308. WSADATA wsaData;
  309. int ret = WSAStartup(0x0002, &wsaData);
  310. ASSERT_EQ(0, ret);
  311. }
  312. #endif
  313. TEST(DecodePathTest, PercentCharacter) {
  314. EXPECT_EQ(
  315. decode_path_component(
  316. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  317. U8("descrip=Gastos áéíóúñÑ 6"));
  318. }
  319. TEST(DecodePathTest, PercentCharacterNUL) {
  320. string expected;
  321. expected.push_back('x');
  322. expected.push_back('\0');
  323. expected.push_back('x');
  324. EXPECT_EQ(decode_path_component("x%00x"), expected);
  325. }
  326. TEST(DecodePathTest, UnicodeEncoding) {
  327. // %u0041 = 'A' (1-byte UTF-8)
  328. EXPECT_EQ("A", decode_path_component("%u0041"));
  329. // %u00E9 = 'é' (2-byte UTF-8)
  330. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  331. // %u3042 = 'あ' (3-byte UTF-8)
  332. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  333. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  334. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  335. // %uD800 = surrogate (invalid, silently dropped)
  336. EXPECT_EQ("", decode_path_component("%uD800"));
  337. }
  338. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  339. // A sign or whitespace inside the two-character escape window must not be
  340. // accepted as a valid percent-encoding; the sequence is passed through
  341. // literally, matching decode_uri_component / decode_path_component.
  342. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  343. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  344. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  345. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  346. // Well-formed escapes still decode.
  347. EXPECT_EQ("-", decode_query_component("%2D", false));
  348. EXPECT_EQ("A", decode_query_component("%41", false));
  349. }
  350. TEST(SanitizeFilenameTest, VariousPatterns) {
  351. // Path traversal
  352. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  353. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  354. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  355. // Normal and edge cases
  356. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  357. EXPECT_EQ("filename.txt",
  358. httplib::sanitize_filename("/path/to/filename.txt"));
  359. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  360. EXPECT_EQ("", httplib::sanitize_filename(".."));
  361. EXPECT_EQ("", httplib::sanitize_filename(""));
  362. // Null bytes stripped
  363. EXPECT_EQ("safe.txt",
  364. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  365. // Whitespace-only rejected
  366. EXPECT_EQ("", httplib::sanitize_filename(" "));
  367. }
  368. // Forward declaration (see the base64_encode note below): split builds move the
  369. // definition into httplib.cc, so re-declaring it here lets the test link.
  370. namespace httplib {
  371. namespace detail {
  372. bool is_chunked_transfer_encoding(const Headers &headers);
  373. } // namespace detail
  374. } // namespace httplib
  375. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  376. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  377. auto make = [](std::initializer_list<const char *> lines) {
  378. Headers h;
  379. for (auto te : lines) {
  380. if (te) { h.emplace("Transfer-Encoding", te); }
  381. }
  382. return h;
  383. };
  384. // Sole coding, matched case-insensitively.
  385. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  386. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  387. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  388. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  389. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  390. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  391. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  392. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  393. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  394. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  395. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  396. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  397. // Multiple Transfer-Encoding lines: iteration order for duplicate keys is not
  398. // portable, so any line naming chunked is treated as chunked (fail safe).
  399. // The result must not depend on the order the lines were added.
  400. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  401. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  402. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  403. }
  404. // Forward declaration: in split builds split.py strips `inline` and moves the
  405. // definition into httplib.cc, so detail::base64_encode is not visible from the
  406. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  407. // in both header-only and split builds.
  408. namespace httplib {
  409. namespace detail {
  410. std::string base64_encode(const std::string &in);
  411. } // namespace detail
  412. } // namespace httplib
  413. TEST(Base64EncodeTest, KnownAnswers) {
  414. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  415. // where the accumulator's top bit is already set before the next shift.
  416. EXPECT_EQ("", detail::base64_encode(""));
  417. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  418. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  419. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  420. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  421. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  422. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  423. // High bytes keep the top bit set across several rounds.
  424. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  425. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  426. }
  427. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  428. string unescapedCharacters = "-_.!~*'()";
  429. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  430. }
  431. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  432. string reservedCharacters = ";,/?:@&=+$";
  433. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  434. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  435. }
  436. TEST(ClientQueryOrder, PreserveOrder) {
  437. // This test reproduces Issue #2259: client may reorder query parameters
  438. // when sending a GET request. The expected behavior is that the client
  439. // preserves the original query string order when the caller supplied it
  440. // as part of the path.
  441. Server svr;
  442. svr.Get("/", [&](const Request &req, Response &res) {
  443. // Echo back the raw target so the test can assert ordering
  444. res.set_content(req.target, "text/plain");
  445. });
  446. std::thread t{[&] { svr.listen(HOST, PORT); }};
  447. auto se = detail::scope_exit([&] {
  448. svr.stop();
  449. t.join();
  450. ASSERT_FALSE(svr.is_running());
  451. });
  452. svr.wait_until_ready();
  453. Client cli(HOST, PORT);
  454. ASSERT_TRUE(cli.is_valid());
  455. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  456. auto res = cli.Get(original);
  457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  458. // Expect the echoed target to exactly match the original path (order
  459. // preserved)
  460. EXPECT_EQ(res->body, original);
  461. }
  462. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  463. string chineseCharacters = U8("中国語");
  464. string russianCharacters = U8("дом");
  465. string brazilianCharacters = U8("óculos");
  466. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  467. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  468. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  469. "%D0%B4%D0%BE%D0%BC");
  470. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  471. }
  472. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  473. string unescapedCharacters = "-_.!~*'()";
  474. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  475. }
  476. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  477. string reservedCharacters = ";,/?:@&=+$";
  478. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  479. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  480. }
  481. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  482. string chineseCharacters = U8("中国語");
  483. string russianCharacters = U8("дом");
  484. string brazilianCharacters = U8("óculos");
  485. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  486. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  487. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  488. "%D0%B4%D0%BE%D0%BC");
  489. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  490. }
  491. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  492. // Issue #2082 use case: encoding path component with ampersand
  493. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  494. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  495. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  496. }
  497. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  498. string unescapedCharacters = "-_.!~*'()";
  499. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  500. }
  501. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  502. string reservedCharacters = ";,/?:@&=+$#";
  503. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  504. }
  505. TEST(EncodeUriTest, TestUTF8Characters) {
  506. string chineseCharacters = U8("中国語");
  507. string russianCharacters = U8("дом");
  508. string brazilianCharacters = U8("óculos");
  509. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  510. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  511. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  512. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  513. }
  514. TEST(EncodeUriTest, TestCompleteUri) {
  515. string uri =
  516. "https://example.com/path/to/resource?query=value&param=test#fragment";
  517. EXPECT_EQ(
  518. httplib::encode_uri(uri),
  519. "https://example.com/path/to/resource?query=value&param=test#fragment");
  520. }
  521. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  522. string uri =
  523. "https://example.com/path with spaces/file name.html?q=hello world";
  524. EXPECT_EQ(httplib::encode_uri(uri),
  525. "https://example.com/path%20with%20spaces/"
  526. "file%20name.html?q=hello%20world");
  527. }
  528. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  529. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  530. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  531. }
  532. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  533. string unescapedCharacters = "-_.!~*'()";
  534. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  535. }
  536. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  537. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  538. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  539. string encodedBrazilian = "%C3%B3culos";
  540. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  541. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  542. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  543. }
  544. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  545. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  546. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  547. "Piri Tommy Villiers - on & on");
  548. }
  549. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  550. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  551. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  552. }
  553. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  554. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  555. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  556. }
  557. TEST(DecodeUriTest, TestUTF8Characters) {
  558. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  559. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  560. string encodedBrazilian = "%C3%B3culos";
  561. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  562. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  563. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  564. }
  565. TEST(DecodeUriTest, TestCompleteUri) {
  566. string encodedUri = "https://example.com/path%20with%20spaces/"
  567. "file%20name.html?q=hello%20world";
  568. EXPECT_EQ(
  569. httplib::decode_uri(encodedUri),
  570. "https://example.com/path with spaces/file name.html?q=hello world");
  571. }
  572. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  573. string original =
  574. "https://example.com/path with spaces/file name.html?q=hello world";
  575. string encoded = httplib::encode_uri(original);
  576. string decoded = httplib::decode_uri(encoded);
  577. EXPECT_EQ(decoded, original);
  578. }
  579. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  580. string original = "Piri Tommy Villiers - on & on";
  581. string encoded = httplib::encode_uri_component(original);
  582. string decoded = httplib::decode_uri_component(encoded);
  583. EXPECT_EQ(decoded, original);
  584. }
  585. TEST(TrimTests, TrimStringTests) {
  586. EXPECT_EQ("abc", detail::trim_copy("abc"));
  587. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  588. EXPECT_TRUE(detail::trim_copy("").empty());
  589. }
  590. TEST(AsciiTest, LocaleIndependentClassification) {
  591. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  592. // which consult the global C locale: std::isalnum(0xC5) can return true
  593. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  594. // helpers must classify every byte by the ASCII grammar alone.
  595. for (int i = 0; i < 256; i++) {
  596. auto c = static_cast<char>(i);
  597. auto is_digit = i >= '0' && i <= '9';
  598. auto is_upper = i >= 'A' && i <= 'Z';
  599. auto is_lower = i >= 'a' && i <= 'z';
  600. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  601. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  602. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  603. << "byte " << i;
  604. }
  605. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  606. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  607. // Non-ASCII bytes must be percent-encoded, never passed through as
  608. // alphanumeric.
  609. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  610. }
  611. TEST(FromCharsTest, Double) {
  612. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  613. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  614. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  615. auto parse = [](const std::string &s, double &v) {
  616. return detail::from_chars(s.data(), s.data() + s.size(), v);
  617. };
  618. double v = -1.0;
  619. // Representative quality values.
  620. EXPECT_EQ(parse("0", v).ec, std::errc{});
  621. EXPECT_DOUBLE_EQ(v, 0.0);
  622. EXPECT_EQ(parse("1", v).ec, std::errc{});
  623. EXPECT_DOUBLE_EQ(v, 1.0);
  624. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  625. EXPECT_DOUBLE_EQ(v, 0.8);
  626. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  627. EXPECT_DOUBLE_EQ(v, 0.001);
  628. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  629. EXPECT_DOUBLE_EQ(v, 1.0);
  630. // A missing integer or fractional part is tolerated.
  631. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  632. EXPECT_DOUBLE_EQ(v, 0.5);
  633. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  634. EXPECT_DOUBLE_EQ(v, 5.0);
  635. // Values outside [0, 1] still parse; the caller range-checks them.
  636. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  637. EXPECT_DOUBLE_EQ(v, 123.456);
  638. // Stops at the first byte that is not part of the number and reports where.
  639. std::string trailing = "0.9, text/html";
  640. auto r = parse(trailing, v);
  641. EXPECT_EQ(r.ec, std::errc{});
  642. EXPECT_DOUBLE_EQ(v, 0.9);
  643. EXPECT_EQ(*r.ptr, ',');
  644. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  645. // outright, and an 'e'/'E' simply ends the number.
  646. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  647. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  648. std::string exp_input = "1.5e3";
  649. r = parse(exp_input, v);
  650. EXPECT_EQ(r.ec, std::errc{});
  651. EXPECT_DOUBLE_EQ(v, 1.5);
  652. EXPECT_EQ(*r.ptr, 'e');
  653. // Invalid inputs.
  654. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  655. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  656. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  657. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  658. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  659. // Pathological but well-formed inputs must stay bounded (no overflow, no
  660. // out-of-bounds table access) and stay within [0, 1] for the caller.
  661. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  662. std::errc{});
  663. EXPECT_DOUBLE_EQ(v, 0.0);
  664. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  665. std::errc{});
  666. EXPECT_GE(v, 0.0);
  667. EXPECT_LE(v, 1.0);
  668. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  669. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  670. }
  671. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  672. // Simple case without quality values
  673. std::vector<std::string> result1;
  674. EXPECT_TRUE(detail::parse_accept_header(
  675. "text/html,application/json,text/plain", result1));
  676. EXPECT_EQ(result1.size(), 3U);
  677. EXPECT_EQ(result1[0], "text/html");
  678. EXPECT_EQ(result1[1], "application/json");
  679. EXPECT_EQ(result1[2], "text/plain");
  680. // With quality values
  681. std::vector<std::string> result2;
  682. EXPECT_TRUE(detail::parse_accept_header(
  683. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  684. EXPECT_EQ(result2.size(), 3U);
  685. EXPECT_EQ(result2[0], "application/json"); // highest q value
  686. EXPECT_EQ(result2[1], "text/html");
  687. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  688. }
  689. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  690. // Mixed with and without quality values
  691. std::vector<std::string> result;
  692. EXPECT_TRUE(detail::parse_accept_header(
  693. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  694. EXPECT_EQ(result.size(), 3U);
  695. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  696. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  697. EXPECT_EQ(result[2], "application/json"); // q=0.5
  698. }
  699. TEST(ParseAcceptHeaderTest, EdgeCases) {
  700. // Empty header
  701. std::vector<std::string> empty_result;
  702. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  703. EXPECT_TRUE(empty_result.empty());
  704. // Single type
  705. std::vector<std::string> single_result;
  706. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  707. EXPECT_EQ(single_result.size(), 1U);
  708. EXPECT_EQ(single_result[0], "application/json");
  709. // Wildcard types
  710. std::vector<std::string> wildcard_result;
  711. EXPECT_TRUE(detail::parse_accept_header(
  712. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  713. EXPECT_EQ(wildcard_result.size(), 3U);
  714. EXPECT_EQ(wildcard_result[0], "application/json");
  715. EXPECT_EQ(wildcard_result[1], "text/*");
  716. EXPECT_EQ(wildcard_result[2], "*/*");
  717. }
  718. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  719. // Common browser Accept header
  720. std::vector<std::string> browser_result;
  721. EXPECT_TRUE(
  722. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  723. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  724. browser_result));
  725. EXPECT_EQ(browser_result.size(), 6U);
  726. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  727. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  728. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  729. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  730. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  731. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  732. // API client header
  733. std::vector<std::string> api_result;
  734. EXPECT_TRUE(detail::parse_accept_header(
  735. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  736. api_result));
  737. EXPECT_EQ(api_result.size(), 3U);
  738. EXPECT_EQ(api_result[0], "application/json");
  739. EXPECT_EQ(api_result[1], "application/xml");
  740. EXPECT_EQ(api_result[2], "text/plain");
  741. }
  742. TEST(ParseAcceptHeaderTest, SpecialCases) {
  743. // Quality value with 3 decimal places
  744. std::vector<std::string> decimal_result;
  745. EXPECT_TRUE(detail::parse_accept_header(
  746. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  747. EXPECT_EQ(decimal_result.size(), 2U);
  748. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  749. EXPECT_EQ(decimal_result[1], "text/html");
  750. // Zero quality (should still be included but with lowest priority)
  751. std::vector<std::string> zero_q_result;
  752. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  753. zero_q_result));
  754. EXPECT_EQ(zero_q_result.size(), 2U);
  755. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  756. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  757. // No spaces around commas
  758. std::vector<std::string> no_space_result;
  759. EXPECT_TRUE(detail::parse_accept_header(
  760. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  761. no_space_result));
  762. EXPECT_EQ(no_space_result.size(), 3U);
  763. EXPECT_EQ(no_space_result[0], "text/html");
  764. EXPECT_EQ(no_space_result[1], "application/json");
  765. EXPECT_EQ(no_space_result[2], "text/plain");
  766. }
  767. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  768. // Quality values always use '.' as the decimal separator, so parsing must
  769. // not depend on the process locale. An embedding application may have
  770. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  771. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  772. std::string saved = cur ? cur : "C";
  773. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  774. "fr_FR.UTF-8"};
  775. bool switched = false;
  776. for (const auto loc : comma_locales) {
  777. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  778. std::localeconv()->decimal_point[0] == ',') {
  779. switched = true;
  780. break;
  781. }
  782. }
  783. if (!switched) {
  784. std::setlocale(LC_NUMERIC, saved.c_str());
  785. GTEST_SKIP() << "no comma-decimal locale available on this host";
  786. }
  787. // The higher-weighted type appears later in the list, so a correct parse
  788. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  789. // sensitive parse reads both weights as 0 and leaves the original order.
  790. std::vector<std::string> result;
  791. EXPECT_TRUE(detail::parse_accept_header(
  792. "application/json;q=0.1,text/html;q=0.9", result));
  793. ASSERT_EQ(result.size(), 2U);
  794. EXPECT_EQ(result[0], "text/html");
  795. EXPECT_EQ(result[1], "application/json");
  796. std::setlocale(LC_NUMERIC, saved.c_str());
  797. }
  798. TEST(ParseAcceptHeaderTest, InvalidCases) {
  799. std::vector<std::string> result;
  800. // Invalid quality value (> 1.0)
  801. EXPECT_FALSE(
  802. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  803. // Invalid quality value (< 0.0)
  804. EXPECT_FALSE(
  805. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  806. // Invalid quality value (not a number)
  807. EXPECT_FALSE(detail::parse_accept_header(
  808. "text/html;q=invalid,application/json", result));
  809. // Empty quality value
  810. EXPECT_FALSE(
  811. detail::parse_accept_header("text/html;q=,application/json", result));
  812. // Invalid media type format (no slash and not wildcard)
  813. EXPECT_FALSE(
  814. detail::parse_accept_header("invalidtype,application/json", result));
  815. // Empty media type
  816. result.clear();
  817. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  818. // Only commas
  819. result.clear();
  820. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  821. // Valid cases should still work
  822. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  823. EXPECT_EQ(result.size(), 1U);
  824. EXPECT_EQ(result[0], "*/*");
  825. EXPECT_TRUE(detail::parse_accept_header("*", result));
  826. EXPECT_EQ(result.size(), 1U);
  827. EXPECT_EQ(result[0], "*");
  828. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  829. EXPECT_EQ(result.size(), 1U);
  830. EXPECT_EQ(result[0], "text/*");
  831. }
  832. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  833. Server svr;
  834. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  835. EXPECT_EQ(req.accept_content_types.size(), 3U);
  836. EXPECT_EQ(req.accept_content_types[0], "application/json");
  837. EXPECT_EQ(req.accept_content_types[1], "text/html");
  838. EXPECT_EQ(req.accept_content_types[2], "*/*");
  839. res.set_content("ok", "text/plain");
  840. });
  841. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  842. EXPECT_TRUE(false);
  843. res.set_content("bad request", "text/plain");
  844. });
  845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  846. auto se = detail::scope_exit([&] {
  847. svr.stop();
  848. listen_thread.join();
  849. ASSERT_FALSE(svr.is_running());
  850. });
  851. svr.wait_until_ready();
  852. Client cli("localhost", PORT);
  853. {
  854. auto res = cli.Get(
  855. "/accept_ok",
  856. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  858. EXPECT_EQ(StatusCode::OK_200, res->status);
  859. }
  860. {
  861. auto res = cli.Get("/accept_bad_request",
  862. Headers{{"Accept", "text/html;q=abc,application/json"}});
  863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  864. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  865. }
  866. }
  867. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  868. Server svr;
  869. svr.Get("/", [](const Request & /*req*/, Response &res) {
  870. res.set_content("ok", "text/plain");
  871. });
  872. std::atomic<int> start_count{0};
  873. std::atomic<bool> running_when_called{false};
  874. svr.set_start_handler([&]() {
  875. running_when_called = svr.is_running();
  876. start_count++;
  877. });
  878. auto port = svr.bind_to_any_port(HOST);
  879. std::thread t([&]() { svr.listen_after_bind(); });
  880. auto se = detail::scope_exit([&] {
  881. svr.stop();
  882. t.join();
  883. ASSERT_FALSE(svr.is_running());
  884. });
  885. svr.wait_until_ready();
  886. // A successful request proves the accept loop is running, which the start
  887. // handler precedes; so by now the handler must have run exactly once.
  888. Client cli(HOST, port);
  889. cli.set_connection_timeout(std::chrono::seconds(5));
  890. auto res = cli.Get("/");
  891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  892. EXPECT_EQ(StatusCode::OK_200, res->status);
  893. EXPECT_EQ(1, start_count.load());
  894. EXPECT_TRUE(running_when_called.load());
  895. }
  896. TEST(DivideTest, DivideStringTests) {
  897. auto divide = [](const std::string &str, char d) {
  898. std::string lhs;
  899. std::string rhs;
  900. detail::divide(str, d,
  901. [&](const char *lhs_data, std::size_t lhs_size,
  902. const char *rhs_data, std::size_t rhs_size) {
  903. lhs.assign(lhs_data, lhs_size);
  904. rhs.assign(rhs_data, rhs_size);
  905. });
  906. return std::make_pair(std::move(lhs), std::move(rhs));
  907. };
  908. {
  909. const auto res = divide("", '=');
  910. EXPECT_EQ(res.first, "");
  911. EXPECT_EQ(res.second, "");
  912. }
  913. {
  914. const auto res = divide("=", '=');
  915. EXPECT_EQ(res.first, "");
  916. EXPECT_EQ(res.second, "");
  917. }
  918. {
  919. const auto res = divide(" ", '=');
  920. EXPECT_EQ(res.first, " ");
  921. EXPECT_EQ(res.second, "");
  922. }
  923. {
  924. const auto res = divide("a", '=');
  925. EXPECT_EQ(res.first, "a");
  926. EXPECT_EQ(res.second, "");
  927. }
  928. {
  929. const auto res = divide("a=", '=');
  930. EXPECT_EQ(res.first, "a");
  931. EXPECT_EQ(res.second, "");
  932. }
  933. {
  934. const auto res = divide("=b", '=');
  935. EXPECT_EQ(res.first, "");
  936. EXPECT_EQ(res.second, "b");
  937. }
  938. {
  939. const auto res = divide("a=b", '=');
  940. EXPECT_EQ(res.first, "a");
  941. EXPECT_EQ(res.second, "b");
  942. }
  943. {
  944. const auto res = divide("a=b=", '=');
  945. EXPECT_EQ(res.first, "a");
  946. EXPECT_EQ(res.second, "b=");
  947. }
  948. {
  949. const auto res = divide("a=b=c", '=');
  950. EXPECT_EQ(res.first, "a");
  951. EXPECT_EQ(res.second, "b=c");
  952. }
  953. }
  954. TEST(SplitTest, ParseQueryString) {
  955. string s = "key1=val1&key2=val2&key3=val3";
  956. Params dic;
  957. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  958. [&](const char *b, const char *e) {
  959. string key, val;
  960. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  961. if (key.empty()) {
  962. key.assign(b2, e2);
  963. } else {
  964. val.assign(b2, e2);
  965. }
  966. });
  967. dic.emplace(key, val);
  968. });
  969. EXPECT_EQ("val1", dic.find("key1")->second);
  970. EXPECT_EQ("val2", dic.find("key2")->second);
  971. EXPECT_EQ("val3", dic.find("key3")->second);
  972. }
  973. TEST(SplitTest, ParseInvalidQueryTests) {
  974. {
  975. string s = " ";
  976. Params dict;
  977. detail::parse_query_text(s, dict);
  978. EXPECT_TRUE(dict.empty());
  979. }
  980. {
  981. string s = " = =";
  982. Params dict;
  983. detail::parse_query_text(s, dict);
  984. EXPECT_TRUE(dict.empty());
  985. }
  986. }
  987. TEST(ParseQueryTest, ParseQueryString) {
  988. {
  989. std::string s = "key1=val1&key2=val2&key3=val3";
  990. Params dic;
  991. detail::parse_query_text(s, dic);
  992. EXPECT_EQ("val1", dic.find("key1")->second);
  993. EXPECT_EQ("val2", dic.find("key2")->second);
  994. EXPECT_EQ("val3", dic.find("key3")->second);
  995. }
  996. {
  997. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  998. Params dic;
  999. detail::parse_query_text(s, dic);
  1000. EXPECT_EQ("", dic.find("key1")->second);
  1001. EXPECT_EQ("val1", dic.find("key2")->second);
  1002. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1003. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1004. }
  1005. }
  1006. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1007. Params dic;
  1008. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1009. dic.emplace("key1", "val1");
  1010. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1011. dic.emplace("key2", "val2");
  1012. dic.emplace("key3", "val3");
  1013. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1014. }
  1015. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1016. string content_type = "multipart/form-data; boundary=something";
  1017. string boundary;
  1018. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1019. EXPECT_TRUE(ret);
  1020. EXPECT_EQ(boundary, "something");
  1021. }
  1022. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1023. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1024. string boundary;
  1025. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1026. EXPECT_TRUE(ret);
  1027. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1028. }
  1029. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1030. string content_type =
  1031. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1032. string boundary;
  1033. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1034. EXPECT_TRUE(ret);
  1035. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1036. }
  1037. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1038. string content_type =
  1039. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1040. string boundary;
  1041. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1042. EXPECT_TRUE(ret);
  1043. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1044. }
  1045. TEST(GetHeaderValueTest, DefaultValue) {
  1046. Headers headers = {{"Dummy", "Dummy"}};
  1047. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1048. EXPECT_STREQ("text/plain", val);
  1049. }
  1050. TEST(GetHeaderValueTest, DefaultValueInt) {
  1051. Headers headers = {{"Dummy", "Dummy"}};
  1052. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1053. EXPECT_EQ(100ull, val);
  1054. }
  1055. TEST(GetHeaderValueTest, RegularValue) {
  1056. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1057. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1058. EXPECT_STREQ("text/html", val);
  1059. }
  1060. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1061. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1062. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1063. EXPECT_STREQ("text/html", val);
  1064. }
  1065. TEST(GetHeaderValueTest, SetContent) {
  1066. Response res;
  1067. res.set_content("html", "text/html");
  1068. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1069. res.set_content("text", "text/plain");
  1070. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1071. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1072. }
  1073. TEST(GetHeaderValueTest, RegularValueInt) {
  1074. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1075. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1076. EXPECT_EQ(100ull, val);
  1077. }
  1078. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1079. Headers headers = {{"Content-Length", "x"}};
  1080. auto is_invalid_value = false;
  1081. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1082. is_invalid_value);
  1083. EXPECT_EQ(0ull, val);
  1084. EXPECT_TRUE(is_invalid_value);
  1085. }
  1086. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1087. // An all-digit value that overflows size_t must be reported as invalid, not
  1088. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1089. // a large length to a small one on 32-bit builds, leaving the framing length
  1090. // wrong while is_invalid_value stayed false.
  1091. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1092. auto is_invalid_value = false;
  1093. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1094. is_invalid_value);
  1095. EXPECT_TRUE(is_invalid_value);
  1096. // A well-formed length is unaffected.
  1097. Headers ok = {{"Content-Length", "1234"}};
  1098. is_invalid_value = false;
  1099. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1100. is_invalid_value);
  1101. EXPECT_EQ(1234ull, val);
  1102. EXPECT_FALSE(is_invalid_value);
  1103. }
  1104. TEST(GetHeaderValueTest, Range) {
  1105. {
  1106. Headers headers = {make_range_header({{1, -1}})};
  1107. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1108. EXPECT_STREQ("bytes=1-", val);
  1109. }
  1110. {
  1111. Headers headers = {make_range_header({{-1, 1}})};
  1112. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1113. EXPECT_STREQ("bytes=-1", val);
  1114. }
  1115. {
  1116. Headers headers = {make_range_header({{1, 10}})};
  1117. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1118. EXPECT_STREQ("bytes=1-10", val);
  1119. }
  1120. {
  1121. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1122. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1123. EXPECT_STREQ("bytes=1-10, 100-", val);
  1124. }
  1125. {
  1126. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1127. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1128. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1129. }
  1130. {
  1131. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1132. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1133. EXPECT_STREQ("bytes=0-0, -1", val);
  1134. }
  1135. }
  1136. TEST(ParseHeaderValueTest, Range) {
  1137. {
  1138. Ranges ranges;
  1139. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1140. EXPECT_TRUE(ret);
  1141. EXPECT_EQ(1u, ranges.size());
  1142. EXPECT_EQ(1u, ranges[0].first);
  1143. EXPECT_EQ(-1, ranges[0].second);
  1144. }
  1145. {
  1146. Ranges ranges;
  1147. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1148. EXPECT_TRUE(ret);
  1149. EXPECT_EQ(1u, ranges.size());
  1150. EXPECT_EQ(-1, ranges[0].first);
  1151. EXPECT_EQ(1u, ranges[0].second);
  1152. }
  1153. {
  1154. Ranges ranges;
  1155. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1156. EXPECT_TRUE(ret);
  1157. EXPECT_EQ(1u, ranges.size());
  1158. EXPECT_EQ(1u, ranges[0].first);
  1159. EXPECT_EQ(10u, ranges[0].second);
  1160. }
  1161. {
  1162. Ranges ranges;
  1163. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1164. EXPECT_FALSE(ret);
  1165. }
  1166. {
  1167. Ranges ranges;
  1168. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1169. EXPECT_TRUE(ret);
  1170. EXPECT_EQ(2u, ranges.size());
  1171. EXPECT_EQ(1u, ranges[0].first);
  1172. EXPECT_EQ(10u, ranges[0].second);
  1173. EXPECT_EQ(100u, ranges[1].first);
  1174. EXPECT_EQ(-1, ranges[1].second);
  1175. }
  1176. {
  1177. Ranges ranges;
  1178. auto ret =
  1179. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1180. EXPECT_TRUE(ret);
  1181. EXPECT_EQ(3u, ranges.size());
  1182. EXPECT_EQ(1u, ranges[0].first);
  1183. EXPECT_EQ(10u, ranges[0].second);
  1184. EXPECT_EQ(100u, ranges[1].first);
  1185. EXPECT_EQ(200u, ranges[1].second);
  1186. EXPECT_EQ(300u, ranges[2].first);
  1187. EXPECT_EQ(400u, ranges[2].second);
  1188. }
  1189. {
  1190. Ranges ranges;
  1191. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1192. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1193. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1194. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1195. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1196. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1197. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1198. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1199. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1200. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1201. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1202. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1203. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1204. EXPECT_TRUE(ranges.empty());
  1205. }
  1206. }
  1207. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1208. Request req;
  1209. req.set_header("Accept-Encoding", "gzip");
  1210. Response res;
  1211. res.set_header("Content-Type", "text/plain");
  1212. auto ret = detail::encoding_type(req, res);
  1213. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1214. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1215. #else
  1216. EXPECT_TRUE(ret == detail::EncodingType::None);
  1217. #endif
  1218. }
  1219. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1220. Request req;
  1221. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1222. Response res;
  1223. res.set_header("Content-Type", "text/plain");
  1224. auto ret = detail::encoding_type(req, res);
  1225. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1226. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1227. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1228. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1229. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1230. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1231. #else
  1232. EXPECT_TRUE(ret == detail::EncodingType::None);
  1233. #endif
  1234. }
  1235. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1236. Request req;
  1237. req.set_header("Accept-Encoding",
  1238. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1239. Response res;
  1240. res.set_header("Content-Type", "text/plain");
  1241. auto ret = detail::encoding_type(req, res);
  1242. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1243. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1244. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1245. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1246. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1247. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1248. #else
  1249. EXPECT_TRUE(ret == detail::EncodingType::None);
  1250. #endif
  1251. }
  1252. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1253. // All supported encodings rejected with q=0 should return None
  1254. Request req;
  1255. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1256. Response res;
  1257. res.set_header("Content-Type", "text/plain");
  1258. auto ret = detail::encoding_type(req, res);
  1259. EXPECT_TRUE(ret == detail::EncodingType::None);
  1260. }
  1261. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1262. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1263. Request req;
  1264. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1265. Response res;
  1266. res.set_header("Content-Type", "text/plain");
  1267. auto ret = detail::encoding_type(req, res);
  1268. EXPECT_TRUE(ret == detail::EncodingType::None);
  1269. }
  1270. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1271. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1272. Request req;
  1273. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1274. Response res;
  1275. res.set_header("Content-Type", "text/plain");
  1276. auto ret = detail::encoding_type(req, res);
  1277. EXPECT_TRUE(ret == detail::EncodingType::None);
  1278. }
  1279. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1280. // RFC 7231: Accept-Encoding values are case-insensitive
  1281. Request req;
  1282. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1283. Response res;
  1284. res.set_header("Content-Type", "text/plain");
  1285. auto ret = detail::encoding_type(req, res);
  1286. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1287. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1288. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1289. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1290. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1291. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1292. #else
  1293. EXPECT_TRUE(ret == detail::EncodingType::None);
  1294. #endif
  1295. }
  1296. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1297. // q value should determine priority, not hardcoded order
  1298. Request req;
  1299. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1300. Response res;
  1301. res.set_header("Content-Type", "text/plain");
  1302. auto ret = detail::encoding_type(req, res);
  1303. // gzip has highest q=1.0, so it should be selected even though
  1304. // br and zstd are also supported
  1305. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1306. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1307. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1308. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1309. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1310. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1311. #else
  1312. EXPECT_TRUE(ret == detail::EncodingType::None);
  1313. #endif
  1314. }
  1315. TEST(BufferStreamTest, read) {
  1316. detail::BufferStream strm1;
  1317. Stream &strm = strm1;
  1318. EXPECT_EQ(5, strm.write("hello"));
  1319. char buf[512];
  1320. EXPECT_EQ(2, strm.read(buf, 2));
  1321. EXPECT_EQ('h', buf[0]);
  1322. EXPECT_EQ('e', buf[1]);
  1323. EXPECT_EQ(2, strm.read(buf, 2));
  1324. EXPECT_EQ('l', buf[0]);
  1325. EXPECT_EQ('l', buf[1]);
  1326. EXPECT_EQ(1, strm.read(buf, 1));
  1327. EXPECT_EQ('o', buf[0]);
  1328. EXPECT_EQ(0, strm.read(buf, 1));
  1329. }
  1330. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1331. auto host = "www.httpwatch.com";
  1332. auto ip = hosted_at(host);
  1333. EXPECT_EQ("23.96.13.243", ip);
  1334. std::vector<std::string> addrs;
  1335. hosted_at(host, addrs);
  1336. EXPECT_EQ(1u, addrs.size());
  1337. }
  1338. #if 0 // It depends on each test environment...
  1339. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1340. auto host = "www.youtube.com";
  1341. std::vector<std::string> addrs;
  1342. hosted_at(host, addrs);
  1343. EXPECT_EQ(20u, addrs.size());
  1344. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1345. EXPECT_TRUE(it != addrs.end());
  1346. }
  1347. #endif
  1348. class ChunkedEncodingTest : public ::testing::Test {
  1349. protected:
  1350. ChunkedEncodingTest()
  1351. : cli_(HOST, PORT)
  1352. #ifdef CPPHTTPLIB_SSL_ENABLED
  1353. ,
  1354. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1355. #endif
  1356. {
  1357. cli_.set_connection_timeout(2);
  1358. #ifdef CPPHTTPLIB_SSL_ENABLED
  1359. cli_.enable_server_certificate_verification(false);
  1360. #endif
  1361. }
  1362. virtual void SetUp() {
  1363. read_file("./image.jpg", image_data_);
  1364. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1365. res.set_content("Hello World!", "text/plain");
  1366. });
  1367. svr_.Get(
  1368. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1369. res.set_chunked_content_provider(
  1370. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1371. size_t remaining = image_data_.size() - offset;
  1372. if (remaining == 0) {
  1373. sink.done();
  1374. } else {
  1375. constexpr size_t CHUNK_SIZE = 1024;
  1376. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1377. sink.write(&image_data_[offset], send_size);
  1378. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1379. }
  1380. return true;
  1381. });
  1382. });
  1383. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1384. svr_.wait_until_ready();
  1385. }
  1386. virtual void TearDown() {
  1387. svr_.stop();
  1388. if (!request_threads_.empty()) {
  1389. std::this_thread::sleep_for(std::chrono::seconds(1));
  1390. for (auto &t : request_threads_) {
  1391. t.join();
  1392. }
  1393. }
  1394. t_.join();
  1395. }
  1396. #ifdef CPPHTTPLIB_SSL_ENABLED
  1397. SSLClient cli_;
  1398. SSLServer svr_;
  1399. #else
  1400. Client cli_;
  1401. Server svr_;
  1402. #endif
  1403. thread t_;
  1404. std::vector<thread> request_threads_;
  1405. std::string image_data_;
  1406. };
  1407. TEST_F(ChunkedEncodingTest, NormalGet) {
  1408. auto res = cli_.Get("/chunked");
  1409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1410. std::string out;
  1411. read_file("./image.jpg", out);
  1412. EXPECT_EQ(StatusCode::OK_200, res->status);
  1413. EXPECT_EQ(out, res->body);
  1414. }
  1415. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1416. std::string body;
  1417. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1418. body.append(data, data_length);
  1419. return true;
  1420. });
  1421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1422. std::string out;
  1423. read_file("./image.jpg", out);
  1424. EXPECT_EQ(StatusCode::OK_200, res->status);
  1425. EXPECT_EQ(out, body);
  1426. }
  1427. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1428. std::string body;
  1429. auto res = cli_.Get(
  1430. "/chunked",
  1431. [&](const Response &response) {
  1432. EXPECT_EQ(StatusCode::OK_200, response.status);
  1433. return true;
  1434. },
  1435. [&](const char *data, size_t data_length) {
  1436. body.append(data, data_length);
  1437. return true;
  1438. });
  1439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1440. std::string out;
  1441. read_file("./image.jpg", out);
  1442. EXPECT_EQ(StatusCode::OK_200, res->status);
  1443. EXPECT_EQ(out, body);
  1444. }
  1445. TEST(RangeTest, FromHTTPBin_Online) {
  1446. auto host = "httpbingo.org";
  1447. auto path = std::string{"/range/32"};
  1448. #ifdef CPPHTTPLIB_SSL_ENABLED
  1449. auto port = 443;
  1450. SSLClient cli(host, port);
  1451. #else
  1452. auto port = 80;
  1453. Client cli(host, port);
  1454. #endif
  1455. cli.set_connection_timeout(5);
  1456. {
  1457. auto res = cli.Get(path);
  1458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1459. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1460. EXPECT_EQ(StatusCode::OK_200, res->status);
  1461. }
  1462. {
  1463. Headers headers = {make_range_header({{1, -1}})};
  1464. auto res = cli.Get(path, headers);
  1465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1466. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1468. }
  1469. {
  1470. Headers headers = {make_range_header({{1, 10}})};
  1471. auto res = cli.Get(path, headers);
  1472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1473. EXPECT_EQ("bcdefghijk", res->body);
  1474. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1475. }
  1476. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1477. // entire resource, while the original httpbin returned 200. Both are
  1478. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1479. {
  1480. Headers headers = {make_range_header({{0, 31}})};
  1481. auto res = cli.Get(path, headers);
  1482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1483. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1484. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1485. res->status == StatusCode::PartialContent_206);
  1486. }
  1487. {
  1488. Headers headers = {make_range_header({{0, -1}})};
  1489. auto res = cli.Get(path, headers);
  1490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1491. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1492. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1493. res->status == StatusCode::PartialContent_206);
  1494. }
  1495. // go-httpbin returns 206 with clamped range for over-range requests,
  1496. // while the original httpbin returned 416. Both behaviors are observed
  1497. // in real servers, so we only verify the request succeeds.
  1498. {
  1499. Headers headers = {make_range_header({{0, 32}})};
  1500. auto res = cli.Get(path, headers);
  1501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1502. }
  1503. }
  1504. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1505. auto host = "unresolvableaddress.local";
  1506. auto path = std::string{"/"};
  1507. #ifdef CPPHTTPLIB_SSL_ENABLED
  1508. auto port = 443;
  1509. SSLClient cli(host, port);
  1510. #else
  1511. auto port = 80;
  1512. Client cli(host, port);
  1513. #endif
  1514. cli.set_connection_timeout(1);
  1515. {
  1516. auto res = cli.Get(path);
  1517. ASSERT_FALSE(res);
  1518. }
  1519. std::this_thread::sleep_for(std::chrono::seconds(8));
  1520. }
  1521. #if defined(__linux__) && defined(__GLIBC__) && \
  1522. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1523. // Forward declaration: in split builds split.py strips `inline` and moves the
  1524. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1525. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1526. // against the symbol in both header-only and split builds.
  1527. namespace httplib {
  1528. namespace detail {
  1529. int getaddrinfo_with_timeout(const char *node, const char *service,
  1530. const struct addrinfo *hints,
  1531. struct addrinfo **res, time_t timeout_sec);
  1532. } // namespace detail
  1533. } // namespace httplib
  1534. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1535. //
  1536. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1537. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1538. // gai_suspend() call hits the connection timeout the function calls
  1539. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1540. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1541. // still alive and still references the now-destroyed stack frame.
  1542. //
  1543. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1544. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1545. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1546. // and runs them in a container.
  1547. namespace {
  1548. bool should_run_issue_2431_tests() {
  1549. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1550. return v && *v && std::string(v) != "0";
  1551. }
  1552. std::string unique_unresolvable_host(int n) {
  1553. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1554. // glibc still asks the configured nameserver — which is exactly the path
  1555. // we want to exercise. A unique label per call avoids the resolver cache.
  1556. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1557. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1558. std::to_string(n) + ".invalid";
  1559. }
  1560. } // namespace
  1561. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1562. if (!should_run_issue_2431_tests()) {
  1563. GTEST_SKIP()
  1564. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1565. }
  1566. for (int i = 0; i < 8; ++i) {
  1567. struct addrinfo hints;
  1568. memset(&hints, 0, sizeof(hints));
  1569. hints.ai_family = AF_UNSPEC;
  1570. hints.ai_socktype = SOCK_STREAM;
  1571. auto host = unique_unresolvable_host(i);
  1572. struct addrinfo *result = nullptr;
  1573. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1574. &result, /*timeout_sec=*/1);
  1575. if (rc == 0 && result) { freeaddrinfo(result); }
  1576. }
  1577. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1578. // stack region they still believe holds their gaicb.
  1579. std::this_thread::sleep_for(std::chrono::seconds(3));
  1580. }
  1581. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1582. if (!should_run_issue_2431_tests()) {
  1583. GTEST_SKIP()
  1584. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1585. }
  1586. std::atomic<bool> stop{false};
  1587. std::vector<std::thread> threads;
  1588. for (int t = 0; t < 8; ++t) {
  1589. threads.emplace_back([t, &stop] {
  1590. int i = 0;
  1591. while (!stop.load(std::memory_order_relaxed)) {
  1592. struct addrinfo hints;
  1593. memset(&hints, 0, sizeof(hints));
  1594. hints.ai_family = AF_UNSPEC;
  1595. hints.ai_socktype = SOCK_STREAM;
  1596. auto host = unique_unresolvable_host(t * 100000 + i++);
  1597. struct addrinfo *result = nullptr;
  1598. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1599. &result, /*timeout_sec=*/1);
  1600. if (rc == 0 && result) { freeaddrinfo(result); }
  1601. }
  1602. });
  1603. }
  1604. std::this_thread::sleep_for(std::chrono::seconds(8));
  1605. stop.store(true, std::memory_order_relaxed);
  1606. for (auto &th : threads) {
  1607. th.join();
  1608. }
  1609. std::this_thread::sleep_for(std::chrono::seconds(3));
  1610. }
  1611. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1612. if (!should_run_issue_2431_tests()) {
  1613. GTEST_SKIP()
  1614. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1615. }
  1616. std::atomic<bool> stop{false};
  1617. std::vector<std::thread> threads;
  1618. for (int t = 0; t < 8; ++t) {
  1619. threads.emplace_back([t, &stop] {
  1620. int i = 0;
  1621. while (!stop.load(std::memory_order_relaxed)) {
  1622. auto host = unique_unresolvable_host(t * 100000 + i++);
  1623. Client cli(host, 80);
  1624. cli.set_connection_timeout(1, 0);
  1625. cli.set_read_timeout(1, 0);
  1626. cli.set_write_timeout(1, 0);
  1627. (void)cli.Get("/");
  1628. }
  1629. });
  1630. }
  1631. std::this_thread::sleep_for(std::chrono::seconds(8));
  1632. stop.store(true, std::memory_order_relaxed);
  1633. for (auto &th : threads) {
  1634. th.join();
  1635. }
  1636. std::this_thread::sleep_for(std::chrono::seconds(3));
  1637. }
  1638. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1639. TEST(ConnectionErrorTest, InvalidHost) {
  1640. auto host = "-abcde.com";
  1641. #ifdef CPPHTTPLIB_SSL_ENABLED
  1642. auto port = 443;
  1643. SSLClient cli(host, port);
  1644. #else
  1645. auto port = 80;
  1646. Client cli(host, port);
  1647. #endif
  1648. cli.set_connection_timeout(std::chrono::seconds(2));
  1649. auto res = cli.Get("/");
  1650. ASSERT_TRUE(!res);
  1651. EXPECT_EQ(Error::Connection, res.error());
  1652. }
  1653. TEST(ConnectionErrorTest, InvalidHost2) {
  1654. auto host = "httpcan.org/";
  1655. #ifdef CPPHTTPLIB_SSL_ENABLED
  1656. SSLClient cli(host);
  1657. #else
  1658. Client cli(host);
  1659. #endif
  1660. cli.set_connection_timeout(std::chrono::seconds(2));
  1661. auto res = cli.Get("/");
  1662. ASSERT_TRUE(!res);
  1663. EXPECT_EQ(Error::Connection, res.error());
  1664. }
  1665. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1666. auto host = "httpcan.org/";
  1667. #ifdef CPPHTTPLIB_SSL_ENABLED
  1668. SSLClient cli(host);
  1669. #else
  1670. Client cli(host);
  1671. #endif
  1672. cli.set_connection_timeout(std::chrono::seconds(2));
  1673. auto res = cli.Get("/");
  1674. ASSERT_TRUE(!res);
  1675. stringstream s;
  1676. s << "error code: " << res.error();
  1677. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1678. }
  1679. TEST(ConnectionErrorTest, InvalidPort) {
  1680. auto host = "localhost";
  1681. auto port = 44380;
  1682. #ifdef CPPHTTPLIB_SSL_ENABLED
  1683. SSLClient cli(host, port);
  1684. #else
  1685. Client cli(host, port);
  1686. #endif
  1687. cli.set_connection_timeout(std::chrono::seconds(2));
  1688. auto res = cli.Get("/");
  1689. ASSERT_TRUE(!res);
  1690. EXPECT_TRUE(Error::Connection == res.error() ||
  1691. Error::ConnectionTimeout == res.error());
  1692. }
  1693. TEST(ConnectionErrorTest, Timeout_Online) {
  1694. auto host = "google.com";
  1695. #ifdef CPPHTTPLIB_SSL_ENABLED
  1696. auto port = 44380;
  1697. SSLClient cli(host, port);
  1698. #else
  1699. auto port = 8080;
  1700. Client cli(host, port);
  1701. #endif
  1702. cli.set_connection_timeout(std::chrono::seconds(2));
  1703. // only probe one address type so that the error reason
  1704. // correlates to the timed-out IPv4, not the unsupported
  1705. // IPv6 connection attempt
  1706. cli.set_address_family(AF_INET);
  1707. auto res = cli.Get("/");
  1708. ASSERT_TRUE(!res);
  1709. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1710. }
  1711. TEST(CancelTest, NoCancel_Online) {
  1712. auto host = "httpbingo.org";
  1713. auto path = std::string{"/range/32"};
  1714. #ifdef CPPHTTPLIB_SSL_ENABLED
  1715. auto port = 443;
  1716. SSLClient cli(host, port);
  1717. #else
  1718. auto port = 80;
  1719. Client cli(host, port);
  1720. #endif
  1721. cli.set_connection_timeout(std::chrono::seconds(5));
  1722. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1724. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1725. EXPECT_EQ(StatusCode::OK_200, res->status);
  1726. }
  1727. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1728. // Use /bytes with a large payload so that the DownloadProgress callback
  1729. // (which only fires for Content-Length responses) is invoked before the
  1730. // entire body is received, giving cancellation a chance to fire.
  1731. auto host = "httpbingo.org";
  1732. auto path = std::string{"/bytes/524288"};
  1733. #ifdef CPPHTTPLIB_SSL_ENABLED
  1734. auto port = 443;
  1735. SSLClient cli(host, port);
  1736. #else
  1737. auto port = 80;
  1738. Client cli(host, port);
  1739. #endif
  1740. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1741. cli.set_connection_timeout(std::chrono::seconds(5));
  1742. ASSERT_TRUE(!res);
  1743. EXPECT_EQ(Error::Canceled, res.error());
  1744. }
  1745. TEST(CancelTest, WithCancelLargePayload_Online) {
  1746. auto host = "httpbingo.org";
  1747. auto path = std::string{"/bytes/524288"};
  1748. #ifdef CPPHTTPLIB_SSL_ENABLED
  1749. auto port = 443;
  1750. SSLClient cli(host, port);
  1751. #else
  1752. auto port = 80;
  1753. Client cli(host, port);
  1754. #endif
  1755. cli.set_connection_timeout(std::chrono::seconds(5));
  1756. uint32_t count = 0;
  1757. auto res =
  1758. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1759. ASSERT_TRUE(!res);
  1760. EXPECT_EQ(Error::Canceled, res.error());
  1761. }
  1762. TEST(CancelTest, NoCancelPost) {
  1763. Server svr;
  1764. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1765. res.set_content("Hello World!", "text/plain");
  1766. });
  1767. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1768. auto se = detail::scope_exit([&] {
  1769. svr.stop();
  1770. thread.join();
  1771. ASSERT_FALSE(svr.is_running());
  1772. });
  1773. svr.wait_until_ready();
  1774. Client cli(HOST, PORT);
  1775. cli.set_connection_timeout(std::chrono::seconds(5));
  1776. auto res =
  1777. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1778. "application/json", [](uint64_t, uint64_t) { return true; });
  1779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1780. EXPECT_EQ("Hello World!", res->body);
  1781. EXPECT_EQ(StatusCode::OK_200, res->status);
  1782. }
  1783. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1784. Server svr;
  1785. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1786. res.set_content("Hello World!", "text/plain");
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. Client cli(HOST, PORT);
  1796. cli.set_connection_timeout(std::chrono::seconds(5));
  1797. auto res =
  1798. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1799. "application/json", [](uint64_t, uint64_t) { return false; });
  1800. ASSERT_TRUE(!res);
  1801. EXPECT_EQ(Error::Canceled, res.error());
  1802. }
  1803. TEST(CancelTest, WithCancelLargePayloadPost) {
  1804. Server svr;
  1805. svr.set_payload_max_length(200 * 1024 * 1024);
  1806. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1807. res.set_content(LARGE_DATA, "text/plain");
  1808. });
  1809. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1810. auto se = detail::scope_exit([&] {
  1811. svr.stop();
  1812. thread.join();
  1813. ASSERT_FALSE(svr.is_running());
  1814. });
  1815. svr.wait_until_ready();
  1816. Client cli(HOST, PORT);
  1817. cli.set_payload_max_length(200 * 1024 * 1024);
  1818. cli.set_connection_timeout(std::chrono::seconds(5));
  1819. auto res =
  1820. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1821. "application/json", [](uint64_t, uint64_t) { return false; });
  1822. ASSERT_TRUE(!res);
  1823. EXPECT_EQ(Error::Canceled, res.error());
  1824. }
  1825. TEST(CancelTest, NoCancelPut) {
  1826. Server svr;
  1827. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1828. res.set_content("Hello World!", "text/plain");
  1829. });
  1830. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1831. auto se = detail::scope_exit([&] {
  1832. svr.stop();
  1833. thread.join();
  1834. ASSERT_FALSE(svr.is_running());
  1835. });
  1836. svr.wait_until_ready();
  1837. Client cli(HOST, PORT);
  1838. cli.set_connection_timeout(std::chrono::seconds(5));
  1839. auto res =
  1840. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1841. "application/json", [](uint64_t, uint64_t) { return true; });
  1842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1843. EXPECT_EQ("Hello World!", res->body);
  1844. EXPECT_EQ(StatusCode::OK_200, res->status);
  1845. }
  1846. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1847. Server svr;
  1848. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1849. res.set_content("Hello World!", "text/plain");
  1850. });
  1851. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1852. auto se = detail::scope_exit([&] {
  1853. svr.stop();
  1854. thread.join();
  1855. ASSERT_FALSE(svr.is_running());
  1856. });
  1857. svr.wait_until_ready();
  1858. Client cli(HOST, PORT);
  1859. cli.set_connection_timeout(std::chrono::seconds(5));
  1860. auto res =
  1861. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1862. "application/json", [](uint64_t, uint64_t) { return false; });
  1863. ASSERT_TRUE(!res);
  1864. EXPECT_EQ(Error::Canceled, res.error());
  1865. }
  1866. TEST(CancelTest, WithCancelLargePayloadPut) {
  1867. Server svr;
  1868. svr.set_payload_max_length(200 * 1024 * 1024);
  1869. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1870. res.set_content(LARGE_DATA, "text/plain");
  1871. });
  1872. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1873. auto se = detail::scope_exit([&] {
  1874. svr.stop();
  1875. thread.join();
  1876. ASSERT_FALSE(svr.is_running());
  1877. });
  1878. svr.wait_until_ready();
  1879. Client cli(HOST, PORT);
  1880. cli.set_payload_max_length(200 * 1024 * 1024);
  1881. cli.set_connection_timeout(std::chrono::seconds(5));
  1882. auto res =
  1883. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1884. "application/json", [](uint64_t, uint64_t) { return false; });
  1885. ASSERT_TRUE(!res);
  1886. EXPECT_EQ(Error::Canceled, res.error());
  1887. }
  1888. TEST(CancelTest, NoCancelPatch) {
  1889. Server svr;
  1890. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1891. res.set_content("Hello World!", "text/plain");
  1892. });
  1893. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1894. auto se = detail::scope_exit([&] {
  1895. svr.stop();
  1896. thread.join();
  1897. ASSERT_FALSE(svr.is_running());
  1898. });
  1899. svr.wait_until_ready();
  1900. Client cli(HOST, PORT);
  1901. cli.set_connection_timeout(std::chrono::seconds(5));
  1902. auto res =
  1903. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1904. "application/json", [](uint64_t, uint64_t) { return true; });
  1905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1906. EXPECT_EQ("Hello World!", res->body);
  1907. EXPECT_EQ(StatusCode::OK_200, res->status);
  1908. }
  1909. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1910. Server svr;
  1911. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1912. res.set_content("Hello World!", "text/plain");
  1913. });
  1914. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1915. auto se = detail::scope_exit([&] {
  1916. svr.stop();
  1917. thread.join();
  1918. ASSERT_FALSE(svr.is_running());
  1919. });
  1920. svr.wait_until_ready();
  1921. Client cli(HOST, PORT);
  1922. cli.set_connection_timeout(std::chrono::seconds(5));
  1923. auto res =
  1924. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1925. "application/json", [](uint64_t, uint64_t) { return false; });
  1926. ASSERT_TRUE(!res);
  1927. EXPECT_EQ(Error::Canceled, res.error());
  1928. }
  1929. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1930. Server svr;
  1931. svr.set_payload_max_length(200 * 1024 * 1024);
  1932. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1933. res.set_content(LARGE_DATA, "text/plain");
  1934. });
  1935. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1936. auto se = detail::scope_exit([&] {
  1937. svr.stop();
  1938. thread.join();
  1939. ASSERT_FALSE(svr.is_running());
  1940. });
  1941. svr.wait_until_ready();
  1942. Client cli(HOST, PORT);
  1943. cli.set_payload_max_length(200 * 1024 * 1024);
  1944. cli.set_connection_timeout(std::chrono::seconds(5));
  1945. auto res =
  1946. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1947. "application/json", [](uint64_t, uint64_t) { return false; });
  1948. ASSERT_TRUE(!res);
  1949. EXPECT_EQ(Error::Canceled, res.error());
  1950. }
  1951. TEST(CancelTest, NoCancelDelete) {
  1952. Server svr;
  1953. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1954. res.set_content("Hello World!", "text/plain");
  1955. });
  1956. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1957. auto se = detail::scope_exit([&] {
  1958. svr.stop();
  1959. thread.join();
  1960. ASSERT_FALSE(svr.is_running());
  1961. });
  1962. svr.wait_until_ready();
  1963. Client cli(HOST, PORT);
  1964. cli.set_connection_timeout(std::chrono::seconds(5));
  1965. auto res =
  1966. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1967. "application/json", [](uint64_t, uint64_t) { return true; });
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. EXPECT_EQ("Hello World!", res->body);
  1970. EXPECT_EQ(StatusCode::OK_200, res->status);
  1971. }
  1972. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1973. Server svr;
  1974. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1975. res.set_content("Hello World!", "text/plain");
  1976. });
  1977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1978. auto se = detail::scope_exit([&] {
  1979. svr.stop();
  1980. thread.join();
  1981. ASSERT_FALSE(svr.is_running());
  1982. });
  1983. svr.wait_until_ready();
  1984. Client cli(HOST, PORT);
  1985. cli.set_connection_timeout(std::chrono::seconds(5));
  1986. auto res =
  1987. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1988. "application/json", [](uint64_t, uint64_t) { return false; });
  1989. ASSERT_TRUE(!res);
  1990. EXPECT_EQ(Error::Canceled, res.error());
  1991. }
  1992. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1993. Server svr;
  1994. svr.set_payload_max_length(200 * 1024 * 1024);
  1995. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1996. res.set_content(LARGE_DATA, "text/plain");
  1997. });
  1998. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1999. auto se = detail::scope_exit([&] {
  2000. svr.stop();
  2001. thread.join();
  2002. ASSERT_FALSE(svr.is_running());
  2003. });
  2004. svr.wait_until_ready();
  2005. Client cli(HOST, PORT);
  2006. cli.set_payload_max_length(200 * 1024 * 1024);
  2007. cli.set_connection_timeout(std::chrono::seconds(5));
  2008. auto res =
  2009. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2010. "application/json", [](uint64_t, uint64_t) { return false; });
  2011. ASSERT_TRUE(!res);
  2012. EXPECT_EQ(Error::Canceled, res.error());
  2013. }
  2014. static std::string remove_whitespace(const std::string &input) {
  2015. std::string output;
  2016. output.reserve(input.size());
  2017. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2018. [](unsigned char c) { return !std::isspace(c); });
  2019. return output;
  2020. }
  2021. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2022. auto host = "httpbingo.org";
  2023. auto path = std::string{"/basic-auth/hello/world"};
  2024. #ifdef CPPHTTPLIB_SSL_ENABLED
  2025. auto port = 443;
  2026. SSLClient cli(host, port);
  2027. #else
  2028. auto port = 80;
  2029. Client cli(host, port);
  2030. #endif
  2031. {
  2032. auto res = cli.Get(path);
  2033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2034. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2035. }
  2036. {
  2037. auto res = cli.Get(
  2038. path, Headers{make_basic_authentication_header("hello", "world")});
  2039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2040. auto body = remove_whitespace(res->body);
  2041. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2042. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2043. EXPECT_EQ(StatusCode::OK_200, res->status);
  2044. }
  2045. {
  2046. cli.set_basic_auth("hello", "world");
  2047. auto res = cli.Get(path);
  2048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2049. auto body = remove_whitespace(res->body);
  2050. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2051. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2052. EXPECT_EQ(StatusCode::OK_200, res->status);
  2053. }
  2054. {
  2055. cli.set_basic_auth("hello", "bad");
  2056. auto res = cli.Get(path);
  2057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2058. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2059. }
  2060. {
  2061. cli.set_basic_auth("bad", "world");
  2062. auto res = cli.Get(path);
  2063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2064. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2065. }
  2066. }
  2067. #ifdef CPPHTTPLIB_SSL_ENABLED
  2068. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2069. auto host = "httpbingo.org";
  2070. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2071. auto paths = std::vector<std::string>{
  2072. "/digest-auth/auth/hello/world/MD5",
  2073. "/digest-auth/auth/hello/world/SHA-256",
  2074. };
  2075. auto port = 443;
  2076. SSLClient cli(host, port);
  2077. {
  2078. auto res = cli.Get(unauth_path);
  2079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2080. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2081. }
  2082. {
  2083. cli.set_digest_auth("hello", "world");
  2084. for (const auto &path : paths) {
  2085. auto res = cli.Get(path.c_str());
  2086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2087. auto body = remove_whitespace(res->body);
  2088. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2089. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2090. EXPECT_EQ(StatusCode::OK_200, res->status);
  2091. }
  2092. cli.set_digest_auth("hello", "bad");
  2093. for (const auto &path : paths) {
  2094. auto res = cli.Get(path.c_str());
  2095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2096. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2097. }
  2098. }
  2099. }
  2100. #endif
  2101. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2102. auto host = "google.com";
  2103. auto another_host = "example.com";
  2104. auto wrong_ip = "0.0.0.0";
  2105. #ifdef CPPHTTPLIB_SSL_ENABLED
  2106. SSLClient cli(host);
  2107. #else
  2108. Client cli(host);
  2109. #endif
  2110. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2111. auto res = cli.Get("/");
  2112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2113. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2114. }
  2115. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2116. auto host = "google.com";
  2117. auto wrong_ip = "0.0.0.0";
  2118. #ifdef CPPHTTPLIB_SSL_ENABLED
  2119. SSLClient cli(host);
  2120. #else
  2121. Client cli(host);
  2122. #endif
  2123. cli.set_hostname_addr_map({{host, wrong_ip}});
  2124. auto res = cli.Get("/");
  2125. ASSERT_TRUE(!res);
  2126. EXPECT_EQ(Error::Connection, res.error());
  2127. }
  2128. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2129. // A mapped value that is not an IP literal must be resolved. "localhost"
  2130. // resolves from the hosts file, so this test needs no external DNS.
  2131. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2132. auto host = "target.invalid";
  2133. Server svr;
  2134. std::string received_host;
  2135. svr.Get("/hi", [&](const Request &req, Response &res) {
  2136. received_host = req.get_header_value("Host");
  2137. res.set_content("Hello World!", "text/plain");
  2138. });
  2139. auto port = svr.bind_to_any_port(HOST);
  2140. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2141. auto se = detail::scope_exit([&] {
  2142. svr.stop();
  2143. thread.join();
  2144. ASSERT_FALSE(svr.is_running());
  2145. });
  2146. svr.wait_until_ready();
  2147. Client cli(host, port);
  2148. cli.set_hostname_addr_map({{host, HOST}});
  2149. auto res = cli.Get("/hi");
  2150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2151. EXPECT_EQ(StatusCode::OK_200, res->status);
  2152. // The mapping only redirects the connection; the identity stays host_.
  2153. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2154. }
  2155. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2156. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2157. auto host = "target.invalid";
  2158. Server svr;
  2159. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2160. res.set_content("Hello World!", "text/plain");
  2161. });
  2162. auto port = svr.bind_to_any_port("127.0.0.1");
  2163. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2164. auto se = detail::scope_exit([&] {
  2165. svr.stop();
  2166. thread.join();
  2167. ASSERT_FALSE(svr.is_running());
  2168. });
  2169. svr.wait_until_ready();
  2170. Client cli(host, port);
  2171. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2172. auto res = cli.Get("/hi");
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ(StatusCode::OK_200, res->status);
  2175. }
  2176. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2177. // An empty mapped value must leave host_ as the connection target. Without
  2178. // that guard the empty value would become the host argument, getaddrinfo
  2179. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2180. // loopback - silently connecting somewhere the caller never asked for.
  2181. // The server listens on loopback, so such a fallback would succeed and is
  2182. // therefore observable as a failure of this test.
  2183. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2184. Server svr;
  2185. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2186. res.set_content("Hello World!", "text/plain");
  2187. });
  2188. auto port = svr.bind_to_any_port(HOST);
  2189. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2190. auto se = detail::scope_exit([&] {
  2191. svr.stop();
  2192. thread.join();
  2193. ASSERT_FALSE(svr.is_running());
  2194. });
  2195. svr.wait_until_ready();
  2196. Client cli(blackhole, port);
  2197. cli.set_hostname_addr_map({{blackhole, ""}});
  2198. cli.set_connection_timeout(1);
  2199. auto res = cli.Get("/hi");
  2200. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2201. }
  2202. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2203. auto host = "httpbingo.org";
  2204. auto path = std::string{"/absolute-redirect/3"};
  2205. #ifdef CPPHTTPLIB_SSL_ENABLED
  2206. SSLClient cli(host);
  2207. #else
  2208. Client cli(host);
  2209. #endif
  2210. cli.set_follow_location(true);
  2211. auto res = cli.Get(path);
  2212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2213. EXPECT_EQ(StatusCode::OK_200, res->status);
  2214. }
  2215. TEST(RedirectTest, Redirect_Online) {
  2216. auto host = "httpbingo.org";
  2217. auto path = std::string{"/redirect/3"};
  2218. #ifdef CPPHTTPLIB_SSL_ENABLED
  2219. SSLClient cli(host);
  2220. #else
  2221. Client cli(host);
  2222. #endif
  2223. cli.set_follow_location(true);
  2224. auto res = cli.Get(path);
  2225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2226. EXPECT_EQ(StatusCode::OK_200, res->status);
  2227. }
  2228. TEST(RelativeRedirectTest, Redirect_Online) {
  2229. auto host = "httpbingo.org";
  2230. auto path = std::string{"/relative-redirect/3"};
  2231. #ifdef CPPHTTPLIB_SSL_ENABLED
  2232. SSLClient cli(host);
  2233. #else
  2234. Client cli(host);
  2235. #endif
  2236. cli.set_follow_location(true);
  2237. auto res = cli.Get(path);
  2238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2239. EXPECT_EQ(StatusCode::OK_200, res->status);
  2240. }
  2241. TEST(TooManyRedirectTest, Redirect_Online) {
  2242. auto host = "httpbingo.org";
  2243. auto path = std::string{"/redirect/21"};
  2244. #ifdef CPPHTTPLIB_SSL_ENABLED
  2245. SSLClient cli(host);
  2246. #else
  2247. Client cli(host);
  2248. #endif
  2249. cli.set_follow_location(true);
  2250. auto res = cli.Get(path);
  2251. ASSERT_TRUE(!res);
  2252. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2253. }
  2254. #ifdef CPPHTTPLIB_SSL_ENABLED
  2255. TEST(YahooRedirectTest, Redirect_Online) {
  2256. Client cli("yahoo.com");
  2257. auto res = cli.Get("/");
  2258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2259. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2260. cli.set_follow_location(true);
  2261. res = cli.Get("/");
  2262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2263. EXPECT_EQ(StatusCode::OK_200, res->status);
  2264. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2265. }
  2266. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2267. #define REDIR_HOST "httpbingo.org"
  2268. #define REDIR_PATH "/redirect-to"
  2269. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2270. SSLClient cli(REDIR_HOST);
  2271. cli.set_follow_location(true);
  2272. auto res =
  2273. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2275. EXPECT_EQ(StatusCode::OK_200, res->status);
  2276. }
  2277. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2278. SSLClient cli(REDIR_HOST);
  2279. cli.set_follow_location(true);
  2280. Params params;
  2281. params.emplace("url", "http://example.com");
  2282. params.emplace("status_code", "302");
  2283. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. }
  2287. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2288. SSLClient cli(REDIR_HOST);
  2289. cli.set_follow_location(true);
  2290. Params params;
  2291. params.emplace("url", "http://example.com");
  2292. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2294. EXPECT_EQ(StatusCode::OK_200, res->status);
  2295. }
  2296. TEST(UrlWithSpace, Redirect_Online) {
  2297. SSLClient cli("edge.forgecdn.net");
  2298. cli.set_follow_location(true);
  2299. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2303. }
  2304. #endif
  2305. #if !defined(_WIN32) && !defined(_WIN64)
  2306. TEST(ReceiveSignals, Signal) {
  2307. auto setupSignalHandlers = []() {
  2308. struct sigaction act;
  2309. sigemptyset(&act.sa_mask);
  2310. act.sa_flags = SA_SIGINFO;
  2311. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2312. switch (sig) {
  2313. case SIGINT:
  2314. default: break;
  2315. }
  2316. };
  2317. ::sigaction(SIGINT, &act, nullptr);
  2318. };
  2319. Server svr;
  2320. int port = 0;
  2321. auto thread = std::thread([&]() {
  2322. setupSignalHandlers();
  2323. port = svr.bind_to_any_port(HOST);
  2324. svr.listen_after_bind();
  2325. });
  2326. auto se = detail::scope_exit([&] {
  2327. svr.stop();
  2328. thread.join();
  2329. ASSERT_FALSE(svr.is_running());
  2330. });
  2331. svr.wait_until_ready();
  2332. ASSERT_TRUE(svr.is_running());
  2333. pthread_kill(thread.native_handle(), SIGINT);
  2334. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2335. ASSERT_TRUE(svr.is_running());
  2336. }
  2337. #endif
  2338. TEST(RedirectToDifferentPort, Redirect) {
  2339. Server svr1;
  2340. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2341. res.set_content("Hello World!", "text/plain");
  2342. });
  2343. int svr1_port = 0;
  2344. auto thread1 = std::thread([&]() {
  2345. svr1_port = svr1.bind_to_any_port(HOST);
  2346. svr1.listen_after_bind();
  2347. });
  2348. Server svr2;
  2349. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2350. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2351. });
  2352. int svr2_port = 0;
  2353. auto thread2 = std::thread([&]() {
  2354. svr2_port = svr2.bind_to_any_port(HOST);
  2355. svr2.listen_after_bind();
  2356. });
  2357. auto se = detail::scope_exit([&] {
  2358. svr2.stop();
  2359. thread2.join();
  2360. svr1.stop();
  2361. thread1.join();
  2362. ASSERT_FALSE(svr2.is_running());
  2363. ASSERT_FALSE(svr1.is_running());
  2364. });
  2365. svr1.wait_until_ready();
  2366. svr2.wait_until_ready();
  2367. Client cli("localhost", svr2_port);
  2368. cli.set_follow_location(true);
  2369. auto res = cli.Get("/2");
  2370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2371. EXPECT_EQ(StatusCode::OK_200, res->status);
  2372. EXPECT_EQ("Hello World!", res->body);
  2373. }
  2374. static void
  2375. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2376. Server svr1;
  2377. std::string captured_authorization;
  2378. svr1.Get("/target", [&](const Request &req, Response &res) {
  2379. captured_authorization = req.get_header_value("Authorization");
  2380. res.set_content("OK", "text/plain");
  2381. });
  2382. int svr1_port = 0;
  2383. auto thread1 = std::thread([&]() {
  2384. svr1_port = svr1.bind_to_any_port(HOST);
  2385. svr1.listen_after_bind();
  2386. });
  2387. Server svr2;
  2388. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2389. res.set_redirect(
  2390. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2391. });
  2392. int svr2_port = 0;
  2393. auto thread2 = std::thread([&]() {
  2394. svr2_port = svr2.bind_to_any_port(HOST);
  2395. svr2.listen_after_bind();
  2396. });
  2397. auto se = detail::scope_exit([&] {
  2398. svr2.stop();
  2399. thread2.join();
  2400. svr1.stop();
  2401. thread1.join();
  2402. ASSERT_FALSE(svr2.is_running());
  2403. ASSERT_FALSE(svr1.is_running());
  2404. });
  2405. svr1.wait_until_ready();
  2406. svr2.wait_until_ready();
  2407. Client cli("localhost", svr2_port);
  2408. cli.set_follow_location(true);
  2409. set_auth(cli);
  2410. auto res = cli.Get("/redir");
  2411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2412. EXPECT_EQ(StatusCode::OK_200, res->status);
  2413. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2414. EXPECT_TRUE(captured_authorization.empty());
  2415. }
  2416. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2417. TestDoNotForwardCredentialsOnRedirect(
  2418. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2419. }
  2420. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2421. TestDoNotForwardCredentialsOnRedirect(
  2422. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2423. }
  2424. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  2425. Server svr1;
  2426. std::string captured_cookie;
  2427. bool target_hit = false;
  2428. svr1.Get("/target", [&](const Request &req, Response &res) {
  2429. captured_cookie = req.get_header_value("Cookie");
  2430. target_hit = true;
  2431. res.set_content("OK", "text/plain");
  2432. });
  2433. int svr1_port = 0;
  2434. auto thread1 = std::thread([&]() {
  2435. svr1_port = svr1.bind_to_any_port(HOST);
  2436. svr1.listen_after_bind();
  2437. });
  2438. Server svr2;
  2439. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2440. res.set_redirect(
  2441. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2442. });
  2443. int svr2_port = 0;
  2444. auto thread2 = std::thread([&]() {
  2445. svr2_port = svr2.bind_to_any_port(HOST);
  2446. svr2.listen_after_bind();
  2447. });
  2448. auto se = detail::scope_exit([&] {
  2449. svr2.stop();
  2450. thread2.join();
  2451. svr1.stop();
  2452. thread1.join();
  2453. ASSERT_FALSE(svr2.is_running());
  2454. ASSERT_FALSE(svr1.is_running());
  2455. });
  2456. svr1.wait_until_ready();
  2457. svr2.wait_until_ready();
  2458. Client cli("localhost", svr2_port);
  2459. cli.set_follow_location(true);
  2460. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  2461. auto res = cli.Get("/redir", headers);
  2462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2463. EXPECT_EQ(StatusCode::OK_200, res->status);
  2464. EXPECT_TRUE(target_hit);
  2465. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  2466. EXPECT_TRUE(captured_cookie.empty());
  2467. }
  2468. TEST(RedirectToSamePort, ForwardCookie) {
  2469. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  2470. // header so that ordinary session flows keep working.
  2471. Server svr;
  2472. std::string captured_cookie;
  2473. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2474. res.set_redirect("/target", 302);
  2475. });
  2476. svr.Get("/target", [&](const Request &req, Response &res) {
  2477. captured_cookie = req.get_header_value("Cookie");
  2478. res.set_content("OK", "text/plain");
  2479. });
  2480. auto port = svr.bind_to_any_port(HOST);
  2481. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2482. auto se = detail::scope_exit([&] {
  2483. svr.stop();
  2484. thread.join();
  2485. ASSERT_FALSE(svr.is_running());
  2486. });
  2487. svr.wait_until_ready();
  2488. Client cli(HOST, port);
  2489. cli.set_follow_location(true);
  2490. Headers headers = {{"Cookie", "session_id=SECRET"}};
  2491. auto res = cli.Get("/redir", headers);
  2492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2493. EXPECT_EQ(StatusCode::OK_200, res->status);
  2494. EXPECT_EQ("session_id=SECRET", captured_cookie);
  2495. }
  2496. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2497. Server svr;
  2498. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2499. // Port number that overflows int — should not crash
  2500. res.set_redirect("http://localhost:99999999999999999999/target");
  2501. });
  2502. auto port = svr.bind_to_any_port(HOST);
  2503. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2504. auto se = detail::scope_exit([&] {
  2505. svr.stop();
  2506. thread.join();
  2507. ASSERT_FALSE(svr.is_running());
  2508. });
  2509. svr.wait_until_ready();
  2510. Client cli(HOST, port);
  2511. cli.set_follow_location(true);
  2512. auto res = cli.Get("/redir");
  2513. // Should fail gracefully, not crash (no valid response due to bad port)
  2514. EXPECT_FALSE(res);
  2515. }
  2516. TEST(RedirectFromPageWithContent, Redirect) {
  2517. Server svr;
  2518. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2519. res.set_content("___", "text/plain");
  2520. res.set_redirect("/2");
  2521. });
  2522. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2523. res.set_content("Hello World!", "text/plain");
  2524. });
  2525. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2526. auto se = detail::scope_exit([&] {
  2527. svr.stop();
  2528. th.join();
  2529. ASSERT_FALSE(svr.is_running());
  2530. });
  2531. svr.wait_until_ready();
  2532. {
  2533. Client cli("localhost", PORT);
  2534. cli.set_follow_location(true);
  2535. std::string body;
  2536. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2537. body.append(data, data_length);
  2538. return true;
  2539. });
  2540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2541. EXPECT_EQ(StatusCode::OK_200, res->status);
  2542. EXPECT_EQ("Hello World!", body);
  2543. }
  2544. {
  2545. Client cli("localhost", PORT);
  2546. std::string body;
  2547. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2548. body.append(data, data_length);
  2549. return true;
  2550. });
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ(StatusCode::Found_302, res->status);
  2553. EXPECT_EQ("___", body);
  2554. }
  2555. }
  2556. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2557. Server svr;
  2558. auto port_str = std::to_string(PORT);
  2559. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2560. auto expected_host = "[::1]:" + port_str;
  2561. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2562. res.set_content("___", "text/plain");
  2563. // res.set_redirect("/2");
  2564. res.set_redirect(redirect_url);
  2565. });
  2566. svr.Get("/2", [&](const Request &req, Response &res) {
  2567. auto host_header = req.headers.find("Host");
  2568. ASSERT_TRUE(host_header != req.headers.end());
  2569. EXPECT_EQ(expected_host, host_header->second);
  2570. res.set_content("Hello World!", "text/plain");
  2571. });
  2572. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. th.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2579. // actually starts anything, so the condition !svr.is_running() will
  2580. // always remain true, and the loop never stops.
  2581. // This basically counts how many milliseconds have passed since the
  2582. // call to svr.listen(), and if after 5 seconds nothing started yet
  2583. // aborts the test.
  2584. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2585. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2586. ASSERT_LT(milliseconds, 5000U);
  2587. }
  2588. {
  2589. Client cli("::1", PORT);
  2590. cli.set_follow_location(true);
  2591. std::string body;
  2592. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2593. body.append(data, data_length);
  2594. return true;
  2595. });
  2596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2597. EXPECT_EQ(StatusCode::OK_200, res->status);
  2598. EXPECT_EQ("Hello World!", body);
  2599. }
  2600. {
  2601. Client cli("::1", PORT);
  2602. std::string body;
  2603. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2604. body.append(data, data_length);
  2605. return true;
  2606. });
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ(StatusCode::Found_302, res->status);
  2609. EXPECT_EQ("___", body);
  2610. }
  2611. }
  2612. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2613. Server svr;
  2614. svr.Get("/foo", [](const Request &req, Response &res) {
  2615. auto a = req.params.find("a");
  2616. if (a != req.params.end()) {
  2617. res.set_content((*a).second, "text/plain");
  2618. res.status = StatusCode::OK_200;
  2619. } else {
  2620. res.status = StatusCode::BadRequest_400;
  2621. }
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. {
  2631. Client cli(HOST, PORT);
  2632. cli.set_path_encode(false);
  2633. auto res = cli.Get("/foo?a=explicitly+encoded");
  2634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2635. EXPECT_EQ(StatusCode::OK_200, res->status);
  2636. // This expects it back with a space, as the `+` won't have been
  2637. // url-encoded, and server-side the params get decoded turning `+`
  2638. // into spaces.
  2639. EXPECT_EQ("explicitly encoded", res->body);
  2640. }
  2641. }
  2642. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  2643. // When path encoding is disabled the client must transmit the supplied
  2644. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  2645. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  2646. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  2647. // than a space (0x20). Assert on the raw wire target to catch this.
  2648. Server svr;
  2649. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2650. svr.Get("/foo", [&](const Request &req, Response &res) {
  2651. EXPECT_EQ(expected_target, req.target);
  2652. res.status = StatusCode::OK_200;
  2653. });
  2654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2655. auto se = detail::scope_exit([&] {
  2656. svr.stop();
  2657. thread.join();
  2658. ASSERT_FALSE(svr.is_running());
  2659. });
  2660. svr.wait_until_ready();
  2661. {
  2662. Client cli(HOST, PORT);
  2663. cli.set_path_encode(false);
  2664. auto res = cli.Get(expected_target.c_str());
  2665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2666. EXPECT_EQ(StatusCode::OK_200, res->status);
  2667. }
  2668. }
  2669. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  2670. // `open_stream()` used to skip the path encoding that the buffered send
  2671. // path applies, so the same `path` produced different bytes in the request
  2672. // line depending on which API was used. Assert the two agree.
  2673. Server svr;
  2674. std::string target;
  2675. svr.Get(".*", [&](const Request &req, Response &res) {
  2676. target = req.target;
  2677. res.status = StatusCode::OK_200;
  2678. });
  2679. auto port = svr.bind_to_any_port(HOST);
  2680. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2681. auto se = detail::scope_exit([&] {
  2682. svr.stop();
  2683. thread.join();
  2684. ASSERT_FALSE(svr.is_running());
  2685. });
  2686. svr.wait_until_ready();
  2687. struct {
  2688. const char *path;
  2689. const char *expected;
  2690. } cases[] = {
  2691. {"/a b?x=1", "/a%20b?x=1"},
  2692. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  2693. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  2694. };
  2695. for (const auto &c : cases) {
  2696. Client cli(HOST, port);
  2697. target.clear();
  2698. auto res = cli.Get(c.path);
  2699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2700. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  2701. auto buffered_target = target;
  2702. target.clear();
  2703. auto handle = cli.open_stream("GET", c.path);
  2704. EXPECT_TRUE(handle.is_valid())
  2705. << "streaming path: " << c.path << ", " << to_string(handle.error);
  2706. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  2707. }
  2708. }
  2709. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  2710. // The `set_path_encode(false)` contract — transmit the supplied target
  2711. // verbatim — must hold for the streaming API too.
  2712. Server svr;
  2713. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  2714. std::string target;
  2715. svr.Get("/foo", [&](const Request &req, Response &res) {
  2716. target = req.target;
  2717. res.status = StatusCode::OK_200;
  2718. });
  2719. auto port = svr.bind_to_any_port(HOST);
  2720. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. {
  2728. Client cli(HOST, port);
  2729. cli.set_path_encode(false);
  2730. auto handle = cli.open_stream("GET", expected_target);
  2731. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2732. EXPECT_EQ(expected_target, target);
  2733. }
  2734. }
  2735. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  2736. // With path encoding enabled a CR/LF in the target is percent-encoded
  2737. // rather than rejected, matching the buffered send path. The CR/LF guard in
  2738. // write_request_line still backstops `set_path_encode(false)`, which is
  2739. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  2740. Server svr;
  2741. // Captured before routing: the decoded path contains a newline, which a
  2742. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  2743. std::string target;
  2744. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  2745. target = req.target;
  2746. res.status = StatusCode::OK_200;
  2747. return Server::HandlerResponse::Handled;
  2748. });
  2749. auto port = svr.bind_to_any_port(HOST);
  2750. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2751. auto se = detail::scope_exit([&] {
  2752. svr.stop();
  2753. thread.join();
  2754. ASSERT_FALSE(svr.is_running());
  2755. });
  2756. svr.wait_until_ready();
  2757. {
  2758. Client cli(HOST, port);
  2759. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2760. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  2761. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  2762. }
  2763. }
  2764. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  2765. // Nothing may reach the wire: a raw CR/LF target would split the request
  2766. // line and inject headers.
  2767. Server svr;
  2768. // Pre-routing so that "not called" means nothing reached the server at all,
  2769. // rather than merely failing to match a handler pattern.
  2770. auto handler_called = false;
  2771. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  2772. handler_called = true;
  2773. res.status = StatusCode::OK_200;
  2774. return Server::HandlerResponse::Handled;
  2775. });
  2776. auto port = svr.bind_to_any_port(HOST);
  2777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2778. auto se = detail::scope_exit([&] {
  2779. svr.stop();
  2780. thread.join();
  2781. ASSERT_FALSE(svr.is_running());
  2782. });
  2783. svr.wait_until_ready();
  2784. {
  2785. Client cli(HOST, port);
  2786. cli.set_path_encode(false);
  2787. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  2788. EXPECT_FALSE(handle.is_valid());
  2789. EXPECT_EQ(Error::Write, handle.error);
  2790. EXPECT_FALSE(handler_called);
  2791. }
  2792. }
  2793. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  2794. // Which of the two branches runs is decided by whether the query component
  2795. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  2796. // an empty query and must still fall back to building one from
  2797. // `req.params`, while a non-empty query must win over `req.params`.
  2798. Server svr;
  2799. std::string target;
  2800. svr.Get("/foo", [&](const Request &req, Response &res) {
  2801. target = req.target;
  2802. res.status = StatusCode::OK_200;
  2803. });
  2804. auto port = svr.bind_to_any_port(HOST);
  2805. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2806. auto se = detail::scope_exit([&] {
  2807. svr.stop();
  2808. thread.join();
  2809. ASSERT_FALSE(svr.is_running());
  2810. });
  2811. svr.wait_until_ready();
  2812. {
  2813. // Trailing `?` -> empty query component -> `req.params` is used.
  2814. Client cli(HOST, port);
  2815. Request req;
  2816. req.method = "GET";
  2817. req.path = "/foo?";
  2818. req.params.emplace("a", "1");
  2819. target.clear();
  2820. auto res = cli.send(req);
  2821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2822. EXPECT_EQ("/foo?a=1", target);
  2823. }
  2824. {
  2825. // Non-empty query in `req.path` -> `req.params` is not appended.
  2826. Client cli(HOST, port);
  2827. Request req;
  2828. req.method = "GET";
  2829. req.path = "/foo?b=2";
  2830. req.params.emplace("a", "1");
  2831. target.clear();
  2832. auto res = cli.send(req);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. EXPECT_EQ("/foo?b=2", target);
  2835. }
  2836. }
  2837. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2838. Server svr;
  2839. svr.Get("/", [](const Request &req, Response &) {
  2840. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2841. });
  2842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2843. auto se = detail::scope_exit([&] {
  2844. svr.stop();
  2845. thread.join();
  2846. ASSERT_FALSE(svr.is_running());
  2847. });
  2848. svr.wait_until_ready();
  2849. {
  2850. Client cli(HOST, PORT);
  2851. cli.set_path_encode(false);
  2852. auto res = cli.Get("/?something=%0A");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::OK_200, res->status);
  2855. }
  2856. }
  2857. TEST(BindServerTest, BindDualStack) {
  2858. Server svr;
  2859. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2860. res.set_content("Hello World!", "text/plain");
  2861. });
  2862. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2863. auto se = detail::scope_exit([&] {
  2864. svr.stop();
  2865. thread.join();
  2866. ASSERT_FALSE(svr.is_running());
  2867. });
  2868. svr.wait_until_ready();
  2869. {
  2870. Client cli("127.0.0.1", PORT);
  2871. auto res = cli.Get("/1");
  2872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2873. EXPECT_EQ(StatusCode::OK_200, res->status);
  2874. EXPECT_EQ("Hello World!", res->body);
  2875. }
  2876. {
  2877. Client cli("::1", PORT);
  2878. auto res = cli.Get("/1");
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. EXPECT_EQ("Hello World!", res->body);
  2882. }
  2883. }
  2884. TEST(BindServerTest, BindAndListenSeparately) {
  2885. Server svr;
  2886. int port = svr.bind_to_any_port("0.0.0.0");
  2887. ASSERT_TRUE(svr.is_valid());
  2888. ASSERT_TRUE(port > 0);
  2889. svr.stop();
  2890. }
  2891. #ifdef CPPHTTPLIB_SSL_ENABLED
  2892. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2894. CLIENT_CA_CERT_DIR);
  2895. int port = svr.bind_to_any_port("0.0.0.0");
  2896. ASSERT_TRUE(svr.is_valid());
  2897. ASSERT_TRUE(port > 0);
  2898. svr.stop();
  2899. }
  2900. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2901. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2902. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2903. int port = svr.bind_to_any_port("0.0.0.0");
  2904. ASSERT_TRUE(svr.is_valid());
  2905. ASSERT_TRUE(port > 0);
  2906. svr.stop();
  2907. }
  2908. TEST(BindServerTest, UpdateCertsPem) {
  2909. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2910. int port = svr.bind_to_any_port("0.0.0.0");
  2911. ASSERT_TRUE(svr.is_valid());
  2912. ASSERT_TRUE(port > 0);
  2913. // Read PEM files
  2914. std::string cert_pem, key_pem, ca_pem;
  2915. read_file(SERVER_CERT_FILE, cert_pem);
  2916. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2917. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2918. // Update server certificates using PEM API
  2919. ASSERT_TRUE(
  2920. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2921. ASSERT_TRUE(svr.is_valid());
  2922. svr.stop();
  2923. }
  2924. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2925. // Start server with client CA (enables client auth)
  2926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2927. ASSERT_TRUE(svr.is_valid());
  2928. bool handler_called = false;
  2929. svr.Get("/test", [&](const Request &req, Response &res) {
  2930. handler_called = true;
  2931. // Verify client certificate is present
  2932. auto cert = req.peer_cert();
  2933. EXPECT_TRUE(static_cast<bool>(cert));
  2934. res.set_content("ok", "text/plain");
  2935. });
  2936. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2937. auto se = detail::scope_exit([&] {
  2938. svr.stop();
  2939. t.join();
  2940. ASSERT_FALSE(svr.is_running());
  2941. });
  2942. svr.wait_until_ready();
  2943. // Read PEM files
  2944. std::string cert_pem, key_pem, ca_pem;
  2945. read_file(SERVER_CERT_FILE, cert_pem);
  2946. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2947. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2948. // Update server certificates and client CA using PEM API while server running
  2949. ASSERT_TRUE(
  2950. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2951. // Connect with client certificate
  2952. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2953. cli.enable_server_certificate_verification(false);
  2954. cli.set_connection_timeout(30);
  2955. auto res = cli.Get("/test");
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. ASSERT_EQ(StatusCode::OK_200, res->status);
  2958. ASSERT_TRUE(handler_called);
  2959. EXPECT_EQ("ok", res->body);
  2960. }
  2961. #endif
  2962. TEST(ErrorHandlerTest, ContentLength) {
  2963. Server svr;
  2964. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2965. res.status = StatusCode::OK_200;
  2966. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2967. "text/html"); // <= Content-Length still 13
  2968. });
  2969. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2970. res.set_content("Hello World!\n", "text/plain");
  2971. res.status = 524;
  2972. });
  2973. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2974. auto se = detail::scope_exit([&] {
  2975. svr.stop();
  2976. thread.join();
  2977. ASSERT_FALSE(svr.is_running());
  2978. });
  2979. svr.wait_until_ready();
  2980. {
  2981. Client cli(HOST, PORT);
  2982. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  2983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2984. EXPECT_EQ(StatusCode::OK_200, res->status);
  2985. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2986. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2987. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2988. }
  2989. }
  2990. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2991. TEST(ExceptionTest, WithoutExceptionHandler) {
  2992. Server svr;
  2993. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2994. throw std::runtime_error("exception...");
  2995. });
  2996. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2997. throw std::runtime_error("exception\r\n...");
  2998. });
  2999. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3000. auto se = detail::scope_exit([&] {
  3001. svr.stop();
  3002. listen_thread.join();
  3003. ASSERT_FALSE(svr.is_running());
  3004. });
  3005. svr.wait_until_ready();
  3006. Client cli("localhost", PORT);
  3007. {
  3008. auto res = cli.Get("/exception");
  3009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3010. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3011. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3012. }
  3013. {
  3014. auto res = cli.Get("/unknown");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3017. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3018. }
  3019. }
  3020. TEST(ExceptionTest, WithExceptionHandler) {
  3021. Server svr;
  3022. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3023. std::exception_ptr ep) {
  3024. EXPECT_FALSE(ep == nullptr);
  3025. try {
  3026. std::rethrow_exception(ep);
  3027. } catch (std::exception &e) {
  3028. EXPECT_EQ("abc", std::string(e.what()));
  3029. } catch (...) {}
  3030. res.status = StatusCode::InternalServerError_500;
  3031. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3032. "text/html"); // <= Content-Length still 13 at this point
  3033. });
  3034. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3035. res.set_content("Hello World!\n", "text/plain");
  3036. throw std::runtime_error("abc");
  3037. });
  3038. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3039. auto se = detail::scope_exit([&] {
  3040. svr.stop();
  3041. thread.join();
  3042. ASSERT_FALSE(svr.is_running());
  3043. });
  3044. svr.wait_until_ready();
  3045. for (size_t i = 0; i < 10; i++) {
  3046. Client cli(HOST, PORT);
  3047. for (size_t j = 0; j < 100; j++) {
  3048. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3050. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3051. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3052. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3053. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3054. }
  3055. cli.set_keep_alive(true);
  3056. for (size_t j = 0; j < 100; j++) {
  3057. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3059. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3060. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3061. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3062. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3063. }
  3064. }
  3065. }
  3066. TEST(ExceptionTest, AndErrorHandler) {
  3067. Server svr;
  3068. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3069. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3070. });
  3071. svr.set_exception_handler(
  3072. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3073. EXPECT_FALSE(ep == nullptr);
  3074. try {
  3075. std::rethrow_exception(ep);
  3076. } catch (std::exception &e) {
  3077. res.set_content(e.what(), "text/html");
  3078. } catch (...) {}
  3079. res.status = StatusCode::InternalServerError_500;
  3080. });
  3081. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3082. throw std::runtime_error("EXCEPTION");
  3083. });
  3084. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3085. res.set_content("ERROR", "text/html");
  3086. res.status = StatusCode::InternalServerError_500;
  3087. });
  3088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(HOST, PORT);
  3096. {
  3097. auto res = cli.Get("/exception");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3100. EXPECT_EQ("EXCEPTION", res->body);
  3101. }
  3102. {
  3103. auto res = cli.Get("/error");
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3106. EXPECT_EQ("ERROR", res->body);
  3107. }
  3108. {
  3109. auto res = cli.Get("/invalid");
  3110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3111. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3112. EXPECT_EQ("NOT_FOUND", res->body);
  3113. }
  3114. }
  3115. #endif
  3116. TEST(NoContentTest, ContentLength) {
  3117. Server svr;
  3118. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3119. res.status = StatusCode::NoContent_204;
  3120. });
  3121. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3122. auto se = detail::scope_exit([&] {
  3123. svr.stop();
  3124. thread.join();
  3125. ASSERT_FALSE(svr.is_running());
  3126. });
  3127. svr.wait_until_ready();
  3128. {
  3129. Client cli(HOST, PORT);
  3130. auto res = cli.Get("/hi");
  3131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3132. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  3133. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3134. }
  3135. }
  3136. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  3137. #ifdef CPPHTTPLIB_SSL_ENABLED
  3138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3139. ASSERT_TRUE(svr.is_valid());
  3140. #else
  3141. Server svr;
  3142. #endif
  3143. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  3144. if (req.path == "/routing_handler") {
  3145. res.set_header("PRE_ROUTING", "on");
  3146. res.set_content("Routing Handler", "text/plain");
  3147. return httplib::Server::HandlerResponse::Handled;
  3148. }
  3149. return httplib::Server::HandlerResponse::Unhandled;
  3150. });
  3151. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3152. res.set_content("Error", "text/html");
  3153. });
  3154. svr.set_post_routing_handler([](const Request &req, Response &res) {
  3155. if (req.path == "/routing_handler") {
  3156. res.set_header("POST_ROUTING", "on");
  3157. }
  3158. });
  3159. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3160. res.set_content("Hello World!\n", "text/plain");
  3161. });
  3162. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3163. auto se = detail::scope_exit([&] {
  3164. svr.stop();
  3165. thread.join();
  3166. ASSERT_FALSE(svr.is_running());
  3167. });
  3168. svr.wait_until_ready();
  3169. {
  3170. #ifdef CPPHTTPLIB_SSL_ENABLED
  3171. SSLClient cli(HOST, PORT);
  3172. cli.enable_server_certificate_verification(false);
  3173. #else
  3174. Client cli(HOST, PORT);
  3175. #endif
  3176. auto res = cli.Get("/routing_handler");
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_EQ("Routing Handler", res->body);
  3180. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  3181. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  3182. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  3183. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  3184. }
  3185. {
  3186. #ifdef CPPHTTPLIB_SSL_ENABLED
  3187. SSLClient cli(HOST, PORT);
  3188. cli.enable_server_certificate_verification(false);
  3189. #else
  3190. Client cli(HOST, PORT);
  3191. #endif
  3192. auto res = cli.Get("/hi");
  3193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3194. EXPECT_EQ(StatusCode::OK_200, res->status);
  3195. EXPECT_EQ("Hello World!\n", res->body);
  3196. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3197. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3198. }
  3199. {
  3200. #ifdef CPPHTTPLIB_SSL_ENABLED
  3201. SSLClient cli(HOST, PORT);
  3202. cli.enable_server_certificate_verification(false);
  3203. #else
  3204. Client cli(HOST, PORT);
  3205. #endif
  3206. auto res = cli.Get("/aaa");
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3209. EXPECT_EQ("Error", res->body);
  3210. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  3211. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  3212. }
  3213. }
  3214. TEST(RequestHandlerTest, PreRequestHandler) {
  3215. auto route_path = "/user/:user";
  3216. Server svr;
  3217. svr.Get("/hi", [](const Request &, Response &res) {
  3218. res.set_content("hi", "text/plain");
  3219. });
  3220. svr.Get(route_path, [](const Request &req, Response &res) {
  3221. res.set_content(req.path_params.at("user"), "text/plain");
  3222. });
  3223. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  3224. if (req.matched_route == route_path) {
  3225. auto user = req.path_params.at("user");
  3226. if (user != "john") {
  3227. res.status = StatusCode::Forbidden_403;
  3228. res.set_content("error", "text/html");
  3229. return Server::HandlerResponse::Handled;
  3230. }
  3231. }
  3232. return Server::HandlerResponse::Unhandled;
  3233. });
  3234. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3235. auto se = detail::scope_exit([&] {
  3236. svr.stop();
  3237. thread.join();
  3238. ASSERT_FALSE(svr.is_running());
  3239. });
  3240. svr.wait_until_ready();
  3241. Client cli(HOST, PORT);
  3242. {
  3243. auto res = cli.Get("/hi");
  3244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3245. EXPECT_EQ(StatusCode::OK_200, res->status);
  3246. EXPECT_EQ("hi", res->body);
  3247. }
  3248. {
  3249. auto res = cli.Get("/user/john");
  3250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3251. EXPECT_EQ(StatusCode::OK_200, res->status);
  3252. EXPECT_EQ("john", res->body);
  3253. }
  3254. {
  3255. auto res = cli.Get("/user/invalid-user");
  3256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3257. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3258. EXPECT_EQ("error", res->body);
  3259. }
  3260. }
  3261. // The pre-request handler must run before the request body is read, so a
  3262. // rejected request never forces the server to buffer a (potentially large)
  3263. // body. Here the posted body is larger than the payload limit: if the body
  3264. // were read first the server would answer 413, but because the pre-request
  3265. // handler runs first it answers 403 and the body is never read.
  3266. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  3267. Server svr;
  3268. svr.set_payload_max_length(8);
  3269. auto handler_ran = false;
  3270. svr.Post("/reject", [&](const Request &req, Response &res) {
  3271. handler_ran = true;
  3272. res.set_content(req.body, "text/plain");
  3273. });
  3274. svr.Post("/accept", [](const Request &req, Response &res) {
  3275. res.set_content(req.body, "text/plain");
  3276. });
  3277. svr.set_pre_request_handler([](const Request &req, Response &res) {
  3278. if (req.matched_route == "/reject") {
  3279. res.status = StatusCode::Forbidden_403;
  3280. res.set_content("denied", "text/plain");
  3281. return Server::HandlerResponse::Handled;
  3282. }
  3283. return Server::HandlerResponse::Unhandled;
  3284. });
  3285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3286. auto se = detail::scope_exit([&] {
  3287. svr.stop();
  3288. thread.join();
  3289. ASSERT_FALSE(svr.is_running());
  3290. });
  3291. svr.wait_until_ready();
  3292. Client cli(HOST, PORT);
  3293. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  3294. // rejects with 403 before the body is read, so 413 is never reached.
  3295. {
  3296. auto res = cli.Post("/reject", "0123456789", "text/plain");
  3297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3298. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  3299. EXPECT_EQ("denied", res->body);
  3300. EXPECT_FALSE(handler_ran);
  3301. }
  3302. // An approved route still reads the body and enforces the payload limit.
  3303. {
  3304. auto res = cli.Post("/accept", "0123456789", "text/plain");
  3305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3306. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  3307. }
  3308. }
  3309. TEST(UserDataTest, BasicOperations) {
  3310. httplib::UserData ud;
  3311. // Initially empty
  3312. EXPECT_FALSE(ud.has("key"));
  3313. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3314. // set and get
  3315. ud.set("key", 42);
  3316. EXPECT_TRUE(ud.has("key"));
  3317. auto *p = ud.get<int>("key");
  3318. ASSERT_NE(nullptr, p);
  3319. EXPECT_EQ(42, *p);
  3320. // Type mismatch → nullptr
  3321. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  3322. // Overwrite with different type
  3323. ud.set("key", std::string("hello"));
  3324. EXPECT_EQ(nullptr, ud.get<int>("key"));
  3325. auto *s = ud.get<std::string>("key");
  3326. ASSERT_NE(nullptr, s);
  3327. EXPECT_EQ("hello", *s);
  3328. // erase
  3329. ud.erase("key");
  3330. EXPECT_FALSE(ud.has("key"));
  3331. // clear
  3332. ud.set("a", 1);
  3333. ud.set("b", 2);
  3334. ud.clear();
  3335. EXPECT_FALSE(ud.has("a"));
  3336. EXPECT_FALSE(ud.has("b"));
  3337. }
  3338. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  3339. struct AuthCtx {
  3340. std::string user_id;
  3341. };
  3342. Server svr;
  3343. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  3344. res.user_data.set("auth", AuthCtx{"alice"});
  3345. return Server::HandlerResponse::Unhandled;
  3346. });
  3347. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  3348. auto *ctx = res.user_data.get<AuthCtx>("auth");
  3349. ASSERT_NE(nullptr, ctx);
  3350. res.set_content("Hello " + ctx->user_id, "text/plain");
  3351. });
  3352. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3353. auto se = detail::scope_exit([&] {
  3354. svr.stop();
  3355. thread.join();
  3356. ASSERT_FALSE(svr.is_running());
  3357. });
  3358. svr.wait_until_ready();
  3359. Client cli(HOST, PORT);
  3360. auto res = cli.Get("/me");
  3361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3362. EXPECT_EQ(StatusCode::OK_200, res->status);
  3363. EXPECT_EQ("Hello alice", res->body);
  3364. }
  3365. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  3366. struct RoleCtx {
  3367. std::string role;
  3368. };
  3369. Server svr;
  3370. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  3371. res.user_data.set("role", RoleCtx{"admin"});
  3372. return Server::HandlerResponse::Unhandled;
  3373. });
  3374. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  3375. auto *ctx = res.user_data.get<RoleCtx>("role");
  3376. ASSERT_NE(nullptr, ctx);
  3377. res.set_content(ctx->role, "text/plain");
  3378. });
  3379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3380. auto se = detail::scope_exit([&] {
  3381. svr.stop();
  3382. thread.join();
  3383. ASSERT_FALSE(svr.is_running());
  3384. });
  3385. svr.wait_until_ready();
  3386. Client cli(HOST, PORT);
  3387. auto res = cli.Get("/role");
  3388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3389. EXPECT_EQ(StatusCode::OK_200, res->status);
  3390. EXPECT_EQ("admin", res->body);
  3391. }
  3392. TEST(InvalidFormatTest, StatusCode) {
  3393. Server svr;
  3394. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3395. res.set_content("Hello World!\n", "text/plain");
  3396. res.status = 9999; // Status should be a three-digit code...
  3397. });
  3398. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3399. auto se = detail::scope_exit([&] {
  3400. svr.stop();
  3401. thread.join();
  3402. ASSERT_FALSE(svr.is_running());
  3403. });
  3404. svr.wait_until_ready();
  3405. {
  3406. Client cli(HOST, PORT);
  3407. auto res = cli.Get("/hi");
  3408. ASSERT_FALSE(res);
  3409. }
  3410. }
  3411. TEST(URLFragmentTest, WithFragment) {
  3412. Server svr;
  3413. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  3414. EXPECT_TRUE(req.target == "/hi");
  3415. });
  3416. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3417. auto se = detail::scope_exit([&] {
  3418. svr.stop();
  3419. thread.join();
  3420. ASSERT_FALSE(svr.is_running());
  3421. });
  3422. svr.wait_until_ready();
  3423. {
  3424. Client cli(HOST, PORT);
  3425. auto res = cli.Get("/hi#key1=val1=key2=val2");
  3426. EXPECT_TRUE(res);
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. res = cli.Get("/hi%23key1=val1=key2=val2");
  3429. EXPECT_TRUE(res);
  3430. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3431. }
  3432. }
  3433. TEST(HeaderWriter, SetHeaderWriter) {
  3434. Server svr;
  3435. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  3436. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  3437. return detail::write_headers(strm, hdrs);
  3438. });
  3439. svr.Get("/hi", [](const Request &req, Response &res) {
  3440. auto it = req.headers.find("CustomClientHeader");
  3441. EXPECT_TRUE(it != req.headers.end());
  3442. EXPECT_EQ(it->second, "CustomClientValue");
  3443. res.set_content("Hello World!\n", "text/plain");
  3444. });
  3445. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3446. auto se = detail::scope_exit([&] {
  3447. svr.stop();
  3448. thread.join();
  3449. ASSERT_FALSE(svr.is_running());
  3450. });
  3451. svr.wait_until_ready();
  3452. {
  3453. Client cli(HOST, PORT);
  3454. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  3455. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  3456. return detail::write_headers(strm, hdrs);
  3457. });
  3458. auto res = cli.Get("/hi");
  3459. EXPECT_TRUE(res);
  3460. EXPECT_EQ(StatusCode::OK_200, res->status);
  3461. auto it = res->headers.find("CustomServerHeader");
  3462. EXPECT_TRUE(it != res->headers.end());
  3463. EXPECT_EQ(it->second, "CustomServerValue");
  3464. }
  3465. }
  3466. class ServerTest : public ::testing::Test {
  3467. protected:
  3468. ServerTest()
  3469. : cli_(HOST, PORT)
  3470. #ifdef CPPHTTPLIB_SSL_ENABLED
  3471. ,
  3472. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3473. #endif
  3474. {
  3475. #ifdef CPPHTTPLIB_SSL_ENABLED
  3476. cli_.enable_server_certificate_verification(false);
  3477. #endif
  3478. // Allow LARGE_DATA (100MB) responses
  3479. cli_.set_payload_max_length(200 * 1024 * 1024);
  3480. }
  3481. virtual void SetUp() {
  3482. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  3483. svr_.set_payload_max_length(200 * 1024 * 1024);
  3484. svr_.set_mount_point("/", "./www");
  3485. svr_.set_mount_point("/mount", "./www2");
  3486. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  3487. svr_.Get("/hi",
  3488. [&](const Request & /*req*/, Response &res) {
  3489. res.set_content("Hello World!", "text/plain");
  3490. })
  3491. .Get("/file_content",
  3492. [&](const Request & /*req*/, Response &res) {
  3493. res.set_file_content("./www/dir/test.html");
  3494. })
  3495. .Get("/file_content_with_content_type",
  3496. [&](const Request & /*req*/, Response &res) {
  3497. res.set_file_content("./www/file", "text/plain");
  3498. })
  3499. .Get("/invalid_file_content",
  3500. [&](const Request & /*req*/, Response &res) {
  3501. res.set_file_content("./www/dir/invalid_file_path");
  3502. })
  3503. .Get("/http_response_splitting",
  3504. [&](const Request & /*req*/, Response &res) {
  3505. res.set_header("a", "1\r\nSet-Cookie: a=1");
  3506. EXPECT_EQ(0U, res.headers.size());
  3507. EXPECT_FALSE(res.has_header("a"));
  3508. res.set_header("a", "1\nSet-Cookie: a=1");
  3509. EXPECT_EQ(0U, res.headers.size());
  3510. EXPECT_FALSE(res.has_header("a"));
  3511. res.set_header("a", "1\rSet-Cookie: a=1");
  3512. EXPECT_EQ(0U, res.headers.size());
  3513. EXPECT_FALSE(res.has_header("a"));
  3514. res.set_header("a\r\nb", "0");
  3515. EXPECT_EQ(0U, res.headers.size());
  3516. EXPECT_FALSE(res.has_header("a"));
  3517. res.set_header("a\rb", "0");
  3518. EXPECT_EQ(0U, res.headers.size());
  3519. EXPECT_FALSE(res.has_header("a"));
  3520. res.set_header("a\nb", "0");
  3521. EXPECT_EQ(0U, res.headers.size());
  3522. EXPECT_FALSE(res.has_header("a"));
  3523. res.set_redirect("1\r\nSet-Cookie: a=1");
  3524. EXPECT_EQ(0U, res.headers.size());
  3525. EXPECT_FALSE(res.has_header("Location"));
  3526. })
  3527. .Get("/slow",
  3528. [&](const Request & /*req*/, Response &res) {
  3529. std::this_thread::sleep_for(std::chrono::seconds(4));
  3530. res.set_content("slow", "text/plain");
  3531. })
  3532. #if 0
  3533. .Post("/slowpost",
  3534. [&](const Request & /*req*/, Response &res) {
  3535. std::this_thread::sleep_for(std::chrono::seconds(2));
  3536. res.set_content("slow", "text/plain");
  3537. })
  3538. #endif
  3539. .Get("/remote_addr",
  3540. [&](const Request &req, Response &res) {
  3541. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  3542. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  3543. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3544. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  3545. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  3546. #endif
  3547. res.set_content(req.remote_addr, "text/plain");
  3548. })
  3549. .Get("/local_addr",
  3550. [&](const Request &req, Response &res) {
  3551. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  3552. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  3553. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3554. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  3555. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  3556. #endif
  3557. auto local_addr = req.local_addr;
  3558. auto local_port = std::to_string(req.local_port);
  3559. res.set_content(local_addr.append(":").append(local_port),
  3560. "text/plain");
  3561. })
  3562. .Get("/endwith%",
  3563. [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("Hello World!", "text/plain");
  3565. })
  3566. .Get("/a\\+\\+b",
  3567. [&](const Request &req, Response &res) {
  3568. ASSERT_TRUE(req.has_param("a +b"));
  3569. auto val = req.get_param_value("a +b");
  3570. res.set_content(val, "text/plain");
  3571. })
  3572. .Get("/", [&](const Request & /*req*/,
  3573. Response &res) { res.set_redirect("/hi"); })
  3574. .Post("/1",
  3575. [](const Request & /*req*/, Response &res) {
  3576. res.set_redirect("/2", StatusCode::SeeOther_303);
  3577. })
  3578. .Get("/2",
  3579. [](const Request & /*req*/, Response &res) {
  3580. res.set_content("redirected.", "text/plain");
  3581. res.status = StatusCode::OK_200;
  3582. })
  3583. .Post("/person",
  3584. [&](const Request &req, Response &res) {
  3585. if (req.has_param("name") && req.has_param("note")) {
  3586. persons_[req.get_param_value("name")] =
  3587. req.get_param_value("note");
  3588. } else {
  3589. res.status = StatusCode::BadRequest_400;
  3590. }
  3591. })
  3592. .Put("/person",
  3593. [&](const Request &req, Response &res) {
  3594. if (req.has_param("name") && req.has_param("note")) {
  3595. persons_[req.get_param_value("name")] =
  3596. req.get_param_value("note");
  3597. } else {
  3598. res.status = StatusCode::BadRequest_400;
  3599. }
  3600. })
  3601. .Get("/person/(.*)",
  3602. [&](const Request &req, Response &res) {
  3603. string name = req.matches[1];
  3604. if (persons_.find(name) != persons_.end()) {
  3605. auto note = persons_[name];
  3606. res.set_content(note, "text/plain");
  3607. } else {
  3608. res.status = StatusCode::NotFound_404;
  3609. }
  3610. })
  3611. .Delete("/person",
  3612. [&](const Request &req, Response &res) {
  3613. if (req.has_param("name")) {
  3614. string name = req.get_param_value("name");
  3615. if (persons_.find(name) != persons_.end()) {
  3616. persons_.erase(name);
  3617. res.set_content("DELETED", "text/plain");
  3618. } else {
  3619. res.status = StatusCode::NotFound_404;
  3620. }
  3621. } else {
  3622. res.status = StatusCode::BadRequest_400;
  3623. }
  3624. })
  3625. .Post("/x-www-form-urlencoded-json",
  3626. [&](const Request &req, Response &res) {
  3627. auto json = req.get_param_value("json");
  3628. ASSERT_EQ(JSON_DATA, json);
  3629. res.set_content(json, "appliation/json");
  3630. res.status = StatusCode::OK_200;
  3631. })
  3632. .Get("/streamed-chunked",
  3633. [&](const Request & /*req*/, Response &res) {
  3634. res.set_chunked_content_provider(
  3635. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3636. sink.os << "123";
  3637. sink.os << "456";
  3638. sink.os << "789";
  3639. sink.done();
  3640. return true;
  3641. });
  3642. })
  3643. .Get("/streamed-chunked-with-prohibited-trailer",
  3644. [&](const Request & /*req*/, Response &res) {
  3645. auto i = new int(0);
  3646. // Declare both a prohibited trailer (Content-Length) and an
  3647. // allowed one
  3648. res.set_header("Trailer", "Content-Length, X-Allowed");
  3649. res.set_chunked_content_provider(
  3650. "text/plain",
  3651. [i](size_t /*offset*/, DataSink &sink) {
  3652. switch (*i) {
  3653. case 0: sink.os << "123"; break;
  3654. case 1: sink.os << "456"; break;
  3655. case 2: sink.os << "789"; break;
  3656. case 3: {
  3657. sink.done_with_trailer(
  3658. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3659. } break;
  3660. }
  3661. (*i)++;
  3662. return true;
  3663. },
  3664. [i](bool success) {
  3665. EXPECT_TRUE(success);
  3666. delete i;
  3667. });
  3668. })
  3669. .Get("/streamed-chunked2",
  3670. [&](const Request & /*req*/, Response &res) {
  3671. auto i = new int(0);
  3672. res.set_chunked_content_provider(
  3673. "text/plain",
  3674. [i](size_t /*offset*/, DataSink &sink) {
  3675. switch (*i) {
  3676. case 0: sink.os << "123"; break;
  3677. case 1: sink.os << "456"; break;
  3678. case 2: sink.os << "789"; break;
  3679. case 3: sink.done(); break;
  3680. }
  3681. (*i)++;
  3682. return true;
  3683. },
  3684. [i](bool success) {
  3685. EXPECT_TRUE(success);
  3686. delete i;
  3687. });
  3688. })
  3689. .Get("/streamed-chunked-with-trailer",
  3690. [&](const Request & /*req*/, Response &res) {
  3691. auto i = new int(0);
  3692. res.set_header("Trailer", "Dummy1, Dummy2");
  3693. res.set_chunked_content_provider(
  3694. "text/plain",
  3695. [i](size_t /*offset*/, DataSink &sink) {
  3696. switch (*i) {
  3697. case 0: sink.os << "123"; break;
  3698. case 1: sink.os << "456"; break;
  3699. case 2: sink.os << "789"; break;
  3700. case 3: {
  3701. sink.done_with_trailer(
  3702. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3703. } break;
  3704. }
  3705. (*i)++;
  3706. return true;
  3707. },
  3708. [i](bool success) {
  3709. EXPECT_TRUE(success);
  3710. delete i;
  3711. });
  3712. })
  3713. .Get("/streamed",
  3714. [&](const Request & /*req*/, Response &res) {
  3715. res.set_content_provider(
  3716. 6, "text/plain",
  3717. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3718. sink.os << (offset < 3 ? "a" : "b");
  3719. return true;
  3720. });
  3721. })
  3722. .Get("/streamed-without-length",
  3723. [&](const Request & /*req*/, Response &res) {
  3724. auto data = new std::string("abcdefg");
  3725. res.set_content_provider(
  3726. "text/plain",
  3727. [data](size_t offset, DataSink &sink) {
  3728. if (offset < data->size()) {
  3729. sink.os << data->substr(offset);
  3730. }
  3731. sink.done();
  3732. return true;
  3733. },
  3734. [data](bool success) {
  3735. EXPECT_TRUE(success);
  3736. delete data;
  3737. });
  3738. })
  3739. .Get("/streamed-with-range",
  3740. [&](const Request &req, Response &res) {
  3741. auto data = new std::string("abcdefg");
  3742. res.set_content_provider(
  3743. data->size(), "text/plain",
  3744. [data](size_t offset, size_t length, DataSink &sink) {
  3745. size_t DATA_CHUNK_SIZE = 4;
  3746. const auto &d = *data;
  3747. auto out_len =
  3748. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3749. auto ret =
  3750. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3751. EXPECT_TRUE(ret);
  3752. return true;
  3753. },
  3754. [data, &req](bool success) {
  3755. EXPECT_EQ(success, !req.has_param("error"));
  3756. delete data;
  3757. });
  3758. })
  3759. .Get("/streamed-cancel",
  3760. [&](const Request & /*req*/, Response &res) {
  3761. res.set_content_provider(
  3762. size_t(-1), "text/plain",
  3763. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3764. sink.os << "data_chunk";
  3765. return true;
  3766. });
  3767. })
  3768. .Get("/regex-with-delimiter",
  3769. [&](const Request &req, Response & /*res*/) {
  3770. ASSERT_TRUE(req.has_param("key"));
  3771. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3772. })
  3773. .Get("/with-range",
  3774. [&](const Request & /*req*/, Response &res) {
  3775. res.set_content("abcdefg", "text/plain");
  3776. })
  3777. .Get("/test-start-time",
  3778. [&](const Request &req, Response & /*res*/) {
  3779. EXPECT_NE(req.start_time_,
  3780. std::chrono::steady_clock::time_point::min());
  3781. })
  3782. .Get("/with-range-customized-response",
  3783. [&](const Request & /*req*/, Response &res) {
  3784. res.status = StatusCode::BadRequest_400;
  3785. res.set_content(JSON_DATA, "application/json");
  3786. })
  3787. .Post("/chunked",
  3788. [&](const Request &req, Response & /*res*/) {
  3789. EXPECT_EQ(req.body, "dechunked post body");
  3790. })
  3791. .Post("/large-chunked",
  3792. [&](const Request &req, Response & /*res*/) {
  3793. std::string expected(6 * 30 * 1024u, 'a');
  3794. EXPECT_EQ(req.body, expected);
  3795. })
  3796. .Post("/multipart",
  3797. [&](const Request &req, Response & /*res*/) {
  3798. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3799. req.form.get_field_count("text2") +
  3800. req.form.get_field_count("file3") +
  3801. req.form.get_field_count("file4"));
  3802. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3803. req.form.get_file_count("file2"));
  3804. ASSERT_TRUE(!req.form.has_file("???"));
  3805. ASSERT_TRUE(!req.form.has_field("???"));
  3806. ASSERT_TRUE(req.body.empty());
  3807. {
  3808. const auto &text = req.form.get_field("text1");
  3809. EXPECT_EQ("text default", text);
  3810. }
  3811. {
  3812. const auto &text = req.form.get_field("text2");
  3813. EXPECT_EQ("aωb", text);
  3814. }
  3815. {
  3816. const auto &file = req.form.get_file("file1");
  3817. EXPECT_EQ("hello.txt", file.filename);
  3818. EXPECT_EQ("text/plain", file.content_type);
  3819. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3820. }
  3821. {
  3822. const auto &file = req.form.get_file("file2");
  3823. EXPECT_EQ("world.json", file.filename);
  3824. EXPECT_EQ("application/json", file.content_type);
  3825. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3826. }
  3827. {
  3828. const auto &text = req.form.get_field("file3");
  3829. EXPECT_EQ(0u, text.size());
  3830. }
  3831. {
  3832. const auto &text = req.form.get_field("file4");
  3833. EXPECT_EQ(0u, text.size());
  3834. }
  3835. })
  3836. .Post("/multipart/multi_file_values",
  3837. [&](const Request &req, Response & /*res*/) {
  3838. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3839. req.form.get_field_count("multi_text1"));
  3840. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3841. ASSERT_TRUE(!req.form.has_file("???"));
  3842. ASSERT_TRUE(!req.form.has_field("???"));
  3843. ASSERT_TRUE(req.body.empty());
  3844. {
  3845. const auto &text = req.form.get_field("text");
  3846. EXPECT_EQ("default text", text);
  3847. }
  3848. {
  3849. const auto &text1_values = req.form.get_fields("multi_text1");
  3850. EXPECT_EQ(2u, text1_values.size());
  3851. EXPECT_EQ("aaaaa", text1_values[0]);
  3852. EXPECT_EQ("bbbbb", text1_values[1]);
  3853. }
  3854. {
  3855. const auto &file1_values = req.form.get_files("multi_file1");
  3856. EXPECT_EQ(2u, file1_values.size());
  3857. auto file1 = file1_values[0];
  3858. EXPECT_EQ(file1.filename, "hello.txt");
  3859. EXPECT_EQ(file1.content_type, "text/plain");
  3860. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3861. auto file2 = file1_values[1];
  3862. EXPECT_EQ(file2.filename, "world.json");
  3863. EXPECT_EQ(file2.content_type, "application/json");
  3864. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3865. }
  3866. })
  3867. .Post("/empty",
  3868. [&](const Request &req, Response &res) {
  3869. EXPECT_EQ(req.body, "");
  3870. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3871. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3872. res.set_content("empty", "text/plain");
  3873. })
  3874. .Post("/empty-no-content-type",
  3875. [&](const Request &req, Response &res) {
  3876. EXPECT_EQ(req.body, "");
  3877. EXPECT_FALSE(req.has_header("Content-Type"));
  3878. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3879. res.set_content("empty-no-content-type", "text/plain");
  3880. })
  3881. .Post("/path-only",
  3882. [&](const Request &req, Response &res) {
  3883. EXPECT_EQ(req.body, "");
  3884. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3885. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3886. res.set_content("path-only", "text/plain");
  3887. })
  3888. .Post("/path-headers-only",
  3889. [&](const Request &req, Response &res) {
  3890. EXPECT_EQ(req.body, "");
  3891. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3892. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3893. EXPECT_EQ("world", req.get_header_value("hello"));
  3894. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3895. res.set_content("path-headers-only", "text/plain");
  3896. })
  3897. .Post("/post-large",
  3898. [&](const Request &req, Response &res) {
  3899. EXPECT_EQ(req.body, LARGE_DATA);
  3900. res.set_content(req.body, "text/plain");
  3901. })
  3902. .Post("/post-loopback",
  3903. [&](const Request &, Response &res,
  3904. ContentReader const &content_reader) {
  3905. std::string body;
  3906. content_reader([&](const char *data, size_t data_length) {
  3907. body.append(data, data_length);
  3908. return true;
  3909. });
  3910. res.set_content(body, "text/plain");
  3911. })
  3912. .Put("/put-loopback",
  3913. [&](const Request &, Response &res,
  3914. ContentReader const &content_reader) {
  3915. std::string body;
  3916. content_reader([&](const char *data, size_t data_length) {
  3917. body.append(data, data_length);
  3918. return true;
  3919. });
  3920. res.set_content(body, "text/plain");
  3921. })
  3922. .Patch("/patch-loopback",
  3923. [&](const Request &, Response &res,
  3924. ContentReader const &content_reader) {
  3925. std::string body;
  3926. content_reader([&](const char *data, size_t data_length) {
  3927. body.append(data, data_length);
  3928. return true;
  3929. });
  3930. res.set_content(body, "text/plain");
  3931. })
  3932. .Put("/empty-no-content-type",
  3933. [&](const Request &req, Response &res) {
  3934. EXPECT_EQ(req.body, "");
  3935. EXPECT_FALSE(req.has_header("Content-Type"));
  3936. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3937. res.set_content("empty-no-content-type", "text/plain");
  3938. })
  3939. .Put("/put",
  3940. [&](const Request &req, Response &res) {
  3941. EXPECT_EQ(req.body, "PUT");
  3942. res.set_content(req.body, "text/plain");
  3943. })
  3944. .Put("/put-large",
  3945. [&](const Request &req, Response &res) {
  3946. EXPECT_EQ(req.body, LARGE_DATA);
  3947. res.set_content(req.body, "text/plain");
  3948. })
  3949. .Patch("/patch",
  3950. [&](const Request &req, Response &res) {
  3951. EXPECT_EQ(req.body, "PATCH");
  3952. res.set_content(req.body, "text/plain");
  3953. })
  3954. .Delete("/delete",
  3955. [&](const Request & /*req*/, Response &res) {
  3956. res.set_content("DELETE", "text/plain");
  3957. })
  3958. .Delete("/delete-body",
  3959. [&](const Request &req, Response &res) {
  3960. EXPECT_EQ(req.body, "content");
  3961. res.set_content(req.body, "text/plain");
  3962. })
  3963. .Options(R"(\*)",
  3964. [&](const Request & /*req*/, Response &res) {
  3965. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3966. })
  3967. .Get("/request-target",
  3968. [&](const Request &req, Response & /*res*/) {
  3969. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3970. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3971. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3972. })
  3973. .Get("/long-query-value",
  3974. [&](const Request &req, Response & /*res*/) {
  3975. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3976. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3977. })
  3978. .Get("/too-long-query-value",
  3979. [&](const Request &req, Response & /*res*/) {
  3980. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3981. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3982. })
  3983. .Get("/array-param",
  3984. [&](const Request &req, Response & /*res*/) {
  3985. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3986. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3987. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3988. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3989. })
  3990. .Get("/array-param-values",
  3991. [&](const Request &req, Response & /*res*/) {
  3992. auto values = req.get_param_values("array");
  3993. EXPECT_EQ(3u, values.size());
  3994. EXPECT_EQ("value1", values[0]);
  3995. EXPECT_EQ("value2", values[1]);
  3996. EXPECT_EQ("value3", values[2]);
  3997. auto empty = req.get_param_values("nonexistent");
  3998. EXPECT_TRUE(empty.empty());
  3999. })
  4000. .Post("/validate-no-multiple-headers",
  4001. [&](const Request &req, Response & /*res*/) {
  4002. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4003. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4004. })
  4005. .Post("/content_receiver",
  4006. [&](const Request &req, Response &res,
  4007. const ContentReader &content_reader) {
  4008. if (req.is_multipart_form_data()) {
  4009. std::vector<FormData> items;
  4010. content_reader(
  4011. [&](const FormData &file) {
  4012. items.push_back(file);
  4013. return true;
  4014. },
  4015. [&](const char *data, size_t data_length) {
  4016. items.back().content.append(data, data_length);
  4017. return true;
  4018. });
  4019. EXPECT_EQ(5u, items.size());
  4020. {
  4021. const auto &file = get_file_value(items, "text1");
  4022. EXPECT_TRUE(file.filename.empty());
  4023. EXPECT_EQ("text default", file.content);
  4024. }
  4025. {
  4026. const auto &file = get_file_value(items, "text2");
  4027. EXPECT_TRUE(file.filename.empty());
  4028. EXPECT_EQ("aωb", file.content);
  4029. }
  4030. {
  4031. const auto &file = get_file_value(items, "file1");
  4032. EXPECT_EQ("hello.txt", file.filename);
  4033. EXPECT_EQ("text/plain", file.content_type);
  4034. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4035. }
  4036. {
  4037. const auto &file = get_file_value(items, "file2");
  4038. EXPECT_EQ("world.json", file.filename);
  4039. EXPECT_EQ("application/json", file.content_type);
  4040. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4041. }
  4042. {
  4043. const auto &file = get_file_value(items, "file3");
  4044. EXPECT_TRUE(file.filename.empty());
  4045. EXPECT_EQ("application/octet-stream", file.content_type);
  4046. EXPECT_EQ(0u, file.content.size());
  4047. }
  4048. } else {
  4049. std::string body;
  4050. content_reader([&](const char *data, size_t data_length) {
  4051. EXPECT_EQ(7U, data_length);
  4052. body.append(data, data_length);
  4053. return true;
  4054. });
  4055. EXPECT_EQ(body, "content");
  4056. res.set_content(body, "text/plain");
  4057. }
  4058. })
  4059. .Put("/content_receiver",
  4060. [&](const Request & /*req*/, Response &res,
  4061. const ContentReader &content_reader) {
  4062. std::string body;
  4063. content_reader([&](const char *data, size_t data_length) {
  4064. body.append(data, data_length);
  4065. return true;
  4066. });
  4067. EXPECT_EQ(body, "content");
  4068. res.set_content(body, "text/plain");
  4069. })
  4070. .Patch("/content_receiver",
  4071. [&](const Request & /*req*/, Response &res,
  4072. const ContentReader &content_reader) {
  4073. std::string body;
  4074. content_reader([&](const char *data, size_t data_length) {
  4075. body.append(data, data_length);
  4076. return true;
  4077. });
  4078. EXPECT_EQ(body, "content");
  4079. res.set_content(body, "text/plain");
  4080. })
  4081. .Post("/query-string-and-body",
  4082. [&](const Request &req, Response & /*res*/) {
  4083. ASSERT_TRUE(req.has_param("key"));
  4084. EXPECT_EQ(req.get_param_value("key"), "value");
  4085. EXPECT_EQ(req.body, "content");
  4086. })
  4087. .Get("/last-request",
  4088. [&](const Request &req, Response & /*res*/) {
  4089. EXPECT_EQ("close", req.get_header_value("Connection"));
  4090. })
  4091. .Get(R"(/redirect/(\d+))",
  4092. [&](const Request &req, Response &res) {
  4093. auto num = std::stoi(req.matches[1]) + 1;
  4094. std::string url = "/redirect/" + std::to_string(num);
  4095. res.set_redirect(url);
  4096. })
  4097. .Post("/binary",
  4098. [&](const Request &req, Response &res) {
  4099. EXPECT_EQ(4U, req.body.size());
  4100. EXPECT_EQ("application/octet-stream",
  4101. req.get_header_value("Content-Type"));
  4102. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4103. res.set_content(req.body, "application/octet-stream");
  4104. })
  4105. .Put("/binary",
  4106. [&](const Request &req, Response &res) {
  4107. EXPECT_EQ(4U, req.body.size());
  4108. EXPECT_EQ("application/octet-stream",
  4109. req.get_header_value("Content-Type"));
  4110. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4111. res.set_content(req.body, "application/octet-stream");
  4112. })
  4113. .Patch("/binary",
  4114. [&](const Request &req, Response &res) {
  4115. EXPECT_EQ(4U, req.body.size());
  4116. EXPECT_EQ("application/octet-stream",
  4117. req.get_header_value("Content-Type"));
  4118. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4119. res.set_content(req.body, "application/octet-stream");
  4120. })
  4121. .Delete("/binary",
  4122. [&](const Request &req, Response &res) {
  4123. EXPECT_EQ(4U, req.body.size());
  4124. EXPECT_EQ("application/octet-stream",
  4125. req.get_header_value("Content-Type"));
  4126. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  4127. res.set_content(req.body, "application/octet-stream");
  4128. })
  4129. .Get("/issue1772",
  4130. [&](const Request & /*req*/, Response &res) {
  4131. res.status = 401;
  4132. res.set_header("WWW-Authenticate", "Basic realm=123456");
  4133. })
  4134. .Delete("/issue609",
  4135. [](const httplib::Request &, httplib::Response &res,
  4136. const httplib::ContentReader &) {
  4137. res.set_content("ok", "text/plain");
  4138. })
  4139. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  4140. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4141. .Get("/compress",
  4142. [&](const Request & /*req*/, Response &res) {
  4143. res.set_content(
  4144. "12345678901234567890123456789012345678901234567890123456789"
  4145. "01234567890123456789012345678901234567890",
  4146. "text/plain");
  4147. })
  4148. .Get("/compress-with-charset",
  4149. [&](const Request & /*req*/, Response &res) {
  4150. res.set_content(
  4151. "12345678901234567890123456789012345678901234567890123456789"
  4152. "01234567890123456789012345678901234567890",
  4153. "application/json; charset=utf-8");
  4154. })
  4155. .Get("/nocompress",
  4156. [&](const Request & /*req*/, Response &res) {
  4157. res.set_content(
  4158. "12345678901234567890123456789012345678901234567890123456789"
  4159. "01234567890123456789012345678901234567890",
  4160. "application/octet-stream");
  4161. })
  4162. .Post("/compress-multipart",
  4163. [&](const Request &req, Response & /*res*/) {
  4164. EXPECT_EQ(2u, req.form.fields.size());
  4165. ASSERT_TRUE(!req.form.has_field("???"));
  4166. {
  4167. const auto &text = req.form.get_field("key1");
  4168. EXPECT_EQ("test", text);
  4169. }
  4170. {
  4171. const auto &text = req.form.get_field("key2");
  4172. EXPECT_EQ("--abcdefg123", text);
  4173. }
  4174. })
  4175. #endif
  4176. ;
  4177. persons_["john"] = "programmer";
  4178. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4179. svr_.wait_until_ready();
  4180. }
  4181. virtual void TearDown() {
  4182. svr_.stop();
  4183. if (!request_threads_.empty()) {
  4184. std::this_thread::sleep_for(std::chrono::seconds(1));
  4185. for (auto &t : request_threads_) {
  4186. t.join();
  4187. }
  4188. }
  4189. t_.join();
  4190. }
  4191. map<string, string> persons_;
  4192. #ifdef CPPHTTPLIB_SSL_ENABLED
  4193. SSLClient cli_;
  4194. SSLServer svr_;
  4195. #else
  4196. Client cli_;
  4197. Server svr_;
  4198. #endif
  4199. thread t_;
  4200. std::vector<thread> request_threads_;
  4201. };
  4202. TEST_F(ServerTest, GetMethod200) {
  4203. auto res = cli_.Get("/hi");
  4204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4205. EXPECT_EQ("HTTP/1.1", res->version);
  4206. EXPECT_EQ(StatusCode::OK_200, res->status);
  4207. EXPECT_EQ("OK", res->reason);
  4208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4209. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4210. EXPECT_EQ("Hello World!", res->body);
  4211. }
  4212. TEST_F(ServerTest, GetEmptyFile) {
  4213. auto res = cli_.Get("/empty_file");
  4214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4215. EXPECT_EQ(StatusCode::OK_200, res->status);
  4216. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4217. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  4218. EXPECT_EQ("", res->body);
  4219. }
  4220. TEST_F(ServerTest, GetFileContent) {
  4221. auto res = cli_.Get("/file_content");
  4222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4223. EXPECT_EQ(StatusCode::OK_200, res->status);
  4224. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4225. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  4226. EXPECT_EQ("test.html", res->body);
  4227. }
  4228. TEST_F(ServerTest, GetFileContentWithRange) {
  4229. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  4230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4232. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4233. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  4234. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  4235. EXPECT_EQ("est", res->body);
  4236. }
  4237. TEST_F(ServerTest, GetFileContentWithContentType) {
  4238. auto res = cli_.Get("/file_content_with_content_type");
  4239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4240. EXPECT_EQ(StatusCode::OK_200, res->status);
  4241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4242. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  4243. EXPECT_EQ("file\n", res->body);
  4244. }
  4245. TEST_F(ServerTest, GetInvalidFileContent) {
  4246. auto res = cli_.Get("/invalid_file_content");
  4247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4249. }
  4250. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  4251. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  4252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4253. EXPECT_EQ("HTTP/1.1", res->version);
  4254. EXPECT_EQ(StatusCode::OK_200, res->status);
  4255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4256. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  4257. EXPECT_EQ("Hello World!", res->body);
  4258. }
  4259. TEST_F(ServerTest, GetMethod302) {
  4260. auto res = cli_.Get("/");
  4261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4262. EXPECT_EQ(StatusCode::Found_302, res->status);
  4263. EXPECT_EQ("/hi", res->get_header_value("Location"));
  4264. }
  4265. TEST_F(ServerTest, GetMethod302Redirect) {
  4266. cli_.set_follow_location(true);
  4267. auto res = cli_.Get("/");
  4268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4269. EXPECT_EQ(StatusCode::OK_200, res->status);
  4270. EXPECT_EQ("Hello World!", res->body);
  4271. EXPECT_EQ("/hi", res->location);
  4272. }
  4273. TEST_F(ServerTest, GetMethod404) {
  4274. auto res = cli_.Get("/invalid");
  4275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4277. }
  4278. TEST_F(ServerTest, HeadMethod200) {
  4279. auto res = cli_.Head("/hi");
  4280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4281. EXPECT_EQ(StatusCode::OK_200, res->status);
  4282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4283. EXPECT_TRUE(res->body.empty());
  4284. }
  4285. TEST_F(ServerTest, HeadMethod200Static) {
  4286. auto res = cli_.Head("/mount/dir/index.html");
  4287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4288. EXPECT_EQ(StatusCode::OK_200, res->status);
  4289. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4290. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  4291. EXPECT_TRUE(res->body.empty());
  4292. }
  4293. TEST_F(ServerTest, HeadMethod404) {
  4294. auto res = cli_.Head("/invalid");
  4295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4296. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4297. EXPECT_TRUE(res->body.empty());
  4298. }
  4299. TEST_F(ServerTest, GetMethodPersonJohn) {
  4300. auto res = cli_.Get("/person/john");
  4301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4304. EXPECT_EQ("programmer", res->body);
  4305. }
  4306. TEST_F(ServerTest, PostMethod1) {
  4307. auto res = cli_.Get("/person/john1");
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4310. res = cli_.Post("/person", "name=john1&note=coder",
  4311. "application/x-www-form-urlencoded");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. ASSERT_EQ(StatusCode::OK_200, res->status);
  4314. res = cli_.Get("/person/john1");
  4315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4316. ASSERT_EQ(StatusCode::OK_200, res->status);
  4317. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4318. ASSERT_EQ("coder", res->body);
  4319. }
  4320. TEST_F(ServerTest, PostMethod2) {
  4321. auto res = cli_.Get("/person/john2");
  4322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4323. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4324. Params params;
  4325. params.emplace("name", "john2");
  4326. params.emplace("note", "coder");
  4327. res = cli_.Post("/person", params);
  4328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4329. ASSERT_EQ(StatusCode::OK_200, res->status);
  4330. res = cli_.Get("/person/john2");
  4331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4332. ASSERT_EQ(StatusCode::OK_200, res->status);
  4333. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4334. ASSERT_EQ("coder", res->body);
  4335. }
  4336. TEST_F(ServerTest, PutMethod3) {
  4337. auto res = cli_.Get("/person/john3");
  4338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4339. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4340. Params params;
  4341. params.emplace("name", "john3");
  4342. params.emplace("note", "coder");
  4343. res = cli_.Put("/person", params);
  4344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4345. ASSERT_EQ(StatusCode::OK_200, res->status);
  4346. res = cli_.Get("/person/john3");
  4347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4348. ASSERT_EQ(StatusCode::OK_200, res->status);
  4349. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4350. ASSERT_EQ("coder", res->body);
  4351. }
  4352. TEST_F(ServerTest, DeleteMethod1) {
  4353. auto res = cli_.Get("/person/john4");
  4354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4356. Params params;
  4357. params.emplace("name", "john4");
  4358. params.emplace("note", "coder");
  4359. res = cli_.Post("/person", params);
  4360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4361. ASSERT_EQ(StatusCode::OK_200, res->status);
  4362. res = cli_.Get("/person/john4");
  4363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4364. ASSERT_EQ(StatusCode::OK_200, res->status);
  4365. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4366. ASSERT_EQ("coder", res->body);
  4367. Params delete_params;
  4368. delete_params.emplace("name", "john4");
  4369. res = cli_.Delete("/person", delete_params);
  4370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4371. ASSERT_EQ(StatusCode::OK_200, res->status);
  4372. ASSERT_EQ("DELETED", res->body);
  4373. res = cli_.Get("/person/john4");
  4374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4375. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4376. }
  4377. TEST_F(ServerTest, DeleteMethod2) {
  4378. auto res = cli_.Get("/person/john5");
  4379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4380. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4381. Params params;
  4382. params.emplace("name", "john5");
  4383. params.emplace("note", "developer");
  4384. res = cli_.Post("/person", params);
  4385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4386. ASSERT_EQ(StatusCode::OK_200, res->status);
  4387. res = cli_.Get("/person/john5");
  4388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4389. ASSERT_EQ(StatusCode::OK_200, res->status);
  4390. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4391. ASSERT_EQ("developer", res->body);
  4392. Params delete_params;
  4393. delete_params.emplace("name", "john5");
  4394. Headers headers;
  4395. headers.emplace("Custom-Header", "test-value");
  4396. res = cli_.Delete("/person", headers, delete_params);
  4397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4398. ASSERT_EQ(StatusCode::OK_200, res->status);
  4399. ASSERT_EQ("DELETED", res->body);
  4400. res = cli_.Get("/person/john5");
  4401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4402. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4403. }
  4404. TEST_F(ServerTest, DeleteMethod3) {
  4405. auto res = cli_.Get("/person/john6");
  4406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4407. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4408. Params params;
  4409. params.emplace("name", "john6");
  4410. params.emplace("note", "tester");
  4411. res = cli_.Post("/person", params);
  4412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4413. ASSERT_EQ(StatusCode::OK_200, res->status);
  4414. res = cli_.Get("/person/john6");
  4415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4416. ASSERT_EQ(StatusCode::OK_200, res->status);
  4417. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  4418. ASSERT_EQ("tester", res->body);
  4419. Params delete_params;
  4420. delete_params.emplace("name", "john6");
  4421. Headers headers;
  4422. headers.emplace("Custom-Header", "test-value");
  4423. res = cli_.Delete("/person", headers, delete_params, nullptr);
  4424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4425. ASSERT_EQ(StatusCode::OK_200, res->status);
  4426. ASSERT_EQ("DELETED", res->body);
  4427. res = cli_.Get("/person/john6");
  4428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4429. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  4430. }
  4431. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  4432. Params params;
  4433. params.emplace("json", JSON_DATA);
  4434. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  4435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4436. ASSERT_EQ(StatusCode::OK_200, res->status);
  4437. ASSERT_EQ(JSON_DATA, res->body);
  4438. }
  4439. TEST_F(ServerTest, PostEmptyContent) {
  4440. auto res = cli_.Post("/empty", "", "text/plain");
  4441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4442. ASSERT_EQ(StatusCode::OK_200, res->status);
  4443. ASSERT_EQ("empty", res->body);
  4444. }
  4445. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  4446. auto res = cli_.Post("/empty-no-content-type");
  4447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4448. ASSERT_EQ(StatusCode::OK_200, res->status);
  4449. ASSERT_EQ("empty-no-content-type", res->body);
  4450. }
  4451. TEST_F(ServerTest, PostPathOnly) {
  4452. auto res = cli_.Post("/path-only");
  4453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4454. ASSERT_EQ(StatusCode::OK_200, res->status);
  4455. ASSERT_EQ("path-only", res->body);
  4456. }
  4457. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  4458. auto res = cli_.Post("/path-headers-only",
  4459. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  4460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4461. ASSERT_EQ(StatusCode::OK_200, res->status);
  4462. ASSERT_EQ("path-headers-only", res->body);
  4463. }
  4464. TEST_F(ServerTest, PostLarge) {
  4465. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  4466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4467. ASSERT_EQ(StatusCode::OK_200, res->status);
  4468. EXPECT_EQ(LARGE_DATA, res->body);
  4469. }
  4470. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  4471. auto res = cli_.Put("/empty-no-content-type");
  4472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4473. ASSERT_EQ(StatusCode::OK_200, res->status);
  4474. ASSERT_EQ("empty-no-content-type", res->body);
  4475. }
  4476. TEST_F(ServerTest, GetMethodDir) {
  4477. auto res = cli_.Get("/dir/");
  4478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4479. EXPECT_EQ(StatusCode::OK_200, res->status);
  4480. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4481. auto body = R"(<html>
  4482. <head>
  4483. </head>
  4484. <body>
  4485. <a href="/dir/test.html">Test</a>
  4486. <a href="/hi">hi</a>
  4487. </body>
  4488. </html>
  4489. )";
  4490. EXPECT_EQ(body, res->body);
  4491. }
  4492. TEST_F(ServerTest, GetMethodDirTest) {
  4493. auto res = cli_.Get("/dir/test.html");
  4494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4495. EXPECT_EQ(StatusCode::OK_200, res->status);
  4496. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4497. EXPECT_EQ("test.html", res->body);
  4498. }
  4499. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  4500. auto res = cli_.Get("/dir/../dir/test.html");
  4501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4504. EXPECT_EQ("test.html", res->body);
  4505. }
  4506. TEST_F(ServerTest, GetMethodInvalidPath) {
  4507. auto res = cli_.Get("/dir/../test.html");
  4508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4509. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4510. }
  4511. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  4512. auto res = cli_.Get("/../www/dir/test.html");
  4513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4514. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4515. }
  4516. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  4517. auto res = cli_.Get("/dir/../../www/dir/test.html");
  4518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4520. }
  4521. TEST_F(ServerTest, GetMethodDirMountTest) {
  4522. auto res = cli_.Get("/mount/dir/test.html");
  4523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4524. EXPECT_EQ(StatusCode::OK_200, res->status);
  4525. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4526. EXPECT_EQ("test.html", res->body);
  4527. }
  4528. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  4529. auto res = cli_.Get("/mount/dir/../dir/test.html");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4533. EXPECT_EQ("test.html", res->body);
  4534. }
  4535. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  4536. auto res = cli_.Get("/mount/dir/../test.html");
  4537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4539. }
  4540. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  4541. auto res = cli_.Get("/mount/dir/test.html%00.js");
  4542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4544. }
  4545. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  4546. auto res = cli_.Get("/mount/../www2/dir/test.html");
  4547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4549. }
  4550. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  4551. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  4552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4554. }
  4555. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  4556. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  4557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4559. }
  4560. TEST_F(ServerTest, PostMethod303) {
  4561. auto res = cli_.Post("/1", "body", "text/plain");
  4562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4563. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4564. EXPECT_EQ("/2", res->get_header_value("Location"));
  4565. }
  4566. TEST_F(ServerTest, PostMethod303Redirect) {
  4567. cli_.set_follow_location(true);
  4568. auto res = cli_.Post("/1", "body", "text/plain");
  4569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4570. EXPECT_EQ(StatusCode::OK_200, res->status);
  4571. EXPECT_EQ("redirected.", res->body);
  4572. EXPECT_EQ("/2", res->location);
  4573. }
  4574. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4575. auto res = cli_.Get("/dir/test.abcde");
  4576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4579. EXPECT_EQ("abcde", res->body);
  4580. }
  4581. TEST_F(ServerTest, StaticFileRange) {
  4582. auto res =
  4583. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  4584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4585. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4586. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4587. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4588. EXPECT_EQ(true, res->has_header("Content-Range"));
  4589. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4590. EXPECT_EQ(std::string("cd"), res->body);
  4591. }
  4592. TEST_F(ServerTest, StaticFileRanges) {
  4593. auto res = cli_.Get("/dir/test.abcde",
  4594. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  4595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4596. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4597. EXPECT_TRUE(
  4598. res->get_header_value("Content-Type")
  4599. .find(
  4600. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4601. 0);
  4602. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4603. }
  4604. TEST_F(ServerTest, StaticFileRangeHead) {
  4605. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4607. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4608. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4609. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4610. EXPECT_EQ(true, res->has_header("Content-Range"));
  4611. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4612. }
  4613. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4614. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  4615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4616. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4618. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4619. EXPECT_EQ(true, res->has_header("Content-Range"));
  4620. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4621. res->get_header_value("Content-Range"));
  4622. EXPECT_EQ("LAST\n", res->body);
  4623. }
  4624. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4625. auto res =
  4626. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  4627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4630. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4631. EXPECT_EQ(true, res->has_header("Content-Range"));
  4632. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4633. }
  4634. TEST_F(ServerTest, StaticFileBigFile) {
  4635. auto res = cli_.Get("/dir/1MB.txt");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4639. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4640. }
  4641. TEST_F(ServerTest, InvalidBaseDirMount) {
  4642. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4643. }
  4644. TEST_F(ServerTest, Binary) {
  4645. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4646. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4647. "application/octet-stream");
  4648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4649. ASSERT_EQ(StatusCode::OK_200, res->status);
  4650. ASSERT_EQ(4U, res->body.size());
  4651. res = cli_.Put("/binary", binary.data(), binary.size(),
  4652. "application/octet-stream");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. ASSERT_EQ(StatusCode::OK_200, res->status);
  4655. ASSERT_EQ(4U, res->body.size());
  4656. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4657. "application/octet-stream");
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. ASSERT_EQ(StatusCode::OK_200, res->status);
  4660. ASSERT_EQ(4U, res->body.size());
  4661. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4662. "application/octet-stream");
  4663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4664. ASSERT_EQ(StatusCode::OK_200, res->status);
  4665. ASSERT_EQ(4U, res->body.size());
  4666. }
  4667. TEST_F(ServerTest, BinaryString) {
  4668. auto binary = std::string("\x00\x01\x02\x03", 4);
  4669. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. ASSERT_EQ(StatusCode::OK_200, res->status);
  4672. ASSERT_EQ(4U, res->body.size());
  4673. res = cli_.Put("/binary", binary, "application/octet-stream");
  4674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4675. ASSERT_EQ(StatusCode::OK_200, res->status);
  4676. ASSERT_EQ(4U, res->body.size());
  4677. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4679. ASSERT_EQ(StatusCode::OK_200, res->status);
  4680. ASSERT_EQ(4U, res->body.size());
  4681. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4683. ASSERT_EQ(StatusCode::OK_200, res->status);
  4684. ASSERT_EQ(4U, res->body.size());
  4685. }
  4686. TEST_F(ServerTest, EmptyRequest) {
  4687. auto res = cli_.Get("");
  4688. ASSERT_TRUE(!res);
  4689. EXPECT_EQ(Error::Connection, res.error());
  4690. }
  4691. TEST_F(ServerTest, LongRequest) {
  4692. std::string request;
  4693. for (size_t i = 0; i < 545; i++) {
  4694. request += "/TooLongRequest";
  4695. }
  4696. request += "OK";
  4697. auto res = cli_.Get(request.c_str());
  4698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4699. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4700. }
  4701. TEST_F(ServerTest, TooLongRequest) {
  4702. std::string request;
  4703. for (size_t i = 0; i < 546; i++) {
  4704. request += "/TooLongRequest";
  4705. }
  4706. request += "_NG";
  4707. auto start = std::chrono::high_resolution_clock::now();
  4708. cli_.set_keep_alive(true);
  4709. auto res = cli_.Get(request.c_str());
  4710. auto end = std::chrono::high_resolution_clock::now();
  4711. auto elapsed =
  4712. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4713. .count();
  4714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4715. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4716. EXPECT_LE(elapsed, 1000);
  4717. EXPECT_EQ("close", res->get_header_value("Connection"));
  4718. EXPECT_FALSE(cli_.is_socket_open());
  4719. }
  4720. TEST_F(ServerTest, AlmostTooLongRequest) {
  4721. // test for #2046 - URI length check shouldn't include other content on req
  4722. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4723. // leading /, space, HTTP/1.1)
  4724. std::string request =
  4725. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4726. auto res = cli_.Get(request.c_str());
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4729. }
  4730. TEST_F(ServerTest, LongHeader) {
  4731. Request req;
  4732. req.method = "GET";
  4733. req.path = "/hi";
  4734. std::string host_and_port;
  4735. host_and_port += HOST;
  4736. host_and_port += ":";
  4737. host_and_port += std::to_string(PORT);
  4738. req.headers.emplace("Host", host_and_port.c_str());
  4739. req.headers.emplace("Accept", "*/*");
  4740. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4741. req.headers.emplace(
  4742. "Header-Name",
  4743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4771. "@@@@@@@@@@@@@@@@");
  4772. auto res = std::make_shared<Response>();
  4773. auto error = Error::Success;
  4774. auto ret = cli_.send(req, *res, error);
  4775. ASSERT_TRUE(ret);
  4776. EXPECT_EQ(StatusCode::OK_200, res->status);
  4777. }
  4778. TEST_F(ServerTest, LongQueryValue) {
  4779. auto start = std::chrono::high_resolution_clock::now();
  4780. cli_.set_keep_alive(true);
  4781. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4782. auto end = std::chrono::high_resolution_clock::now();
  4783. auto elapsed =
  4784. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4785. .count();
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4788. EXPECT_LE(elapsed, 1000);
  4789. EXPECT_EQ("close", res->get_header_value("Connection"));
  4790. EXPECT_FALSE(cli_.is_socket_open());
  4791. }
  4792. TEST_F(ServerTest, TooLongQueryValue) {
  4793. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4794. ASSERT_FALSE(res);
  4795. EXPECT_EQ(Error::Read, res.error());
  4796. }
  4797. TEST_F(ServerTest, TooLongHeader) {
  4798. Request req;
  4799. req.method = "GET";
  4800. req.path = "/hi";
  4801. std::string host_and_port;
  4802. host_and_port += HOST;
  4803. host_and_port += ":";
  4804. host_and_port += std::to_string(PORT);
  4805. req.headers.emplace("Host", host_and_port.c_str());
  4806. req.headers.emplace("Accept", "*/*");
  4807. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4808. req.headers.emplace(
  4809. "Header-Name",
  4810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4838. "@@@@@@@@@@@@@@@@@");
  4839. auto res = std::make_shared<Response>();
  4840. auto error = Error::Success;
  4841. auto ret = cli_.send(req, *res, error);
  4842. ASSERT_TRUE(ret);
  4843. EXPECT_EQ(StatusCode::OK_200, res->status);
  4844. }
  4845. TEST_F(ServerTest, HeaderCountAtLimit) {
  4846. // Test with headers just under the 100 limit
  4847. httplib::Headers headers;
  4848. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4849. // This should keep us just under the 100 header limit
  4850. for (int i = 0; i < 95; i++) {
  4851. std::string name = "X-Test-Header-" + std::to_string(i);
  4852. std::string value = "value" + std::to_string(i);
  4853. headers.emplace(name, value);
  4854. }
  4855. // This should work fine as we're under the limit
  4856. auto res = cli_.Get("/hi", headers);
  4857. EXPECT_TRUE(res);
  4858. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4859. }
  4860. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4861. // Test with many headers to exceed the 100 limit
  4862. httplib::Headers headers;
  4863. // Add 150 headers to definitely exceed the 100 limit
  4864. for (int i = 0; i < 150; i++) {
  4865. std::string name = "X-Test-Header-" + std::to_string(i);
  4866. std::string value = "value" + std::to_string(i);
  4867. headers.emplace(name, value);
  4868. }
  4869. // This should fail due to exceeding header count limit
  4870. cli_.set_keep_alive(true);
  4871. auto res = cli_.Get("/hi", headers);
  4872. // The server should respond with 400 Bad Request
  4873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4874. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4875. EXPECT_EQ("close", res->get_header_value("Connection"));
  4876. EXPECT_FALSE(cli_.is_socket_open());
  4877. }
  4878. TEST_F(ServerTest, PercentEncoding) {
  4879. auto res = cli_.Get("/e%6edwith%");
  4880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. }
  4883. TEST_F(ServerTest, PercentEncodingUnicode) {
  4884. auto res = cli_.Get("/e%u006edwith%");
  4885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. }
  4888. TEST_F(ServerTest, InvalidPercentEncoding) {
  4889. auto res = cli_.Get("/%endwith%");
  4890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4891. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4892. }
  4893. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4894. auto res = cli_.Get("/%uendwith%");
  4895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4897. }
  4898. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4899. auto res = cli_.Get("/hello?aaa=bbb%");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4902. }
  4903. TEST_F(ServerTest, PlusSignEncoding) {
  4904. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4906. EXPECT_EQ(StatusCode::OK_200, res->status);
  4907. EXPECT_EQ("a +b", res->body);
  4908. }
  4909. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4910. // This test simulates a potential DoS attack using many headers
  4911. // to verify our security fix prevents memory exhaustion
  4912. httplib::Headers attack_headers;
  4913. // Attempt to add many headers like an attacker would (200 headers to far
  4914. // exceed limit)
  4915. for (int i = 0; i < 200; i++) {
  4916. std::string name = "X-Attack-Header-" + std::to_string(i);
  4917. std::string value = "attack_payload_" + std::to_string(i);
  4918. attack_headers.emplace(name, value);
  4919. }
  4920. // Try to POST with excessive headers
  4921. cli_.set_keep_alive(true);
  4922. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4923. // Should either fail or return 400 Bad Request due to security limit
  4924. if (res) {
  4925. // If we get a response, it should be 400 Bad Request
  4926. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4927. EXPECT_EQ("close", res->get_header_value("Connection"));
  4928. }
  4929. EXPECT_FALSE(cli_.is_socket_open());
  4930. }
  4931. TEST_F(ServerTest, MultipartFormData) {
  4932. UploadFormDataItems items = {
  4933. {"text1", "text default", "", ""},
  4934. {"text2", "aωb", "", ""},
  4935. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4936. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4937. {"file3", "", "", "application/octet-stream"},
  4938. {"file4", "", "", " application/json tmp-string "}};
  4939. auto res = cli_.Post("/multipart", items);
  4940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4941. EXPECT_EQ(StatusCode::OK_200, res->status);
  4942. }
  4943. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4944. UploadFormDataItems items = {
  4945. {"text", "default text", "", ""},
  4946. {"multi_text1", "aaaaa", "", ""},
  4947. {"multi_text1", "bbbbb", "", ""},
  4948. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4949. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4950. "application/json"},
  4951. };
  4952. auto res = cli_.Post("/multipart/multi_file_values", items);
  4953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4954. EXPECT_EQ(StatusCode::OK_200, res->status);
  4955. }
  4956. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4957. auto res = cli_.Get("/hi");
  4958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4959. EXPECT_EQ(StatusCode::OK_200, res->status);
  4960. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4961. EXPECT_EQ("Hello World!", res->body);
  4962. }
  4963. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4964. Request req;
  4965. req.method = "POST";
  4966. req.path = "/chunked";
  4967. std::string host_and_port;
  4968. host_and_port += HOST;
  4969. host_and_port += ":";
  4970. host_and_port += std::to_string(PORT);
  4971. req.headers.emplace("Host", host_and_port.c_str());
  4972. req.headers.emplace("Accept", "*/*");
  4973. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4974. req.headers.emplace("Content-Type", "text/plain");
  4975. req.headers.emplace("Content-Length", "0");
  4976. req.headers.emplace(
  4977. "Transfer-Encoding",
  4978. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4979. // Client does not chunk, so make a chunked body manually.
  4980. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4981. auto res = std::make_shared<Response>();
  4982. auto error = Error::Success;
  4983. auto ret = cli_.send(req, *res, error);
  4984. ASSERT_TRUE(ret);
  4985. EXPECT_EQ(StatusCode::OK_200, res->status);
  4986. }
  4987. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4988. // rather than treat them as valid lengths.
  4989. template <typename ClientT>
  4990. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4991. Request req;
  4992. req.method = "POST";
  4993. req.path = "/chunked";
  4994. std::string host_and_port;
  4995. host_and_port += HOST;
  4996. host_and_port += ":";
  4997. host_and_port += std::to_string(PORT);
  4998. req.headers.emplace("Host", host_and_port.c_str());
  4999. req.headers.emplace("Content-Length", "0");
  5000. req.headers.emplace("Transfer-Encoding", "chunked");
  5001. req.body = body;
  5002. auto res = std::make_shared<Response>();
  5003. auto error = Error::Success;
  5004. ASSERT_TRUE(cli.send(req, *res, error));
  5005. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5006. }
  5007. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5008. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5009. }
  5010. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5011. expect_chunked_body_rejected(
  5012. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5013. }
  5014. TEST_F(ServerTest, GetStreamed2) {
  5015. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5018. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5019. EXPECT_EQ(true, res->has_header("Content-Range"));
  5020. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5021. EXPECT_EQ(std::string("ab"), res->body);
  5022. }
  5023. TEST_F(ServerTest, GetStreamed) {
  5024. auto res = cli_.Get("/streamed");
  5025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5026. EXPECT_EQ(StatusCode::OK_200, res->status);
  5027. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5028. EXPECT_EQ(std::string("aaabbb"), res->body);
  5029. }
  5030. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5031. auto res = cli_.Get("/streamed-without-length",
  5032. Headers{make_range_header({{0, -1}})});
  5033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ(false, res->has_header("Content-Length"));
  5036. EXPECT_EQ(false, res->has_header("Content-Range"));
  5037. EXPECT_EQ(std::string("abcdefg"), res->body);
  5038. }
  5039. TEST_F(ServerTest, GetStreamedWithRange1) {
  5040. auto res =
  5041. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  5042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5043. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5044. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5045. EXPECT_EQ(true, res->has_header("Content-Range"));
  5046. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5047. EXPECT_EQ(std::string("def"), res->body);
  5048. }
  5049. TEST_F(ServerTest, GetStreamedWithRange2) {
  5050. auto res =
  5051. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  5052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5053. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5054. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5055. EXPECT_EQ(true, res->has_header("Content-Range"));
  5056. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5057. EXPECT_EQ(std::string("bcdefg"), res->body);
  5058. }
  5059. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  5060. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  5061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5063. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5064. EXPECT_EQ(true, res->has_header("Content-Range"));
  5065. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  5066. EXPECT_EQ(std::string("efg"), res->body);
  5067. }
  5068. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  5069. auto res =
  5070. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  5071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5072. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5073. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5074. EXPECT_EQ(false, res->has_header("Content-Range"));
  5075. EXPECT_EQ(0U, res->body.size());
  5076. }
  5077. TEST_F(ServerTest, GetStreamedWithRangeError) {
  5078. auto res =
  5079. cli_.Get("/streamed-with-range",
  5080. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  5081. "92233720368547758079223372036854775807"}});
  5082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5083. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5084. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5085. EXPECT_EQ(false, res->has_header("Content-Range"));
  5086. EXPECT_EQ(0U, res->body.size());
  5087. }
  5088. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  5089. auto res = cli_.Get(
  5090. "/with-range",
  5091. Headers{{"Range",
  5092. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  5093. {"Accept-Encoding", ""}});
  5094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5095. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5096. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5097. EXPECT_EQ(true, res->has_header("Content-Range"));
  5098. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5099. EXPECT_EQ(std::string("abcdefg"), res->body);
  5100. }
  5101. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  5102. auto res = cli_.Get("/with-range", Headers{
  5103. {"Range", "bytes=0-"},
  5104. {"Accept-Encoding", ""},
  5105. });
  5106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5107. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5108. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  5109. EXPECT_EQ(true, res->has_header("Content-Range"));
  5110. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  5111. EXPECT_EQ(std::string("abcdefg"), res->body);
  5112. }
  5113. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  5114. auto res = cli_.Get("/streamed-with-range",
  5115. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5117. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5118. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5119. EXPECT_EQ(false, res->has_header("Content-Range"));
  5120. EXPECT_EQ(267U, res->body.size());
  5121. // Check that both range contents are present
  5122. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  5123. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5124. // Check that Content-Range headers are present for both ranges
  5125. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  5126. std::string::npos);
  5127. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5128. std::string::npos);
  5129. }
  5130. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  5131. Ranges ranges;
  5132. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  5133. ranges.emplace_back(0, -1);
  5134. }
  5135. auto res = cli_.Get("/streamed-with-range?error",
  5136. Headers{{make_range_header(ranges)}});
  5137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5140. EXPECT_EQ(false, res->has_header("Content-Range"));
  5141. EXPECT_EQ(0U, res->body.size());
  5142. }
  5143. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  5144. auto res = cli_.Get("/streamed-with-range",
  5145. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  5146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5147. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5148. EXPECT_EQ(5U, res->body.size());
  5149. // Check that overlapping ranges are coalesced into a single range
  5150. EXPECT_EQ("bcdef", res->body);
  5151. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  5152. // Should be single range, not multipart
  5153. EXPECT_TRUE(res->has_header("Content-Range"));
  5154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5155. }
  5156. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  5157. auto res = cli_.Get("/streamed-with-range",
  5158. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  5159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5160. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5161. EXPECT_EQ(268U, res->body.size());
  5162. // Check that both range contents are present
  5163. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  5164. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  5165. // Check that Content-Range headers are present for both ranges
  5166. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  5167. std::string::npos);
  5168. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  5169. std::string::npos);
  5170. }
  5171. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  5172. auto res = cli_.Get("/streamed-with-range",
  5173. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  5174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5176. EXPECT_EQ(269U, res->body.size());
  5177. // Check that both duplicate range contents are present
  5178. size_t first_abc = res->body.find("abc\r\n");
  5179. EXPECT_TRUE(first_abc != std::string::npos);
  5180. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  5181. EXPECT_TRUE(second_abc != std::string::npos);
  5182. // Check that Content-Range headers are present for both ranges
  5183. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  5184. EXPECT_TRUE(first_range != std::string::npos);
  5185. size_t second_range =
  5186. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  5187. EXPECT_TRUE(second_range != std::string::npos);
  5188. }
  5189. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  5190. auto res =
  5191. cli_.Get("/streamed-with-range?error",
  5192. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  5193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5194. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5195. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  5196. EXPECT_EQ(false, res->has_header("Content-Range"));
  5197. EXPECT_EQ(0U, res->body.size());
  5198. }
  5199. TEST_F(ServerTest, GetStreamedEndless) {
  5200. uint64_t offset = 0;
  5201. auto res = cli_.Get("/streamed-cancel",
  5202. [&](const char * /*data*/, uint64_t data_length) {
  5203. if (offset < 100) {
  5204. offset += data_length;
  5205. return true;
  5206. }
  5207. return false;
  5208. });
  5209. ASSERT_TRUE(!res);
  5210. EXPECT_EQ(Error::Canceled, res.error());
  5211. }
  5212. TEST_F(ServerTest, ClientStop) {
  5213. std::atomic_size_t count{4};
  5214. std::vector<std::thread> threads;
  5215. for (auto i = count.load(); i != 0; --i) {
  5216. threads.emplace_back([&]() {
  5217. auto res = cli_.Get("/streamed-cancel",
  5218. [&](const char *, uint64_t) { return true; });
  5219. --count;
  5220. ASSERT_TRUE(!res);
  5221. EXPECT_TRUE(res.error() == Error::Canceled ||
  5222. res.error() == Error::Read || res.error() == Error::Write);
  5223. });
  5224. }
  5225. std::this_thread::sleep_for(std::chrono::seconds(2));
  5226. while (count != 0) {
  5227. cli_.stop();
  5228. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  5229. }
  5230. for (auto &t : threads) {
  5231. t.join();
  5232. }
  5233. }
  5234. TEST_F(ServerTest, GetWithRange1) {
  5235. auto res = cli_.Get("/with-range", Headers{
  5236. make_range_header({{3, 5}}),
  5237. {"Accept-Encoding", ""},
  5238. });
  5239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5241. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  5242. EXPECT_EQ(true, res->has_header("Content-Range"));
  5243. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  5244. EXPECT_EQ(std::string("def"), res->body);
  5245. }
  5246. TEST_F(ServerTest, GetWithRange2) {
  5247. auto res = cli_.Get("/with-range", Headers{
  5248. make_range_header({{1, -1}}),
  5249. {"Accept-Encoding", ""},
  5250. });
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5253. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5254. EXPECT_EQ(true, res->has_header("Content-Range"));
  5255. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  5256. EXPECT_EQ(std::string("bcdefg"), res->body);
  5257. }
  5258. TEST_F(ServerTest, GetWithRange3) {
  5259. auto res = cli_.Get("/with-range", Headers{
  5260. make_range_header({{0, 0}}),
  5261. {"Accept-Encoding", ""},
  5262. });
  5263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5264. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5265. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  5266. EXPECT_EQ(true, res->has_header("Content-Range"));
  5267. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  5268. EXPECT_EQ(std::string("a"), res->body);
  5269. }
  5270. TEST_F(ServerTest, GetWithRange4) {
  5271. auto res = cli_.Get("/with-range", Headers{
  5272. make_range_header({{-1, 2}}),
  5273. {"Accept-Encoding", ""},
  5274. });
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5277. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5278. EXPECT_EQ(true, res->has_header("Content-Range"));
  5279. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  5280. EXPECT_EQ(std::string("fg"), res->body);
  5281. }
  5282. TEST_F(ServerTest, GetWithRange5) {
  5283. auto res = cli_.Get("/with-range", Headers{
  5284. make_range_header({{0, 5}}),
  5285. {"Accept-Encoding", ""},
  5286. });
  5287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5288. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5289. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ(true, res->has_header("Content-Range"));
  5291. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  5292. EXPECT_EQ(std::string("abcdef"), res->body);
  5293. }
  5294. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  5295. auto res =
  5296. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5299. }
  5300. TEST_F(ServerTest, GetWithRangeMultipart) {
  5301. auto res =
  5302. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5305. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  5306. EXPECT_EQ(false, res->has_header("Content-Range"));
  5307. EXPECT_EQ(267U, res->body.size());
  5308. }
  5309. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  5310. auto res = cli_.Get("/with-range",
  5311. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  5312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5313. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  5314. }
  5315. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  5316. auto res = cli_.Get("/with-range-customized-response",
  5317. Headers{{make_range_header({{1, 2}})}});
  5318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5319. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5320. EXPECT_EQ(true, res->has_header("Content-Length"));
  5321. EXPECT_EQ(false, res->has_header("Content-Range"));
  5322. EXPECT_EQ(JSON_DATA, res->body);
  5323. }
  5324. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  5325. auto res = cli_.Get("/with-range-customized-response",
  5326. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5329. EXPECT_EQ(true, res->has_header("Content-Length"));
  5330. EXPECT_EQ(false, res->has_header("Content-Range"));
  5331. EXPECT_EQ(JSON_DATA, res->body);
  5332. }
  5333. TEST_F(ServerTest, Issue1772) {
  5334. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  5337. }
  5338. TEST_F(ServerTest, Issue609) {
  5339. auto res = cli_.Delete("/issue609");
  5340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5341. EXPECT_EQ(StatusCode::OK_200, res->status);
  5342. EXPECT_EQ(std::string("ok"), res->body);
  5343. }
  5344. TEST_F(ServerTest, GetStreamedChunked) {
  5345. auto res = cli_.Get("/streamed-chunked");
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. EXPECT_EQ(std::string("123456789"), res->body);
  5349. }
  5350. TEST_F(ServerTest, GetStreamedChunked2) {
  5351. auto res = cli_.Get("/streamed-chunked2");
  5352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. EXPECT_EQ(std::string("123456789"), res->body);
  5355. }
  5356. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  5357. auto res = cli_.Get("/streamed-chunked-with-trailer");
  5358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5359. EXPECT_EQ(StatusCode::OK_200, res->status);
  5360. EXPECT_EQ(std::string("123456789"), res->body);
  5361. EXPECT_TRUE(res->has_header("Trailer"));
  5362. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  5363. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  5364. // Trailers are now stored separately from headers (security fix)
  5365. EXPECT_EQ(2U, res->trailers.size());
  5366. EXPECT_TRUE(res->has_trailer("Dummy1"));
  5367. EXPECT_TRUE(res->has_trailer("Dummy2"));
  5368. EXPECT_FALSE(res->has_trailer("Dummy3"));
  5369. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  5370. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  5371. // Verify trailers are NOT in headers (security verification)
  5372. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  5373. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  5374. }
  5375. TEST_F(ServerTest, LargeChunkedPost) {
  5376. Request req;
  5377. req.method = "POST";
  5378. req.path = "/large-chunked";
  5379. std::string host_and_port;
  5380. host_and_port += HOST;
  5381. host_and_port += ":";
  5382. host_and_port += std::to_string(PORT);
  5383. req.headers.emplace("Host", host_and_port.c_str());
  5384. req.headers.emplace("Accept", "*/*");
  5385. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5386. req.headers.emplace("Content-Type", "text/plain");
  5387. req.headers.emplace("Content-Length", "0");
  5388. req.headers.emplace("Transfer-Encoding", "chunked");
  5389. std::string long_string(30 * 1024u, 'a');
  5390. std::string chunk = "7800\r\n" + long_string + "\r\n";
  5391. // Attempt to make a large enough post to exceed OS buffers, to test that
  5392. // the server handles short reads if the full chunk data isn't available.
  5393. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  5394. auto res = std::make_shared<Response>();
  5395. auto error = Error::Success;
  5396. auto ret = cli_.send(req, *res, error);
  5397. ASSERT_TRUE(ret);
  5398. EXPECT_EQ(StatusCode::OK_200, res->status);
  5399. }
  5400. TEST_F(ServerTest, GetMethodRemoteAddr) {
  5401. auto res = cli_.Get("/remote_addr");
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5405. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  5406. }
  5407. TEST_F(ServerTest, GetMethodLocalAddr) {
  5408. auto res = cli_.Get("/local_addr");
  5409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5410. EXPECT_EQ(StatusCode::OK_200, res->status);
  5411. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5412. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  5413. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  5414. }
  5415. TEST_F(ServerTest, HTTPResponseSplitting) {
  5416. auto res = cli_.Get("/http_response_splitting");
  5417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5418. EXPECT_EQ(StatusCode::OK_200, res->status);
  5419. }
  5420. TEST_F(ServerTest, SlowRequest) {
  5421. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5422. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5423. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  5424. }
  5425. #if 0
  5426. TEST_F(ServerTest, SlowPost) {
  5427. char buffer[64 * 1024];
  5428. memset(buffer, 0x42, sizeof(buffer));
  5429. auto res = cli_.Post(
  5430. "/slowpost", 64 * 1024 * 1024,
  5431. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5432. auto ret = sink.write(buffer, sizeof(buffer));
  5433. EXPECT_TRUE(ret);
  5434. return true;
  5435. },
  5436. "text/plain");
  5437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5438. EXPECT_EQ(StatusCode::OK_200, res->status);
  5439. }
  5440. TEST_F(ServerTest, SlowPostFail) {
  5441. char buffer[64 * 1024];
  5442. memset(buffer, 0x42, sizeof(buffer));
  5443. cli_.set_write_timeout(std::chrono::seconds(0));
  5444. auto res = cli_.Post(
  5445. "/slowpost", 64 * 1024 * 1024,
  5446. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5447. sink.write(buffer, sizeof(buffer));
  5448. return true;
  5449. },
  5450. "text/plain");
  5451. ASSERT_TRUE(!res);
  5452. EXPECT_EQ(Error::Write, res.error());
  5453. }
  5454. #endif
  5455. TEST_F(ServerTest, Put) {
  5456. auto res = cli_.Put("/put", "PUT", "text/plain");
  5457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5458. EXPECT_EQ(StatusCode::OK_200, res->status);
  5459. EXPECT_EQ("PUT", res->body);
  5460. }
  5461. TEST_F(ServerTest, PutWithContentProvider) {
  5462. auto res = cli_.Put(
  5463. "/put", 3,
  5464. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5465. sink.os << "PUT";
  5466. return true;
  5467. },
  5468. "text/plain");
  5469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5470. EXPECT_EQ(StatusCode::OK_200, res->status);
  5471. EXPECT_EQ("PUT", res->body);
  5472. }
  5473. TEST_F(ServerTest, PostWithContentProviderAbort) {
  5474. auto res = cli_.Post(
  5475. "/post", 42,
  5476. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5477. return false;
  5478. },
  5479. "text/plain");
  5480. ASSERT_TRUE(!res);
  5481. EXPECT_EQ(Error::Canceled, res.error());
  5482. }
  5483. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  5484. auto res = cli_.Put(
  5485. "/put",
  5486. [](size_t /*offset*/, DataSink &sink) {
  5487. sink.os << "PUT";
  5488. sink.done();
  5489. return true;
  5490. },
  5491. "text/plain");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::OK_200, res->status);
  5494. EXPECT_EQ("PUT", res->body);
  5495. }
  5496. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  5497. auto res = cli_.Post(
  5498. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5499. "text/plain");
  5500. ASSERT_TRUE(!res);
  5501. EXPECT_EQ(Error::Canceled, res.error());
  5502. }
  5503. TEST_F(ServerTest, PostLoopBack) {
  5504. std::string body;
  5505. auto res = cli_.Post(
  5506. "/post-loopback", 9,
  5507. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5508. EXPECT_EQ(9u, length);
  5509. sink.write("123", 3);
  5510. sink.write("456", 3);
  5511. sink.write("789", 3);
  5512. return true;
  5513. },
  5514. "text/plain",
  5515. [&body](const char *data, size_t data_length) {
  5516. body.append(data, data_length);
  5517. return true;
  5518. });
  5519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. EXPECT_EQ("123456789", body);
  5522. }
  5523. TEST_F(ServerTest, PutLoopBack) {
  5524. std::string body;
  5525. auto res = cli_.Put(
  5526. "/put-loopback", 9,
  5527. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5528. EXPECT_EQ(9u, length);
  5529. sink.write("123", 3);
  5530. sink.write("456", 3);
  5531. sink.write("789", 3);
  5532. return true;
  5533. },
  5534. "text/plain",
  5535. [&body](const char *data, size_t data_length) {
  5536. body.append(data, data_length);
  5537. return true;
  5538. });
  5539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5540. EXPECT_EQ(StatusCode::OK_200, res->status);
  5541. EXPECT_EQ("123456789", body);
  5542. }
  5543. TEST_F(ServerTest, PatchLoopBack) {
  5544. std::string body;
  5545. auto res = cli_.Patch(
  5546. "/patch-loopback", 9,
  5547. [](size_t /*offset*/, size_t length, DataSink &sink) {
  5548. EXPECT_EQ(9u, length);
  5549. sink.write("123", 3);
  5550. sink.write("456", 3);
  5551. sink.write("789", 3);
  5552. return true;
  5553. },
  5554. "text/plain",
  5555. [&body](const char *data, size_t data_length) {
  5556. body.append(data, data_length);
  5557. return true;
  5558. });
  5559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5560. EXPECT_EQ(StatusCode::OK_200, res->status);
  5561. EXPECT_EQ("123456789", body);
  5562. }
  5563. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  5564. std::string body;
  5565. auto res = cli_.Post(
  5566. "/post-loopback",
  5567. [](size_t /*offset*/, DataSink &sink) {
  5568. sink.write("123", 3);
  5569. sink.write("456", 3);
  5570. sink.write("789", 3);
  5571. sink.done();
  5572. return true;
  5573. },
  5574. "text/plain",
  5575. [&body](const char *data, size_t data_length) {
  5576. body.append(data, data_length);
  5577. return true;
  5578. });
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. EXPECT_EQ(StatusCode::OK_200, res->status);
  5581. EXPECT_EQ("123456789", body);
  5582. }
  5583. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5584. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5585. cli_.set_compress(true);
  5586. auto res = cli_.Put(
  5587. "/put", 3,
  5588. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5589. sink.os << "PUT";
  5590. return true;
  5591. },
  5592. "text/plain");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. EXPECT_EQ(StatusCode::OK_200, res->status);
  5595. EXPECT_EQ("PUT", res->body);
  5596. }
  5597. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5598. cli_.set_compress(true);
  5599. auto res = cli_.Post(
  5600. "/post", 42,
  5601. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5602. return false;
  5603. },
  5604. "text/plain");
  5605. ASSERT_TRUE(!res);
  5606. EXPECT_EQ(Error::Canceled, res.error());
  5607. }
  5608. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5609. cli_.set_compress(true);
  5610. auto res = cli_.Put(
  5611. "/put",
  5612. [](size_t /*offset*/, DataSink &sink) {
  5613. sink.os << "PUT";
  5614. sink.done();
  5615. return true;
  5616. },
  5617. "text/plain");
  5618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. EXPECT_EQ("PUT", res->body);
  5621. }
  5622. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5623. cli_.set_compress(true);
  5624. auto res = cli_.Post(
  5625. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5626. "text/plain");
  5627. ASSERT_TRUE(!res);
  5628. EXPECT_EQ(Error::Canceled, res.error());
  5629. }
  5630. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5631. cli_.set_compress(true);
  5632. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. EXPECT_EQ(StatusCode::OK_200, res->status);
  5635. EXPECT_EQ(LARGE_DATA, res->body);
  5636. }
  5637. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5638. #ifdef CPPHTTPLIB_SSL_ENABLED
  5639. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5640. Client cli(s.c_str());
  5641. cli.enable_server_certificate_verification(false);
  5642. #else
  5643. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5644. Client cli(s.c_str());
  5645. #endif
  5646. cli.set_compress(true);
  5647. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5649. EXPECT_EQ(StatusCode::OK_200, res->status);
  5650. EXPECT_EQ(LARGE_DATA, res->body);
  5651. // The compressed size should be less than a 10th of the original. May vary
  5652. // depending on the zlib library.
  5653. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5654. static_cast<uint64_t>(10 * 1024 * 1024));
  5655. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5656. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5657. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5658. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5659. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5660. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5661. #endif
  5662. }
  5663. TEST_F(ServerTest, PutContentWithDeflate) {
  5664. cli_.set_compress(false);
  5665. Headers headers;
  5666. headers.emplace("Content-Encoding", "deflate");
  5667. // PUT in deflate format:
  5668. auto res = cli_.Put("/put", headers,
  5669. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::OK_200, res->status);
  5672. EXPECT_EQ("PUT", res->body);
  5673. }
  5674. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5675. Headers headers;
  5676. headers.emplace("Accept-Encoding", "gzip, deflate");
  5677. auto res = cli_.Get("/streamed-chunked", headers);
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. EXPECT_EQ(StatusCode::OK_200, res->status);
  5680. EXPECT_EQ(std::string("123456789"), res->body);
  5681. }
  5682. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5683. Headers headers;
  5684. headers.emplace("Accept-Encoding", "gzip, deflate");
  5685. auto res = cli_.Get("/streamed-chunked2", headers);
  5686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5687. EXPECT_EQ(StatusCode::OK_200, res->status);
  5688. EXPECT_EQ(std::string("123456789"), res->body);
  5689. }
  5690. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5691. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5693. EXPECT_EQ(StatusCode::OK_200, res->status);
  5694. }
  5695. TEST(GzipDecompressor, ChunkedDecompression) {
  5696. std::string data;
  5697. for (size_t i = 0; i < 32 * 1024; ++i) {
  5698. data.push_back(static_cast<char>('a' + i % 26));
  5699. }
  5700. std::string compressed_data;
  5701. {
  5702. httplib::detail::gzip_compressor compressor;
  5703. bool result = compressor.compress(
  5704. data.data(), data.size(),
  5705. /*last=*/true,
  5706. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5707. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5708. compressed_data_size);
  5709. return true;
  5710. });
  5711. ASSERT_TRUE(result);
  5712. }
  5713. std::string decompressed_data;
  5714. {
  5715. httplib::detail::gzip_decompressor decompressor;
  5716. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5717. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5718. size_t chunk_size = 130;
  5719. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5720. chunk_begin += chunk_size) {
  5721. size_t current_chunk_size =
  5722. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5723. bool result = decompressor.decompress(
  5724. compressed_data.data() + chunk_begin, current_chunk_size,
  5725. [&](const char *decompressed_data_chunk,
  5726. size_t decompressed_data_chunk_size) {
  5727. decompressed_data.insert(decompressed_data.size(),
  5728. decompressed_data_chunk,
  5729. decompressed_data_chunk_size);
  5730. return true;
  5731. });
  5732. ASSERT_TRUE(result);
  5733. }
  5734. }
  5735. ASSERT_EQ(data, decompressed_data);
  5736. }
  5737. TEST(GzipDecompressor, DeflateDecompression) {
  5738. std::string original_text = "Raw deflate without gzip";
  5739. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5740. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5741. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5742. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5743. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5744. std::string decompressed_data;
  5745. {
  5746. httplib::detail::gzip_decompressor decompressor;
  5747. bool result = decompressor.decompress(
  5748. compressed_data.data(), compressed_data.size(),
  5749. [&](const char *decompressed_data_chunk,
  5750. size_t decompressed_data_chunk_size) {
  5751. decompressed_data.insert(decompressed_data.size(),
  5752. decompressed_data_chunk,
  5753. decompressed_data_chunk_size);
  5754. return true;
  5755. });
  5756. ASSERT_TRUE(result);
  5757. }
  5758. ASSERT_EQ(original_text, decompressed_data);
  5759. }
  5760. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5761. std::string original_text = "Raw deflate without gzip";
  5762. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5763. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5764. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5765. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5766. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5767. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5768. std::string decompressed_data;
  5769. {
  5770. httplib::detail::gzip_decompressor decompressor;
  5771. bool result = decompressor.decompress(
  5772. compressed_data.data(), compressed_data.size(),
  5773. [&](const char *decompressed_data_chunk,
  5774. size_t decompressed_data_chunk_size) {
  5775. decompressed_data.insert(decompressed_data.size(),
  5776. decompressed_data_chunk,
  5777. decompressed_data_chunk_size);
  5778. return true;
  5779. });
  5780. ASSERT_TRUE(result);
  5781. }
  5782. ASSERT_EQ(original_text, decompressed_data);
  5783. }
  5784. #endif
  5785. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5786. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5787. Headers headers;
  5788. headers.emplace("Accept-Encoding", "br");
  5789. auto res = cli_.Get("/streamed-chunked", headers);
  5790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. EXPECT_EQ(std::string("123456789"), res->body);
  5793. }
  5794. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5795. Headers headers;
  5796. headers.emplace("Accept-Encoding", "br");
  5797. auto res = cli_.Get("/streamed-chunked2", headers);
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::OK_200, res->status);
  5800. EXPECT_EQ(std::string("123456789"), res->body);
  5801. }
  5802. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5803. cli_.set_compress(true);
  5804. auto res = cli_.Put(
  5805. "/put", 3,
  5806. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5807. sink.os << "PUT";
  5808. return true;
  5809. },
  5810. "text/plain");
  5811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5812. EXPECT_EQ(StatusCode::OK_200, res->status);
  5813. EXPECT_EQ("PUT", res->body);
  5814. }
  5815. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5816. cli_.set_compress(true);
  5817. auto res = cli_.Put(
  5818. "/put",
  5819. [](size_t /*offset*/, DataSink &sink) {
  5820. sink.os << "PUT";
  5821. sink.done();
  5822. return true;
  5823. },
  5824. "text/plain");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::OK_200, res->status);
  5827. EXPECT_EQ("PUT", res->body);
  5828. }
  5829. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5830. cli_.set_compress(true);
  5831. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::OK_200, res->status);
  5834. EXPECT_EQ(LARGE_DATA, res->body);
  5835. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5836. }
  5837. #endif
  5838. TEST_F(ServerTest, Patch) {
  5839. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5841. EXPECT_EQ(StatusCode::OK_200, res->status);
  5842. EXPECT_EQ("PATCH", res->body);
  5843. }
  5844. TEST_F(ServerTest, Delete) {
  5845. auto res = cli_.Delete("/delete");
  5846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5847. EXPECT_EQ(StatusCode::OK_200, res->status);
  5848. EXPECT_EQ("DELETE", res->body);
  5849. }
  5850. TEST_F(ServerTest, DeleteContentReceiver) {
  5851. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5853. EXPECT_EQ(StatusCode::OK_200, res->status);
  5854. EXPECT_EQ("content", res->body);
  5855. }
  5856. TEST_F(ServerTest, Options) {
  5857. auto res = cli_.Options("*");
  5858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5861. EXPECT_TRUE(res->body.empty());
  5862. }
  5863. TEST_F(ServerTest, URL) {
  5864. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5866. EXPECT_EQ(StatusCode::OK_200, res->status);
  5867. }
  5868. TEST_F(ServerTest, ArrayParam) {
  5869. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5871. EXPECT_EQ(StatusCode::OK_200, res->status);
  5872. }
  5873. TEST_F(ServerTest, ArrayParamValues) {
  5874. auto res =
  5875. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. EXPECT_EQ(StatusCode::OK_200, res->status);
  5878. }
  5879. TEST_F(ServerTest, NoMultipleHeaders) {
  5880. Headers headers = {{"Content-Length", "5"}};
  5881. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5882. "text/plain");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. EXPECT_EQ(StatusCode::OK_200, res->status);
  5885. }
  5886. TEST_F(ServerTest, PostContentReceiver) {
  5887. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5889. ASSERT_EQ(StatusCode::OK_200, res->status);
  5890. ASSERT_EQ("content", res->body);
  5891. }
  5892. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5893. UploadFormDataItems items = {
  5894. {"text1", "text default", "", ""},
  5895. {"text2", "aωb", "", ""},
  5896. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5897. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5898. {"file3", "", "", "application/octet-stream"},
  5899. };
  5900. auto res = cli_.Post("/content_receiver", items);
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. }
  5904. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5905. UploadFormDataItems items = {
  5906. {"text1", "text default", "", ""},
  5907. {"text2", "aωb", "", ""},
  5908. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5909. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5910. {"file3", "", "", "application/octet-stream"},
  5911. };
  5912. auto boundary = std::string("+++++");
  5913. std::string body;
  5914. for (const auto &item : items) {
  5915. body += "--" + boundary + "\r\n";
  5916. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5917. if (!item.filename.empty()) {
  5918. body += "; filename=\"" + item.filename + "\"";
  5919. }
  5920. body += "\r\n";
  5921. if (!item.content_type.empty()) {
  5922. body += "Content-Type: " + item.content_type + "\r\n";
  5923. }
  5924. body += "\r\n";
  5925. body += item.content + "\r\n";
  5926. }
  5927. body += "--" + boundary + "--\r\n";
  5928. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5929. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. EXPECT_EQ(StatusCode::OK_200, res->status);
  5932. }
  5933. TEST(MultipartFormDataTest, FieldEscaping) {
  5934. Server svr;
  5935. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5936. const ContentReader &content_reader) {
  5937. ASSERT_TRUE(req.is_multipart_form_data());
  5938. std::vector<FormData> received;
  5939. content_reader(
  5940. [&](const FormData &file) {
  5941. received.push_back(file);
  5942. return true;
  5943. },
  5944. [&](const char *data, size_t data_length) {
  5945. received.back().content.append(data, data_length);
  5946. return true;
  5947. });
  5948. // '"', CR and LF in names and filenames are escaped following the
  5949. // WHATWG HTML standard, so each part still parses as a single part
  5950. // with no injected headers. Content types get CR/LF escaped too,
  5951. // while '"' (legal there, e.g. quoted charset) is preserved.
  5952. ASSERT_EQ(4U, received.size());
  5953. EXPECT_EQ("na%22me", received[0].name);
  5954. EXPECT_EQ("quoted name", received[0].content);
  5955. EXPECT_EQ("file", received[1].name);
  5956. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  5957. received[1].filename);
  5958. EXPECT_EQ("application/octet-stream", received[1].content_type);
  5959. EXPECT_EQ("injected", received[1].content);
  5960. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  5961. EXPECT_EQ("my%22file.txt", received[2].filename);
  5962. EXPECT_EQ("cr lf name", received[2].content);
  5963. EXPECT_EQ("typed", received[3].name);
  5964. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  5965. received[3].content_type);
  5966. EXPECT_EQ("typed content", received[3].content);
  5967. });
  5968. auto port = svr.bind_to_any_port("localhost");
  5969. auto t = std::thread([&]() { svr.listen_after_bind(); });
  5970. auto se = detail::scope_exit([&] {
  5971. svr.stop();
  5972. t.join();
  5973. ASSERT_FALSE(svr.is_running());
  5974. });
  5975. svr.wait_until_ready();
  5976. Client cli("localhost", port);
  5977. UploadFormDataItems items = {
  5978. {"na\"me", "quoted name", "", ""},
  5979. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  5980. "application/octet-stream"},
  5981. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  5982. {"typed", "typed content", "",
  5983. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  5984. };
  5985. auto res = cli.Post("/post", items);
  5986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5987. EXPECT_EQ(StatusCode::OK_200, res->status);
  5988. }
  5989. TEST(MultipartFormDataTest, PublicWriterAPI) {
  5990. const UploadFormDataItems items = {
  5991. {"name1", "Content 1", "", ""},
  5992. {"name2", "Content 2", "file2.txt", "text/plain"},
  5993. };
  5994. Server svr;
  5995. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5996. const ContentReader &content_reader) {
  5997. ASSERT_TRUE(req.is_multipart_form_data());
  5998. std::vector<FormData> received;
  5999. content_reader(
  6000. [&](const FormData &file) {
  6001. received.push_back(file);
  6002. return true;
  6003. },
  6004. [&](const char *data, size_t data_length) {
  6005. received.back().content.append(data, data_length);
  6006. return true;
  6007. });
  6008. ASSERT_EQ(2U, received.size());
  6009. EXPECT_EQ("name1", received[0].name);
  6010. EXPECT_EQ("Content 1", received[0].content);
  6011. EXPECT_EQ("name2", received[1].name);
  6012. EXPECT_EQ("Content 2", received[1].content);
  6013. EXPECT_EQ("file2.txt", received[1].filename);
  6014. EXPECT_EQ("text/plain", received[1].content_type);
  6015. });
  6016. auto port = svr.bind_to_any_port("localhost");
  6017. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6018. auto se = detail::scope_exit([&] {
  6019. svr.stop();
  6020. t.join();
  6021. ASSERT_FALSE(svr.is_running());
  6022. });
  6023. svr.wait_until_ready();
  6024. Client cli("localhost", port);
  6025. // Whole-body serialization with a generated boundary
  6026. {
  6027. MultipartFormDataWriter writer;
  6028. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  6029. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  6030. writer.content_type());
  6031. auto body = writer.serialize(items);
  6032. EXPECT_EQ(body.size(), writer.content_length(items));
  6033. auto res = cli.Post("/post", body, writer.content_type());
  6034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. }
  6037. // Per-part framing with a custom boundary via a content provider
  6038. {
  6039. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  6040. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  6041. MultipartFormDataWriter writer("custom-boundary_123");
  6042. EXPECT_EQ("custom-boundary_123", writer.boundary());
  6043. std::string body;
  6044. for (const auto &item : items) {
  6045. body += writer.item_begin(item);
  6046. body += item.content;
  6047. body += MultipartFormDataWriter::item_end();
  6048. }
  6049. body += writer.finish();
  6050. EXPECT_EQ(body.size(), writer.content_length(items));
  6051. auto res = cli.Post(
  6052. "/post", body.size(),
  6053. [&](size_t offset, size_t length, DataSink &sink) {
  6054. sink.write(body.data() + offset, length);
  6055. return true;
  6056. },
  6057. writer.content_type());
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. }
  6061. }
  6062. TEST_F(ServerTest, PostContentReceiverGzip) {
  6063. cli_.set_compress(true);
  6064. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. ASSERT_EQ(StatusCode::OK_200, res->status);
  6067. ASSERT_EQ("content", res->body);
  6068. }
  6069. TEST_F(ServerTest, PutContentReceiver) {
  6070. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. ASSERT_EQ(StatusCode::OK_200, res->status);
  6073. ASSERT_EQ("content", res->body);
  6074. }
  6075. TEST_F(ServerTest, PatchContentReceiver) {
  6076. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  6077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6078. ASSERT_EQ(StatusCode::OK_200, res->status);
  6079. ASSERT_EQ("content", res->body);
  6080. }
  6081. template <typename ClientType>
  6082. void TestWithHeadersAndContentReceiver(
  6083. ClientType &cli,
  6084. std::function<Result(ClientType &, const std::string &, const Headers &,
  6085. const std::string &, const std::string &,
  6086. ContentReceiver, DownloadProgress)>
  6087. request_func) {
  6088. Headers headers;
  6089. headers.emplace("X-Custom-Header", "test-value");
  6090. std::string received_body;
  6091. auto res = request_func(
  6092. cli, "/content_receiver", headers, "content", "application/json",
  6093. [&](const char *data, size_t data_length) {
  6094. received_body.append(data, data_length);
  6095. return true;
  6096. },
  6097. nullptr);
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("content", received_body);
  6101. }
  6102. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  6103. #ifdef CPPHTTPLIB_SSL_ENABLED
  6104. using ClientT = SSLClient;
  6105. #else
  6106. using ClientT = Client;
  6107. #endif
  6108. TestWithHeadersAndContentReceiver<ClientT>(
  6109. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6110. const std::string &body, const std::string &content_type,
  6111. ContentReceiver receiver, DownloadProgress progress) {
  6112. return cli.Post(path, headers, body, content_type, receiver, progress);
  6113. });
  6114. }
  6115. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  6116. #ifdef CPPHTTPLIB_SSL_ENABLED
  6117. using ClientT = SSLClient;
  6118. #else
  6119. using ClientT = Client;
  6120. #endif
  6121. TestWithHeadersAndContentReceiver<ClientT>(
  6122. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6123. const std::string &body, const std::string &content_type,
  6124. ContentReceiver receiver, DownloadProgress progress) {
  6125. return cli.Put(path, headers, body, content_type, receiver, progress);
  6126. });
  6127. }
  6128. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  6129. #ifdef CPPHTTPLIB_SSL_ENABLED
  6130. using ClientT = SSLClient;
  6131. #else
  6132. using ClientT = Client;
  6133. #endif
  6134. TestWithHeadersAndContentReceiver<ClientT>(
  6135. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6136. const std::string &body, const std::string &content_type,
  6137. ContentReceiver receiver, DownloadProgress progress) {
  6138. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6139. });
  6140. }
  6141. template <typename ClientType>
  6142. void TestWithHeadersAndContentReceiverWithProgress(
  6143. ClientType &cli,
  6144. std::function<Result(ClientType &, const std::string &, const Headers &,
  6145. const std::string &, const std::string &,
  6146. ContentReceiver, DownloadProgress)>
  6147. request_func) {
  6148. Headers headers;
  6149. headers.emplace("X-Test-Header", "progress-test");
  6150. std::string received_body;
  6151. auto progress_called = false;
  6152. auto res = request_func(
  6153. cli, "/content_receiver", headers, "content", "text/plain",
  6154. [&](const char *data, size_t data_length) {
  6155. received_body.append(data, data_length);
  6156. return true;
  6157. },
  6158. [&](uint64_t /*current*/, uint64_t /*total*/) {
  6159. progress_called = true;
  6160. return true;
  6161. });
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::OK_200, res->status);
  6164. EXPECT_EQ("content", received_body);
  6165. EXPECT_TRUE(progress_called);
  6166. }
  6167. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  6168. #ifdef CPPHTTPLIB_SSL_ENABLED
  6169. using ClientT = SSLClient;
  6170. #else
  6171. using ClientT = Client;
  6172. #endif
  6173. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6174. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6175. const std::string &body, const std::string &content_type,
  6176. ContentReceiver receiver, DownloadProgress progress) {
  6177. return cli.Post(path, headers, body, content_type, receiver, progress);
  6178. });
  6179. }
  6180. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  6181. #ifdef CPPHTTPLIB_SSL_ENABLED
  6182. using ClientT = SSLClient;
  6183. #else
  6184. using ClientT = Client;
  6185. #endif
  6186. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6187. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6188. const std::string &body, const std::string &content_type,
  6189. ContentReceiver receiver, DownloadProgress progress) {
  6190. return cli.Put(path, headers, body, content_type, receiver, progress);
  6191. });
  6192. }
  6193. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  6194. #ifdef CPPHTTPLIB_SSL_ENABLED
  6195. using ClientT = SSLClient;
  6196. #else
  6197. using ClientT = Client;
  6198. #endif
  6199. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  6200. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6201. const std::string &body, const std::string &content_type,
  6202. ContentReceiver receiver, DownloadProgress progress) {
  6203. return cli.Patch(path, headers, body, content_type, receiver, progress);
  6204. });
  6205. }
  6206. template <typename ClientType>
  6207. void TestWithHeadersAndContentReceiverError(
  6208. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  6209. const Headers &, const std::string &,
  6210. const std::string &, ContentReceiver)>
  6211. request_func) {
  6212. Headers headers;
  6213. headers.emplace("X-Error-Test", "true");
  6214. std::string received_body;
  6215. auto receiver_failed = false;
  6216. auto res =
  6217. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  6218. [&](const char *data, size_t data_length) {
  6219. received_body.append(data, data_length);
  6220. receiver_failed = true;
  6221. return false;
  6222. });
  6223. ASSERT_FALSE(res);
  6224. EXPECT_TRUE(receiver_failed);
  6225. }
  6226. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  6227. #ifdef CPPHTTPLIB_SSL_ENABLED
  6228. using ClientT = SSLClient;
  6229. #else
  6230. using ClientT = Client;
  6231. #endif
  6232. TestWithHeadersAndContentReceiverError<ClientT>(
  6233. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6234. const std::string &body, const std::string &content_type,
  6235. ContentReceiver receiver) {
  6236. return cli.Post(path, headers, body, content_type, receiver);
  6237. });
  6238. }
  6239. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  6240. #ifdef CPPHTTPLIB_SSL_ENABLED
  6241. using ClientT = SSLClient;
  6242. #else
  6243. using ClientT = Client;
  6244. #endif
  6245. TestWithHeadersAndContentReceiverError<ClientT>(
  6246. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6247. const std::string &body, const std::string &content_type,
  6248. ContentReceiver receiver) {
  6249. return cli.Put(path, headers, body, content_type, receiver);
  6250. });
  6251. }
  6252. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  6253. #ifdef CPPHTTPLIB_SSL_ENABLED
  6254. using ClientT = SSLClient;
  6255. #else
  6256. using ClientT = Client;
  6257. #endif
  6258. TestWithHeadersAndContentReceiverError<ClientT>(
  6259. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  6260. const std::string &body, const std::string &content_type,
  6261. ContentReceiver receiver) {
  6262. return cli.Patch(path, headers, body, content_type, receiver);
  6263. });
  6264. }
  6265. TEST_F(ServerTest, PostQueryStringAndBody) {
  6266. auto res =
  6267. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. ASSERT_EQ(StatusCode::OK_200, res->status);
  6270. }
  6271. TEST_F(ServerTest, HTTP2Magic) {
  6272. Request req;
  6273. req.method = "PRI";
  6274. req.path = "*";
  6275. req.body = "SM";
  6276. auto res = std::make_shared<Response>();
  6277. auto error = Error::Success;
  6278. auto ret = cli_.send(req, *res, error);
  6279. ASSERT_TRUE(ret);
  6280. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6281. }
  6282. TEST_F(ServerTest, KeepAlive) {
  6283. auto res = cli_.Get("/hi");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::OK_200, res->status);
  6286. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6287. EXPECT_EQ("Hello World!", res->body);
  6288. res = cli_.Get("/hi");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6292. EXPECT_EQ("Hello World!", res->body);
  6293. res = cli_.Get("/hi");
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::OK_200, res->status);
  6296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6297. EXPECT_EQ("Hello World!", res->body);
  6298. res = cli_.Get("/not-exist");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6301. res = cli_.Post("/empty", "", "text/plain");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::OK_200, res->status);
  6304. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6305. EXPECT_EQ("empty", res->body);
  6306. EXPECT_EQ("close", res->get_header_value("Connection"));
  6307. res = cli_.Post(
  6308. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  6309. "text/plain");
  6310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6311. EXPECT_EQ(StatusCode::OK_200, res->status);
  6312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6313. EXPECT_EQ("empty", res->body);
  6314. cli_.set_keep_alive(false);
  6315. res = cli_.Get("/last-request");
  6316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6317. EXPECT_EQ(StatusCode::OK_200, res->status);
  6318. EXPECT_EQ("close", res->get_header_value("Connection"));
  6319. }
  6320. TEST_F(ServerTest, TooManyRedirect) {
  6321. cli_.set_follow_location(true);
  6322. auto res = cli_.Get("/redirect/0");
  6323. ASSERT_TRUE(!res);
  6324. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  6325. }
  6326. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  6327. Request req;
  6328. req.method = "FOOBAR";
  6329. req.path = "/hi";
  6330. cli_.set_keep_alive(true);
  6331. auto res = cli_.send(req);
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6334. EXPECT_EQ("close", res->get_header_value("Connection"));
  6335. EXPECT_FALSE(cli_.is_socket_open());
  6336. }
  6337. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  6338. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6339. TEST_F(ServerTest, Gzip) {
  6340. Headers headers;
  6341. headers.emplace("Accept-Encoding", "gzip, deflate");
  6342. auto res = cli_.Get("/compress", headers);
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6346. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6348. "7890123456789012345678901234567890",
  6349. res->body);
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. }
  6352. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  6353. Headers headers;
  6354. headers.emplace("Accept-Encoding", "gzip, deflate");
  6355. auto res = cli_.Get("/compress-with-charset", headers);
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6358. EXPECT_EQ("application/json; charset=utf-8",
  6359. res->get_header_value("Content-Type"));
  6360. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6361. "7890123456789012345678901234567890",
  6362. res->body);
  6363. EXPECT_EQ(StatusCode::OK_200, res->status);
  6364. }
  6365. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  6366. Headers headers;
  6367. headers.emplace("Accept-Encoding", "");
  6368. auto res = cli_.Get("/compress", headers);
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6372. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6373. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6374. "7890123456789012345678901234567890",
  6375. res->body);
  6376. EXPECT_EQ(StatusCode::OK_200, res->status);
  6377. }
  6378. TEST_F(ServerTest, GzipWithContentReceiver) {
  6379. Headers headers;
  6380. headers.emplace("Accept-Encoding", "gzip, deflate");
  6381. std::string body;
  6382. auto res = cli_.Get("/compress", headers,
  6383. [&](const char *data, uint64_t data_length) {
  6384. EXPECT_EQ(100U, data_length);
  6385. body.append(data, data_length);
  6386. return true;
  6387. });
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6390. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6391. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6392. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6393. "7890123456789012345678901234567890",
  6394. body);
  6395. EXPECT_EQ(StatusCode::OK_200, res->status);
  6396. }
  6397. TEST_F(ServerTest, GzipWithoutDecompressing) {
  6398. Headers headers;
  6399. headers.emplace("Accept-Encoding", "gzip, deflate");
  6400. cli_.set_decompress(false);
  6401. auto res = cli_.Get("/compress", headers);
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6404. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6405. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  6406. EXPECT_EQ(33U, res->body.size());
  6407. EXPECT_EQ(StatusCode::OK_200, res->status);
  6408. }
  6409. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  6410. Headers headers;
  6411. headers.emplace("Accept-Encoding", "");
  6412. std::string body;
  6413. auto res = cli_.Get("/compress", headers,
  6414. [&](const char *data, uint64_t data_length) {
  6415. EXPECT_EQ(100U, data_length);
  6416. body.append(data, data_length);
  6417. return true;
  6418. });
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6422. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6423. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6424. "7890123456789012345678901234567890",
  6425. body);
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. }
  6428. TEST_F(ServerTest, NoGzip) {
  6429. Headers headers;
  6430. headers.emplace("Accept-Encoding", "gzip, deflate");
  6431. auto res = cli_.Get("/nocompress", headers);
  6432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6433. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6434. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6435. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6436. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6437. "7890123456789012345678901234567890",
  6438. res->body);
  6439. EXPECT_EQ(StatusCode::OK_200, res->status);
  6440. }
  6441. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  6442. Headers headers;
  6443. headers.emplace("Accept-Encoding", "gzip, deflate");
  6444. std::string body;
  6445. auto res = cli_.Get("/nocompress", headers,
  6446. [&](const char *data, uint64_t data_length) {
  6447. EXPECT_EQ(100U, data_length);
  6448. body.append(data, data_length);
  6449. return true;
  6450. });
  6451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6452. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6453. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6454. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6455. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6456. "7890123456789012345678901234567890",
  6457. body);
  6458. EXPECT_EQ(StatusCode::OK_200, res->status);
  6459. }
  6460. TEST_F(ServerTest, MultipartFormDataGzip) {
  6461. UploadFormDataItems items = {
  6462. {"key1", "test", "", ""},
  6463. {"key2", "--abcdefg123", "", ""},
  6464. };
  6465. cli_.set_compress(true);
  6466. auto res = cli_.Post("/compress-multipart", items);
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::OK_200, res->status);
  6469. }
  6470. #endif
  6471. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6472. TEST_F(ServerTest, Brotli) {
  6473. Headers headers;
  6474. headers.emplace("Accept-Encoding", "br");
  6475. auto res = cli_.Get("/compress", headers);
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6478. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6479. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  6480. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6481. "7890123456789012345678901234567890",
  6482. res->body);
  6483. EXPECT_EQ(StatusCode::OK_200, res->status);
  6484. }
  6485. #endif
  6486. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6487. TEST_F(ServerTest, Zstd) {
  6488. Headers headers;
  6489. headers.emplace("Accept-Encoding", "zstd");
  6490. auto res = cli_.Get("/compress", headers);
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6494. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6495. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6496. "7890123456789012345678901234567890",
  6497. res->body);
  6498. EXPECT_EQ(StatusCode::OK_200, res->status);
  6499. }
  6500. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  6501. Headers headers;
  6502. headers.emplace("Accept-Encoding", "");
  6503. auto res = cli_.Get("/compress", headers);
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6507. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6508. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6509. "7890123456789012345678901234567890",
  6510. res->body);
  6511. EXPECT_EQ(StatusCode::OK_200, res->status);
  6512. }
  6513. TEST_F(ServerTest, ZstdWithContentReceiver) {
  6514. Headers headers;
  6515. headers.emplace("Accept-Encoding", "zstd");
  6516. std::string body;
  6517. auto res = cli_.Get("/compress", headers,
  6518. [&](const char *data, uint64_t data_length) {
  6519. EXPECT_EQ(100U, data_length);
  6520. body.append(data, data_length);
  6521. return true;
  6522. });
  6523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6524. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6525. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6526. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6527. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6528. "7890123456789012345678901234567890",
  6529. body);
  6530. EXPECT_EQ(StatusCode::OK_200, res->status);
  6531. }
  6532. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  6533. Headers headers;
  6534. headers.emplace("Accept-Encoding", "zstd");
  6535. cli_.set_decompress(false);
  6536. auto res = cli_.Get("/compress", headers);
  6537. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  6538. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  6539. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  6540. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  6541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6542. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  6543. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6544. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  6545. EXPECT_EQ(StatusCode::OK_200, res->status);
  6546. ASSERT_EQ(26U, res->body.size());
  6547. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  6548. 0);
  6549. }
  6550. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  6551. Headers headers;
  6552. headers.emplace("Accept-Encoding", "");
  6553. std::string body;
  6554. auto res = cli_.Get("/compress", headers,
  6555. [&](const char *data, uint64_t data_length) {
  6556. EXPECT_EQ(100U, data_length);
  6557. body.append(data, data_length);
  6558. return true;
  6559. });
  6560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6561. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6563. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6564. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6565. "7890123456789012345678901234567890",
  6566. body);
  6567. EXPECT_EQ(StatusCode::OK_200, res->status);
  6568. }
  6569. TEST_F(ServerTest, NoZstd) {
  6570. Headers headers;
  6571. headers.emplace("Accept-Encoding", "zstd");
  6572. auto res = cli_.Get("/nocompress", headers);
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6575. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6576. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6577. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6578. "7890123456789012345678901234567890",
  6579. res->body);
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. }
  6582. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  6583. Headers headers;
  6584. headers.emplace("Accept-Encoding", "zstd");
  6585. std::string body;
  6586. auto res = cli_.Get("/nocompress", headers,
  6587. [&](const char *data, uint64_t data_length) {
  6588. EXPECT_EQ(100U, data_length);
  6589. body.append(data, data_length);
  6590. return true;
  6591. });
  6592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6593. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  6594. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6595. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  6596. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  6597. "7890123456789012345678901234567890",
  6598. body);
  6599. EXPECT_EQ(StatusCode::OK_200, res->status);
  6600. }
  6601. // TODO: How to enable zstd ??
  6602. TEST_F(ServerTest, MultipartFormDataZstd) {
  6603. UploadFormDataItems items = {
  6604. {"key1", "test", "", ""},
  6605. {"key2", "--abcdefg123", "", ""},
  6606. };
  6607. Headers headers;
  6608. headers.emplace("Accept-Encoding", "zstd");
  6609. cli_.set_compress(true);
  6610. auto res = cli_.Post("/compress-multipart", headers, items);
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. EXPECT_EQ(StatusCode::OK_200, res->status);
  6613. }
  6614. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  6615. Headers headers;
  6616. headers.emplace("Accept-Encoding", "zstd");
  6617. cli_.set_compress(true);
  6618. auto res = cli_.Put(
  6619. "/put", headers, 3,
  6620. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6621. sink.os << "PUT";
  6622. return true;
  6623. },
  6624. "text/plain");
  6625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6626. EXPECT_EQ(StatusCode::OK_200, res->status);
  6627. EXPECT_EQ("PUT", res->body);
  6628. }
  6629. // Pre-compression logging tests
  6630. TEST_F(ServerTest, PreCompressionLogging) {
  6631. // Test data for compression (matches the actual /compress endpoint content)
  6632. const std::string test_content =
  6633. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6634. "3456789012345678901234567890";
  6635. // Variables to capture logging data
  6636. std::string pre_compression_body;
  6637. std::string pre_compression_content_type;
  6638. std::string pre_compression_content_encoding;
  6639. std::string post_compression_body;
  6640. std::string post_compression_content_type;
  6641. std::string post_compression_content_encoding;
  6642. // Set up pre-compression logger
  6643. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  6644. const Response &res) {
  6645. pre_compression_body = res.body;
  6646. pre_compression_content_type = res.get_header_value("Content-Type");
  6647. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  6648. });
  6649. // Set up post-compression logger
  6650. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6651. post_compression_body = res.body;
  6652. post_compression_content_type = res.get_header_value("Content-Type");
  6653. post_compression_content_encoding =
  6654. res.get_header_value("Content-Encoding");
  6655. });
  6656. // Test with gzip compression
  6657. Headers headers;
  6658. headers.emplace("Accept-Encoding", "gzip");
  6659. auto res = cli_.Get("/compress", headers);
  6660. // Verify response was compressed
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::OK_200, res->status);
  6663. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6664. // Verify pre-compression logger captured uncompressed content
  6665. EXPECT_EQ(test_content, pre_compression_body);
  6666. EXPECT_EQ("text/plain", pre_compression_content_type);
  6667. EXPECT_TRUE(pre_compression_content_encoding
  6668. .empty()); // No encoding header before compression
  6669. // Verify post-compression logger captured compressed content
  6670. EXPECT_NE(test_content,
  6671. post_compression_body); // Should be different after compression
  6672. EXPECT_EQ("text/plain", post_compression_content_type);
  6673. EXPECT_EQ("gzip", post_compression_content_encoding);
  6674. // Verify compressed content is smaller
  6675. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6676. }
  6677. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  6678. const std::string test_content =
  6679. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6680. "3456789012345678901234567890";
  6681. std::string pre_compression_body;
  6682. std::string post_compression_body;
  6683. svr_.set_pre_compression_logger(
  6684. [&](const Request & /*req*/, const Response &res) {
  6685. pre_compression_body = res.body;
  6686. });
  6687. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6688. post_compression_body = res.body;
  6689. });
  6690. Headers headers;
  6691. headers.emplace("Accept-Encoding", "br");
  6692. auto res = cli_.Get("/compress", headers);
  6693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6694. EXPECT_EQ(StatusCode::OK_200, res->status);
  6695. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  6696. // Verify pre-compression content is uncompressed
  6697. EXPECT_EQ(test_content, pre_compression_body);
  6698. // Verify post-compression content is compressed
  6699. EXPECT_NE(test_content, post_compression_body);
  6700. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6701. }
  6702. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6703. const std::string test_content =
  6704. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6705. "3456789012345678901234567890";
  6706. std::string pre_compression_body;
  6707. std::string post_compression_body;
  6708. svr_.set_pre_compression_logger(
  6709. [&](const Request & /*req*/, const Response &res) {
  6710. pre_compression_body = res.body;
  6711. });
  6712. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6713. post_compression_body = res.body;
  6714. });
  6715. // Request without compression (use /nocompress endpoint)
  6716. Headers headers;
  6717. auto res = cli_.Get("/nocompress", headers);
  6718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6719. EXPECT_EQ(StatusCode::OK_200, res->status);
  6720. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6721. // Pre-compression logger should not be called when no compression is applied
  6722. EXPECT_TRUE(
  6723. pre_compression_body.empty()); // Pre-compression logger not called
  6724. EXPECT_EQ(
  6725. test_content,
  6726. post_compression_body); // Post-compression logger captures final content
  6727. }
  6728. TEST_F(ServerTest, LoggerSeesContentLength) {
  6729. size_t logged_content_length = 0;
  6730. std::string logged_content_length_header;
  6731. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6732. logged_content_length = res.content_length_;
  6733. logged_content_length_header = res.get_header_value("Content-Length");
  6734. });
  6735. auto res = cli_.Get("/nocompress");
  6736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6737. EXPECT_EQ(StatusCode::OK_200, res->status);
  6738. EXPECT_EQ(res->body.size(), logged_content_length);
  6739. EXPECT_EQ(std::to_string(logged_content_length),
  6740. logged_content_length_header);
  6741. }
  6742. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6743. const std::string test_content =
  6744. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6745. "3456789012345678901234567890";
  6746. std::string pre_compression_body;
  6747. bool pre_logger_called = false;
  6748. // Set only pre-compression logger
  6749. svr_.set_pre_compression_logger(
  6750. [&](const Request & /*req*/, const Response &res) {
  6751. pre_compression_body = res.body;
  6752. pre_logger_called = true;
  6753. });
  6754. Headers headers;
  6755. headers.emplace("Accept-Encoding", "gzip");
  6756. auto res = cli_.Get("/compress", headers);
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6760. // Verify pre-compression logger was called
  6761. EXPECT_TRUE(pre_logger_called);
  6762. EXPECT_EQ(test_content, pre_compression_body);
  6763. }
  6764. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6765. {
  6766. // Test with Expect: 100-continue header - success case
  6767. // Server returns 100 Continue, client sends body, server returns 200 OK
  6768. Request req;
  6769. req.method = "POST";
  6770. req.path = "/post-large";
  6771. req.set_header("Expect", "100-continue");
  6772. req.body = LARGE_DATA;
  6773. Response res;
  6774. auto error = Error::Success;
  6775. cli_.set_keep_alive(true);
  6776. auto ret = cli_.send(req, res, error);
  6777. EXPECT_TRUE(ret);
  6778. EXPECT_EQ(StatusCode::OK_200, res.status);
  6779. EXPECT_EQ(LARGE_DATA, res.body);
  6780. }
  6781. {
  6782. // Test with Expect: 100-continue header - error case
  6783. // Client should not send the body when server returns an error
  6784. Request req;
  6785. req.method = "POST";
  6786. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6787. req.set_header("Expect", "100-continue");
  6788. req.body = LARGE_DATA;
  6789. Response res;
  6790. auto error = Error::Success;
  6791. auto start = std::chrono::high_resolution_clock::now();
  6792. cli_.set_keep_alive(true);
  6793. auto ret = cli_.send(req, res, error);
  6794. auto end = std::chrono::high_resolution_clock::now();
  6795. auto elapsed =
  6796. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6797. .count();
  6798. // With Expect: 100-continue, request completes successfully but with error
  6799. EXPECT_TRUE(ret);
  6800. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6801. EXPECT_EQ("close", res.get_header_value("Connection"));
  6802. EXPECT_FALSE(cli_.is_socket_open());
  6803. EXPECT_LE(elapsed, 2000);
  6804. }
  6805. {
  6806. // Send an extra GET request to ensure error recovery without hanging
  6807. Request req;
  6808. req.method = "GET";
  6809. req.path = "/hi";
  6810. auto start = std::chrono::high_resolution_clock::now();
  6811. auto res = cli_.send(req);
  6812. auto end = std::chrono::high_resolution_clock::now();
  6813. auto elapsed =
  6814. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6815. .count();
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. EXPECT_EQ("Hello World!", res->body);
  6819. EXPECT_LE(elapsed, 500);
  6820. }
  6821. }
  6822. TEST(ZstdDecompressor, ChunkedDecompression) {
  6823. std::string data;
  6824. for (size_t i = 0; i < 32 * 1024; ++i) {
  6825. data.push_back(static_cast<char>('a' + i % 26));
  6826. }
  6827. std::string compressed_data;
  6828. {
  6829. httplib::detail::zstd_compressor compressor;
  6830. bool result = compressor.compress(
  6831. data.data(), data.size(),
  6832. /*last=*/true,
  6833. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6834. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6835. compressed_data_size);
  6836. return true;
  6837. });
  6838. ASSERT_TRUE(result);
  6839. }
  6840. std::string decompressed_data;
  6841. {
  6842. httplib::detail::zstd_decompressor decompressor;
  6843. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6844. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6845. size_t chunk_size = 130;
  6846. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6847. chunk_begin += chunk_size) {
  6848. size_t current_chunk_size =
  6849. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6850. bool result = decompressor.decompress(
  6851. compressed_data.data() + chunk_begin, current_chunk_size,
  6852. [&](const char *decompressed_data_chunk,
  6853. size_t decompressed_data_chunk_size) {
  6854. decompressed_data.insert(decompressed_data.size(),
  6855. decompressed_data_chunk,
  6856. decompressed_data_chunk_size);
  6857. return true;
  6858. });
  6859. ASSERT_TRUE(result);
  6860. }
  6861. }
  6862. ASSERT_EQ(data, decompressed_data);
  6863. }
  6864. TEST(ZstdDecompressor, Decompress) {
  6865. std::string original_text = "Compressed with ZSTD";
  6866. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6867. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6868. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6869. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6870. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6871. std::string decompressed_data;
  6872. {
  6873. httplib::detail::zstd_decompressor decompressor;
  6874. bool result = decompressor.decompress(
  6875. compressed_data.data(), compressed_data.size(),
  6876. [&](const char *decompressed_data_chunk,
  6877. size_t decompressed_data_chunk_size) {
  6878. decompressed_data.insert(decompressed_data.size(),
  6879. decompressed_data_chunk,
  6880. decompressed_data_chunk_size);
  6881. return true;
  6882. });
  6883. ASSERT_TRUE(result);
  6884. }
  6885. ASSERT_EQ(original_text, decompressed_data);
  6886. }
  6887. #endif
  6888. // Sends a raw request to a server listening at HOST:PORT.
  6889. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6890. std::string *resp = nullptr) {
  6891. auto error = Error::Success;
  6892. auto client_sock = detail::create_client_socket(
  6893. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6894. /*connection_timeout_sec=*/5, 0,
  6895. /*read_timeout_sec=*/5, 0,
  6896. /*write_timeout_sec=*/5, 0, std::string(), error);
  6897. if (client_sock == INVALID_SOCKET) { return false; }
  6898. auto ret = detail::process_client_socket(
  6899. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6900. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6901. if (req.size() !=
  6902. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6903. return false;
  6904. }
  6905. char buf[512];
  6906. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6907. while (line_reader.getline()) {
  6908. if (resp) { *resp += line_reader.ptr(); }
  6909. }
  6910. return true;
  6911. });
  6912. detail::close_socket(client_sock);
  6913. return ret;
  6914. }
  6915. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6916. Server svr;
  6917. std::string header_value;
  6918. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6919. header_value = req.get_header_value("foo");
  6920. res.set_content("ok", "text/plain");
  6921. });
  6922. thread t = thread([&] { svr.listen(HOST, PORT); });
  6923. auto se = detail::scope_exit([&] {
  6924. svr.stop();
  6925. t.join();
  6926. ASSERT_FALSE(svr.is_running());
  6927. });
  6928. svr.wait_until_ready();
  6929. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6930. // like characters are not treated the same - use vertical tab and escape.
  6931. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6932. "foo: \t \v bar \x1B\t \r\n"
  6933. "Connection: close\r\n"
  6934. "\r\n";
  6935. std::string res;
  6936. ASSERT_TRUE(send_request(5, req, &res));
  6937. EXPECT_EQ(header_value, "");
  6938. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6939. }
  6940. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  6941. Server svr;
  6942. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  6943. auto i = new int(0);
  6944. res.set_header("Trailer", "X-Safe, X-Reflected");
  6945. res.set_chunked_content_provider(
  6946. "text/plain",
  6947. [i](size_t /*offset*/, DataSink &sink) {
  6948. if (*i == 0) {
  6949. sink.os << "body";
  6950. } else {
  6951. Headers trailer;
  6952. // A valid trailer that must survive.
  6953. trailer.emplace("X-Safe", "safe");
  6954. // Attacker-controlled value carrying CR/LF (response splitting).
  6955. trailer.emplace("X-Reflected",
  6956. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6957. // Attacker-controlled name carrying CR/LF.
  6958. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  6959. sink.done_with_trailer(trailer);
  6960. }
  6961. (*i)++;
  6962. return true;
  6963. },
  6964. [i](bool /*success*/) { delete i; });
  6965. });
  6966. thread t = thread([&] { svr.listen(HOST, PORT); });
  6967. auto se = detail::scope_exit([&] {
  6968. svr.stop();
  6969. t.join();
  6970. ASSERT_FALSE(svr.is_running());
  6971. });
  6972. svr.wait_until_ready();
  6973. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  6974. "Host: " + HOST +
  6975. "\r\n"
  6976. "Connection: close\r\n"
  6977. "\r\n";
  6978. std::string res;
  6979. ASSERT_TRUE(send_request(5, req, &res));
  6980. // The injected fields must not appear anywhere in the raw response.
  6981. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  6982. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  6983. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  6984. // Invalid trailers are dropped entirely, matching set_header().
  6985. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  6986. // The valid trailer still passes through.
  6987. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  6988. }
  6989. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  6990. Server svr;
  6991. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  6992. // res.headers is a public field an application can populate directly,
  6993. // bypassing set_header()'s validation (e.g. reflecting a request value).
  6994. // A valid header that must survive.
  6995. res.headers.emplace("X-Safe", "safe");
  6996. // Attacker-controlled value carrying CR/LF (response splitting).
  6997. res.headers.emplace("X-Reflected",
  6998. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  6999. // Attacker-controlled name carrying CR/LF.
  7000. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  7001. res.set_content("body", "text/plain");
  7002. });
  7003. thread t = thread([&] { svr.listen(HOST, PORT); });
  7004. auto se = detail::scope_exit([&] {
  7005. svr.stop();
  7006. t.join();
  7007. ASSERT_FALSE(svr.is_running());
  7008. });
  7009. svr.wait_until_ready();
  7010. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  7011. "Host: " + HOST +
  7012. "\r\n"
  7013. "Connection: close\r\n"
  7014. "\r\n";
  7015. std::string res;
  7016. ASSERT_TRUE(send_request(5, req, &res));
  7017. // The injected fields must not appear anywhere in the raw response.
  7018. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  7019. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  7020. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  7021. // Invalid headers are dropped entirely, matching set_header().
  7022. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  7023. // The valid header still passes through.
  7024. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  7025. }
  7026. // Forward declaration: in split builds split.py strips `inline` and moves the
  7027. // definition into httplib.cc, so detail::write_request_line is not visible from
  7028. // the public httplib.h. Re-declaring it here lets the tests link against the
  7029. // symbol in both header-only and split builds.
  7030. namespace httplib {
  7031. namespace detail {
  7032. ssize_t write_request_line(Stream &strm, const std::string &method,
  7033. const std::string &path);
  7034. } // namespace detail
  7035. } // namespace httplib
  7036. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  7037. // A well-formed target is written verbatim.
  7038. {
  7039. detail::BufferStream strm;
  7040. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  7041. EXPECT_GT(n, 0);
  7042. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  7043. }
  7044. // A target carrying CR/LF must be rejected before anything reaches the wire,
  7045. // otherwise it splits the request line and injects a header or a whole
  7046. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  7047. // when path encoding is disabled.
  7048. const std::string evil_targets[] = {
  7049. "/a\r\nInjected: pwned",
  7050. "/a\rInjected",
  7051. "/a\nInjected",
  7052. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  7053. };
  7054. for (const auto &evil : evil_targets) {
  7055. detail::BufferStream strm;
  7056. auto n = detail::write_request_line(strm, "GET", evil);
  7057. EXPECT_LT(n, 0);
  7058. EXPECT_TRUE(strm.get_buffer().empty());
  7059. }
  7060. }
  7061. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  7062. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  7063. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  7064. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  7065. // client must fail cleanly with Error::Write instead of putting a
  7066. // request-line-less, header-injecting request on the wire.
  7067. Server svr;
  7068. svr.Get("/a", [](const Request &, Response &res) {
  7069. res.set_content("ok", "text/plain");
  7070. });
  7071. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7072. auto se = detail::scope_exit([&] {
  7073. svr.stop();
  7074. thread.join();
  7075. ASSERT_FALSE(svr.is_running());
  7076. });
  7077. svr.wait_until_ready();
  7078. {
  7079. Client cli(HOST, PORT);
  7080. cli.set_path_encode(false);
  7081. // The request is rejected before anything is written, so the connection
  7082. // stays silent and the subsequent response read would otherwise block for
  7083. // the full default read timeout. Shorten it -- the assertion is on the
  7084. // error, not the timeout.
  7085. cli.set_read_timeout(1, 0);
  7086. auto res = cli.Get("/a\r\nInjected: pwned");
  7087. EXPECT_FALSE(res);
  7088. EXPECT_EQ(Error::Write, res.error());
  7089. }
  7090. }
  7091. // Sends a raw request and verifies that there isn't a crash or exception.
  7092. static void test_raw_request(const std::string &req,
  7093. std::string *out = nullptr) {
  7094. Server svr;
  7095. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7096. res.set_content("ok", "text/plain");
  7097. });
  7098. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  7099. res.set_content("ok", "text/plain");
  7100. });
  7101. svr.Get("/header_field_value_check",
  7102. [&](const Request & /*req*/, Response &res) {
  7103. res.set_content("ok", "text/plain");
  7104. });
  7105. // Server read timeout must be longer than the client read timeout for the
  7106. // bug to reproduce, probably to force the server to process a request
  7107. // without a trailing blank line.
  7108. const time_t client_read_timeout_sec = 1;
  7109. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  7110. bool listen_thread_ok = false;
  7111. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  7112. auto se = detail::scope_exit([&] {
  7113. svr.stop();
  7114. t.join();
  7115. ASSERT_FALSE(svr.is_running());
  7116. EXPECT_TRUE(listen_thread_ok);
  7117. });
  7118. svr.wait_until_ready();
  7119. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  7120. }
  7121. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  7122. // A certain header line causes an exception if the header property is parsed
  7123. // naively with a single regex. This occurs with libc++ but not libstdc++.
  7124. test_raw_request(
  7125. "GET /hi HTTP/1.1\r\n"
  7126. " : "
  7127. " "
  7128. " ");
  7129. }
  7130. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  7131. // A certain header line causes an exception if the header property *name* is
  7132. // parsed with a regular expression starting with "(.+?):" - this is a non-
  7133. // greedy matcher and requires backtracking when there are a lot of ":"
  7134. // characters.
  7135. // This occurs with libc++ but not libstdc++.
  7136. test_raw_request(
  7137. "GET /hi HTTP/1.1\r\n"
  7138. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  7139. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7140. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  7141. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  7142. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  7143. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  7144. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  7145. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  7146. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7147. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7148. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  7149. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7150. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  7151. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  7152. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  7153. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  7154. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  7155. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  7156. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  7157. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  7158. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  7159. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  7160. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  7161. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  7162. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  7163. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  7164. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  7165. "&&&%%%");
  7166. }
  7167. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  7168. // Make sure this doesn't crash the server.
  7169. // In a previous version of the header line regex, the "\r" rendered the line
  7170. // unparsable and the regex engine repeatedly backtracked, trying to look for
  7171. // a new position where the leading white space ended and the field value
  7172. // began.
  7173. // The crash occurs with libc++ but not libstdc++.
  7174. test_raw_request("GET /hi HTTP/1.1\r\n"
  7175. "a:" +
  7176. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  7177. "\r\n"
  7178. "\r\n");
  7179. }
  7180. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  7181. std::string out;
  7182. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7183. "Content-Type: text/plain\r\n"
  7184. "Transfer-Encoding: chunked\r\n"
  7185. "\r\n"
  7186. "nothex\r\n",
  7187. &out);
  7188. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7189. }
  7190. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  7191. std::string out;
  7192. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7193. "Content-Type: text/plain\r\n"
  7194. "Transfer-Encoding: chunked\r\n"
  7195. "\r\n"
  7196. "3\r\n"
  7197. "xyz\r\n"
  7198. "NaN\r\n",
  7199. &out);
  7200. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7201. }
  7202. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  7203. std::string out;
  7204. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  7205. "Content-Type: text/plain\r\n"
  7206. "Transfer-Encoding: chunked\r\n"
  7207. "\r\n"
  7208. // Length is too large for 64 bits.
  7209. "1ffffffffffffffff\r\n"
  7210. "xyz\r\n",
  7211. &out);
  7212. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7213. }
  7214. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  7215. test_raw_request("GET /hi HTTP/1.1\r\n"
  7216. "Content-Type: text/plain\r\n\r");
  7217. }
  7218. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  7219. std::string out;
  7220. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  7221. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7222. }
  7223. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  7224. Server svr;
  7225. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  7226. EXPECT_TRUE(!req.remote_addr.empty());
  7227. });
  7228. thread t = thread([&] { svr.listen(HOST, PORT); });
  7229. auto se = detail::scope_exit([&] {
  7230. svr.stop();
  7231. t.join();
  7232. ASSERT_FALSE(svr.is_running());
  7233. });
  7234. svr.wait_until_ready();
  7235. // Send an invalid request line to trigger Bad Request
  7236. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  7237. std::string out;
  7238. ASSERT_TRUE(send_request(5, bad_req, &out));
  7239. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7240. }
  7241. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  7242. std::string out;
  7243. std::string request(
  7244. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  7245. test_raw_request(request, &out);
  7246. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7247. }
  7248. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  7249. std::string out;
  7250. std::string request(
  7251. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  7252. test_raw_request(request, &out);
  7253. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7254. }
  7255. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  7256. std::string out;
  7257. std::string request(
  7258. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  7259. test_raw_request(request, &out);
  7260. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  7261. }
  7262. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  7263. std::string out;
  7264. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  7265. "Test: \r\n\r\n",
  7266. &out);
  7267. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  7268. }
  7269. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  7270. Server svr;
  7271. std::string x_custom;
  7272. std::string cookie;
  7273. std::string xff;
  7274. std::string x_unicode;
  7275. std::string x_iis;
  7276. svr.Get("/check", [&](const Request &req, Response &res) {
  7277. x_custom = req.get_header_value("X-Custom");
  7278. cookie = req.get_header_value("Cookie");
  7279. xff = req.get_header_value("X-Forwarded-For");
  7280. x_unicode = req.get_header_value("X-Unicode");
  7281. x_iis = req.get_header_value("X-IIS");
  7282. res.set_content("ok", "text/plain");
  7283. });
  7284. thread t = thread([&] { svr.listen(HOST, PORT); });
  7285. auto se = detail::scope_exit([&] {
  7286. svr.stop();
  7287. t.join();
  7288. ASSERT_FALSE(svr.is_running());
  7289. });
  7290. svr.wait_until_ready();
  7291. const std::string req = "GET /check HTTP/1.1\r\n"
  7292. "Host: localhost\r\n"
  7293. "X-Custom: a%0D%0AInjected: b\r\n"
  7294. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  7295. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  7296. "X-Unicode: %E3%81%82\r\n"
  7297. "X-IIS: %u00E9\r\n"
  7298. "Connection: close\r\n"
  7299. "\r\n";
  7300. std::string res;
  7301. ASSERT_TRUE(send_request(5, req, &res));
  7302. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7303. // Every value must be returned verbatim (wire form), with no decoding.
  7304. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  7305. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  7306. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  7307. EXPECT_EQ("%E3%81%82", x_unicode);
  7308. EXPECT_EQ("%u00E9", x_iis);
  7309. }
  7310. // Applications that previously relied on automatic percent-decoding can
  7311. // reproduce the old behavior by explicitly calling decode_path_component()
  7312. // or, for RFC 3986 conformance, decode_uri_component().
  7313. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  7314. Server svr;
  7315. std::string decoded;
  7316. svr.Get("/check", [&](const Request &req, Response &res) {
  7317. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  7318. res.set_content("ok", "text/plain");
  7319. });
  7320. thread t = thread([&] { svr.listen(HOST, PORT); });
  7321. auto se = detail::scope_exit([&] {
  7322. svr.stop();
  7323. t.join();
  7324. ASSERT_FALSE(svr.is_running());
  7325. });
  7326. svr.wait_until_ready();
  7327. const std::string req = "GET /check HTTP/1.1\r\n"
  7328. "Host: localhost\r\n"
  7329. "X-Custom: hello%20world\r\n"
  7330. "Connection: close\r\n"
  7331. "\r\n";
  7332. std::string res;
  7333. ASSERT_TRUE(send_request(5, req, &res));
  7334. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7335. EXPECT_EQ("hello world", decoded);
  7336. }
  7337. // Regression test for #2033. Browsers send Referer values that include
  7338. // percent-encoded characters such as %0A inside the URL. Decoding the
  7339. // header value would either trip the post-decode CR/LF/NUL guard (the
  7340. // original bug, returning 400) or, after that guard was relaxed, silently
  7341. // store a literal LF — both unacceptable. The wire form must round-trip.
  7342. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  7343. Server svr;
  7344. std::string referer;
  7345. svr.Get("/check", [&](const Request &req, Response &res) {
  7346. referer = req.get_header_value("Referer");
  7347. res.set_content("ok", "text/plain");
  7348. });
  7349. thread t = thread([&] { svr.listen(HOST, PORT); });
  7350. auto se = detail::scope_exit([&] {
  7351. svr.stop();
  7352. t.join();
  7353. ASSERT_FALSE(svr.is_running());
  7354. });
  7355. svr.wait_until_ready();
  7356. const std::string req = "GET /check HTTP/1.1\r\n"
  7357. "Host: localhost\r\n"
  7358. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  7359. "Connection: close\r\n"
  7360. "\r\n";
  7361. std::string res;
  7362. ASSERT_TRUE(send_request(5, req, &res));
  7363. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  7364. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  7365. }
  7366. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  7367. Server svr;
  7368. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  7369. res.set_header("Cache-Control", "no-cache");
  7370. res.set_chunked_content_provider(
  7371. "text/event-stream", [](size_t offset, DataSink &sink) {
  7372. std::string s = "data:";
  7373. s += std::to_string(offset);
  7374. s += "\n\n";
  7375. auto ret = sink.write(s.data(), s.size());
  7376. EXPECT_TRUE(ret);
  7377. std::this_thread::sleep_for(std::chrono::seconds(1));
  7378. return true;
  7379. });
  7380. });
  7381. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7382. svr.wait_until_ready();
  7383. Client client(HOST, PORT);
  7384. const Headers headers = {{"Accept", "text/event-stream"}};
  7385. auto get_thread = std::thread([&client, &headers]() {
  7386. auto res = client.Get(
  7387. "/events", headers,
  7388. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  7389. });
  7390. auto se = detail::scope_exit([&] {
  7391. svr.stop();
  7392. get_thread.join();
  7393. listen_thread.join();
  7394. ASSERT_FALSE(svr.is_running());
  7395. });
  7396. // Give GET time to get a few messages.
  7397. std::this_thread::sleep_for(std::chrono::seconds(2));
  7398. }
  7399. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  7400. httplib::Server svr;
  7401. svr.Post("/hi",
  7402. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7403. res.status = StatusCode::OK_200;
  7404. });
  7405. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7406. svr.wait_until_ready();
  7407. Client cli(HOST, PORT);
  7408. auto res = cli.Post("/hi", "data", "text/plain");
  7409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7410. EXPECT_EQ(StatusCode::OK_200, res->status);
  7411. svr.stop();
  7412. thread.join();
  7413. ASSERT_FALSE(svr.is_running());
  7414. res = cli.Post("/hi", "data", "text/plain");
  7415. ASSERT_FALSE(res);
  7416. }
  7417. TEST(ServerStopTest, ListenFailure) {
  7418. Server svr;
  7419. auto t = thread([&]() {
  7420. auto ret = svr.listen("????", PORT);
  7421. EXPECT_FALSE(ret);
  7422. });
  7423. svr.wait_until_ready();
  7424. svr.stop();
  7425. t.join();
  7426. }
  7427. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7428. TEST(ServerStopTest, Decommision) {
  7429. Server svr;
  7430. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  7431. for (int i = 0; i < 4; i++) {
  7432. auto is_even = !(i % 2);
  7433. std::thread t{[&] {
  7434. try {
  7435. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7436. if (is_even) {
  7437. throw std::runtime_error("Some thing that happens to go wrong.");
  7438. }
  7439. svr.listen(HOST, PORT);
  7440. } catch (...) { svr.decommission(); }
  7441. }};
  7442. svr.wait_until_ready();
  7443. // Server is up
  7444. {
  7445. Client cli(HOST, PORT);
  7446. auto res = cli.Get("/hi");
  7447. if (is_even) {
  7448. EXPECT_FALSE(res);
  7449. } else {
  7450. EXPECT_TRUE(res);
  7451. EXPECT_EQ("hi...", res->body);
  7452. }
  7453. }
  7454. svr.stop();
  7455. t.join();
  7456. // Server is down...
  7457. {
  7458. Client cli(HOST, PORT);
  7459. auto res = cli.Get("/hi");
  7460. EXPECT_FALSE(res);
  7461. }
  7462. }
  7463. }
  7464. #endif
  7465. // Helper function for string body upload progress tests
  7466. template <typename SetupHandler, typename ClientCall>
  7467. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  7468. ClientCall &&client_call,
  7469. const string &body) {
  7470. Server svr;
  7471. setup_handler(svr);
  7472. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7473. auto se = detail::scope_exit([&] {
  7474. svr.stop();
  7475. t.join();
  7476. });
  7477. svr.wait_until_ready();
  7478. Client cli(HOST, PORT);
  7479. vector<uint64_t> progress_values;
  7480. bool progress_called = false;
  7481. auto res =
  7482. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7483. progress_values.push_back(current);
  7484. progress_called = true;
  7485. return true;
  7486. });
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(200, res->status);
  7489. EXPECT_TRUE(progress_called);
  7490. }
  7491. TEST(UploadProgressTest, PostStringBodyBasic) {
  7492. TestStringBodyUploadProgress(
  7493. [](Server &svr) {
  7494. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7495. res.set_content("received", "text/plain");
  7496. });
  7497. },
  7498. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7499. return cli.Post("/test", body, "text/plain", progress_callback);
  7500. },
  7501. "test data for upload progress");
  7502. }
  7503. TEST(UploadProgressTest, PutStringBodyBasic) {
  7504. TestStringBodyUploadProgress(
  7505. [](Server &svr) {
  7506. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  7507. res.set_content("put received", "text/plain");
  7508. });
  7509. },
  7510. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7511. return cli.Put("/test", body, "text/plain", progress_callback);
  7512. },
  7513. "put test data for upload progress");
  7514. }
  7515. TEST(UploadProgressTest, PatchStringBodyBasic) {
  7516. TestStringBodyUploadProgress(
  7517. [](Server &svr) {
  7518. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  7519. res.set_content("patch received", "text/plain");
  7520. });
  7521. },
  7522. [](Client &cli, const string &body, UploadProgress progress_callback) {
  7523. return cli.Patch("/test", body, "text/plain", progress_callback);
  7524. },
  7525. "patch test data for upload progress");
  7526. }
  7527. // Helper function for content provider upload progress tests
  7528. template <typename SetupHandler, typename ClientCall>
  7529. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  7530. ClientCall &&client_call) {
  7531. Server svr;
  7532. setup_handler(svr);
  7533. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7534. auto se = detail::scope_exit([&] {
  7535. svr.stop();
  7536. t.join();
  7537. });
  7538. svr.wait_until_ready();
  7539. Client cli(HOST, PORT);
  7540. vector<uint64_t> progress_values;
  7541. auto res =
  7542. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  7543. progress_values.push_back(current);
  7544. return true;
  7545. });
  7546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7547. EXPECT_EQ(200, res->status);
  7548. EXPECT_FALSE(progress_values.empty());
  7549. }
  7550. TEST(UploadProgressTest, PostContentProviderProgress) {
  7551. TestContentProviderUploadProgress(
  7552. [](Server &svr) {
  7553. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  7554. res.set_content("provider received", "text/plain");
  7555. });
  7556. },
  7557. [](Client &cli, UploadProgress progress_callback) {
  7558. return cli.Post(
  7559. "/test", 10,
  7560. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  7561. sink.os << "test data";
  7562. return true;
  7563. },
  7564. "text/plain", progress_callback);
  7565. });
  7566. }
  7567. // Helper function for multipart upload progress tests
  7568. template <typename SetupHandler, typename ClientCall>
  7569. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  7570. ClientCall &&client_call,
  7571. const string &endpoint) {
  7572. Server svr;
  7573. setup_handler(svr);
  7574. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7575. auto se = detail::scope_exit([&] {
  7576. svr.stop();
  7577. t.join();
  7578. });
  7579. svr.wait_until_ready();
  7580. Client cli(HOST, PORT);
  7581. vector<uint64_t> progress_values;
  7582. UploadFormDataItems items = {
  7583. {"field1", "value1", "", ""},
  7584. {"field2", "longer value for progress tracking test", "", ""},
  7585. {"file1", "file content data for upload progress", "test.txt",
  7586. "text/plain"}};
  7587. auto res = client_call(cli, endpoint, items,
  7588. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7589. progress_values.push_back(current);
  7590. return true;
  7591. });
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_EQ(200, res->status);
  7594. EXPECT_FALSE(progress_values.empty());
  7595. }
  7596. TEST(UploadProgressTest, PostMultipartProgress) {
  7597. TestMultipartUploadProgress(
  7598. [](Server &svr) {
  7599. svr.Post("/multipart", [](const Request &req, Response &res) {
  7600. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  7601. res.set_content("multipart received", "text/plain");
  7602. });
  7603. },
  7604. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  7605. UploadProgress progress_callback) {
  7606. return cli.Post(endpoint, items, progress_callback);
  7607. },
  7608. "/multipart");
  7609. }
  7610. // Helper function for basic download progress tests
  7611. template <typename SetupHandler, typename ClientCall>
  7612. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  7613. ClientCall &&client_call, const string &endpoint,
  7614. size_t expected_content_size) {
  7615. Server svr;
  7616. setup_handler(svr);
  7617. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7618. auto se = detail::scope_exit([&] {
  7619. svr.stop();
  7620. t.join();
  7621. });
  7622. svr.wait_until_ready();
  7623. Client cli(HOST, PORT);
  7624. vector<uint64_t> progress_values;
  7625. auto res = client_call(cli, endpoint,
  7626. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7627. progress_values.push_back(current);
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_EQ(200, res->status);
  7632. EXPECT_FALSE(progress_values.empty());
  7633. EXPECT_EQ(expected_content_size, res->body.size());
  7634. }
  7635. TEST(DownloadProgressTest, GetBasic) {
  7636. TestBasicDownloadProgress(
  7637. [](Server &svr) {
  7638. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  7639. string content(1000, 'D');
  7640. res.set_content(content, "text/plain");
  7641. });
  7642. },
  7643. [](Client &cli, const string &endpoint,
  7644. DownloadProgress progress_callback) {
  7645. return cli.Get(endpoint, progress_callback);
  7646. },
  7647. "/download", 1000u);
  7648. }
  7649. // Helper function for content receiver download progress tests
  7650. template <typename SetupHandler, typename ClientCall>
  7651. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  7652. ClientCall &&client_call,
  7653. const string &endpoint,
  7654. size_t expected_content_size) {
  7655. Server svr;
  7656. setup_handler(svr);
  7657. thread t = thread([&]() { svr.listen(HOST, PORT); });
  7658. auto se = detail::scope_exit([&] {
  7659. svr.stop();
  7660. t.join();
  7661. });
  7662. svr.wait_until_ready();
  7663. Client cli(HOST, PORT);
  7664. vector<uint64_t> progress_values;
  7665. string received_body;
  7666. auto res = client_call(
  7667. cli, endpoint,
  7668. [&](const char *data, size_t data_length) -> bool {
  7669. received_body.append(data, data_length);
  7670. return true;
  7671. },
  7672. [&](uint64_t current, uint64_t /*total*/) -> bool {
  7673. progress_values.push_back(current);
  7674. return true;
  7675. });
  7676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7677. EXPECT_EQ(200, res->status);
  7678. EXPECT_FALSE(progress_values.empty());
  7679. EXPECT_EQ(expected_content_size, received_body.size());
  7680. EXPECT_TRUE(res->body.empty());
  7681. }
  7682. TEST(DownloadProgressTest, GetWithContentReceiver) {
  7683. TestContentReceiverDownloadProgress(
  7684. [](Server &svr) {
  7685. svr.Get("/download-receiver",
  7686. [](const Request & /*req*/, Response &res) {
  7687. string content(2000, 'R');
  7688. res.set_content(content, "text/plain");
  7689. });
  7690. },
  7691. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  7692. DownloadProgress progress_callback) {
  7693. return cli.Get(endpoint, content_receiver, progress_callback);
  7694. },
  7695. "/download-receiver", 2000u);
  7696. }
  7697. TEST(StreamingTest, NoContentLengthStreaming) {
  7698. Server svr;
  7699. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  7700. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  7701. if (offset < 6) {
  7702. sink.os << (offset < 3 ? "a" : "b");
  7703. } else {
  7704. sink.done();
  7705. }
  7706. return true;
  7707. });
  7708. });
  7709. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7710. auto listen_se = detail::scope_exit([&] {
  7711. svr.stop();
  7712. listen_thread.join();
  7713. ASSERT_FALSE(svr.is_running());
  7714. });
  7715. svr.wait_until_ready();
  7716. Client client(HOST, PORT);
  7717. auto get_thread = std::thread([&client]() {
  7718. std::string s;
  7719. auto res =
  7720. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  7721. s += std::string(data, len);
  7722. return true;
  7723. });
  7724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7725. EXPECT_EQ(StatusCode::OK_200, res->status);
  7726. EXPECT_EQ("aaabbb", s);
  7727. });
  7728. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  7729. // Give GET time to get a few messages.
  7730. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7731. }
  7732. TEST(MountTest, Unmount) {
  7733. Server svr;
  7734. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7735. auto se = detail::scope_exit([&] {
  7736. svr.stop();
  7737. listen_thread.join();
  7738. ASSERT_FALSE(svr.is_running());
  7739. });
  7740. svr.wait_until_ready();
  7741. Client cli("localhost", PORT);
  7742. svr.set_mount_point("/mount2", "./www2");
  7743. auto res = cli.Get("/");
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7746. res = cli.Get("/mount2/dir/test.html");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. svr.set_mount_point("/", "./www");
  7750. res = cli.Get("/dir/");
  7751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7752. EXPECT_EQ(StatusCode::OK_200, res->status);
  7753. svr.remove_mount_point("/");
  7754. res = cli.Get("/dir/");
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7757. svr.remove_mount_point("/mount2");
  7758. res = cli.Get("/mount2/dir/test.html");
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7761. }
  7762. TEST(MountTest, Redicect) {
  7763. Server svr;
  7764. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7765. auto se = detail::scope_exit([&] {
  7766. svr.stop();
  7767. listen_thread.join();
  7768. ASSERT_FALSE(svr.is_running());
  7769. });
  7770. svr.set_mount_point("/", "./www");
  7771. svr.wait_until_ready();
  7772. Client cli("localhost", PORT);
  7773. auto res = cli.Get("/dir/");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. res = cli.Get("/dir");
  7777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7778. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7779. res = cli.Get("/file");
  7780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7781. EXPECT_EQ(StatusCode::OK_200, res->status);
  7782. res = cli.Get("/file/");
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7785. cli.set_follow_location(true);
  7786. res = cli.Get("/dir");
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. EXPECT_EQ(StatusCode::OK_200, res->status);
  7789. }
  7790. TEST(MountTest, MultibytesPathName) {
  7791. Server svr;
  7792. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7793. auto se = detail::scope_exit([&] {
  7794. svr.stop();
  7795. listen_thread.join();
  7796. ASSERT_FALSE(svr.is_running());
  7797. });
  7798. svr.set_mount_point("/", "./www");
  7799. svr.wait_until_ready();
  7800. Client cli("localhost", PORT);
  7801. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  7805. }
  7806. #ifdef _WIN32
  7807. // Issue #2435: mmap::open() must succeed even when another handle holds
  7808. // the file open for writing (e.g. an active log file).
  7809. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  7810. const char *path = "mmap_concurrent_writer_test.txt";
  7811. const char *content = "hello";
  7812. {
  7813. std::ofstream f(path, std::ios::binary);
  7814. f.write(content, static_cast<std::streamsize>(strlen(content)));
  7815. }
  7816. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  7817. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  7818. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  7819. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  7820. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  7821. detail::mmap m(path);
  7822. ASSERT_TRUE(m.is_open());
  7823. EXPECT_EQ(strlen(content), m.size());
  7824. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  7825. }
  7826. #endif
  7827. TEST(KeepAliveTest, ReadTimeout) {
  7828. Server svr;
  7829. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7830. std::this_thread::sleep_for(std::chrono::seconds(2));
  7831. res.set_content("a", "text/plain");
  7832. });
  7833. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7834. res.set_content("b", "text/plain");
  7835. });
  7836. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7837. auto se = detail::scope_exit([&] {
  7838. svr.stop();
  7839. listen_thread.join();
  7840. ASSERT_FALSE(svr.is_running());
  7841. });
  7842. svr.wait_until_ready();
  7843. Client cli("localhost", PORT);
  7844. cli.set_keep_alive(true);
  7845. cli.set_read_timeout(std::chrono::seconds(1));
  7846. auto resa = cli.Get("/a");
  7847. ASSERT_FALSE(resa);
  7848. EXPECT_EQ(Error::Read, resa.error());
  7849. auto resb = cli.Get("/b");
  7850. ASSERT_TRUE(resb);
  7851. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7852. EXPECT_EQ("b", resb->body);
  7853. }
  7854. TEST(KeepAliveTest, MaxCount) {
  7855. size_t keep_alive_max_count = 3;
  7856. Server svr;
  7857. svr.set_keep_alive_max_count(keep_alive_max_count);
  7858. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7859. res.set_content("Hello World!", "text/plain");
  7860. });
  7861. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7862. auto se = detail::scope_exit([&] {
  7863. svr.stop();
  7864. listen_thread.join();
  7865. ASSERT_FALSE(svr.is_running());
  7866. });
  7867. svr.wait_until_ready();
  7868. Client cli(HOST, PORT);
  7869. cli.set_keep_alive(true);
  7870. for (size_t i = 0; i < 5; i++) {
  7871. auto result = cli.Get("/hi");
  7872. ASSERT_TRUE(result);
  7873. EXPECT_EQ(StatusCode::OK_200, result->status);
  7874. if (i == keep_alive_max_count - 1) {
  7875. EXPECT_EQ("close", result->get_header_value("Connection"));
  7876. } else {
  7877. EXPECT_FALSE(result->has_header("Connection"));
  7878. }
  7879. }
  7880. }
  7881. TEST(KeepAliveTest, Issue1041) {
  7882. Server svr;
  7883. svr.set_keep_alive_timeout(3);
  7884. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7885. res.set_content("Hello World!", "text/plain");
  7886. });
  7887. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7888. auto se = detail::scope_exit([&] {
  7889. svr.stop();
  7890. listen_thread.join();
  7891. ASSERT_FALSE(svr.is_running());
  7892. });
  7893. svr.wait_until_ready();
  7894. Client cli(HOST, PORT);
  7895. cli.set_keep_alive(true);
  7896. auto result = cli.Get("/hi");
  7897. ASSERT_TRUE(result);
  7898. EXPECT_EQ(StatusCode::OK_200, result->status);
  7899. std::this_thread::sleep_for(std::chrono::seconds(5));
  7900. result = cli.Get("/hi");
  7901. ASSERT_TRUE(result);
  7902. EXPECT_EQ(StatusCode::OK_200, result->status);
  7903. }
  7904. TEST(KeepAliveTest, Issue1959) {
  7905. Server svr;
  7906. svr.set_keep_alive_timeout(5);
  7907. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7908. res.set_content("a", "text/plain");
  7909. });
  7910. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7911. auto se = detail::scope_exit([&] {
  7912. if (!svr.is_running()) return;
  7913. svr.stop();
  7914. listen_thread.join();
  7915. ASSERT_FALSE(svr.is_running());
  7916. });
  7917. svr.wait_until_ready();
  7918. Client cli("localhost", PORT);
  7919. cli.set_keep_alive(true);
  7920. using namespace std::chrono;
  7921. auto start = steady_clock::now();
  7922. cli.Get("/a");
  7923. svr.stop();
  7924. listen_thread.join();
  7925. auto end = steady_clock::now();
  7926. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7927. EXPECT_LT(elapsed, 5000);
  7928. }
  7929. #ifdef CPPHTTPLIB_SSL_ENABLED
  7930. TEST(KeepAliveTest, SSLClientReconnection) {
  7931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7932. ASSERT_TRUE(svr.is_valid());
  7933. svr.set_keep_alive_timeout(1);
  7934. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7935. res.set_content("Hello World!", "text/plain");
  7936. });
  7937. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7938. auto se = detail::scope_exit([&] {
  7939. svr.stop();
  7940. listen_thread.join();
  7941. ASSERT_FALSE(svr.is_running());
  7942. });
  7943. svr.wait_until_ready();
  7944. SSLClient cli(HOST, PORT);
  7945. cli.enable_server_certificate_verification(false);
  7946. cli.set_keep_alive(true);
  7947. auto result = cli.Get("/hi");
  7948. ASSERT_TRUE(result);
  7949. EXPECT_EQ(StatusCode::OK_200, result->status);
  7950. result = cli.Get("/hi");
  7951. ASSERT_TRUE(result);
  7952. EXPECT_EQ(StatusCode::OK_200, result->status);
  7953. std::this_thread::sleep_for(std::chrono::seconds(2));
  7954. // Recoonect
  7955. result = cli.Get("/hi");
  7956. ASSERT_TRUE(result);
  7957. EXPECT_EQ(StatusCode::OK_200, result->status);
  7958. result = cli.Get("/hi");
  7959. ASSERT_TRUE(result);
  7960. EXPECT_EQ(StatusCode::OK_200, result->status);
  7961. }
  7962. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7964. ASSERT_TRUE(svr.is_valid());
  7965. svr.set_keep_alive_timeout(1);
  7966. std::string content = "reconnect";
  7967. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7968. res.set_content("Hello World!", "text/plain");
  7969. });
  7970. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7971. auto se = detail::scope_exit([&] {
  7972. svr.stop();
  7973. listen_thread.join();
  7974. ASSERT_FALSE(svr.is_running());
  7975. });
  7976. svr.wait_until_ready();
  7977. SSLClient cli(HOST, PORT);
  7978. cli.enable_server_certificate_verification(false);
  7979. cli.set_keep_alive(true);
  7980. auto result = cli.Post(
  7981. "/hi", content.size(),
  7982. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7983. sink.write(content.c_str(), content.size());
  7984. return true;
  7985. },
  7986. "text/plain");
  7987. ASSERT_TRUE(result);
  7988. EXPECT_EQ(200, result->status);
  7989. std::this_thread::sleep_for(std::chrono::seconds(2));
  7990. // Recoonect
  7991. result = cli.Post(
  7992. "/hi", content.size(),
  7993. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7994. sink.write(content.c_str(), content.size());
  7995. return true;
  7996. },
  7997. "text/plain");
  7998. ASSERT_TRUE(result);
  7999. EXPECT_EQ(200, result->status);
  8000. result = cli.Post(
  8001. "/hi", content.size(),
  8002. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8003. sink.write(content.c_str(), content.size());
  8004. return true;
  8005. },
  8006. "text/plain");
  8007. ASSERT_TRUE(result);
  8008. EXPECT_EQ(200, result->status);
  8009. }
  8010. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  8011. using namespace httplib::tls;
  8012. {
  8013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8014. ASSERT_TRUE(svr.is_valid());
  8015. svr.Get("/sni", [&](const Request &req, Response &res) {
  8016. std::string expected = req.sni();
  8017. EXPECT_EQ(expected, req.get_param_value("expected"));
  8018. res.set_content("ok", "text/plain");
  8019. });
  8020. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  8021. auto se = detail::scope_exit([&] {
  8022. svr.stop();
  8023. listen_thread.join();
  8024. ASSERT_FALSE(svr.is_running());
  8025. });
  8026. svr.wait_until_ready();
  8027. {
  8028. SSLClient cli("localhost", PORT);
  8029. cli.enable_server_certificate_verification(false);
  8030. auto res = cli.Get("/sni?expected=localhost");
  8031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8032. }
  8033. {
  8034. SSLClient cli("::1", PORT);
  8035. cli.enable_server_certificate_verification(false);
  8036. auto res = cli.Get("/sni?expected=");
  8037. // NOTE: This may fail if the server is listening on IPv4 only
  8038. // (e.g., when localhost resolves to 127.0.0.1 only)
  8039. if (res) {
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. } else {
  8042. EXPECT_EQ(Error::Connection, res.error());
  8043. }
  8044. }
  8045. }
  8046. }
  8047. #endif
  8048. TEST(ClientProblemDetectionTest, ContentProvider) {
  8049. Server svr;
  8050. size_t content_length = 1024 * 1024;
  8051. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8052. res.set_content_provider(
  8053. content_length, "text/plain",
  8054. [&](size_t offset, size_t length, DataSink &sink) {
  8055. auto out_len = std::min(length, static_cast<size_t>(1024));
  8056. std::string out(out_len, '@');
  8057. sink.write(out.data(), out_len);
  8058. return offset < 4096;
  8059. },
  8060. [](bool success) { ASSERT_FALSE(success); });
  8061. });
  8062. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  8063. res.set_content_provider(
  8064. 0, "text/plain",
  8065. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  8066. EXPECT_TRUE(false);
  8067. return true;
  8068. },
  8069. [](bool success) { ASSERT_FALSE(success); });
  8070. });
  8071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8072. auto se = detail::scope_exit([&] {
  8073. svr.stop();
  8074. listen_thread.join();
  8075. ASSERT_FALSE(svr.is_running());
  8076. });
  8077. svr.wait_until_ready();
  8078. Client cli("localhost", PORT);
  8079. {
  8080. auto res = cli.Get("/hi", [&](const char * /*data*/,
  8081. size_t /*data_length*/) { return false; });
  8082. ASSERT_FALSE(res);
  8083. }
  8084. {
  8085. auto res = cli.Get("/empty", [&](const char * /*data*/,
  8086. size_t /*data_length*/) { return false; });
  8087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8088. }
  8089. }
  8090. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  8091. Server svr;
  8092. svr.set_error_handler([](Request const &, Response &res) -> void {
  8093. res.set_chunked_content_provider(
  8094. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8095. sink.os << "hello";
  8096. sink.os << "world";
  8097. sink.done();
  8098. return true;
  8099. });
  8100. });
  8101. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8102. auto se = detail::scope_exit([&] {
  8103. svr.stop();
  8104. listen_thread.join();
  8105. ASSERT_FALSE(svr.is_running());
  8106. });
  8107. svr.wait_until_ready();
  8108. Client cli("localhost", PORT);
  8109. auto res = cli.Get("/");
  8110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8111. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8112. EXPECT_EQ("helloworld", res->body);
  8113. }
  8114. TEST(LongPollingTest, ClientCloseDetection) {
  8115. Server svr;
  8116. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8117. res.set_chunked_content_provider(
  8118. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8119. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8120. sink.os << "hello";
  8121. auto count = 10;
  8122. while (count > 0 && sink.is_writable()) {
  8123. this_thread::sleep_for(chrono::milliseconds(10));
  8124. count--;
  8125. }
  8126. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  8127. return true;
  8128. });
  8129. });
  8130. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8131. auto se = detail::scope_exit([&] {
  8132. svr.stop();
  8133. listen_thread.join();
  8134. ASSERT_FALSE(svr.is_running());
  8135. });
  8136. svr.wait_until_ready();
  8137. Client cli("localhost", PORT);
  8138. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8139. EXPECT_EQ("hello", string(data, data_length));
  8140. return false; // close the socket immediately.
  8141. });
  8142. ASSERT_FALSE(res);
  8143. }
  8144. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  8145. Server svr;
  8146. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  8147. res.set_chunked_content_provider(
  8148. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  8149. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  8150. sink.os << "hello";
  8151. EXPECT_TRUE(sink.os.good());
  8152. // Wait for the client to close the connection
  8153. auto count = 10;
  8154. while (count > 0 && sink.is_writable()) {
  8155. this_thread::sleep_for(chrono::milliseconds(10));
  8156. count--;
  8157. }
  8158. // After client disconnect, write repeatedly until the socket
  8159. // write actually fails (small writes may be absorbed by the
  8160. // kernel buffer)
  8161. std::string chunk(1024, 'x');
  8162. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  8163. sink.os << chunk;
  8164. }
  8165. EXPECT_TRUE(sink.os.fail());
  8166. return true;
  8167. });
  8168. });
  8169. auto port = svr.bind_to_any_port("localhost");
  8170. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  8171. auto se = detail::scope_exit([&] {
  8172. svr.stop();
  8173. listen_thread.join();
  8174. ASSERT_FALSE(svr.is_running());
  8175. });
  8176. svr.wait_until_ready();
  8177. Client cli("localhost", port);
  8178. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  8179. EXPECT_EQ("hello", string(data, data_length));
  8180. return false; // close the socket immediately.
  8181. });
  8182. ASSERT_FALSE(res);
  8183. }
  8184. TEST(GetWithParametersTest, GetWithParameters) {
  8185. Server svr;
  8186. svr.Get("/", [&](const Request &req, Response &) {
  8187. EXPECT_EQ("world", req.get_param_value("hello"));
  8188. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8189. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8190. });
  8191. svr.Get("/params", [&](const Request &req, Response &) {
  8192. EXPECT_EQ("world", req.get_param_value("hello"));
  8193. EXPECT_EQ("world2", req.get_param_value("hello2"));
  8194. EXPECT_EQ("world3", req.get_param_value("hello3"));
  8195. });
  8196. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  8197. EXPECT_EQ("resource-id", req.matches[1]);
  8198. EXPECT_EQ("foo", req.get_param_value("param1"));
  8199. EXPECT_EQ("bar", req.get_param_value("param2"));
  8200. });
  8201. svr.Get("/users/:id", [&](const Request &req, Response &) {
  8202. EXPECT_EQ("user-id", req.path_params.at("id"));
  8203. EXPECT_EQ("foo", req.get_param_value("param1"));
  8204. EXPECT_EQ("bar", req.get_param_value("param2"));
  8205. });
  8206. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8207. auto se = detail::scope_exit([&] {
  8208. svr.stop();
  8209. listen_thread.join();
  8210. ASSERT_FALSE(svr.is_running());
  8211. });
  8212. svr.wait_until_ready();
  8213. {
  8214. Client cli(HOST, PORT);
  8215. Params params;
  8216. params.emplace("hello", "world");
  8217. params.emplace("hello2", "world2");
  8218. params.emplace("hello3", "world3");
  8219. auto res = cli.Get("/", params, Headers{});
  8220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8221. EXPECT_EQ(StatusCode::OK_200, res->status);
  8222. }
  8223. {
  8224. Client cli(HOST, PORT);
  8225. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  8226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8227. EXPECT_EQ(StatusCode::OK_200, res->status);
  8228. }
  8229. {
  8230. Client cli(HOST, PORT);
  8231. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  8232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8233. EXPECT_EQ(StatusCode::OK_200, res->status);
  8234. }
  8235. {
  8236. Client cli(HOST, PORT);
  8237. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  8238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8239. EXPECT_EQ(StatusCode::OK_200, res->status);
  8240. }
  8241. }
  8242. TEST(GetWithParametersTest, GetWithParameters2) {
  8243. Server svr;
  8244. svr.Get("/", [&](const Request &req, Response &res) {
  8245. auto text = req.get_param_value("hello");
  8246. res.set_content(text, "text/plain");
  8247. });
  8248. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8249. auto se = detail::scope_exit([&] {
  8250. svr.stop();
  8251. listen_thread.join();
  8252. ASSERT_FALSE(svr.is_running());
  8253. });
  8254. svr.wait_until_ready();
  8255. Client cli("localhost", PORT);
  8256. Params params;
  8257. params.emplace("hello", "world");
  8258. std::string body;
  8259. auto res = cli.Get("/", params, Headers{},
  8260. [&](const char *data, size_t data_length) {
  8261. body.append(data, data_length);
  8262. return true;
  8263. });
  8264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8265. EXPECT_EQ(StatusCode::OK_200, res->status);
  8266. EXPECT_EQ("world", body);
  8267. }
  8268. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  8269. Server svr;
  8270. svr.Get("/search", [&](const Request &req, Response &res) {
  8271. auto q = req.get_param_value("q");
  8272. res.set_content(q, "text/plain");
  8273. });
  8274. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8275. auto se = detail::scope_exit([&] {
  8276. svr.stop();
  8277. listen_thread.join();
  8278. ASSERT_FALSE(svr.is_running());
  8279. });
  8280. svr.wait_until_ready();
  8281. Client cli("localhost", PORT);
  8282. // Verify that Get(path, params) works without requiring Headers argument
  8283. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  8284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8285. EXPECT_EQ(StatusCode::OK_200, res->status);
  8286. EXPECT_EQ("cpp-httplib", res->body);
  8287. }
  8288. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  8289. auto host = "httpbingo.org";
  8290. auto path = std::string{"/range/32"};
  8291. #ifdef CPPHTTPLIB_SSL_ENABLED
  8292. SSLClient cli(host);
  8293. #else
  8294. Client cli(host);
  8295. #endif
  8296. cli.set_default_headers({make_range_header({{1, 10}})});
  8297. cli.set_connection_timeout(5);
  8298. {
  8299. auto res = cli.Get(path);
  8300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8301. EXPECT_EQ("bcdefghijk", res->body);
  8302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8303. }
  8304. {
  8305. auto res = cli.Get(path);
  8306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8307. EXPECT_EQ("bcdefghijk", res->body);
  8308. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8309. }
  8310. }
  8311. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  8312. Server svr;
  8313. svr.set_default_headers({{"Hello", "World"}});
  8314. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  8315. res.set_content("ok", "text/plain");
  8316. });
  8317. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8318. auto se = detail::scope_exit([&] {
  8319. svr.stop();
  8320. listen_thread.join();
  8321. ASSERT_FALSE(svr.is_running());
  8322. });
  8323. svr.wait_until_ready();
  8324. Client cli("localhost", PORT);
  8325. auto res = cli.Get("/");
  8326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8327. EXPECT_EQ(StatusCode::OK_200, res->status);
  8328. EXPECT_EQ("ok", res->body);
  8329. EXPECT_EQ("World", res->get_header_value("Hello"));
  8330. }
  8331. #ifdef CPPHTTPLIB_SSL_ENABLED
  8332. TEST(KeepAliveTest, ReadTimeoutSSL) {
  8333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8334. ASSERT_TRUE(svr.is_valid());
  8335. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  8336. std::this_thread::sleep_for(std::chrono::seconds(2));
  8337. res.set_content("a", "text/plain");
  8338. });
  8339. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  8340. res.set_content("b", "text/plain");
  8341. });
  8342. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8343. auto se = detail::scope_exit([&] {
  8344. svr.stop();
  8345. listen_thread.join();
  8346. ASSERT_FALSE(svr.is_running());
  8347. });
  8348. svr.wait_until_ready();
  8349. SSLClient cli("localhost", PORT);
  8350. cli.enable_server_certificate_verification(false);
  8351. cli.set_keep_alive(true);
  8352. cli.set_read_timeout(std::chrono::seconds(1));
  8353. auto resa = cli.Get("/a");
  8354. ASSERT_TRUE(!resa);
  8355. EXPECT_EQ(Error::Read, resa.error());
  8356. auto resb = cli.Get("/b");
  8357. ASSERT_TRUE(resb);
  8358. EXPECT_EQ(StatusCode::OK_200, resb->status);
  8359. EXPECT_EQ("b", resb->body);
  8360. }
  8361. #endif
  8362. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  8363. protected:
  8364. ServerTestWithAI_PASSIVE()
  8365. : cli_(HOST, PORT)
  8366. #ifdef CPPHTTPLIB_SSL_ENABLED
  8367. ,
  8368. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8369. #endif
  8370. {
  8371. #ifdef CPPHTTPLIB_SSL_ENABLED
  8372. cli_.enable_server_certificate_verification(false);
  8373. #endif
  8374. }
  8375. virtual void SetUp() {
  8376. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8377. res.set_content("Hello World!", "text/plain");
  8378. });
  8379. t_ = thread(
  8380. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  8381. svr_.wait_until_ready();
  8382. }
  8383. virtual void TearDown() {
  8384. svr_.stop();
  8385. t_.join();
  8386. }
  8387. #ifdef CPPHTTPLIB_SSL_ENABLED
  8388. SSLClient cli_;
  8389. SSLServer svr_;
  8390. #else
  8391. Client cli_;
  8392. Server svr_;
  8393. #endif
  8394. thread t_;
  8395. };
  8396. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  8397. auto res = cli_.Get("/hi");
  8398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8399. EXPECT_EQ(StatusCode::OK_200, res->status);
  8400. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8401. EXPECT_EQ("Hello World!", res->body);
  8402. }
  8403. class ServerUpDownTest : public ::testing::Test {
  8404. protected:
  8405. ServerUpDownTest() : cli_(HOST, PORT) {}
  8406. virtual void SetUp() {
  8407. t_ = thread([&]() {
  8408. svr_.bind_to_any_port(HOST);
  8409. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  8410. ASSERT_TRUE(svr_.listen_after_bind());
  8411. });
  8412. svr_.wait_until_ready();
  8413. }
  8414. virtual void TearDown() {
  8415. svr_.stop();
  8416. t_.join();
  8417. }
  8418. Client cli_;
  8419. Server svr_;
  8420. thread t_;
  8421. };
  8422. TEST_F(ServerUpDownTest, QuickStartStop) {
  8423. // Should not crash, especially when run with
  8424. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  8425. }
  8426. class PayloadMaxLengthTest : public ::testing::Test {
  8427. protected:
  8428. PayloadMaxLengthTest()
  8429. : cli_(HOST, PORT)
  8430. #ifdef CPPHTTPLIB_SSL_ENABLED
  8431. ,
  8432. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8433. #endif
  8434. {
  8435. #ifdef CPPHTTPLIB_SSL_ENABLED
  8436. cli_.enable_server_certificate_verification(false);
  8437. #endif
  8438. }
  8439. virtual void SetUp() {
  8440. svr_.set_payload_max_length(8);
  8441. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8442. res.set_content("test", "text/plain");
  8443. });
  8444. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8445. svr_.wait_until_ready();
  8446. }
  8447. virtual void TearDown() {
  8448. svr_.stop();
  8449. t_.join();
  8450. }
  8451. #ifdef CPPHTTPLIB_SSL_ENABLED
  8452. SSLClient cli_;
  8453. SSLServer svr_;
  8454. #else
  8455. Client cli_;
  8456. Server svr_;
  8457. #endif
  8458. thread t_;
  8459. };
  8460. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  8461. auto res = cli_.Post("/test", "123456789", "text/plain");
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8464. res = cli_.Post("/test", "12345678", "text/plain");
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  8469. // Test chunked encoding with payload exceeding the 8-byte limit
  8470. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  8471. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  8472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8473. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8474. }
  8475. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  8476. // Test chunked encoding with payload within the 8-byte limit
  8477. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  8478. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(StatusCode::OK_200, res->status);
  8481. }
  8482. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  8483. // Test using send_request to send chunked data exceeding payload limit
  8484. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  8485. "Host: " +
  8486. std::string(HOST) + ":" + std::to_string(PORT) +
  8487. "\r\n"
  8488. "Transfer-Encoding: chunked\r\n"
  8489. "Connection: close\r\n"
  8490. "\r\n"
  8491. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  8492. "0123456789\r\n"
  8493. "0\r\n" // End chunk
  8494. "\r\n";
  8495. std::string response;
  8496. bool result = send_request(1, chunked_request, &response);
  8497. if (!result) {
  8498. // If send_request fails, it might be because the server closed the
  8499. // connection due to payload limit enforcement, which is acceptable
  8500. SUCCEED()
  8501. << "Server rejected oversized chunked request (connection closed)";
  8502. } else {
  8503. // If we got a response, check if it's an error response or connection was
  8504. // closed early Short response length indicates connection was closed due to
  8505. // payload limit
  8506. if (response.length() <= 10) {
  8507. SUCCEED() << "Server closed connection for oversized chunked request";
  8508. } else {
  8509. // Check for error status codes
  8510. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8511. response.find("Payload Too Large") != std::string::npos ||
  8512. response.find("400") != std::string::npos);
  8513. }
  8514. }
  8515. }
  8516. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  8517. // Test request without Content-Length header exceeding payload limit
  8518. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8519. "Host: " +
  8520. std::string(HOST) + ":" +
  8521. std::to_string(PORT) +
  8522. "\r\n"
  8523. "Connection: close\r\n"
  8524. "\r\n";
  8525. // Add payload exceeding the 8-byte limit
  8526. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  8527. request_without_content_length += large_payload;
  8528. std::string response;
  8529. bool result = send_request(1, request_without_content_length, &response);
  8530. if (!result) {
  8531. // If send_request fails, server likely closed connection due to payload
  8532. // limit
  8533. SUCCEED() << "Server rejected oversized request without Content-Length "
  8534. "(connection closed)";
  8535. } else {
  8536. // Check if server responded with error or closed connection early
  8537. if (response.length() <= 10) {
  8538. SUCCEED() << "Server closed connection for oversized request without "
  8539. "Content-Length";
  8540. } else {
  8541. // Check for error status codes
  8542. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8543. response.find("Payload Too Large") != std::string::npos ||
  8544. response.find("400") != std::string::npos);
  8545. }
  8546. }
  8547. }
  8548. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  8549. // Test request without Content-Length header within payload limit
  8550. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8551. "Host: " +
  8552. std::string(HOST) + ":" +
  8553. std::to_string(PORT) +
  8554. "\r\n"
  8555. "Connection: close\r\n"
  8556. "\r\n";
  8557. // Add payload within the 8-byte limit
  8558. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  8559. request_without_content_length += small_payload;
  8560. std::string response;
  8561. bool result = send_request(1, request_without_content_length, &response);
  8562. // For requests without Content-Length, the server may have different behavior
  8563. // The key is that it should not reject due to payload limit for small
  8564. // payloads
  8565. if (result) {
  8566. // Check for any HTTP response (success or error, but not connection closed)
  8567. if (response.length() > 10) {
  8568. SUCCEED()
  8569. << "Server processed request without Content-Length within limit";
  8570. } else {
  8571. // Short response might indicate connection closed, which is acceptable
  8572. SUCCEED() << "Server closed connection for request without "
  8573. "Content-Length (acceptable behavior)";
  8574. }
  8575. } else {
  8576. // Connection failure might be due to protocol requirements
  8577. SUCCEED() << "Connection issue with request without Content-Length "
  8578. "(environment-specific)";
  8579. }
  8580. }
  8581. class LargePayloadMaxLengthTest : public ::testing::Test {
  8582. protected:
  8583. LargePayloadMaxLengthTest()
  8584. : cli_(HOST, PORT)
  8585. #ifdef CPPHTTPLIB_SSL_ENABLED
  8586. ,
  8587. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  8588. #endif
  8589. {
  8590. #ifdef CPPHTTPLIB_SSL_ENABLED
  8591. cli_.enable_server_certificate_verification(false);
  8592. #endif
  8593. }
  8594. virtual void SetUp() {
  8595. // Set 10MB payload limit
  8596. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  8597. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  8598. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  8599. res.set_content("Large payload test", "text/plain");
  8600. });
  8601. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  8602. svr_.wait_until_ready();
  8603. }
  8604. virtual void TearDown() {
  8605. svr_.stop();
  8606. t_.join();
  8607. }
  8608. #ifdef CPPHTTPLIB_SSL_ENABLED
  8609. SSLClient cli_;
  8610. SSLServer svr_;
  8611. #else
  8612. Client cli_;
  8613. Server svr_;
  8614. #endif
  8615. thread t_;
  8616. };
  8617. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  8618. // Test chunked encoding with payload within 10MB limit
  8619. std::string medium_payload(5 * 1024 * 1024,
  8620. 'A'); // 5MB payload, within 10MB limit
  8621. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  8622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. }
  8625. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  8626. // Test chunked encoding with payload exceeding 10MB limit
  8627. std::string large_payload(12 * 1024 * 1024,
  8628. 'B'); // 12MB payload, exceeds 10MB limit
  8629. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  8630. // Server may either return 413 or close the connection
  8631. if (res) {
  8632. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8633. } else {
  8634. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  8635. }
  8636. }
  8637. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  8638. // Test request without Content-Length header within 10MB limit
  8639. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8640. "Host: " +
  8641. std::string(HOST) + ":" +
  8642. std::to_string(PORT) +
  8643. "\r\n"
  8644. "Connection: close\r\n"
  8645. "\r\n";
  8646. // Add 1MB payload (within 10MB limit)
  8647. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  8648. request_without_content_length += medium_payload;
  8649. std::string response;
  8650. bool result = send_request(5, request_without_content_length, &response);
  8651. if (result) {
  8652. // Should get a proper HTTP response for payloads within limit
  8653. if (response.length() > 10) {
  8654. SUCCEED() << "Server processed 1MB request without Content-Length within "
  8655. "10MB limit";
  8656. } else {
  8657. SUCCEED() << "Server closed connection (acceptable behavior for no "
  8658. "Content-Length)";
  8659. }
  8660. } else {
  8661. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  8662. }
  8663. }
  8664. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  8665. // Test request without Content-Length header exceeding 10MB limit
  8666. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  8667. "Host: " +
  8668. std::string(HOST) + ":" +
  8669. std::to_string(PORT) +
  8670. "\r\n"
  8671. "Connection: close\r\n"
  8672. "\r\n";
  8673. // Add 12MB payload (exceeds 10MB limit)
  8674. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  8675. request_without_content_length += large_payload;
  8676. std::string response;
  8677. bool result = send_request(10, request_without_content_length, &response);
  8678. if (!result) {
  8679. // Server should close connection due to payload limit
  8680. SUCCEED() << "Server rejected 12MB request without Content-Length "
  8681. "(connection closed)";
  8682. } else {
  8683. // Check for error response
  8684. if (response.length() <= 10) {
  8685. SUCCEED()
  8686. << "Server closed connection for 12MB request exceeding 10MB limit";
  8687. } else {
  8688. EXPECT_TRUE(response.find("413") != std::string::npos ||
  8689. response.find("Payload Too Large") != std::string::npos ||
  8690. response.find("400") != std::string::npos);
  8691. }
  8692. }
  8693. }
  8694. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8695. // `payload_max_length` is not enforced on decompressed body in ContentReader
  8696. // path.
  8697. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  8698. Server svr;
  8699. const size_t LIMIT = 64 * 1024; // 64KB
  8700. svr.set_payload_max_length(LIMIT);
  8701. size_t total = 0;
  8702. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  8703. const ContentReader &content_reader) {
  8704. content_reader([&](const char * /*data*/, size_t len) {
  8705. total += len;
  8706. return true;
  8707. });
  8708. res.status = 200;
  8709. res.set_content("stream_ok", "text/plain");
  8710. });
  8711. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8712. auto se = detail::scope_exit([&] {
  8713. svr.stop();
  8714. thread.join();
  8715. ASSERT_FALSE(svr.is_running());
  8716. });
  8717. svr.wait_until_ready();
  8718. // Prepare 256KB raw data and gzip-compress it
  8719. std::string raw(256 * 1024, 'A');
  8720. std::string gz;
  8721. {
  8722. z_stream zs{};
  8723. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  8724. Z_DEFAULT_STRATEGY);
  8725. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  8726. zs.avail_in = static_cast<uInt>(raw.size());
  8727. char outbuf[4096];
  8728. int ret;
  8729. do {
  8730. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  8731. zs.avail_out = sizeof(outbuf);
  8732. ret = deflate(&zs, Z_FINISH);
  8733. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  8734. } while (ret != Z_STREAM_END);
  8735. deflateEnd(&zs);
  8736. }
  8737. Client cli(HOST, PORT);
  8738. cli.set_connection_timeout(std::chrono::seconds(5));
  8739. Headers headers = {{"Content-Encoding", "gzip"}};
  8740. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  8741. "application/octet-stream");
  8742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8743. // Server must reject oversized decompressed payloads with 413.
  8744. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  8745. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  8746. EXPECT_LE(total, LIMIT);
  8747. }
  8748. #endif
  8749. // Regression test for DoS vulnerability: a malicious server sending a response
  8750. // without Content-Length header must not cause unbounded memory consumption on
  8751. // the client side. The client should stop reading after a reasonable limit,
  8752. // similar to the server-side set_payload_max_length protection.
  8753. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  8754. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8755. #ifndef _WIN32
  8756. signal(SIGPIPE, SIG_IGN);
  8757. #endif
  8758. auto server_thread = std::thread([] {
  8759. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  8760. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8761. default_socket_options(srv);
  8762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8763. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8764. sockaddr_in addr{};
  8765. addr.sin_family = AF_INET;
  8766. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8768. int opt = 1;
  8769. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8770. #ifdef _WIN32
  8771. reinterpret_cast<const char *>(&opt),
  8772. #else
  8773. &opt,
  8774. #endif
  8775. sizeof(opt));
  8776. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8777. ::listen(srv, 1);
  8778. sockaddr_in cli_addr{};
  8779. socklen_t cli_len = sizeof(cli_addr);
  8780. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8781. if (cli != INVALID_SOCKET) {
  8782. char buf[4096];
  8783. ::recv(cli, buf, sizeof(buf), 0);
  8784. // Malicious response: no Content-Length, no chunked encoding
  8785. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8786. "Connection: close\r\n"
  8787. "\r\n";
  8788. ::send(cli,
  8789. #ifdef _WIN32
  8790. static_cast<const char *>(response_header.c_str()),
  8791. static_cast<int>(response_header.size()),
  8792. #else
  8793. response_header.c_str(), response_header.size(),
  8794. #endif
  8795. 0);
  8796. // Send 10MB of data
  8797. std::string chunk(64 * 1024, 'A');
  8798. size_t total_sent = 0;
  8799. while (total_sent < MALICIOUS_DATA_SIZE) {
  8800. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  8801. auto sent = ::send(cli,
  8802. #ifdef _WIN32
  8803. static_cast<const char *>(chunk.c_str()),
  8804. static_cast<int>(to_send),
  8805. #else
  8806. chunk.c_str(), to_send,
  8807. #endif
  8808. 0);
  8809. if (sent <= 0) break;
  8810. total_sent += static_cast<size_t>(sent);
  8811. }
  8812. detail::close_socket(cli);
  8813. }
  8814. detail::close_socket(srv);
  8815. });
  8816. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8817. size_t total_read = 0;
  8818. {
  8819. Client cli("127.0.0.1", PORT + 2);
  8820. cli.set_read_timeout(5, 0);
  8821. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8822. auto stream = cli.open_stream("GET", "/malicious");
  8823. ASSERT_TRUE(stream.is_valid());
  8824. char buffer[64 * 1024];
  8825. ssize_t n;
  8826. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8827. total_read += static_cast<size_t>(n);
  8828. }
  8829. } // StreamHandle and Client destroyed here, closing the socket
  8830. server_thread.join();
  8831. // With set_payload_max_length, the client must stop reading before consuming
  8832. // all 10MB. The read loop should be cut off at or near the configured limit.
  8833. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  8834. << "Client read " << total_read << " bytes, exceeding the configured "
  8835. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  8836. }
  8837. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  8838. // the entire response body without truncation.
  8839. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  8840. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  8841. #ifndef _WIN32
  8842. signal(SIGPIPE, SIG_IGN);
  8843. #endif
  8844. auto server_thread = std::thread([] {
  8845. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8846. default_socket_options(srv);
  8847. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8848. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8849. sockaddr_in addr{};
  8850. addr.sin_family = AF_INET;
  8851. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8852. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8853. int opt = 1;
  8854. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8855. #ifdef _WIN32
  8856. reinterpret_cast<const char *>(&opt),
  8857. #else
  8858. &opt,
  8859. #endif
  8860. sizeof(opt));
  8861. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8862. ::listen(srv, 1);
  8863. sockaddr_in cli_addr{};
  8864. socklen_t cli_len = sizeof(cli_addr);
  8865. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8866. if (cli != INVALID_SOCKET) {
  8867. char buf[4096];
  8868. ::recv(cli, buf, sizeof(buf), 0);
  8869. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8870. "Connection: close\r\n"
  8871. "\r\n";
  8872. ::send(cli,
  8873. #ifdef _WIN32
  8874. static_cast<const char *>(response_header.c_str()),
  8875. static_cast<int>(response_header.size()),
  8876. #else
  8877. response_header.c_str(), response_header.size(),
  8878. #endif
  8879. 0);
  8880. std::string chunk(64 * 1024, 'A');
  8881. size_t total_sent = 0;
  8882. while (total_sent < DATA_SIZE) {
  8883. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8884. auto sent = ::send(cli,
  8885. #ifdef _WIN32
  8886. static_cast<const char *>(chunk.c_str()),
  8887. static_cast<int>(to_send),
  8888. #else
  8889. chunk.c_str(), to_send,
  8890. #endif
  8891. 0);
  8892. if (sent <= 0) break;
  8893. total_sent += static_cast<size_t>(sent);
  8894. }
  8895. #ifdef _WIN32
  8896. ::shutdown(cli, SD_SEND);
  8897. #else
  8898. ::shutdown(cli, SHUT_WR);
  8899. #endif
  8900. // Drain until the client closes its end, ensuring all data is delivered
  8901. char drain[1024];
  8902. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8903. detail::close_socket(cli);
  8904. }
  8905. detail::close_socket(srv);
  8906. });
  8907. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8908. size_t total_read = 0;
  8909. {
  8910. Client cli("127.0.0.1", PORT + 2);
  8911. cli.set_read_timeout(5, 0);
  8912. cli.set_payload_max_length(0); // 0 means no limit
  8913. auto stream = cli.open_stream("GET", "/data");
  8914. ASSERT_TRUE(stream.is_valid());
  8915. char buffer[64 * 1024];
  8916. ssize_t n;
  8917. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8918. total_read += static_cast<size_t>(n);
  8919. }
  8920. }
  8921. server_thread.join();
  8922. EXPECT_EQ(total_read, DATA_SIZE)
  8923. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8924. << " bytes without truncation, but only read " << total_read << " bytes.";
  8925. }
  8926. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8927. // enormous Content-Length must not cause the client to pre-allocate a huge
  8928. // response body buffer. The reservation is capped at payload_max_length_, and
  8929. // the read itself fails when the body exceeds the limit.
  8930. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8931. #ifndef _WIN32
  8932. signal(SIGPIPE, SIG_IGN);
  8933. #endif
  8934. auto server_thread = std::thread([] {
  8935. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8936. default_socket_options(srv);
  8937. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8938. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8939. sockaddr_in addr{};
  8940. addr.sin_family = AF_INET;
  8941. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8942. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8943. int opt = 1;
  8944. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8945. #ifdef _WIN32
  8946. reinterpret_cast<const char *>(&opt),
  8947. #else
  8948. &opt,
  8949. #endif
  8950. sizeof(opt));
  8951. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8952. ::listen(srv, 1);
  8953. sockaddr_in cli_addr{};
  8954. socklen_t cli_len = sizeof(cli_addr);
  8955. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8956. if (cli != INVALID_SOCKET) {
  8957. char buf[4096];
  8958. ::recv(cli, buf, sizeof(buf), 0);
  8959. // Malicious response: claim a 20GB body but send only a tiny payload.
  8960. std::string response = "HTTP/1.1 200 OK\r\n"
  8961. "Content-Length: 20000000000\r\n"
  8962. "\r\n"
  8963. "abc";
  8964. ::send(cli,
  8965. #ifdef _WIN32
  8966. static_cast<const char *>(response.c_str()),
  8967. static_cast<int>(response.size()),
  8968. #else
  8969. response.c_str(), response.size(),
  8970. #endif
  8971. 0);
  8972. detail::close_socket(cli);
  8973. }
  8974. detail::close_socket(srv);
  8975. });
  8976. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8977. {
  8978. Client cli("127.0.0.1", PORT + 2);
  8979. cli.set_read_timeout(5, 0);
  8980. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8981. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8982. // (server claims more bytes than payload_max_length permits), but it must
  8983. // not exhaust memory before getting there.
  8984. auto res = cli.Get("/malicious");
  8985. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8986. }
  8987. server_thread.join();
  8988. }
  8989. // Verify that content_receiver bypasses the default payload_max_length,
  8990. // allowing streaming downloads larger than 100MB without requiring an explicit
  8991. // set_payload_max_length call.
  8992. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8993. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8994. #ifndef _WIN32
  8995. signal(SIGPIPE, SIG_IGN);
  8996. #endif
  8997. auto server_thread = std::thread([] {
  8998. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8999. default_socket_options(srv);
  9000. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9001. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9002. sockaddr_in addr{};
  9003. addr.sin_family = AF_INET;
  9004. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9005. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9006. int opt = 1;
  9007. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9008. #ifdef _WIN32
  9009. reinterpret_cast<const char *>(&opt),
  9010. #else
  9011. &opt,
  9012. #endif
  9013. sizeof(opt));
  9014. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9015. ::listen(srv, 1);
  9016. sockaddr_in cli_addr{};
  9017. socklen_t cli_len = sizeof(cli_addr);
  9018. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9019. if (cli != INVALID_SOCKET) {
  9020. char buf[4096];
  9021. ::recv(cli, buf, sizeof(buf), 0);
  9022. // Response with Content-Length larger than default 100MB limit
  9023. auto content_length = std::to_string(DATA_SIZE);
  9024. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9025. "Content-Length: " +
  9026. content_length +
  9027. "\r\n"
  9028. "Connection: close\r\n"
  9029. "\r\n";
  9030. ::send(cli,
  9031. #ifdef _WIN32
  9032. static_cast<const char *>(response_header.c_str()),
  9033. static_cast<int>(response_header.size()),
  9034. #else
  9035. response_header.c_str(), response_header.size(),
  9036. #endif
  9037. 0);
  9038. std::string chunk(64 * 1024, 'A');
  9039. size_t total_sent = 0;
  9040. while (total_sent < DATA_SIZE) {
  9041. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9042. auto sent = ::send(cli,
  9043. #ifdef _WIN32
  9044. static_cast<const char *>(chunk.c_str()),
  9045. static_cast<int>(to_send),
  9046. #else
  9047. chunk.c_str(), to_send,
  9048. #endif
  9049. 0);
  9050. if (sent <= 0) break;
  9051. total_sent += static_cast<size_t>(sent);
  9052. }
  9053. detail::close_socket(cli);
  9054. }
  9055. detail::close_socket(srv);
  9056. });
  9057. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9058. size_t total_received = 0;
  9059. {
  9060. Client cli("127.0.0.1", PORT + 2);
  9061. cli.set_read_timeout(10, 0);
  9062. // Do NOT call set_payload_max_length — use the default 100MB limit
  9063. auto res =
  9064. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9065. total_received += data_length;
  9066. return true;
  9067. });
  9068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. }
  9071. server_thread.join();
  9072. EXPECT_EQ(total_received, DATA_SIZE)
  9073. << "With content_receiver, the client should read all " << DATA_SIZE
  9074. << " bytes despite the default 100MB payload_max_length, but only read "
  9075. << total_received << " bytes.";
  9076. }
  9077. // Verify that an explicit set_payload_max_length smaller than the response is
  9078. // enforced even when a content_receiver is used.
  9079. TEST(ClientVulnerabilityTest,
  9080. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  9081. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9082. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  9083. #ifndef _WIN32
  9084. signal(SIGPIPE, SIG_IGN);
  9085. #endif
  9086. auto server_thread = std::thread([] {
  9087. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9088. default_socket_options(srv);
  9089. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9090. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9091. sockaddr_in addr{};
  9092. addr.sin_family = AF_INET;
  9093. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9094. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9095. int opt = 1;
  9096. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9097. #ifdef _WIN32
  9098. reinterpret_cast<const char *>(&opt),
  9099. #else
  9100. &opt,
  9101. #endif
  9102. sizeof(opt));
  9103. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9104. ::listen(srv, 1);
  9105. sockaddr_in cli_addr{};
  9106. socklen_t cli_len = sizeof(cli_addr);
  9107. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9108. if (cli != INVALID_SOCKET) {
  9109. char buf[4096];
  9110. ::recv(cli, buf, sizeof(buf), 0);
  9111. auto content_length = std::to_string(DATA_SIZE);
  9112. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9113. "Content-Length: " +
  9114. content_length +
  9115. "\r\n"
  9116. "Connection: close\r\n"
  9117. "\r\n";
  9118. ::send(cli,
  9119. #ifdef _WIN32
  9120. static_cast<const char *>(response_header.c_str()),
  9121. static_cast<int>(response_header.size()),
  9122. #else
  9123. response_header.c_str(), response_header.size(),
  9124. #endif
  9125. 0);
  9126. std::string chunk(64 * 1024, 'A');
  9127. size_t total_sent = 0;
  9128. while (total_sent < DATA_SIZE) {
  9129. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9130. auto sent = ::send(cli,
  9131. #ifdef _WIN32
  9132. static_cast<const char *>(chunk.c_str()),
  9133. static_cast<int>(to_send),
  9134. #else
  9135. chunk.c_str(), to_send,
  9136. #endif
  9137. 0);
  9138. if (sent <= 0) break;
  9139. total_sent += static_cast<size_t>(sent);
  9140. }
  9141. detail::close_socket(cli);
  9142. }
  9143. detail::close_socket(srv);
  9144. });
  9145. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9146. size_t total_received = 0;
  9147. {
  9148. Client cli("127.0.0.1", PORT + 2);
  9149. cli.set_read_timeout(10, 0);
  9150. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  9151. auto res =
  9152. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9153. total_received += data_length;
  9154. return true;
  9155. });
  9156. // Should fail because 200MB exceeds the explicit 150MB limit
  9157. EXPECT_FALSE(res);
  9158. }
  9159. server_thread.join();
  9160. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  9161. << "Client with content_receiver should respect the explicit "
  9162. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  9163. << total_received << " bytes.";
  9164. }
  9165. // Verify that an explicit set_payload_max_length larger than the response
  9166. // allows the content_receiver to read all data successfully.
  9167. TEST(ClientVulnerabilityTest,
  9168. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  9169. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  9170. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  9171. #ifndef _WIN32
  9172. signal(SIGPIPE, SIG_IGN);
  9173. #endif
  9174. auto server_thread = std::thread([] {
  9175. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9176. default_socket_options(srv);
  9177. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9178. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9179. sockaddr_in addr{};
  9180. addr.sin_family = AF_INET;
  9181. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  9182. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9183. int opt = 1;
  9184. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9185. #ifdef _WIN32
  9186. reinterpret_cast<const char *>(&opt),
  9187. #else
  9188. &opt,
  9189. #endif
  9190. sizeof(opt));
  9191. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9192. ::listen(srv, 1);
  9193. sockaddr_in cli_addr{};
  9194. socklen_t cli_len = sizeof(cli_addr);
  9195. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9196. if (cli != INVALID_SOCKET) {
  9197. char buf[4096];
  9198. ::recv(cli, buf, sizeof(buf), 0);
  9199. auto content_length = std::to_string(DATA_SIZE);
  9200. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9201. "Content-Length: " +
  9202. content_length +
  9203. "\r\n"
  9204. "Connection: close\r\n"
  9205. "\r\n";
  9206. ::send(cli,
  9207. #ifdef _WIN32
  9208. static_cast<const char *>(response_header.c_str()),
  9209. static_cast<int>(response_header.size()),
  9210. #else
  9211. response_header.c_str(), response_header.size(),
  9212. #endif
  9213. 0);
  9214. std::string chunk(64 * 1024, 'A');
  9215. size_t total_sent = 0;
  9216. while (total_sent < DATA_SIZE) {
  9217. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  9218. auto sent = ::send(cli,
  9219. #ifdef _WIN32
  9220. static_cast<const char *>(chunk.c_str()),
  9221. static_cast<int>(to_send),
  9222. #else
  9223. chunk.c_str(), to_send,
  9224. #endif
  9225. 0);
  9226. if (sent <= 0) break;
  9227. total_sent += static_cast<size_t>(sent);
  9228. }
  9229. #ifdef _WIN32
  9230. ::shutdown(cli, SD_SEND);
  9231. #else
  9232. ::shutdown(cli, SHUT_WR);
  9233. #endif
  9234. char drain[1024];
  9235. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  9236. detail::close_socket(cli);
  9237. }
  9238. detail::close_socket(srv);
  9239. });
  9240. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9241. size_t total_received = 0;
  9242. {
  9243. Client cli("127.0.0.1", PORT + 2);
  9244. cli.set_read_timeout(10, 0);
  9245. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  9246. auto res =
  9247. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  9248. total_received += data_length;
  9249. return true;
  9250. });
  9251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9252. EXPECT_EQ(StatusCode::OK_200, res->status);
  9253. }
  9254. server_thread.join();
  9255. EXPECT_EQ(total_received, DATA_SIZE)
  9256. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  9257. << " bytes (larger than " << DATA_SIZE
  9258. << " bytes response), content_receiver should read all data, but only "
  9259. "read "
  9260. << total_received << " bytes.";
  9261. }
  9262. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  9263. // Regression test for "zip bomb" attack on the client side: a malicious server
  9264. // sends a small gzip-compressed response that decompresses to a huge payload.
  9265. // The client must enforce payload_max_length on the decompressed size.
  9266. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  9267. constexpr size_t DECOMPRESSED_SIZE =
  9268. 10 * 1024 * 1024; // 10MB after decompression
  9269. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  9270. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  9271. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  9272. std::string compressed;
  9273. {
  9274. httplib::detail::gzip_compressor compressor;
  9275. bool ok =
  9276. compressor.compress(uncompressed.data(), uncompressed.size(),
  9277. /*last=*/true, [&](const char *buf, size_t len) {
  9278. compressed.append(buf, len);
  9279. return true;
  9280. });
  9281. ASSERT_TRUE(ok);
  9282. }
  9283. // Sanity: compressed data should be much smaller than the decompressed size
  9284. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  9285. #ifndef _WIN32
  9286. signal(SIGPIPE, SIG_IGN);
  9287. #endif
  9288. // Set up the listening socket in the main thread so the server is guaranteed
  9289. // to be ready before the client connects (eliminates race condition).
  9290. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9291. default_socket_options(srv);
  9292. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  9293. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  9294. sockaddr_in addr{};
  9295. addr.sin_family = AF_INET;
  9296. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  9297. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9298. int opt = 1;
  9299. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  9300. #ifdef _WIN32
  9301. reinterpret_cast<const char *>(&opt),
  9302. #else
  9303. &opt,
  9304. #endif
  9305. sizeof(opt));
  9306. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  9307. ASSERT_EQ(0, ::listen(srv, 1));
  9308. auto server_thread = std::thread([&compressed, srv] {
  9309. sockaddr_in cli_addr{};
  9310. socklen_t cli_len = sizeof(cli_addr);
  9311. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9312. if (cli != INVALID_SOCKET) {
  9313. // Read the full HTTP request (until \r\n\r\n)
  9314. char buf[4096];
  9315. size_t total = 0;
  9316. while (total < sizeof(buf)) {
  9317. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  9318. if (n <= 0) break;
  9319. total += static_cast<size_t>(n);
  9320. // Check for end of headers
  9321. if (total >= 4) {
  9322. std::string req(buf, total);
  9323. if (req.find("\r\n\r\n") != std::string::npos) break;
  9324. }
  9325. }
  9326. // Malicious response: gzip-compressed body, no Content-Length
  9327. std::string response_header = "HTTP/1.1 200 OK\r\n"
  9328. "Content-Encoding: gzip\r\n"
  9329. "Connection: close\r\n"
  9330. "\r\n";
  9331. ::send(cli,
  9332. #ifdef _WIN32
  9333. static_cast<const char *>(response_header.c_str()),
  9334. static_cast<int>(response_header.size()),
  9335. #else
  9336. response_header.c_str(), response_header.size(),
  9337. #endif
  9338. 0);
  9339. // Send the compressed payload (small on the wire, huge when decompressed)
  9340. size_t total_sent = 0;
  9341. while (total_sent < compressed.size()) {
  9342. auto to_send = std::min(compressed.size() - total_sent,
  9343. static_cast<size_t>(64 * 1024));
  9344. auto sent =
  9345. ::send(cli,
  9346. #ifdef _WIN32
  9347. static_cast<const char *>(compressed.c_str() + total_sent),
  9348. static_cast<int>(to_send),
  9349. #else
  9350. compressed.c_str() + total_sent, to_send,
  9351. #endif
  9352. 0);
  9353. if (sent <= 0) break;
  9354. total_sent += static_cast<size_t>(sent);
  9355. }
  9356. detail::close_socket(cli);
  9357. }
  9358. });
  9359. auto se = detail::scope_exit([&] {
  9360. detail::close_socket(srv);
  9361. server_thread.join();
  9362. });
  9363. size_t total_decompressed = 0;
  9364. {
  9365. Client cli("127.0.0.1", PORT + 3);
  9366. cli.set_read_timeout(5, 0);
  9367. cli.set_decompress(true);
  9368. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  9369. auto stream = cli.open_stream("GET", "/zipbomb");
  9370. ASSERT_TRUE(stream.is_valid());
  9371. char buffer[64 * 1024];
  9372. ssize_t n;
  9373. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  9374. total_decompressed += static_cast<size_t>(n);
  9375. }
  9376. }
  9377. // The decompressed size must be capped by payload_max_length. Without
  9378. // protection, the client would decompress the full 10MB from a tiny
  9379. // compressed payload, enabling a zip bomb DoS attack.
  9380. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  9381. << "Client decompressed " << total_decompressed
  9382. << " bytes from a gzip response. The decompressed size should be "
  9383. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  9384. }
  9385. #endif
  9386. TEST(HostAndPortPropertiesTest, NoSSL) {
  9387. httplib::Client cli("www.google.com", 1234);
  9388. ASSERT_EQ("www.google.com", cli.host());
  9389. ASSERT_EQ(1234, cli.port());
  9390. }
  9391. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  9392. httplib::Client cli("www.google.com:1234");
  9393. ASSERT_EQ("www.google.com", cli.host());
  9394. ASSERT_EQ(1234, cli.port());
  9395. }
  9396. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  9397. // Port number that overflows int — should not crash, client becomes invalid
  9398. httplib::Client cli("http://www.google.com:99999999999999999999");
  9399. ASSERT_FALSE(cli.is_valid());
  9400. }
  9401. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  9402. // Port 99999 exceeds valid range (1-65535) — should not crash
  9403. httplib::Client cli("http://www.google.com:99999");
  9404. ASSERT_FALSE(cli.is_valid());
  9405. }
  9406. #ifdef CPPHTTPLIB_SSL_ENABLED
  9407. TEST(HostAndPortPropertiesTest, SSL) {
  9408. httplib::SSLClient cli("www.google.com");
  9409. ASSERT_EQ("www.google.com", cli.host());
  9410. ASSERT_EQ(443, cli.port());
  9411. }
  9412. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  9413. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  9414. std::string cert;
  9415. read_file(CA_CERT_FILE, cert);
  9416. httplib::SSLClient httplib_client("www.google.com");
  9417. // Load CA store first time
  9418. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9419. // Load CA store second time (update)
  9420. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  9421. // Verify client is still valid and can make connections
  9422. httplib_client.enable_server_certificate_verification(true);
  9423. auto res = httplib_client.Get("/");
  9424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9425. // Google may return 200 or 301 depending on various factors
  9426. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  9427. res->status == StatusCode::MovedPermanently_301);
  9428. }
  9429. TEST(SSLClientTest, ServerNameIndication_Online) {
  9430. auto host = "httpbingo.org";
  9431. auto path = std::string{"/get"};
  9432. SSLClient cli(host, 443);
  9433. auto res = cli.Get(path);
  9434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9435. ASSERT_EQ(StatusCode::OK_200, res->status);
  9436. }
  9437. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  9438. // Use a site that will cause SSL verification failure due to self-signed cert
  9439. SSLClient cli("self-signed.badssl.com", 443);
  9440. cli.enable_server_certificate_verification(true);
  9441. auto res = cli.Get("/");
  9442. ASSERT_TRUE(!res);
  9443. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9444. // Verify backend error is captured for SSLServerVerification
  9445. // This occurs when certificate verification fails
  9446. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  9447. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  9448. EXPECT_NE(0UL, res.ssl_backend_error());
  9449. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9450. // For OpenSSL, ssl_error is 0 for verification errors
  9451. EXPECT_EQ(0, res.ssl_error());
  9452. #if !defined(_WIN32) || \
  9453. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9454. // On non-Windows or when Windows Schannel is disabled, the error comes
  9455. // from OpenSSL's verification
  9456. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  9457. res.ssl_backend_error());
  9458. #endif
  9459. #endif
  9460. }
  9461. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  9462. // Use a site where hostname doesn't match the certificate
  9463. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  9464. SSLClient cli("wrong.host.badssl.com", 443);
  9465. cli.enable_server_certificate_verification(true);
  9466. cli.enable_server_hostname_verification(true);
  9467. auto res = cli.Get("/");
  9468. ASSERT_TRUE(!res);
  9469. // The error type depends on when hostname verification occurs:
  9470. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  9471. // - Mbed TLS: SSLServerVerification (during handshake)
  9472. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  9473. res.error() == Error::SSLServerVerification);
  9474. // Verify backend error is captured for hostname verification failure
  9475. EXPECT_NE(0UL, res.ssl_backend_error());
  9476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9477. // For OpenSSL, ssl_error is 0 for verification errors
  9478. EXPECT_EQ(0, res.ssl_error());
  9479. #if !defined(_WIN32) || \
  9480. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9481. // On non-Windows or when Windows Schannel is disabled, the error comes
  9482. // from OpenSSL's hostname verification
  9483. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  9484. res.ssl_backend_error());
  9485. #endif
  9486. #endif
  9487. }
  9488. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  9489. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  9490. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  9491. SSLClient cli("www.google.com", 443);
  9492. cli.enable_server_certificate_verification(true);
  9493. auto res = cli.Get("/");
  9494. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9495. }
  9496. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  9497. SSLClient cli("www.google.com", 443);
  9498. cli.enable_server_certificate_verification(true);
  9499. cli.enable_windows_certificate_verification(false);
  9500. auto res = cli.Get("/");
  9501. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  9502. }
  9503. #endif
  9504. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  9505. Client cli("https://google.com");
  9506. auto res = cli.Get("/");
  9507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9508. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9509. }
  9510. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  9511. SSLClient cli("google.com");
  9512. cli.set_ca_cert_path(CA_CERT_FILE);
  9513. auto res = cli.Get("/");
  9514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9515. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9516. }
  9517. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  9518. SSLClient cli("google.com");
  9519. cli.enable_server_certificate_verification(true);
  9520. cli.set_ca_cert_path("hello");
  9521. auto res = cli.Get("/");
  9522. ASSERT_TRUE(!res);
  9523. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  9524. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  9525. // should be set
  9526. EXPECT_EQ(0, res.ssl_error());
  9527. // Verify backend error is captured for SSLLoadingCerts
  9528. // This error occurs when loading CA certificates fails
  9529. EXPECT_NE(0UL, res.ssl_backend_error());
  9530. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9531. // OpenSSL specific error codes:
  9532. // > openssl errstr 0x80000002
  9533. // error:80000002:system library::No such file or directory
  9534. // > openssl errstr 0xA000126
  9535. // error:0A000126:SSL routines::unexpected eof while reading
  9536. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  9537. res.ssl_backend_error() == 0xA000126);
  9538. #endif
  9539. }
  9540. TEST(SSLClientTest, ServerCertificateVerification4) {
  9541. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9542. ASSERT_TRUE(svr.is_valid());
  9543. svr.Get("/test", [&](const Request &, Response &res) {
  9544. res.set_content("test", "text/plain");
  9545. svr.stop();
  9546. ASSERT_TRUE(true);
  9547. });
  9548. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9549. auto se = detail::scope_exit([&] {
  9550. t.join();
  9551. ASSERT_FALSE(svr.is_running());
  9552. });
  9553. svr.wait_until_ready();
  9554. SSLClient cli("127.0.0.1", PORT);
  9555. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9556. cli.enable_server_certificate_verification(true);
  9557. cli.set_connection_timeout(30);
  9558. auto res = cli.Get("/test");
  9559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9560. ASSERT_EQ(StatusCode::OK_200, res->status);
  9561. }
  9562. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  9563. std::string cert;
  9564. read_file(CA_CERT_FILE, cert);
  9565. SSLClient cli("google.com");
  9566. cli.load_ca_cert_store(cert.data(), cert.size());
  9567. const auto res = cli.Get("/");
  9568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9569. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9570. }
  9571. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  9572. // clang-format off
  9573. static constexpr char cert[] =
  9574. "GlobalSign Root CA\n"
  9575. "==================\n"
  9576. "-----BEGIN CERTIFICATE-----\n"
  9577. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  9578. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  9579. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  9580. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  9581. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  9582. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  9583. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  9584. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  9585. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  9586. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  9587. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  9588. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  9589. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  9590. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  9591. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  9592. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  9593. "-----END CERTIFICATE-----\n";
  9594. // clang-format on
  9595. SSLClient cli("google.com");
  9596. cli.load_ca_cert_store(cert, sizeof(cert));
  9597. const auto res = cli.Get("/");
  9598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9599. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  9600. }
  9601. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  9602. SSLClient cli("www.youtube.com");
  9603. cli.set_ca_cert_path(CA_CERT_FILE);
  9604. cli.enable_server_certificate_verification(true);
  9605. cli.set_follow_location(true);
  9606. auto res = cli.Get("/");
  9607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9608. ASSERT_EQ(StatusCode::OK_200, res->status);
  9609. }
  9610. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  9611. SSLClient cli("wWw.YouTube.Com");
  9612. cli.set_ca_cert_path(CA_CERT_FILE);
  9613. cli.enable_server_certificate_verification(true);
  9614. cli.enable_server_hostname_verification(true);
  9615. cli.set_follow_location(true);
  9616. auto res = cli.Get("/");
  9617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9618. ASSERT_EQ(StatusCode::OK_200, res->status);
  9619. }
  9620. TEST(SSLClientTest, HostNameMatchCase_Online) {
  9621. SSLClient cli("gOoGlE.COm");
  9622. cli.enable_server_certificate_verification(true);
  9623. cli.enable_server_hostname_verification(true);
  9624. cli.set_follow_location(true);
  9625. auto res = cli.Get("/");
  9626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9627. ASSERT_EQ(StatusCode::OK_200, res->status);
  9628. }
  9629. TEST(SSLClientTest, Issue2004_Online) {
  9630. Client client("https://google.com");
  9631. client.set_follow_location(true);
  9632. auto res = client.Get("/");
  9633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9634. ASSERT_EQ(StatusCode::OK_200, res->status);
  9635. auto body = res->body;
  9636. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  9637. }
  9638. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  9639. // Create SSLClient with invalid cert/key to make is_valid() return false
  9640. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  9641. "nonexistent_key.pem");
  9642. // is_valid() should be false due to cert loading failure
  9643. ASSERT_FALSE(cli.is_valid());
  9644. auto res = cli.Get("/");
  9645. ASSERT_FALSE(res);
  9646. EXPECT_EQ(Error::SSLConnection, res.error());
  9647. }
  9648. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  9649. // Test for Issue #2251: SSL error not properly reported when client cert
  9650. // and key paths are swapped or mismatched
  9651. // This simulates the scenario where user accidentally swaps the cert and key
  9652. // files
  9653. // Using client cert file as private key and vice versa (completely wrong)
  9654. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  9655. // Should fail validation due to cert/key mismatch
  9656. ASSERT_FALSE(cli.is_valid());
  9657. // Attempt to make a request should fail with proper error
  9658. auto res = cli.Get("/");
  9659. ASSERT_FALSE(res);
  9660. EXPECT_EQ(Error::SSLConnection, res.error());
  9661. // SSL error should be recorded in the Result object (this is the key fix for
  9662. // Issue #2251)
  9663. auto backend_error = res.ssl_backend_error();
  9664. EXPECT_NE(0u, backend_error);
  9665. }
  9666. // Tests cert/key mismatch detection at the TLS context level
  9667. TEST(TlsApiTest, ClientCertKeyMismatch) {
  9668. // Test that using mismatched cert/key causes connection failure.
  9669. // We verify this at the SSLClient level rather than through internal
  9670. // TLS API functions.
  9671. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  9672. cli.enable_server_certificate_verification(false);
  9673. cli.set_connection_timeout(2);
  9674. // The mismatch should cause a connection or handshake error
  9675. auto res = cli.Get("/test");
  9676. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  9677. // Either way, the request should fail
  9678. EXPECT_FALSE(res);
  9679. }
  9680. #endif
  9681. #if 0
  9682. TEST(SSLClientTest, SetInterfaceWithINET6) {
  9683. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  9684. ASSERT_TRUE(cli != nullptr);
  9685. cli->set_address_family(AF_INET6);
  9686. cli->set_interface("en0");
  9687. auto res = cli->Get("/get");
  9688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9689. ASSERT_EQ(StatusCode::OK_200, res->status);
  9690. }
  9691. #endif
  9692. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  9693. #ifdef CPPHTTPLIB_SSL_ENABLED
  9694. void ClientCertPresent(
  9695. const std::string &client_cert_file,
  9696. const std::string &client_private_key_file,
  9697. const std::string &client_encrypted_private_key_pass = std::string()) {
  9698. using namespace httplib::tls;
  9699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9700. CLIENT_CA_CERT_DIR);
  9701. ASSERT_TRUE(svr.is_valid());
  9702. svr.Get("/test", [&](const Request &req, Response &res) {
  9703. res.set_content("test", "text/plain");
  9704. auto cert = req.peer_cert();
  9705. ASSERT_TRUE(static_cast<bool>(cert));
  9706. std::string common_name = cert.subject_cn();
  9707. EXPECT_EQ("Common Name", common_name);
  9708. });
  9709. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9710. auto se = detail::scope_exit([&] {
  9711. svr.stop();
  9712. t.join();
  9713. ASSERT_FALSE(svr.is_running());
  9714. });
  9715. svr.wait_until_ready();
  9716. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  9717. client_encrypted_private_key_pass);
  9718. cli.enable_server_certificate_verification(false);
  9719. cli.set_connection_timeout(30);
  9720. auto res = cli.Get("/test");
  9721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9722. ASSERT_EQ(StatusCode::OK_200, res->status);
  9723. }
  9724. TEST(SSLClientServerTest, ClientCertPresent) {
  9725. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9726. }
  9727. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  9728. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9729. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9730. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9731. }
  9732. // PEM memory-based constructor tests (works with all TLS backends)
  9733. void PemMemoryClientCertPresent(
  9734. const std::string &client_cert_file,
  9735. const std::string &client_private_key_file,
  9736. const std::string &client_encrypted_private_key_pass = std::string()) {
  9737. // Read PEM files into memory
  9738. std::string server_cert_pem, server_key_pem;
  9739. std::string client_ca_pem;
  9740. std::string client_cert_pem, client_key_pem;
  9741. read_file(SERVER_CERT_FILE, server_cert_pem);
  9742. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9743. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9744. read_file(client_cert_file, client_cert_pem);
  9745. read_file(client_private_key_file, client_key_pem);
  9746. // Create server with PEM memory
  9747. SSLServer::PemMemory server_pem = {
  9748. server_cert_pem.c_str(),
  9749. server_cert_pem.size(),
  9750. server_key_pem.c_str(),
  9751. server_key_pem.size(),
  9752. client_ca_pem.c_str(),
  9753. client_ca_pem.size(),
  9754. nullptr // no password for server key
  9755. };
  9756. SSLServer svr(server_pem);
  9757. ASSERT_TRUE(svr.is_valid());
  9758. svr.Get("/test", [&](const Request &, Response &res) {
  9759. res.set_content("test", "text/plain");
  9760. });
  9761. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9762. auto se = detail::scope_exit([&] {
  9763. svr.stop();
  9764. t.join();
  9765. ASSERT_FALSE(svr.is_running());
  9766. });
  9767. svr.wait_until_ready();
  9768. // Create client with PEM memory
  9769. const char *password = client_encrypted_private_key_pass.empty()
  9770. ? nullptr
  9771. : client_encrypted_private_key_pass.c_str();
  9772. SSLClient::PemMemory client_pem = {
  9773. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  9774. client_key_pem.size(), password};
  9775. SSLClient cli(HOST, PORT, client_pem);
  9776. cli.enable_server_certificate_verification(false);
  9777. cli.set_connection_timeout(30);
  9778. auto res = cli.Get("/test");
  9779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9780. ASSERT_EQ(StatusCode::OK_200, res->status);
  9781. }
  9782. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  9783. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9784. }
  9785. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  9786. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  9787. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  9788. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  9789. }
  9790. TEST(SSLClientServerTest, ClientCertMissing) {
  9791. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9792. CLIENT_CA_CERT_DIR);
  9793. ASSERT_TRUE(svr.is_valid());
  9794. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  9795. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9796. auto se = detail::scope_exit([&] {
  9797. svr.stop();
  9798. t.join();
  9799. ASSERT_FALSE(svr.is_running());
  9800. });
  9801. svr.wait_until_ready();
  9802. SSLClient cli(HOST, PORT);
  9803. cli.set_connection_timeout(30);
  9804. auto res = cli.Get("/test");
  9805. ASSERT_TRUE(!res);
  9806. // When client cert is missing and server requires it, connection fails
  9807. // Error type depends on backend implementation
  9808. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  9809. res.error() == Error::SSLConnection);
  9810. // Verify backend error is captured
  9811. // Note: This test may have different error codes depending on the exact
  9812. // verification failure
  9813. EXPECT_NE(0UL, res.ssl_backend_error());
  9814. }
  9815. TEST(SSLClientServerTest, TrustDirOptional) {
  9816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9817. ASSERT_TRUE(svr.is_valid());
  9818. svr.Get("/test", [&](const Request &, Response &res) {
  9819. res.set_content("test", "text/plain");
  9820. });
  9821. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9822. auto se = detail::scope_exit([&] {
  9823. svr.stop();
  9824. t.join();
  9825. ASSERT_FALSE(svr.is_running());
  9826. });
  9827. svr.wait_until_ready();
  9828. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9829. cli.enable_server_certificate_verification(false);
  9830. cli.set_connection_timeout(30);
  9831. auto res = cli.Get("/test");
  9832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9833. ASSERT_EQ(StatusCode::OK_200, res->status);
  9834. }
  9835. TEST(SSLClientServerTest, SSLConnectTimeout) {
  9836. class NoListenSSLServer : public SSLServer {
  9837. public:
  9838. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  9839. const char *client_ca_cert_file_path,
  9840. const char *client_ca_cert_dir_path = nullptr)
  9841. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  9842. client_ca_cert_dir_path),
  9843. stop_(false) {}
  9844. std::atomic_bool stop_;
  9845. private:
  9846. bool process_and_close_socket(socket_t /*sock*/) override {
  9847. // Don't create SSL context
  9848. while (!stop_.load()) {
  9849. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9850. }
  9851. return true;
  9852. }
  9853. };
  9854. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9855. CLIENT_CA_CERT_FILE);
  9856. ASSERT_TRUE(svr.is_valid());
  9857. svr.Get("/test", [&](const Request &, Response &res) {
  9858. res.set_content("test", "text/plain");
  9859. });
  9860. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9861. auto se = detail::scope_exit([&] {
  9862. svr.stop_ = true;
  9863. svr.stop();
  9864. t.join();
  9865. ASSERT_FALSE(svr.is_running());
  9866. });
  9867. svr.wait_until_ready();
  9868. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9869. cli.enable_server_certificate_verification(false);
  9870. cli.set_connection_timeout(1);
  9871. auto res = cli.Get("/test");
  9872. ASSERT_TRUE(!res);
  9873. EXPECT_EQ(Error::SSLConnection, res.error());
  9874. // Timeout results in WantRead error code (maps to backend-specific value)
  9875. EXPECT_NE(0, res.ssl_error());
  9876. }
  9877. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  9878. // Test SSLServer with client certificate verification using the standard
  9879. // constructor (ContextSetupCallback is tested by backend-specific tests)
  9880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  9881. CLIENT_CA_CERT_DIR);
  9882. ASSERT_TRUE(svr.is_valid());
  9883. svr.Get("/test", [&](const Request &req, Response &res) {
  9884. res.set_content("test", "text/plain");
  9885. auto cert = req.peer_cert();
  9886. ASSERT_TRUE(static_cast<bool>(cert));
  9887. auto common_name = cert.subject_cn();
  9888. EXPECT_EQ("Common Name", common_name);
  9889. });
  9890. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9891. auto se = detail::scope_exit([&] {
  9892. svr.stop();
  9893. t.join();
  9894. ASSERT_FALSE(svr.is_running());
  9895. });
  9896. svr.wait_until_ready();
  9897. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9898. cli.enable_server_certificate_verification(false);
  9899. cli.set_connection_timeout(30);
  9900. auto res = cli.Get("/test");
  9901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9902. ASSERT_EQ(StatusCode::OK_200, res->status);
  9903. }
  9904. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9905. // Verifies that wildcard matching and exact matching work consistently
  9906. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9907. using namespace httplib::tls;
  9908. // We need a running server to test against
  9909. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9910. ASSERT_TRUE(svr.is_valid());
  9911. svr.Get("/test", [](const Request &, Response &res) {
  9912. res.set_content("ok", "text/plain");
  9913. });
  9914. thread t([&]() { svr.listen(HOST, PORT); });
  9915. auto se = detail::scope_exit([&] {
  9916. svr.stop();
  9917. t.join();
  9918. });
  9919. svr.wait_until_ready();
  9920. bool verify_callback_called = false;
  9921. bool verify_result_wrong = false;
  9922. SSLClient cli(HOST, PORT);
  9923. cli.enable_server_certificate_verification(true);
  9924. cli.set_ca_cert_path(CA_CERT_FILE);
  9925. cli.set_connection_timeout(5);
  9926. // Note: Test certificate has CN="Common Name", not "localhost"
  9927. bool verify_result_cn = false;
  9928. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9929. verify_callback_called = true;
  9930. if (!ctx.cert) return false;
  9931. // Test 1: "Common Name" should match (our test server cert CN)
  9932. verify_result_cn = ctx.check_hostname("Common Name");
  9933. // Test 2: wrong hostname should not match
  9934. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9935. return true; // Accept for the purpose of this test
  9936. });
  9937. auto res = cli.Get("/test");
  9938. // The request may succeed or fail depending on cert configuration
  9939. // but the callback should have been called
  9940. ASSERT_TRUE(verify_callback_called)
  9941. << "Verify callback should have been called";
  9942. // CN="Common Name" should match our test certificate
  9943. //
  9944. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9945. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9946. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9947. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9948. // <openssl/base.h>, which is included transitively when
  9949. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9950. #if defined(OPENSSL_IS_BORINGSSL)
  9951. EXPECT_FALSE(verify_result_cn)
  9952. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9953. #else
  9954. EXPECT_TRUE(verify_result_cn)
  9955. << "verify_hostname should match 'Common Name' (certificate CN)";
  9956. #endif
  9957. // Wrong hostname should not match
  9958. EXPECT_FALSE(verify_result_wrong)
  9959. << "verify_hostname should not match 'wronghost.example.com'";
  9960. }
  9961. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  9962. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  9963. // X509_check_ip behavior and must hold for every backend.
  9964. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  9965. using namespace httplib::tls;
  9966. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  9967. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  9968. ASSERT_TRUE(svr.is_valid());
  9969. svr.Get("/test", [](const Request &, Response &res) {
  9970. res.set_content("ok", "text/plain");
  9971. });
  9972. thread t([&]() { svr.listen(HOST, PORT); });
  9973. auto se = detail::scope_exit([&] {
  9974. svr.stop();
  9975. t.join();
  9976. });
  9977. svr.wait_until_ready();
  9978. bool verify_callback_called = false;
  9979. bool ip_matched_via_cn = true;
  9980. SSLClient cli(HOST, PORT);
  9981. cli.enable_server_certificate_verification(true);
  9982. cli.set_ca_cert_path(CA_CERT_FILE);
  9983. cli.set_connection_timeout(5);
  9984. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9985. verify_callback_called = true;
  9986. if (!ctx.cert) return false;
  9987. // The IP appears only in the CN, so it must NOT be accepted.
  9988. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  9989. return true; // Accept for the purpose of this test
  9990. });
  9991. cli.Get("/test");
  9992. ASSERT_TRUE(verify_callback_called)
  9993. << "Verify callback should have been called";
  9994. EXPECT_FALSE(ip_matched_via_cn)
  9995. << "An IP host must not be authenticated via the certificate CN";
  9996. }
  9997. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  9998. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  9999. using namespace httplib::tls;
  10000. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  10001. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  10002. ASSERT_TRUE(svr.is_valid());
  10003. svr.Get("/test", [](const Request &, Response &res) {
  10004. res.set_content("ok", "text/plain");
  10005. });
  10006. thread t([&]() { svr.listen(HOST, PORT); });
  10007. auto se = detail::scope_exit([&] {
  10008. svr.stop();
  10009. t.join();
  10010. });
  10011. svr.wait_until_ready();
  10012. bool verify_callback_called = false;
  10013. bool san_matched = false;
  10014. bool wrong_ipv6_matched = true;
  10015. bool cn_ipv6_matched = true;
  10016. SSLClient cli(HOST, PORT);
  10017. cli.enable_server_certificate_verification(true);
  10018. cli.set_ca_cert_path(CA_CERT_FILE);
  10019. cli.set_connection_timeout(5);
  10020. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10021. verify_callback_called = true;
  10022. if (!ctx.cert) return false;
  10023. // Matches the IPv6 iPAddress SAN.
  10024. san_matched = ctx.check_hostname("2001:db8::1");
  10025. // A different IPv6 address must not match.
  10026. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  10027. // "::1" lives only in the CN, so it must not be accepted.
  10028. cn_ipv6_matched = ctx.check_hostname("::1");
  10029. return true; // Accept for the purpose of this test
  10030. });
  10031. cli.Get("/test");
  10032. ASSERT_TRUE(verify_callback_called)
  10033. << "Verify callback should have been called";
  10034. EXPECT_TRUE(san_matched)
  10035. << "verify_hostname should match an IPv6 iPAddress SAN";
  10036. EXPECT_FALSE(wrong_ipv6_matched)
  10037. << "verify_hostname should not match a non-matching IPv6 address";
  10038. EXPECT_FALSE(cn_ipv6_matched)
  10039. << "An IPv6 host must not be authenticated via the certificate CN";
  10040. }
  10041. #endif
  10042. // mbedTLS-specific callback constructor test
  10043. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  10044. #ifdef CPPHTTPLIB_SSL_ENABLED
  10045. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  10046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10047. ASSERT_TRUE(svr.is_valid());
  10048. // Set up a handler to verify client certificate is present
  10049. bool client_cert_verified = false;
  10050. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10051. // Verify that client certificate was provided
  10052. client_cert_verified = true;
  10053. res.set_content("success", "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. ASSERT_FALSE(svr.is_running());
  10060. });
  10061. svr.wait_until_ready();
  10062. // Client with certificate
  10063. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10064. cli.enable_server_certificate_verification(false);
  10065. cli.set_connection_timeout(30);
  10066. auto res = cli.Get("/test");
  10067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10068. ASSERT_EQ(StatusCode::OK_200, res->status);
  10069. ASSERT_TRUE(client_cert_verified);
  10070. EXPECT_EQ("success", res->body);
  10071. }
  10072. #endif
  10073. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  10074. // backends
  10075. #ifdef CPPHTTPLIB_SSL_ENABLED
  10076. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  10077. using namespace httplib::tls;
  10078. // Test that when client CA cert file is provided,
  10079. // the server properly requests and validates client certificates
  10080. // Create a server with client authentication
  10081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  10082. ASSERT_TRUE(svr.is_valid());
  10083. bool handler_called = false;
  10084. svr.Get("/test", [&](const Request &req, Response &res) {
  10085. handler_called = true;
  10086. // Verify that a client certificate was provided
  10087. auto cert = req.peer_cert();
  10088. ASSERT_TRUE(static_cast<bool>(cert));
  10089. // Get the issuer name
  10090. std::string issuer_str = cert.issuer_name();
  10091. ASSERT_FALSE(issuer_str.empty());
  10092. // The client certificate should be issued by our test CA
  10093. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  10094. res.set_content("authenticated", "text/plain");
  10095. });
  10096. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10097. auto se = detail::scope_exit([&] {
  10098. svr.stop();
  10099. t.join();
  10100. ASSERT_FALSE(svr.is_running());
  10101. });
  10102. svr.wait_until_ready();
  10103. // Connect with a client certificate issued by the CA
  10104. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10105. cli.enable_server_certificate_verification(false);
  10106. cli.set_connection_timeout(30);
  10107. auto res = cli.Get("/test");
  10108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10109. ASSERT_EQ(StatusCode::OK_200, res->status);
  10110. ASSERT_TRUE(handler_called);
  10111. EXPECT_EQ("authenticated", res->body);
  10112. }
  10113. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  10114. using namespace httplib::tls;
  10115. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10116. ASSERT_TRUE(svr.is_valid());
  10117. svr.Get("/test", [](const Request &, Response &res) {
  10118. res.set_content("ok", "text/plain");
  10119. });
  10120. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10121. auto se = detail::scope_exit([&] {
  10122. svr.stop();
  10123. t.join();
  10124. });
  10125. svr.wait_until_ready();
  10126. SSLClient cli(HOST, PORT);
  10127. cli.enable_server_certificate_verification(false);
  10128. cli.set_connection_timeout(30);
  10129. bool cert_checked = false;
  10130. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10131. if (ctx.cert) {
  10132. auto sans = ctx.sans();
  10133. // Test certificate may or may not have SANs - just verify the API
  10134. // works If SANs exist, verify the types are valid
  10135. for (const auto &san : sans) {
  10136. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  10137. san.type == SanType::EMAIL || san.type == SanType::URI ||
  10138. san.type == SanType::OTHER);
  10139. EXPECT_FALSE(san.value.empty());
  10140. }
  10141. cert_checked = true;
  10142. }
  10143. return true;
  10144. });
  10145. auto res = cli.Get("/test");
  10146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10147. EXPECT_TRUE(cert_checked);
  10148. }
  10149. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  10150. using namespace httplib::tls;
  10151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10152. ASSERT_TRUE(svr.is_valid());
  10153. svr.Get("/test", [](const Request &, Response &res) {
  10154. res.set_content("ok", "text/plain");
  10155. });
  10156. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10157. auto se = detail::scope_exit([&] {
  10158. svr.stop();
  10159. t.join();
  10160. });
  10161. svr.wait_until_ready();
  10162. SSLClient cli(HOST, PORT);
  10163. cli.enable_server_certificate_verification(false);
  10164. cli.set_connection_timeout(30);
  10165. bool validity_checked = false;
  10166. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10167. if (ctx.cert) {
  10168. time_t not_before = 0, not_after = 0;
  10169. bool result = ctx.validity(not_before, not_after);
  10170. EXPECT_TRUE(result);
  10171. // Verify that not_before < now < not_after for a valid cert
  10172. time_t now = time(nullptr);
  10173. EXPECT_LT(not_before, now);
  10174. EXPECT_GT(not_after, now);
  10175. validity_checked = true;
  10176. }
  10177. return true;
  10178. });
  10179. auto res = cli.Get("/test");
  10180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10181. EXPECT_TRUE(validity_checked);
  10182. }
  10183. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  10184. using namespace httplib::tls;
  10185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10186. ASSERT_TRUE(svr.is_valid());
  10187. svr.Get("/test", [](const Request &, Response &res) {
  10188. res.set_content("ok", "text/plain");
  10189. });
  10190. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10191. auto se = detail::scope_exit([&] {
  10192. svr.stop();
  10193. t.join();
  10194. });
  10195. svr.wait_until_ready();
  10196. SSLClient cli(HOST, PORT);
  10197. cli.enable_server_certificate_verification(false);
  10198. cli.set_connection_timeout(30);
  10199. bool serial_checked = false;
  10200. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10201. if (ctx.cert) {
  10202. std::string serial = ctx.serial();
  10203. EXPECT_FALSE(serial.empty());
  10204. // Serial should be a hex string
  10205. for (char c : serial) {
  10206. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  10207. (c >= 'a' && c <= 'f'));
  10208. }
  10209. serial_checked = true;
  10210. }
  10211. return true;
  10212. });
  10213. auto res = cli.Get("/test");
  10214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10215. EXPECT_TRUE(serial_checked);
  10216. }
  10217. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  10218. // Test 1: Valid CA file - no error should be recorded
  10219. {
  10220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  10221. CLIENT_CA_CERT_FILE);
  10222. ASSERT_TRUE(svr.is_valid());
  10223. // With valid setup, last_ssl_error should be 0
  10224. EXPECT_EQ(0, svr.ssl_last_error());
  10225. }
  10226. // Test 2: Invalid CA file content
  10227. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  10228. {
  10229. // Create a temporary file with completely invalid content
  10230. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  10231. {
  10232. std::ofstream ofs(temp_invalid_ca);
  10233. ofs << "This is not a certificate file at all\n";
  10234. ofs << "Just plain text content\n";
  10235. }
  10236. // Create server with invalid CA file
  10237. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  10238. // Clean up temporary file
  10239. std::remove(temp_invalid_ca);
  10240. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  10241. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  10242. // Note: SSL_CTX_load_verify_locations typically fails first,
  10243. // but our error handling code path is still exercised
  10244. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  10245. }
  10246. }
  10247. TEST(VerifyCallbackTest, VerifyContextFields) {
  10248. using namespace httplib::tls;
  10249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10250. ASSERT_TRUE(svr.is_valid());
  10251. svr.Get("/test", [](const Request &, Response &res) {
  10252. res.set_content("ok", "text/plain");
  10253. });
  10254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. t.join();
  10258. });
  10259. svr.wait_until_ready();
  10260. SSLClient cli(HOST, PORT);
  10261. cli.enable_server_certificate_verification(false);
  10262. cli.set_connection_timeout(30);
  10263. int callback_count = 0;
  10264. bool saw_leaf_cert = false;
  10265. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  10266. if (ctx.cert) {
  10267. callback_count++;
  10268. // We should see at least one certificate (the leaf)
  10269. std::string cn = ctx.subject_cn();
  10270. if (!cn.empty()) { saw_leaf_cert = true; }
  10271. // Verify context fields are populated
  10272. EXPECT_NE(ctx.session, nullptr);
  10273. EXPECT_GE(ctx.depth, 0);
  10274. }
  10275. return true;
  10276. });
  10277. auto res = cli.Get("/test");
  10278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10279. EXPECT_GT(callback_count, 0);
  10280. EXPECT_TRUE(saw_leaf_cert);
  10281. }
  10282. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  10283. using httplib::tls::TlsError;
  10284. // Test that verify_error_to_string returns empty for success
  10285. std::string success_str = TlsError::verify_error_to_string(0);
  10286. EXPECT_TRUE(success_str.empty());
  10287. // Test that verify_error_to_string returns non-empty for error codes
  10288. // Using a common error code (certificate expired)
  10289. std::string error_str =
  10290. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  10291. EXPECT_FALSE(error_str.empty());
  10292. }
  10293. TEST(SessionVerifierTest, CertificateAccepted) {
  10294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10295. ASSERT_TRUE(svr.is_valid());
  10296. svr.Get("/test", [](const Request &, Response &res) {
  10297. res.set_content("ok", "text/plain");
  10298. });
  10299. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. t.join();
  10303. });
  10304. svr.wait_until_ready();
  10305. SSLClient cli(HOST, PORT);
  10306. cli.enable_server_certificate_verification(false);
  10307. cli.set_connection_timeout(30);
  10308. bool callback_called = false;
  10309. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10310. EXPECT_NE(session, nullptr);
  10311. callback_called = true;
  10312. return SSLVerifierResponse::CertificateAccepted;
  10313. });
  10314. auto res = cli.Get("/test");
  10315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10316. EXPECT_EQ(200, res->status);
  10317. EXPECT_TRUE(callback_called);
  10318. }
  10319. TEST(SessionVerifierTest, CertificateRejected) {
  10320. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10321. ASSERT_TRUE(svr.is_valid());
  10322. svr.Get("/test", [](const Request &, Response &res) {
  10323. res.set_content("ok", "text/plain");
  10324. });
  10325. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10326. auto se = detail::scope_exit([&] {
  10327. svr.stop();
  10328. t.join();
  10329. });
  10330. svr.wait_until_ready();
  10331. SSLClient cli(HOST, PORT);
  10332. cli.enable_server_certificate_verification(false);
  10333. cli.set_connection_timeout(30);
  10334. bool callback_called = false;
  10335. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10336. EXPECT_NE(session, nullptr);
  10337. callback_called = true;
  10338. return SSLVerifierResponse::CertificateRejected;
  10339. });
  10340. auto res = cli.Get("/test");
  10341. EXPECT_FALSE(res);
  10342. EXPECT_TRUE(callback_called);
  10343. }
  10344. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  10345. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10346. ASSERT_TRUE(svr.is_valid());
  10347. svr.Get("/test", [](const Request &, Response &res) {
  10348. res.set_content("ok", "text/plain");
  10349. });
  10350. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10351. auto se = detail::scope_exit([&] {
  10352. svr.stop();
  10353. t.join();
  10354. });
  10355. svr.wait_until_ready();
  10356. // NoDecisionMade with verification disabled should succeed (no default check)
  10357. SSLClient cli(HOST, PORT);
  10358. cli.enable_server_certificate_verification(false);
  10359. cli.set_connection_timeout(30);
  10360. bool callback_called = false;
  10361. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10362. EXPECT_NE(session, nullptr);
  10363. callback_called = true;
  10364. return SSLVerifierResponse::NoDecisionMade;
  10365. });
  10366. auto res = cli.Get("/test");
  10367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10368. EXPECT_EQ(200, res->status);
  10369. EXPECT_TRUE(callback_called);
  10370. }
  10371. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  10372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10373. ASSERT_TRUE(svr.is_valid());
  10374. svr.Get("/test", [](const Request &, Response &res) {
  10375. res.set_content("ok", "text/plain");
  10376. });
  10377. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. t.join();
  10381. });
  10382. svr.wait_until_ready();
  10383. // NoDecisionMade with verification enabled should fail (self-signed cert).
  10384. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  10385. // so we only check that the request fails, not whether the callback was
  10386. // called.
  10387. SSLClient cli(HOST, PORT);
  10388. cli.enable_server_certificate_verification(true);
  10389. cli.set_connection_timeout(30);
  10390. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  10391. EXPECT_NE(session, nullptr);
  10392. return SSLVerifierResponse::NoDecisionMade;
  10393. });
  10394. auto res = cli.Get("/test");
  10395. EXPECT_FALSE(res);
  10396. }
  10397. TEST(SSLClientServerTest, ClientCAListFromPem) {
  10398. // Test SSL server using PemMemory constructor with client CA certificates
  10399. // Read PEM files
  10400. std::string server_cert_pem, server_key_pem, client_ca_pem;
  10401. read_file(SERVER_CERT_FILE, server_cert_pem);
  10402. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  10403. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  10404. // Create SSLServer with PemMemory constructor including client CA
  10405. SSLServer::PemMemory server_pem = {
  10406. server_cert_pem.c_str(),
  10407. server_cert_pem.size(),
  10408. server_key_pem.c_str(),
  10409. server_key_pem.size(),
  10410. client_ca_pem.c_str(),
  10411. client_ca_pem.size(),
  10412. nullptr // no password for server key
  10413. };
  10414. SSLServer svr(server_pem);
  10415. ASSERT_TRUE(svr.is_valid());
  10416. // No SSL error should be recorded for valid setup
  10417. EXPECT_EQ(0, svr.ssl_last_error());
  10418. // Set up server endpoints
  10419. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  10420. res.set_content("ok", "text/plain");
  10421. });
  10422. // Start server in a thread
  10423. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  10424. svr.wait_until_ready();
  10425. // Connect with client certificate (using constructor with paths)
  10426. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  10427. cli.enable_server_certificate_verification(false);
  10428. auto res = cli.Get("/test-pem-ca");
  10429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10430. EXPECT_EQ(200, res->status);
  10431. EXPECT_EQ("ok", res->body);
  10432. svr.stop();
  10433. server_thread.join();
  10434. }
  10435. #endif
  10436. #ifdef _WIN32
  10437. TEST(CleanupTest, WSACleanup) {
  10438. int ret = WSACleanup();
  10439. ASSERT_EQ(0, ret);
  10440. }
  10441. #endif
  10442. #ifndef CPPHTTPLIB_SSL_ENABLED
  10443. TEST(NoSSLSupport, SimpleInterface) {
  10444. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  10445. }
  10446. #endif
  10447. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10448. TEST(InvalidScheme, SimpleInterface) {
  10449. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  10450. }
  10451. #endif
  10452. TEST(NoScheme, SimpleInterface) {
  10453. Client cli("yahoo.com:80");
  10454. ASSERT_TRUE(cli.is_valid());
  10455. }
  10456. TEST(SendAPI, SimpleInterface_Online) {
  10457. Client cli("http://yahoo.com");
  10458. Request req;
  10459. req.method = "GET";
  10460. req.path = "/";
  10461. auto res = cli.send(req);
  10462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10463. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10464. }
  10465. TEST(SendAPI, WithParamsInRequest) {
  10466. Server svr;
  10467. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  10468. EXPECT_TRUE(req.has_param("test"));
  10469. EXPECT_EQ("test_value", req.get_param_value("test"));
  10470. });
  10471. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10472. auto se = detail::scope_exit([&] {
  10473. svr.stop();
  10474. t.join();
  10475. ASSERT_FALSE(svr.is_running());
  10476. });
  10477. svr.wait_until_ready();
  10478. Client cli(HOST, PORT);
  10479. {
  10480. Request req;
  10481. req.method = "GET";
  10482. req.path = "/";
  10483. req.params.emplace("test", "test_value");
  10484. auto res = cli.send(req);
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. }
  10487. {
  10488. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  10489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10490. }
  10491. }
  10492. TEST(ClientImplMethods, GetSocketTest) {
  10493. httplib::Server svr;
  10494. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10495. res.status = StatusCode::OK_200;
  10496. });
  10497. auto port = svr.bind_to_any_port("127.0.0.1");
  10498. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10499. auto se = detail::scope_exit([&] {
  10500. svr.stop();
  10501. thread.join();
  10502. ASSERT_FALSE(svr.is_running());
  10503. });
  10504. svr.wait_until_ready();
  10505. {
  10506. httplib::Client cli("127.0.0.1", port);
  10507. cli.set_keep_alive(true);
  10508. // Use the behavior of cpp-httplib of opening the connection
  10509. // only when the first request happens. If that changes,
  10510. // this test would be obsolete.
  10511. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  10512. // This also implicitly tests the server. But other tests would fail much
  10513. // earlier than this one to be considered.
  10514. auto res = cli.Get("/");
  10515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10516. EXPECT_EQ(StatusCode::OK_200, res->status);
  10517. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  10518. }
  10519. }
  10520. #ifdef CPPHTTPLIB_SSL_ENABLED
  10521. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  10522. Client cli("http://yahoo.com");
  10523. auto res = cli.Get("/");
  10524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10525. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10526. cli.set_follow_location(true);
  10527. res = cli.Get("/");
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(StatusCode::OK_200, res->status);
  10530. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10531. }
  10532. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  10533. Client cli("https://yahoo.com");
  10534. auto res = cli.Get("/");
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10537. cli.set_follow_location(true);
  10538. res = cli.Get("/");
  10539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10540. EXPECT_EQ(StatusCode::OK_200, res->status);
  10541. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10542. }
  10543. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  10544. Client cli("https://yahoo.com");
  10545. auto res = cli.Get("/");
  10546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10547. ASSERT_FALSE(!res);
  10548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10549. ASSERT_FALSE(res == nullptr);
  10550. ASSERT_TRUE(res != nullptr);
  10551. EXPECT_EQ(Error::Success, res.error());
  10552. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  10553. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  10554. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10555. cli.set_follow_location(true);
  10556. res = cli.Get("/");
  10557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10558. EXPECT_EQ(Error::Success, res.error());
  10559. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  10560. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  10561. EXPECT_EQ(StatusCode::OK_200, res->status);
  10562. EXPECT_EQ("https://www.yahoo.com/", res->location);
  10563. }
  10564. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10565. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  10566. Client cli("https://cdnjs.cloudflare.com");
  10567. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  10568. Headers{{"Accept-Encoding", "br"}});
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::OK_200, res->status);
  10571. EXPECT_EQ(287630U, res->body.size());
  10572. EXPECT_EQ("application/javascript; charset=utf-8",
  10573. res->get_header_value("Content-Type"));
  10574. }
  10575. #endif
  10576. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  10577. #undef REDIR_HOST // Silence compiler warning
  10578. #define REDIR_HOST "https://httpbingo.org"
  10579. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  10580. Client cli(REDIR_HOST);
  10581. cli.set_follow_location(true);
  10582. auto res =
  10583. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  10584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10585. EXPECT_EQ(StatusCode::OK_200, res->status);
  10586. }
  10587. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  10588. Client cli(REDIR_HOST);
  10589. cli.set_follow_location(true);
  10590. Params params;
  10591. params.emplace("url", "http://example.com");
  10592. params.emplace("status_code", "302");
  10593. auto res = cli.Get(REDIR_PATH, params, Headers{});
  10594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10595. EXPECT_EQ(StatusCode::OK_200, res->status);
  10596. }
  10597. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  10598. Client cli(REDIR_HOST);
  10599. cli.set_follow_location(true);
  10600. Params params;
  10601. params.emplace("url", "http://example.com");
  10602. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  10603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10604. EXPECT_EQ(StatusCode::OK_200, res->status);
  10605. }
  10606. TEST(HttpToHttpsRedirectTest, CertFile) {
  10607. auto ssl_port = PORT + 1;
  10608. Server svr;
  10609. ASSERT_TRUE(svr.is_valid());
  10610. svr.Get("/index", [&](const Request &, Response &res) {
  10611. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10612. "/index");
  10613. svr.stop();
  10614. });
  10615. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10616. ASSERT_TRUE(ssl_svr.is_valid());
  10617. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  10618. res.set_content("test", "text/plain");
  10619. ssl_svr.stop();
  10620. });
  10621. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10622. thread t2 =
  10623. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  10624. auto se = detail::scope_exit([&] {
  10625. t2.join();
  10626. t.join();
  10627. ASSERT_FALSE(svr.is_running());
  10628. });
  10629. svr.wait_until_ready();
  10630. ssl_svr.wait_until_ready();
  10631. Client cli("127.0.0.1", PORT);
  10632. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  10633. cli.enable_server_certificate_verification(true);
  10634. cli.set_follow_location(true);
  10635. cli.set_connection_timeout(30);
  10636. auto res = cli.Get("/index");
  10637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10638. ASSERT_EQ(StatusCode::OK_200, res->status);
  10639. }
  10640. TEST(SSLClientRedirectTest, CertFile) {
  10641. auto ssl_port = PORT + 1;
  10642. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10643. ASSERT_TRUE(ssl_svr1.is_valid());
  10644. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10645. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10646. "/index");
  10647. ssl_svr1.stop();
  10648. });
  10649. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10650. ASSERT_TRUE(ssl_svr2.is_valid());
  10651. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10652. res.set_content("test", "text/plain");
  10653. ssl_svr2.stop();
  10654. });
  10655. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10656. thread t2 =
  10657. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10658. auto se = detail::scope_exit([&] {
  10659. t2.join();
  10660. t.join();
  10661. ASSERT_FALSE(ssl_svr1.is_running());
  10662. });
  10663. ssl_svr1.wait_until_ready();
  10664. ssl_svr2.wait_until_ready();
  10665. SSLClient cli("127.0.0.1", PORT);
  10666. std::string cert;
  10667. read_file(SERVER_CERT2_FILE, cert);
  10668. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10669. cli.enable_server_certificate_verification(true);
  10670. cli.set_follow_location(true);
  10671. cli.set_connection_timeout(30);
  10672. auto res = cli.Get("/index");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. ASSERT_EQ(StatusCode::OK_200, res->status);
  10675. }
  10676. #endif
  10677. #ifdef CPPHTTPLIB_SSL_ENABLED
  10678. // Test that set_ca_cert_store() skips system certs (consistent with
  10679. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  10680. // should be trusted - system certs should NOT be loaded.
  10681. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  10682. // Load a specific cert that is NOT a system CA cert
  10683. std::string cert;
  10684. read_file(SERVER_CERT2_FILE, cert);
  10685. SSLClient cli("google.com");
  10686. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10687. cli.enable_server_certificate_verification(true);
  10688. // This should FAIL because:
  10689. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  10690. // 2. System certs should NOT be loaded when custom store is set
  10691. // If system certs WERE loaded, this would succeed
  10692. auto res = cli.Get("/");
  10693. ASSERT_FALSE(res);
  10694. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10695. }
  10696. // Same as above, but through the native store handle path. Regression test:
  10697. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  10698. // merged system certs into the user-provided store.
  10699. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  10700. std::string cert;
  10701. read_file(SERVER_CERT2_FILE, cert);
  10702. SSLClient cli("google.com");
  10703. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10704. cli.enable_server_certificate_verification(true);
  10705. auto res = cli.Get("/");
  10706. ASSERT_FALSE(res);
  10707. EXPECT_EQ(Error::SSLServerVerification, res.error());
  10708. }
  10709. // A custom store set via the native handle must still verify a server whose
  10710. // cert it does contain.
  10711. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  10712. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10713. ASSERT_TRUE(svr.is_valid());
  10714. svr.Get("/test", [&](const Request &, Response &res) {
  10715. res.set_content("test", "text/plain");
  10716. });
  10717. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10718. auto se = detail::scope_exit([&] {
  10719. svr.stop();
  10720. t.join();
  10721. ASSERT_FALSE(svr.is_running());
  10722. });
  10723. svr.wait_until_ready();
  10724. SSLClient cli("127.0.0.1", PORT);
  10725. std::string cert;
  10726. read_file(SERVER_CERT2_FILE, cert);
  10727. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  10728. cli.enable_server_certificate_verification(true);
  10729. cli.set_connection_timeout(30);
  10730. auto res = cli.Get("/test");
  10731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10732. ASSERT_EQ(StatusCode::OK_200, res->status);
  10733. }
  10734. // CA certs loaded through the universal Client must be transferred to the
  10735. // client created internally for following an HTTPS redirect. Regression test:
  10736. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  10737. // the CA data for redirect transfer.
  10738. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  10739. auto ssl_port = PORT + 1;
  10740. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10741. ASSERT_TRUE(ssl_svr1.is_valid());
  10742. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  10743. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  10744. "/index");
  10745. });
  10746. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10747. ASSERT_TRUE(ssl_svr2.is_valid());
  10748. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  10749. res.set_content("test", "text/plain");
  10750. });
  10751. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  10752. thread t2 =
  10753. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  10754. auto se = detail::scope_exit([&] {
  10755. ssl_svr2.stop();
  10756. ssl_svr1.stop();
  10757. t2.join();
  10758. t.join();
  10759. ASSERT_FALSE(ssl_svr1.is_running());
  10760. });
  10761. ssl_svr1.wait_until_ready();
  10762. ssl_svr2.wait_until_ready();
  10763. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10764. std::string cert;
  10765. read_file(SERVER_CERT2_FILE, cert);
  10766. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10767. cli.enable_server_certificate_verification(true);
  10768. cli.set_follow_location(true);
  10769. cli.set_connection_timeout(30);
  10770. auto res = cli.Get("/index");
  10771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10772. ASSERT_EQ(StatusCode::OK_200, res->status);
  10773. }
  10774. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  10775. // so a host signed by a system CA verifies even though a custom CA is set
  10776. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  10777. std::string cert;
  10778. read_file(SERVER_CERT2_FILE, cert);
  10779. SSLClient cli("google.com");
  10780. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10781. cli.enable_system_ca(true);
  10782. cli.enable_server_certificate_verification(true);
  10783. auto res = cli.Get("/");
  10784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10785. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10786. }
  10787. // The custom CA remains effective when combined with the system CA
  10788. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  10789. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10790. ASSERT_TRUE(svr.is_valid());
  10791. svr.Get("/test", [&](const Request &, Response &res) {
  10792. res.set_content("test", "text/plain");
  10793. });
  10794. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10795. auto se = detail::scope_exit([&] {
  10796. svr.stop();
  10797. t.join();
  10798. ASSERT_FALSE(svr.is_running());
  10799. });
  10800. svr.wait_until_ready();
  10801. SSLClient cli("127.0.0.1", PORT);
  10802. std::string cert;
  10803. read_file(SERVER_CERT2_FILE, cert);
  10804. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10805. cli.enable_system_ca(true);
  10806. cli.enable_server_certificate_verification(true);
  10807. cli.set_connection_timeout(30);
  10808. auto res = cli.Get("/test");
  10809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10810. ASSERT_EQ(StatusCode::OK_200, res->status);
  10811. }
  10812. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  10813. // skip chain verification entirely (only the certificate identity was
  10814. // checked), so a server presenting an untrusted certificate with a matching
  10815. // IP SAN was accepted. The chain must be validated for IP hosts too.
  10816. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  10817. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10818. ASSERT_TRUE(svr.is_valid());
  10819. svr.Get("/test", [&](const Request &, Response &res) {
  10820. res.set_content("test", "text/plain");
  10821. });
  10822. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10823. auto se = detail::scope_exit([&] {
  10824. svr.stop();
  10825. t.join();
  10826. ASSERT_FALSE(svr.is_running());
  10827. });
  10828. svr.wait_until_ready();
  10829. SSLClient cli("127.0.0.1", PORT);
  10830. std::string cert;
  10831. // A trusted CA that did not sign the server certificate. The server cert
  10832. // (cert2) carries the matching IP SAN, so only chain validation can reject
  10833. // this connection.
  10834. read_file(CLIENT_CA_CERT_FILE, cert);
  10835. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10836. cli.enable_server_certificate_verification(true);
  10837. cli.set_connection_timeout(30);
  10838. auto res = cli.Get("/test");
  10839. ASSERT_FALSE(res);
  10840. }
  10841. // enable_system_ca(false) prevents system CA loading entirely
  10842. TEST(SSLClientTest, DisableSystemCa_Online) {
  10843. SSLClient cli("google.com");
  10844. cli.enable_system_ca(false);
  10845. cli.enable_server_certificate_verification(true);
  10846. auto res = cli.Get("/");
  10847. ASSERT_FALSE(res);
  10848. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  10849. // itself when the CA chain is empty
  10850. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  10851. res.error() == Error::SSLConnection);
  10852. }
  10853. // The universal Client forwards enable_system_ca()
  10854. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  10855. std::string cert;
  10856. read_file(SERVER_CERT2_FILE, cert);
  10857. Client cli("https://google.com");
  10858. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10859. cli.enable_system_ca(true);
  10860. cli.enable_server_certificate_verification(true);
  10861. auto res = cli.Get("/");
  10862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10863. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  10864. }
  10865. // The system CA policy must carry over to the client created internally for
  10866. // following a cross-host HTTPS redirect
  10867. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  10868. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  10869. ASSERT_TRUE(svr.is_valid());
  10870. svr.Get("/index", [&](const Request &, Response &res) {
  10871. res.set_redirect("https://www.google.com/");
  10872. });
  10873. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  10874. auto se = detail::scope_exit([&] {
  10875. svr.stop();
  10876. t.join();
  10877. ASSERT_FALSE(svr.is_running());
  10878. });
  10879. svr.wait_until_ready();
  10880. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  10881. std::string cert;
  10882. read_file(SERVER_CERT2_FILE, cert);
  10883. cli.load_ca_cert_store(cert.c_str(), cert.size());
  10884. cli.enable_system_ca(true);
  10885. cli.enable_server_certificate_verification(true);
  10886. cli.set_follow_location(true);
  10887. cli.set_connection_timeout(30);
  10888. // Receiving any response proves the redirect client completed the TLS
  10889. // handshake with a system-CA-signed host
  10890. auto res = cli.Get("/index");
  10891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10892. }
  10893. TEST(MultipartFormDataTest, LargeData) {
  10894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10895. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  10896. const ContentReader &content_reader) {
  10897. if (req.is_multipart_form_data()) {
  10898. std::vector<FormData> items;
  10899. content_reader(
  10900. [&](const FormData &file) {
  10901. items.push_back(file);
  10902. return true;
  10903. },
  10904. [&](const char *data, size_t data_length) {
  10905. items.back().content.append(data, data_length);
  10906. return true;
  10907. });
  10908. EXPECT_TRUE(std::string(items[0].name) == "document");
  10909. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10910. EXPECT_TRUE(items[0].filename == "2MB_data");
  10911. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10912. EXPECT_TRUE(items[1].name == "hello");
  10913. EXPECT_TRUE(items[1].content == "world");
  10914. EXPECT_TRUE(items[1].filename == "");
  10915. EXPECT_TRUE(items[1].content_type == "");
  10916. } else {
  10917. std::string body;
  10918. content_reader([&](const char *data, size_t data_length) {
  10919. body.append(data, data_length);
  10920. return true;
  10921. });
  10922. }
  10923. });
  10924. auto port = svr.bind_to_any_port(HOST);
  10925. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10926. auto se = detail::scope_exit([&] {
  10927. svr.stop();
  10928. t.join();
  10929. ASSERT_FALSE(svr.is_running());
  10930. });
  10931. svr.wait_until_ready();
  10932. {
  10933. std::string data(1024 * 1024 * 2, '.');
  10934. std::stringstream buffer;
  10935. buffer << data;
  10936. SSLClient cli(HOST, port);
  10937. cli.enable_server_certificate_verification(false);
  10938. UploadFormDataItems items{
  10939. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10940. {"hello", "world", "", ""},
  10941. };
  10942. auto res = cli.Post("/post", items);
  10943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10944. ASSERT_EQ(StatusCode::OK_200, res->status);
  10945. }
  10946. }
  10947. TEST(MultipartFormDataTest, DataProviderItems) {
  10948. std::random_device seed_gen;
  10949. std::mt19937 random(seed_gen());
  10950. std::string rand1;
  10951. rand1.resize(1000);
  10952. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  10953. std::string rand2;
  10954. rand2.resize(3000);
  10955. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  10956. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10957. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  10958. const ContentReader &content_reader) {
  10959. ASSERT_FALSE(req.is_multipart_form_data());
  10960. std::string body;
  10961. content_reader([&](const char *data, size_t data_length) {
  10962. body.append(data, data_length);
  10963. return true;
  10964. });
  10965. EXPECT_EQ(body, "");
  10966. });
  10967. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  10968. const ContentReader &content_reader) {
  10969. ASSERT_TRUE(req.is_multipart_form_data());
  10970. std::vector<FormData> items;
  10971. content_reader(
  10972. [&](const FormData &file) {
  10973. items.push_back(file);
  10974. return true;
  10975. },
  10976. [&](const char *data, size_t data_length) {
  10977. items.back().content.append(data, data_length);
  10978. return true;
  10979. });
  10980. ASSERT_TRUE(items.size() == 2);
  10981. EXPECT_EQ(std::string(items[0].name), "name1");
  10982. EXPECT_EQ(items[0].content, "Testing123");
  10983. EXPECT_EQ(items[0].filename, "filename1");
  10984. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  10985. EXPECT_EQ(items[1].name, "name2");
  10986. EXPECT_EQ(items[1].content, "Testing456");
  10987. EXPECT_EQ(items[1].filename, "");
  10988. EXPECT_EQ(items[1].content_type, "");
  10989. });
  10990. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  10991. const ContentReader &content_reader) {
  10992. ASSERT_TRUE(req.is_multipart_form_data());
  10993. std::vector<FormData> items;
  10994. content_reader(
  10995. [&](const FormData &file) {
  10996. items.push_back(file);
  10997. return true;
  10998. },
  10999. [&](const char *data, size_t data_length) {
  11000. items.back().content.append(data, data_length);
  11001. return true;
  11002. });
  11003. ASSERT_TRUE(items.size() == 2);
  11004. EXPECT_EQ(items[0].name, "name3");
  11005. EXPECT_EQ(items[0].content, rand1);
  11006. EXPECT_EQ(items[0].filename, "filename3");
  11007. EXPECT_EQ(items[0].content_type, "");
  11008. EXPECT_EQ(items[1].name, "name4");
  11009. EXPECT_EQ(items[1].content, rand2);
  11010. EXPECT_EQ(items[1].filename, "filename4");
  11011. EXPECT_EQ(items[1].content_type, "");
  11012. });
  11013. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  11014. const ContentReader &content_reader) {
  11015. ASSERT_TRUE(req.is_multipart_form_data());
  11016. std::vector<FormData> items;
  11017. content_reader(
  11018. [&](const FormData &file) {
  11019. items.push_back(file);
  11020. return true;
  11021. },
  11022. [&](const char *data, size_t data_length) {
  11023. items.back().content.append(data, data_length);
  11024. return true;
  11025. });
  11026. ASSERT_TRUE(items.size() == 4);
  11027. EXPECT_EQ(std::string(items[0].name), "name1");
  11028. EXPECT_EQ(items[0].content, "Testing123");
  11029. EXPECT_EQ(items[0].filename, "filename1");
  11030. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  11031. EXPECT_EQ(items[1].name, "name2");
  11032. EXPECT_EQ(items[1].content, "Testing456");
  11033. EXPECT_EQ(items[1].filename, "");
  11034. EXPECT_EQ(items[1].content_type, "");
  11035. EXPECT_EQ(items[2].name, "name3");
  11036. EXPECT_EQ(items[2].content, rand1);
  11037. EXPECT_EQ(items[2].filename, "filename3");
  11038. EXPECT_EQ(items[2].content_type, "");
  11039. EXPECT_EQ(items[3].name, "name4");
  11040. EXPECT_EQ(items[3].content, rand2);
  11041. EXPECT_EQ(items[3].filename, "filename4");
  11042. EXPECT_EQ(items[3].content_type, "");
  11043. });
  11044. auto port = svr.bind_to_any_port("localhost");
  11045. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11046. auto se = detail::scope_exit([&] {
  11047. svr.stop();
  11048. t.join();
  11049. ASSERT_FALSE(svr.is_running());
  11050. });
  11051. svr.wait_until_ready();
  11052. {
  11053. SSLClient cli("localhost", port);
  11054. cli.enable_server_certificate_verification(false);
  11055. UploadFormDataItems items{
  11056. {"name1", "Testing123", "filename1", "application/octet-stream"},
  11057. {"name2", "Testing456", "", ""}, // not a file
  11058. };
  11059. {
  11060. auto res = cli.Post("/post-none", {}, {}, {});
  11061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11062. ASSERT_EQ(StatusCode::OK_200, res->status);
  11063. }
  11064. FormDataProviderItems providers;
  11065. {
  11066. auto res =
  11067. cli.Post("/post-items", {}, items, providers); // empty providers
  11068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11069. ASSERT_EQ(StatusCode::OK_200, res->status);
  11070. }
  11071. providers.push_back({"name3",
  11072. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11073. // test the offset is given correctly at each step
  11074. if (!offset)
  11075. sink.os.write(rand1.data(), 30);
  11076. else if (offset == 30)
  11077. sink.os.write(rand1.data() + 30, 300);
  11078. else if (offset == 330)
  11079. sink.os.write(rand1.data() + 330, 670);
  11080. else if (offset == rand1.size())
  11081. sink.done();
  11082. return true;
  11083. },
  11084. "filename3",
  11085. {}});
  11086. providers.push_back({"name4",
  11087. [&](size_t offset, httplib::DataSink &sink) -> bool {
  11088. // test the offset is given correctly at each step
  11089. if (!offset)
  11090. sink.os.write(rand2.data(), 2000);
  11091. else if (offset == 2000)
  11092. sink.os.write(rand2.data() + 2000, 1);
  11093. else if (offset == 2001)
  11094. sink.os.write(rand2.data() + 2001, 999);
  11095. else if (offset == rand2.size())
  11096. sink.done();
  11097. return true;
  11098. },
  11099. "filename4",
  11100. {}});
  11101. {
  11102. auto res = cli.Post("/post-providers", {}, {}, providers);
  11103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11104. ASSERT_EQ(StatusCode::OK_200, res->status);
  11105. }
  11106. {
  11107. auto res = cli.Post("/post-both", {}, items, providers);
  11108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11109. ASSERT_EQ(StatusCode::OK_200, res->status);
  11110. }
  11111. }
  11112. }
  11113. TEST(MultipartFormDataTest, BadHeader) {
  11114. Server svr;
  11115. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11116. res.set_content("ok", "text/plain");
  11117. });
  11118. thread t = thread([&] { svr.listen(HOST, PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. svr.stop();
  11121. t.join();
  11122. ASSERT_FALSE(svr.is_running());
  11123. });
  11124. svr.wait_until_ready();
  11125. const std::string body =
  11126. "This is the preamble. It is to be ignored, though it\r\n"
  11127. "is a handy place for composition agents to include an\r\n"
  11128. "explanatory note to non-MIME conformant readers.\r\n"
  11129. "\r\n"
  11130. "\r\n"
  11131. "--simple boundary\r\n"
  11132. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11133. ": BAD...\r\n"
  11134. "\r\n"
  11135. "value1\r\n"
  11136. "--simple boundary\r\n"
  11137. "Content-Disposition: form-data; name=\"field2\"; "
  11138. "filename=\"example.txt\"\r\n"
  11139. "\r\n"
  11140. "value2\r\n"
  11141. "--simple boundary--\r\n"
  11142. "This is the epilogue. It is also to be ignored.\r\n";
  11143. std::string content_type =
  11144. R"(multipart/form-data; boundary="simple boundary")";
  11145. Client cli(HOST, PORT);
  11146. auto res = cli.Post("/post", body, content_type.c_str());
  11147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11148. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11149. }
  11150. TEST(MultipartFormDataTest, WithPreamble) {
  11151. Server svr;
  11152. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11153. res.set_content("ok", "text/plain");
  11154. });
  11155. thread t = thread([&] { svr.listen(HOST, PORT); });
  11156. auto se = detail::scope_exit([&] {
  11157. svr.stop();
  11158. t.join();
  11159. ASSERT_FALSE(svr.is_running());
  11160. });
  11161. svr.wait_until_ready();
  11162. const std::string body =
  11163. "This is the preamble. It is to be ignored, though it\r\n"
  11164. "is a handy place for composition agents to include an\r\n"
  11165. "explanatory note to non-MIME conformant readers.\r\n"
  11166. "\r\n"
  11167. "\r\n"
  11168. "--simple boundary\r\n"
  11169. "Content-Disposition: form-data; name=\"field1\"\r\n"
  11170. "\r\n"
  11171. "value1\r\n"
  11172. "--simple boundary\r\n"
  11173. "Content-Disposition: form-data; name=\"field2\"; "
  11174. "filename=\"example.txt\"\r\n"
  11175. "\r\n"
  11176. "value2\r\n"
  11177. "--simple boundary--\r\n"
  11178. "This is the epilogue. It is also to be ignored.\r\n";
  11179. std::string content_type =
  11180. R"(multipart/form-data; boundary="simple boundary")";
  11181. Client cli(HOST, PORT);
  11182. auto res = cli.Post("/post", body, content_type.c_str());
  11183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11184. EXPECT_EQ(StatusCode::OK_200, res->status);
  11185. }
  11186. TEST(MultipartFormDataTest, PostCustomBoundary) {
  11187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11188. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  11189. const ContentReader &content_reader) {
  11190. if (req.is_multipart_form_data()) {
  11191. std::vector<FormData> items;
  11192. content_reader(
  11193. [&](const FormData &file) {
  11194. items.push_back(file);
  11195. return true;
  11196. },
  11197. [&](const char *data, size_t data_length) {
  11198. items.back().content.append(data, data_length);
  11199. return true;
  11200. });
  11201. EXPECT_TRUE(std::string(items[0].name) == "document");
  11202. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11203. EXPECT_TRUE(items[0].filename == "2MB_data");
  11204. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11205. EXPECT_TRUE(items[1].name == "hello");
  11206. EXPECT_TRUE(items[1].content == "world");
  11207. EXPECT_TRUE(items[1].filename == "");
  11208. EXPECT_TRUE(items[1].content_type == "");
  11209. } else {
  11210. std::string body;
  11211. content_reader([&](const char *data, size_t data_length) {
  11212. body.append(data, data_length);
  11213. return true;
  11214. });
  11215. }
  11216. });
  11217. auto port = svr.bind_to_any_port("localhost");
  11218. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11219. auto se = detail::scope_exit([&] {
  11220. svr.stop();
  11221. t.join();
  11222. ASSERT_FALSE(svr.is_running());
  11223. });
  11224. svr.wait_until_ready();
  11225. {
  11226. std::string data(1024 * 1024 * 2, '.');
  11227. std::stringstream buffer;
  11228. buffer << data;
  11229. SSLClient cli("localhost", port);
  11230. cli.enable_server_certificate_verification(false);
  11231. UploadFormDataItems items{
  11232. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11233. {"hello", "world", "", ""},
  11234. };
  11235. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  11236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11237. ASSERT_EQ(StatusCode::OK_200, res->status);
  11238. }
  11239. }
  11240. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  11241. std::string data(1024 * 1024 * 2, '&');
  11242. std::stringstream buffer;
  11243. buffer << data;
  11244. Client cli("https://localhost:8080");
  11245. UploadFormDataItems items{
  11246. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11247. {"hello", "world", "", ""},
  11248. };
  11249. for (const char &c : " \t\r\n") {
  11250. auto res =
  11251. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  11252. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11253. ASSERT_FALSE(res);
  11254. }
  11255. }
  11256. TEST(MultipartFormDataTest, PutFormData) {
  11257. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11258. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  11259. const ContentReader &content_reader) {
  11260. if (req.is_multipart_form_data()) {
  11261. std::vector<FormData> items;
  11262. content_reader(
  11263. [&](const FormData &file) {
  11264. items.push_back(file);
  11265. return true;
  11266. },
  11267. [&](const char *data, size_t data_length) {
  11268. items.back().content.append(data, data_length);
  11269. return true;
  11270. });
  11271. EXPECT_TRUE(std::string(items[0].name) == "document");
  11272. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11273. EXPECT_TRUE(items[0].filename == "2MB_data");
  11274. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11275. EXPECT_TRUE(items[1].name == "hello");
  11276. EXPECT_TRUE(items[1].content == "world");
  11277. EXPECT_TRUE(items[1].filename == "");
  11278. EXPECT_TRUE(items[1].content_type == "");
  11279. } else {
  11280. std::string body;
  11281. content_reader([&](const char *data, size_t data_length) {
  11282. body.append(data, data_length);
  11283. return true;
  11284. });
  11285. }
  11286. });
  11287. auto port = svr.bind_to_any_port("localhost");
  11288. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11289. auto se = detail::scope_exit([&] {
  11290. svr.stop();
  11291. t.join();
  11292. ASSERT_FALSE(svr.is_running());
  11293. });
  11294. svr.wait_until_ready();
  11295. {
  11296. std::string data(1024 * 1024 * 2, '&');
  11297. std::stringstream buffer;
  11298. buffer << data;
  11299. SSLClient cli("localhost", port);
  11300. cli.enable_server_certificate_verification(false);
  11301. UploadFormDataItems items{
  11302. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11303. {"hello", "world", "", ""},
  11304. };
  11305. auto res = cli.Put("/put", items);
  11306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11307. ASSERT_EQ(StatusCode::OK_200, res->status);
  11308. }
  11309. }
  11310. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  11311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11312. svr.Put("/put_customboundary",
  11313. [&](const Request &req, const Response & /*res*/,
  11314. const ContentReader &content_reader) {
  11315. if (req.is_multipart_form_data()) {
  11316. std::vector<FormData> items;
  11317. content_reader(
  11318. [&](const FormData &file) {
  11319. items.push_back(file);
  11320. return true;
  11321. },
  11322. [&](const char *data, size_t data_length) {
  11323. items.back().content.append(data, data_length);
  11324. return true;
  11325. });
  11326. EXPECT_TRUE(std::string(items[0].name) == "document");
  11327. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  11328. EXPECT_TRUE(items[0].filename == "2MB_data");
  11329. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  11330. EXPECT_TRUE(items[1].name == "hello");
  11331. EXPECT_TRUE(items[1].content == "world");
  11332. EXPECT_TRUE(items[1].filename == "");
  11333. EXPECT_TRUE(items[1].content_type == "");
  11334. } else {
  11335. std::string body;
  11336. content_reader([&](const char *data, size_t data_length) {
  11337. body.append(data, data_length);
  11338. return true;
  11339. });
  11340. }
  11341. });
  11342. auto port = svr.bind_to_any_port("localhost");
  11343. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11344. auto se = detail::scope_exit([&] {
  11345. svr.stop();
  11346. t.join();
  11347. ASSERT_FALSE(svr.is_running());
  11348. });
  11349. svr.wait_until_ready();
  11350. {
  11351. std::string data(1024 * 1024 * 2, '&');
  11352. std::stringstream buffer;
  11353. buffer << data;
  11354. SSLClient cli("localhost", port);
  11355. cli.enable_server_certificate_verification(false);
  11356. UploadFormDataItems items{
  11357. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11358. {"hello", "world", "", ""},
  11359. };
  11360. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  11361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11362. ASSERT_EQ(StatusCode::OK_200, res->status);
  11363. }
  11364. }
  11365. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  11366. std::string data(1024 * 1024 * 2, '&');
  11367. std::stringstream buffer;
  11368. buffer << data;
  11369. Client cli("https://localhost:8080");
  11370. cli.enable_server_certificate_verification(false);
  11371. UploadFormDataItems items{
  11372. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  11373. {"hello", "world", "", ""},
  11374. };
  11375. for (const char &c : " \t\r\n") {
  11376. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  11377. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  11378. ASSERT_FALSE(res);
  11379. }
  11380. }
  11381. TEST(MultipartFormDataTest, AlternateFilename) {
  11382. auto handled = false;
  11383. Server svr;
  11384. svr.Post("/test", [&](const Request &req, Response &res) {
  11385. ASSERT_EQ(2u, req.form.files.size());
  11386. ASSERT_EQ(1u, req.form.fields.size());
  11387. // Test files
  11388. const auto &file1 = req.form.get_file("file1");
  11389. ASSERT_EQ("file1", file1.name);
  11390. ASSERT_EQ("A.txt", file1.filename);
  11391. ASSERT_EQ("text/plain", file1.content_type);
  11392. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  11393. const auto &file2 = req.form.get_file("file2");
  11394. ASSERT_EQ("file2", file2.name);
  11395. ASSERT_EQ("a.html", file2.filename);
  11396. ASSERT_EQ("text/html", file2.content_type);
  11397. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  11398. file2.content);
  11399. // Test text field
  11400. const auto &text = req.form.get_field("text");
  11401. ASSERT_EQ("text default", text);
  11402. res.set_content("ok", "text/plain");
  11403. handled = true;
  11404. });
  11405. thread t = thread([&] { svr.listen(HOST, PORT); });
  11406. auto se = detail::scope_exit([&] {
  11407. svr.stop();
  11408. t.join();
  11409. ASSERT_FALSE(svr.is_running());
  11410. ASSERT_TRUE(handled);
  11411. });
  11412. svr.wait_until_ready();
  11413. auto req = "POST /test HTTP/1.1\r\n"
  11414. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11415. "Content-Length: 399\r\n"
  11416. "\r\n"
  11417. "----------\r\n"
  11418. "Content-Disposition: form-data; name=\"text\"\r\n"
  11419. "\r\n"
  11420. "text default\r\n"
  11421. "----------\r\n"
  11422. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  11423. "filename=\"a.txt\"; name=\"file1\"\r\n"
  11424. "Content-Type: text/plain\r\n"
  11425. "\r\n"
  11426. "Content of a.txt.\r\n"
  11427. "\r\n"
  11428. "----------\r\n"
  11429. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  11430. "\"a.html\"\r\n"
  11431. "Content-Type: text/html\r\n"
  11432. "\r\n"
  11433. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  11434. "\r\n"
  11435. "------------\r\n";
  11436. ASSERT_TRUE(send_request(1, req));
  11437. }
  11438. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  11439. auto handled = false;
  11440. Server svr;
  11441. svr.Post("/test", [&](const Request &req, Response &res) {
  11442. // Case-insensitive "utf-8''" prefix with a long value
  11443. const auto &file = req.form.get_file("file1");
  11444. ASSERT_EQ("file1", file.name);
  11445. // 8000 chars exercises both the Content-Disposition parser and the
  11446. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  11447. // Prior to the fix, std::regex_match on this header would cause O(N)
  11448. // stack recursion in libstdc++, leading to SIGSEGV.
  11449. std::string expected_filename(8000, 'A');
  11450. ASSERT_EQ(expected_filename, file.filename);
  11451. res.set_content("ok", "text/plain");
  11452. handled = true;
  11453. });
  11454. thread t = thread([&] { svr.listen(HOST, PORT); });
  11455. auto se = detail::scope_exit([&] {
  11456. svr.stop();
  11457. t.join();
  11458. ASSERT_FALSE(svr.is_running());
  11459. ASSERT_TRUE(handled);
  11460. });
  11461. svr.wait_until_ready();
  11462. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  11463. // Regression test for GHSA-qq6v-r583-3h69
  11464. std::string long_filename(8000, 'A');
  11465. std::string body = "----------\r\n"
  11466. "Content-Disposition: form-data; name=\"file1\"; "
  11467. "filename*=\"Utf-8''" +
  11468. long_filename +
  11469. "\"\r\n"
  11470. "\r\n"
  11471. "hello\r\n"
  11472. "------------\r\n";
  11473. auto req = "POST /test HTTP/1.1\r\n"
  11474. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11475. "Content-Length: " +
  11476. std::to_string(body.size()) + "\r\n\r\n" + body;
  11477. ASSERT_TRUE(send_request(1, req));
  11478. }
  11479. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  11480. auto handled = false;
  11481. Server svr;
  11482. svr.Post("/test", [&](const Request &req, Response &) {
  11483. ASSERT_EQ(2u, req.form.fields.size());
  11484. const auto &text1 = req.form.get_field("text1");
  11485. ASSERT_EQ("text1", text1);
  11486. const auto &text2 = req.form.get_field("text2");
  11487. ASSERT_EQ("text2", text2);
  11488. handled = true;
  11489. });
  11490. thread t = thread([&] { svr.listen(HOST, PORT); });
  11491. auto se = detail::scope_exit([&] {
  11492. svr.stop();
  11493. t.join();
  11494. ASSERT_FALSE(svr.is_running());
  11495. ASSERT_TRUE(handled);
  11496. });
  11497. svr.wait_until_ready();
  11498. auto req = "POST /test HTTP/1.1\r\n"
  11499. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11500. "Content-Length: 146\r\n"
  11501. "\r\n----------\r\n"
  11502. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11503. "\r\n"
  11504. "text1"
  11505. "\r\n----------\r\n"
  11506. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11507. "\r\n"
  11508. "text2"
  11509. "\r\n------------";
  11510. std::string response;
  11511. ASSERT_TRUE(send_request(1, req, &response));
  11512. ASSERT_EQ("200", response.substr(9, 3));
  11513. }
  11514. TEST(MultipartFormDataTest, ContentLength) {
  11515. auto handled = false;
  11516. Server svr;
  11517. svr.Post("/test", [&](const Request &req, Response &) {
  11518. ASSERT_EQ(2u, req.form.fields.size());
  11519. const auto &text1 = req.form.get_field("text1");
  11520. ASSERT_EQ("text1", text1);
  11521. const auto &text2 = req.form.get_field("text2");
  11522. ASSERT_EQ("text2", text2);
  11523. handled = true;
  11524. });
  11525. thread t = thread([&] { svr.listen(HOST, PORT); });
  11526. auto se = detail::scope_exit([&] {
  11527. svr.stop();
  11528. t.join();
  11529. ASSERT_FALSE(svr.is_running());
  11530. ASSERT_TRUE(handled);
  11531. });
  11532. svr.wait_until_ready();
  11533. auto req = "POST /test HTTP/1.1\r\n"
  11534. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11535. "Content-Length: 167\r\n"
  11536. "\r\n----------\r\n"
  11537. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11538. "Content-Length: 5\r\n"
  11539. "\r\n"
  11540. "text1"
  11541. "\r\n----------\r\n"
  11542. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11543. "\r\n"
  11544. "text2"
  11545. "\r\n------------\r\n";
  11546. std::string response;
  11547. ASSERT_TRUE(send_request(1, req, &response));
  11548. ASSERT_EQ("200", response.substr(9, 3));
  11549. }
  11550. TEST(MultipartFormDataTest, AccessPartHeaders) {
  11551. auto handled = false;
  11552. Server svr;
  11553. svr.Post("/test", [&](const Request &req, Response &) {
  11554. ASSERT_EQ(2u, req.form.fields.size());
  11555. const auto &text1 = req.form.get_field("text1");
  11556. ASSERT_EQ("text1", text1);
  11557. // TODO: Add header access for text fields if needed
  11558. const auto &text2 = req.form.get_field("text2");
  11559. ASSERT_EQ("text2", text2);
  11560. // TODO: Header access for text fields needs to be implemented
  11561. // auto &headers = it->second.headers;
  11562. // ASSERT_EQ(3U, headers.size());
  11563. // auto custom_header = headers.find("x-whatever");
  11564. // ASSERT_TRUE(custom_header != headers.end());
  11565. // ASSERT_NE("customvalue", custom_header->second);
  11566. // ASSERT_EQ("CustomValue", custom_header->second);
  11567. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  11568. handled = true;
  11569. });
  11570. thread t = thread([&] { svr.listen(HOST, PORT); });
  11571. auto se = detail::scope_exit([&] {
  11572. svr.stop();
  11573. t.join();
  11574. ASSERT_FALSE(svr.is_running());
  11575. ASSERT_TRUE(handled);
  11576. });
  11577. svr.wait_until_ready();
  11578. auto req = "POST /test HTTP/1.1\r\n"
  11579. "Content-Type: multipart/form-data;boundary=--------\r\n"
  11580. "Content-Length: 232\r\n"
  11581. "\r\n----------\r\n"
  11582. "Content-Disposition: form-data; name=\"text1\"\r\n"
  11583. "Content-Length: 5\r\n"
  11584. "X-Test: 1\r\n"
  11585. "\r\n"
  11586. "text1"
  11587. "\r\n----------\r\n"
  11588. "Content-Disposition: form-data; name=\"text2\"\r\n"
  11589. "Content-Type: text/plain\r\n"
  11590. "X-Whatever: CustomValue\r\n"
  11591. "\r\n"
  11592. "text2"
  11593. "\r\n------------\r\n"
  11594. "That should be disregarded. Not even read";
  11595. std::string response;
  11596. ASSERT_TRUE(send_request(1, req, &response));
  11597. ASSERT_EQ("200", response.substr(9, 3));
  11598. }
  11599. TEST(MultipartFormDataTest, LargeHeader) {
  11600. auto handled = false;
  11601. Server svr;
  11602. svr.Post("/test", [&](const Request &req, Response &) {
  11603. ASSERT_EQ(1u, req.form.fields.size());
  11604. const auto &text = req.form.get_field("name1");
  11605. ASSERT_EQ("text1", text);
  11606. handled = true;
  11607. });
  11608. thread t = thread([&] { svr.listen(HOST, PORT); });
  11609. auto se = detail::scope_exit([&] {
  11610. svr.stop();
  11611. t.join();
  11612. ASSERT_FALSE(svr.is_running());
  11613. ASSERT_TRUE(handled);
  11614. });
  11615. svr.wait_until_ready();
  11616. auto boundary = std::string("cpp-httplib-multipart-data");
  11617. std::string content = "--" + boundary +
  11618. "\r\n"
  11619. "Content-Disposition: form-data; name=\"name1\"\r\n"
  11620. "\r\n"
  11621. "text1\r\n"
  11622. "--" +
  11623. boundary + "--\r\n";
  11624. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  11625. "Content-Type: multipart/form-data;boundary=" +
  11626. boundary +
  11627. "\r\n"
  11628. "Content-Length: " +
  11629. std::to_string(content.size()) +
  11630. "\r\n"
  11631. "Dummy-Header: ";
  11632. std::string header_suffix = "\r\n"
  11633. "\r\n";
  11634. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  11635. size_t header_dummy_size =
  11636. read_buff_size -
  11637. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  11638. auto header_dummy = std::string(header_dummy_size, '@');
  11639. auto req = header_prefix + header_dummy + header_suffix + content;
  11640. std::string response;
  11641. ASSERT_TRUE(send_request(1, req, &response));
  11642. ASSERT_EQ("200", response.substr(9, 3));
  11643. }
  11644. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  11645. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  11646. // (not chunked Transfer-Encoding) after the streaming refactor.
  11647. auto handled = false;
  11648. Server svr;
  11649. svr.Post("/upload", [&](const Request &req, Response &res) {
  11650. auto cl_it = req.headers.find("Content-Length");
  11651. EXPECT_TRUE(cl_it != req.headers.end());
  11652. auto te_it = req.headers.find("Transfer-Encoding");
  11653. EXPECT_TRUE(te_it == req.headers.end());
  11654. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  11655. res.set_content("ok", "text/plain");
  11656. handled = true;
  11657. });
  11658. auto port = svr.bind_to_any_port(HOST);
  11659. auto t = thread([&] { svr.listen_after_bind(); });
  11660. auto se = detail::scope_exit([&] {
  11661. svr.stop();
  11662. t.join();
  11663. ASSERT_FALSE(svr.is_running());
  11664. ASSERT_TRUE(handled);
  11665. });
  11666. svr.wait_until_ready();
  11667. UploadFormDataItems items = {
  11668. {"field1", "hello", "", "text/plain"},
  11669. {"file1", "world", "test.txt", "application/octet-stream"},
  11670. };
  11671. Client cli(HOST, port);
  11672. auto res = cli.Post("/upload", {}, items);
  11673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11674. EXPECT_EQ(StatusCode::OK_200, res->status);
  11675. }
  11676. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  11677. // Verify that make_multipart_content_provider coalesces many small segments
  11678. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  11679. constexpr size_t kItemCount = 1000;
  11680. UploadFormDataItems items;
  11681. items.reserve(kItemCount);
  11682. for (size_t i = 0; i < kItemCount; i++) {
  11683. items.push_back(
  11684. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11685. }
  11686. const std::string boundary = "----test-boundary";
  11687. auto content_length = detail::get_multipart_content_length(items, boundary);
  11688. auto provider = detail::make_multipart_content_provider(items, boundary);
  11689. // Drive the provider the same way write_content_with_progress does
  11690. size_t write_count = 0;
  11691. size_t total_bytes = 0;
  11692. DataSink sink;
  11693. size_t offset = 0;
  11694. sink.write = [&](const char *d, size_t l) -> bool {
  11695. (void)d;
  11696. write_count++;
  11697. total_bytes += l;
  11698. offset += l;
  11699. return true;
  11700. };
  11701. sink.is_writable = []() -> bool { return true; };
  11702. while (offset < content_length) {
  11703. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  11704. }
  11705. EXPECT_EQ(content_length, total_bytes);
  11706. // The total number of segments is 3 * kItemCount + 1 = 3001.
  11707. // With buffering into 64KB blocks, write_count should be much smaller.
  11708. auto segment_count = 3 * kItemCount + 1;
  11709. EXPECT_LT(write_count, segment_count / 10);
  11710. }
  11711. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  11712. // Integration test: send many UploadFormDataItems and verify the server
  11713. // receives all of them correctly (#2410).
  11714. constexpr size_t kItemCount = 500;
  11715. auto handled = false;
  11716. Server svr;
  11717. svr.Post("/upload", [&](const Request &req, Response &res) {
  11718. EXPECT_EQ(kItemCount, req.form.fields.size());
  11719. for (size_t i = 0; i < kItemCount; i++) {
  11720. auto key = "field" + std::to_string(i);
  11721. auto val = "value" + std::to_string(i);
  11722. auto it = req.form.fields.find(key);
  11723. if (it != req.form.fields.end()) {
  11724. EXPECT_EQ(val, it->second.content);
  11725. } else {
  11726. ADD_FAILURE() << "Missing field: " << key;
  11727. }
  11728. }
  11729. res.set_content("ok", "text/plain");
  11730. handled = true;
  11731. });
  11732. auto port = svr.bind_to_any_port(HOST);
  11733. auto t = thread([&] { svr.listen_after_bind(); });
  11734. auto se = detail::scope_exit([&] {
  11735. svr.stop();
  11736. t.join();
  11737. ASSERT_FALSE(svr.is_running());
  11738. ASSERT_TRUE(handled);
  11739. });
  11740. svr.wait_until_ready();
  11741. UploadFormDataItems items;
  11742. items.reserve(kItemCount);
  11743. for (size_t i = 0; i < kItemCount; i++) {
  11744. items.push_back(
  11745. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  11746. }
  11747. Client cli(HOST, port);
  11748. auto res = cli.Post("/upload", items);
  11749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11750. EXPECT_EQ(StatusCode::OK_200, res->status);
  11751. }
  11752. TEST(MultipartFormDataTest, MakeFileProvider) {
  11753. // Verify make_file_provider sends a file's contents correctly.
  11754. const std::string file_content(4096, 'Z');
  11755. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  11756. {
  11757. std::ofstream ofs(tmp_path, std::ios::binary);
  11758. ofs.write(file_content.data(),
  11759. static_cast<std::streamsize>(file_content.size()));
  11760. }
  11761. auto handled = false;
  11762. Server svr;
  11763. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  11764. const ContentReader &content_reader) {
  11765. ASSERT_TRUE(req.is_multipart_form_data());
  11766. std::vector<FormData> items;
  11767. content_reader(
  11768. [&](const FormData &file) {
  11769. items.push_back(file);
  11770. return true;
  11771. },
  11772. [&](const char *data, size_t data_length) {
  11773. items.back().content.append(data, data_length);
  11774. return true;
  11775. });
  11776. ASSERT_EQ(1u, items.size());
  11777. EXPECT_EQ("myfile", items[0].name);
  11778. EXPECT_EQ("data.bin", items[0].filename);
  11779. EXPECT_EQ("application/octet-stream", items[0].content_type);
  11780. EXPECT_EQ(file_content, items[0].content);
  11781. handled = true;
  11782. });
  11783. auto port = svr.bind_to_any_port(HOST);
  11784. auto t = thread([&] { svr.listen_after_bind(); });
  11785. auto se = detail::scope_exit([&] {
  11786. svr.stop();
  11787. t.join();
  11788. ASSERT_FALSE(svr.is_running());
  11789. ASSERT_TRUE(handled);
  11790. std::remove(tmp_path.c_str());
  11791. });
  11792. svr.wait_until_ready();
  11793. FormDataProviderItems providers;
  11794. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  11795. "application/octet-stream"));
  11796. Client cli(HOST, port);
  11797. auto res = cli.Post("/upload", {}, {}, providers);
  11798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11799. EXPECT_EQ(StatusCode::OK_200, res->status);
  11800. }
  11801. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  11802. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  11803. // (100) headers is rejected with a 400 Bad Request response.
  11804. Server svr;
  11805. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  11806. res.set_content("ok", "text/plain");
  11807. });
  11808. thread t = thread([&] { svr.listen(HOST, PORT); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. t.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. // Build a multipart part with 101 custom headers (exceeding
  11816. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  11817. std::stringstream body;
  11818. body << "--simpleboundary\r\n"
  11819. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  11820. for (int i = 0; i < 101; i++) {
  11821. body << "X-Custom-Header-" << i << ": value\r\n";
  11822. }
  11823. body << "\r\n"
  11824. << "value1\r\n"
  11825. << "--simpleboundary--\r\n";
  11826. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  11827. Client cli(HOST, PORT);
  11828. auto res = cli.Post("/post", body.str(), content_type.c_str());
  11829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11830. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11831. }
  11832. TEST(MakeFileBodyTest, Basic) {
  11833. const std::string file_content(4096, 'Z');
  11834. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  11835. {
  11836. std::ofstream ofs(tmp_path, std::ios::binary);
  11837. ofs.write(file_content.data(),
  11838. static_cast<std::streamsize>(file_content.size()));
  11839. }
  11840. auto handled = false;
  11841. Server svr;
  11842. svr.Post("/upload", [&](const Request &req, Response &res) {
  11843. EXPECT_EQ(file_content, req.body);
  11844. handled = true;
  11845. res.status = StatusCode::OK_200;
  11846. });
  11847. auto port = svr.bind_to_any_port(HOST);
  11848. auto t = thread([&] { svr.listen_after_bind(); });
  11849. auto se = detail::scope_exit([&] {
  11850. svr.stop();
  11851. t.join();
  11852. ASSERT_FALSE(svr.is_running());
  11853. ASSERT_TRUE(handled);
  11854. std::remove(tmp_path.c_str());
  11855. });
  11856. svr.wait_until_ready();
  11857. auto fb = make_file_body(tmp_path);
  11858. ASSERT_GT(fb.first, 0u);
  11859. Client cli(HOST, port);
  11860. auto res =
  11861. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  11862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11863. EXPECT_EQ(StatusCode::OK_200, res->status);
  11864. }
  11865. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  11866. static constexpr unsigned int number_of_tasks{1000000};
  11867. std::atomic_uint count{0};
  11868. std::unique_ptr<TaskQueue> task_queue{
  11869. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  11870. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11871. auto queued = task_queue->enqueue(
  11872. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  11873. EXPECT_TRUE(queued);
  11874. }
  11875. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11876. task_queue->shutdown();
  11877. #else
  11878. EXPECT_NO_THROW(task_queue->shutdown());
  11879. #endif
  11880. EXPECT_EQ(number_of_tasks, count.load());
  11881. }
  11882. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  11883. static constexpr unsigned int number_of_tasks{1000000};
  11884. static constexpr unsigned int qlimit{2};
  11885. unsigned int queued_count{0};
  11886. std::atomic_uint count{0};
  11887. std::unique_ptr<TaskQueue> task_queue{
  11888. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  11889. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  11890. if (task_queue->enqueue(
  11891. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  11892. queued_count++;
  11893. }
  11894. }
  11895. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11896. task_queue->shutdown();
  11897. #else
  11898. EXPECT_NO_THROW(task_queue->shutdown());
  11899. #endif
  11900. EXPECT_EQ(queued_count, count.load());
  11901. EXPECT_TRUE(queued_count <= number_of_tasks);
  11902. EXPECT_TRUE(queued_count >= qlimit);
  11903. }
  11904. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  11905. // Use a short idle timeout so a dynamic thread spawns, times out and
  11906. // exits during the test, and the pool keeps working afterwards.
  11907. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  11908. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  11909. /*idle_timeout_sec=*/1}};
  11910. std::atomic_uint count{0};
  11911. std::condition_variable cv;
  11912. std::mutex mtx;
  11913. bool release = false;
  11914. // Block the base thread so the second task spawns a dynamic thread.
  11915. EXPECT_TRUE(task_queue->enqueue([&] {
  11916. std::unique_lock<std::mutex> lock(mtx);
  11917. while (!release) {
  11918. cv.wait(lock);
  11919. }
  11920. count++;
  11921. }));
  11922. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11923. // Let the dynamic thread finish its task and exceed the idle timeout.
  11924. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11925. {
  11926. std::unique_lock<std::mutex> lock(mtx);
  11927. release = true;
  11928. }
  11929. cv.notify_all();
  11930. // The pool must still accept and run tasks after the dynamic thread exited.
  11931. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  11932. task_queue->shutdown();
  11933. EXPECT_EQ(3u, count.load());
  11934. }
  11935. TEST(TaskQueueTest, MaxQueuedRequests) {
  11936. static constexpr unsigned int qlimit{3};
  11937. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  11938. std::condition_variable sem_cv;
  11939. std::mutex sem_mtx;
  11940. int credits = 0;
  11941. bool queued;
  11942. /* Fill up the queue with tasks that will block until we give them credits to
  11943. * complete. */
  11944. for (unsigned int n = 0; n <= qlimit;) {
  11945. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  11946. std::unique_lock<std::mutex> lock(sem_mtx);
  11947. while (credits <= 0) {
  11948. sem_cv.wait(lock);
  11949. }
  11950. /* Consume the credit and signal the test code if they are all gone. */
  11951. if (--credits == 0) { sem_cv.notify_one(); }
  11952. });
  11953. if (n < qlimit) {
  11954. /* The first qlimit enqueues must succeed. */
  11955. EXPECT_TRUE(queued);
  11956. } else {
  11957. /* The last one will succeed only when the worker thread
  11958. * starts and dequeues the first blocking task. Although
  11959. * not necessary for the correctness of this test, we sleep for
  11960. * a short while to avoid busy waiting. */
  11961. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11962. }
  11963. if (queued) { n++; }
  11964. }
  11965. /* Further enqueues must fail since the queue is full. */
  11966. for (auto i = 0; i < 4; i++) {
  11967. queued = task_queue->enqueue([] {});
  11968. EXPECT_FALSE(queued);
  11969. }
  11970. /* Give the credits to allow the previous tasks to complete. */
  11971. {
  11972. std::unique_lock<std::mutex> lock(sem_mtx);
  11973. credits += qlimit + 1;
  11974. }
  11975. sem_cv.notify_all();
  11976. /* Wait for all the credits to be consumed. */
  11977. {
  11978. std::unique_lock<std::mutex> lock(sem_mtx);
  11979. while (credits > 0) {
  11980. sem_cv.wait(lock);
  11981. }
  11982. }
  11983. /* Check that we are able again to enqueue at least qlimit tasks. */
  11984. for (unsigned int i = 0; i < qlimit; i++) {
  11985. queued = task_queue->enqueue([] {});
  11986. EXPECT_TRUE(queued);
  11987. }
  11988. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11989. task_queue->shutdown();
  11990. #else
  11991. EXPECT_NO_THROW(task_queue->shutdown());
  11992. #endif
  11993. }
  11994. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  11995. Server svr;
  11996. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11997. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  11998. });
  11999. svr.Get("/hello", [](const Request &req, Response &res) {
  12000. res.set_content(req.get_param_value("key"), "text/plain");
  12001. });
  12002. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12003. auto se = detail::scope_exit([&] {
  12004. svr.stop();
  12005. thread.join();
  12006. ASSERT_FALSE(svr.is_running());
  12007. });
  12008. svr.wait_until_ready();
  12009. {
  12010. Client cli(HOST, PORT);
  12011. cli.set_follow_location(true);
  12012. auto res = cli.Get("/");
  12013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12014. EXPECT_EQ(StatusCode::OK_200, res->status);
  12015. EXPECT_EQ("val&key2=val2", res->body);
  12016. }
  12017. }
  12018. #endif
  12019. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  12020. Server svr;
  12021. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12022. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  12023. });
  12024. svr.Get("/hello", [](const Request &req, Response &res) {
  12025. res.set_content(req.get_param_value("key"), "text/plain");
  12026. });
  12027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12028. auto se = detail::scope_exit([&] {
  12029. svr.stop();
  12030. thread.join();
  12031. ASSERT_FALSE(svr.is_running());
  12032. });
  12033. svr.wait_until_ready();
  12034. {
  12035. Client cli(HOST, PORT);
  12036. cli.set_follow_location(true);
  12037. auto res = cli.Get("/");
  12038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12039. EXPECT_EQ(StatusCode::OK_200, res->status);
  12040. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  12041. }
  12042. }
  12043. TEST(RedirectTest, RedirectWithPlusInPath) {
  12044. Server svr;
  12045. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12046. res.set_redirect("/a+b");
  12047. });
  12048. // Route pattern uses regex; escape + as \\+
  12049. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  12050. res.set_content(req.path, "text/plain");
  12051. });
  12052. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12053. auto se = detail::scope_exit([&] {
  12054. svr.stop();
  12055. thread.join();
  12056. ASSERT_FALSE(svr.is_running());
  12057. });
  12058. svr.wait_until_ready();
  12059. {
  12060. Client cli(HOST, PORT);
  12061. cli.set_follow_location(true);
  12062. auto res = cli.Get("/");
  12063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12064. EXPECT_EQ(StatusCode::OK_200, res->status);
  12065. EXPECT_EQ("/a+b", res->body);
  12066. }
  12067. }
  12068. #ifdef CPPHTTPLIB_SSL_ENABLED
  12069. TEST(RedirectTest, Issue2185_Online) {
  12070. SSLClient client("github.com");
  12071. client.set_follow_location(true);
  12072. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  12073. "Coollab-Windows.zip");
  12074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12075. EXPECT_EQ(StatusCode::OK_200, res->status);
  12076. EXPECT_EQ(9920427U, res->body.size());
  12077. }
  12078. #endif
  12079. TEST(VulnerabilityTest, CRLFInjection) {
  12080. Server svr;
  12081. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  12082. res.set_content("Hello 1", "text/plain");
  12083. });
  12084. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  12085. res.set_content("Hello 2", "text/plain");
  12086. });
  12087. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  12088. res.set_content("Hello 3", "text/plain");
  12089. });
  12090. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  12091. res.set_content("Hello 4", "text/plain");
  12092. });
  12093. svr.set_logger([](const Request &req, const Response & /*res*/) {
  12094. for (const auto &x : req.headers) {
  12095. auto key = x.first;
  12096. EXPECT_STRNE("evil", key.c_str());
  12097. }
  12098. });
  12099. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12100. auto se = detail::scope_exit([&] {
  12101. svr.stop();
  12102. thread.join();
  12103. ASSERT_FALSE(svr.is_running());
  12104. });
  12105. svr.wait_until_ready();
  12106. {
  12107. Client cli(HOST, PORT);
  12108. cli.Post("/test1", "A=B",
  12109. "application/x-www-form-urlencoded\r\nevil: hello1");
  12110. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  12111. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  12112. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  12113. }
  12114. }
  12115. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  12116. auto server_thread = std::thread([] {
  12117. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12118. default_socket_options(srv);
  12119. sockaddr_in addr{};
  12120. addr.sin_family = AF_INET;
  12121. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  12122. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12123. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12124. ::listen(srv, 1);
  12125. sockaddr_in cli_addr{};
  12126. socklen_t cli_len = sizeof(cli_addr);
  12127. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12128. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  12129. std::string buf_all;
  12130. char buf[2048];
  12131. ssize_t n;
  12132. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  12133. buf_all.append(buf, static_cast<size_t>(n));
  12134. size_t pos;
  12135. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  12136. auto request_block = buf_all.substr(0, pos + 4); // include separator
  12137. auto e = request_block.find("\r\n");
  12138. if (e != std::string::npos) {
  12139. auto request_line = request_block.substr(0, e);
  12140. std::string msg =
  12141. "CRLF injection detected in request line: '" + request_line + "'";
  12142. EXPECT_FALSE(true) << msg;
  12143. }
  12144. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  12145. ::send(cli,
  12146. #ifdef _WIN32
  12147. static_cast<const char *>(resp.c_str()),
  12148. static_cast<int>(resp.size()),
  12149. #else
  12150. resp.c_str(), resp.size(),
  12151. #endif
  12152. 0);
  12153. buf_all.erase(0, pos + 4);
  12154. }
  12155. }
  12156. detail::close_socket(cli);
  12157. detail::close_socket(srv);
  12158. });
  12159. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12160. auto cli = Client("127.0.0.1", PORT + 1);
  12161. auto headers = Headers{
  12162. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  12163. {"Connection", "keep-alive"}};
  12164. auto res = cli.Get("/hi", headers);
  12165. EXPECT_FALSE(res);
  12166. EXPECT_EQ(Error::InvalidHeaders, res.error());
  12167. server_thread.join();
  12168. }
  12169. TEST(PathParamsTest, StaticMatch) {
  12170. const auto pattern = "/users/all";
  12171. detail::PathParamsMatcher matcher(pattern);
  12172. Request request;
  12173. request.path = "/users/all";
  12174. ASSERT_TRUE(matcher.match(request));
  12175. std::unordered_map<std::string, std::string> expected_params = {};
  12176. EXPECT_EQ(request.path_params, expected_params);
  12177. }
  12178. TEST(PathParamsTest, StaticMismatch) {
  12179. const auto pattern = "/users/all";
  12180. detail::PathParamsMatcher matcher(pattern);
  12181. Request request;
  12182. request.path = "/users/1";
  12183. ASSERT_FALSE(matcher.match(request));
  12184. }
  12185. TEST(PathParamsTest, SingleParamInTheMiddle) {
  12186. const auto pattern = "/users/:id/subscriptions";
  12187. detail::PathParamsMatcher matcher(pattern);
  12188. Request request;
  12189. request.path = "/users/42/subscriptions";
  12190. ASSERT_TRUE(matcher.match(request));
  12191. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12192. EXPECT_EQ(request.path_params, expected_params);
  12193. }
  12194. TEST(PathParamsTest, SingleParamInTheEnd) {
  12195. const auto pattern = "/users/:id";
  12196. detail::PathParamsMatcher matcher(pattern);
  12197. Request request;
  12198. request.path = "/users/24";
  12199. ASSERT_TRUE(matcher.match(request));
  12200. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  12201. EXPECT_EQ(request.path_params, expected_params);
  12202. }
  12203. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  12204. const auto pattern = "/users/:id/";
  12205. detail::PathParamsMatcher matcher(pattern);
  12206. Request request;
  12207. request.path = "/users/42/";
  12208. ASSERT_TRUE(matcher.match(request));
  12209. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  12210. EXPECT_EQ(request.path_params, expected_params);
  12211. }
  12212. TEST(PathParamsTest, EmptyParam) {
  12213. const auto pattern = "/users/:id/";
  12214. detail::PathParamsMatcher matcher(pattern);
  12215. Request request;
  12216. request.path = "/users//";
  12217. ASSERT_TRUE(matcher.match(request));
  12218. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  12219. EXPECT_EQ(request.path_params, expected_params);
  12220. }
  12221. TEST(PathParamsTest, FragmentMismatch) {
  12222. const auto pattern = "/users/:id/";
  12223. detail::PathParamsMatcher matcher(pattern);
  12224. Request request;
  12225. request.path = "/admins/24/";
  12226. ASSERT_FALSE(matcher.match(request));
  12227. }
  12228. TEST(PathParamsTest, ExtraFragments) {
  12229. const auto pattern = "/users/:id";
  12230. detail::PathParamsMatcher matcher(pattern);
  12231. Request request;
  12232. request.path = "/users/42/subscriptions";
  12233. ASSERT_FALSE(matcher.match(request));
  12234. }
  12235. TEST(PathParamsTest, MissingTrailingParam) {
  12236. const auto pattern = "/users/:id";
  12237. detail::PathParamsMatcher matcher(pattern);
  12238. Request request;
  12239. request.path = "/users";
  12240. ASSERT_FALSE(matcher.match(request));
  12241. }
  12242. TEST(PathParamsTest, MissingParamInTheMiddle) {
  12243. const auto pattern = "/users/:id/subscriptions";
  12244. detail::PathParamsMatcher matcher(pattern);
  12245. Request request;
  12246. request.path = "/users/subscriptions";
  12247. ASSERT_FALSE(matcher.match(request));
  12248. }
  12249. TEST(PathParamsTest, MultipleParams) {
  12250. const auto pattern = "/users/:userid/subscriptions/:subid";
  12251. detail::PathParamsMatcher matcher(pattern);
  12252. Request request;
  12253. request.path = "/users/42/subscriptions/2";
  12254. ASSERT_TRUE(matcher.match(request));
  12255. std::unordered_map<std::string, std::string> expected_params = {
  12256. {"userid", "42"}, {"subid", "2"}};
  12257. EXPECT_EQ(request.path_params, expected_params);
  12258. }
  12259. TEST(PathParamsTest, SequenceOfParams) {
  12260. const auto pattern = "/values/:x/:y/:z";
  12261. detail::PathParamsMatcher matcher(pattern);
  12262. Request request;
  12263. request.path = "/values/1/2/3";
  12264. ASSERT_TRUE(matcher.match(request));
  12265. std::unordered_map<std::string, std::string> expected_params = {
  12266. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  12267. EXPECT_EQ(request.path_params, expected_params);
  12268. }
  12269. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  12270. const auto pattern = "/prefix:suffix";
  12271. detail::PathParamsMatcher matcher(pattern);
  12272. Request request;
  12273. request.path = "/prefix:suffix";
  12274. ASSERT_TRUE(matcher.match(request));
  12275. const std::unordered_map<std::string, std::string> expected_params = {};
  12276. EXPECT_EQ(request.path_params, expected_params);
  12277. }
  12278. TEST(ParseUrlTest, VariousPatterns) {
  12279. {
  12280. detail::UrlComponents uc;
  12281. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  12282. EXPECT_EQ("http", uc.scheme);
  12283. EXPECT_EQ("example.com", uc.host);
  12284. EXPECT_EQ("8080", uc.port);
  12285. EXPECT_EQ("/path", uc.path);
  12286. EXPECT_EQ("?q=1", uc.query);
  12287. }
  12288. {
  12289. detail::UrlComponents uc;
  12290. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  12291. EXPECT_EQ("https", uc.scheme);
  12292. EXPECT_EQ("example.com", uc.host);
  12293. EXPECT_TRUE(uc.port.empty());
  12294. EXPECT_EQ("/path", uc.path);
  12295. }
  12296. {
  12297. detail::UrlComponents uc;
  12298. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  12299. EXPECT_EQ("::1", uc.host);
  12300. EXPECT_EQ("8080", uc.port);
  12301. EXPECT_EQ("/path", uc.path);
  12302. }
  12303. {
  12304. detail::UrlComponents uc;
  12305. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  12306. }
  12307. {
  12308. detail::UrlComponents uc;
  12309. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  12310. EXPECT_TRUE(uc.scheme.empty());
  12311. EXPECT_EQ("example.com", uc.host);
  12312. EXPECT_EQ("/path", uc.path);
  12313. EXPECT_EQ("?q=1", uc.query);
  12314. }
  12315. {
  12316. detail::UrlComponents uc;
  12317. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  12318. EXPECT_TRUE(uc.host.empty());
  12319. EXPECT_EQ("/path", uc.path);
  12320. EXPECT_EQ("?q=1", uc.query);
  12321. }
  12322. {
  12323. detail::UrlComponents uc;
  12324. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  12325. EXPECT_EQ("example.com", uc.host);
  12326. EXPECT_EQ("8080", uc.port);
  12327. }
  12328. {
  12329. // Unix socket path — must not be parsed as host
  12330. detail::UrlComponents uc;
  12331. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  12332. EXPECT_TRUE(uc.host.empty());
  12333. }
  12334. {
  12335. detail::UrlComponents uc;
  12336. ASSERT_TRUE(detail::parse_url("", uc));
  12337. EXPECT_TRUE(uc.host.empty());
  12338. EXPECT_TRUE(uc.path.empty());
  12339. }
  12340. {
  12341. detail::UrlComponents uc;
  12342. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  12343. }
  12344. {
  12345. detail::UrlComponents uc;
  12346. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  12347. }
  12348. {
  12349. // Accepted by parse_url; callers restrict to http/https
  12350. detail::UrlComponents uc;
  12351. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  12352. EXPECT_EQ("ftp", uc.scheme);
  12353. }
  12354. {
  12355. detail::UrlComponents uc;
  12356. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  12357. }
  12358. {
  12359. detail::UrlComponents uc;
  12360. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  12361. }
  12362. }
  12363. TEST(ParseUrlTest, FragmentHandling) {
  12364. {
  12365. detail::UrlComponents uc;
  12366. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  12367. EXPECT_EQ("/path", uc.path);
  12368. EXPECT_TRUE(uc.query.empty());
  12369. }
  12370. {
  12371. detail::UrlComponents uc;
  12372. ASSERT_TRUE(detail::parse_url("#frag", uc));
  12373. EXPECT_TRUE(uc.path.empty());
  12374. EXPECT_TRUE(uc.query.empty());
  12375. }
  12376. }
  12377. TEST(ParseUrlTest, UserinfoHandling) {
  12378. // Userinfo with @ but no colon — host includes @
  12379. detail::UrlComponents uc;
  12380. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  12381. EXPECT_EQ("user@host.com", uc.host);
  12382. EXPECT_EQ("/path", uc.path);
  12383. }
  12384. TEST(ParseUrlTest, IPv6EdgeCases) {
  12385. {
  12386. detail::UrlComponents uc;
  12387. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  12388. EXPECT_TRUE(uc.scheme.empty());
  12389. EXPECT_EQ("::1", uc.host);
  12390. EXPECT_EQ("8080", uc.port);
  12391. }
  12392. {
  12393. // Zone ID '%25' is not in [a-fA-F0-9:]
  12394. detail::UrlComponents uc;
  12395. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  12396. }
  12397. }
  12398. TEST(ParseUrlTest, SchemeEdgeCases) {
  12399. {
  12400. detail::UrlComponents uc;
  12401. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  12402. }
  12403. {
  12404. detail::UrlComponents uc;
  12405. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  12406. }
  12407. {
  12408. detail::UrlComponents uc;
  12409. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  12410. }
  12411. }
  12412. TEST(ParseUrlTest, PortEdgeCases) {
  12413. {
  12414. detail::UrlComponents uc;
  12415. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  12416. EXPECT_TRUE(uc.port.empty());
  12417. EXPECT_EQ("/path", uc.path);
  12418. }
  12419. {
  12420. // parse_url accepts any port string; validation is done by parse_port
  12421. detail::UrlComponents uc;
  12422. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  12423. EXPECT_EQ("abc", uc.port);
  12424. }
  12425. }
  12426. TEST(ParseUrlTest, WebSocketPatterns) {
  12427. {
  12428. detail::UrlComponents uc;
  12429. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  12430. EXPECT_EQ("ws", uc.scheme);
  12431. EXPECT_EQ("echo.example.com", uc.host);
  12432. EXPECT_EQ("8080", uc.port);
  12433. EXPECT_EQ("/ws", uc.path);
  12434. }
  12435. {
  12436. detail::UrlComponents uc;
  12437. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  12438. EXPECT_EQ("wss", uc.scheme);
  12439. EXPECT_EQ("echo.example.com", uc.host);
  12440. EXPECT_TRUE(uc.port.empty());
  12441. EXPECT_EQ("/ws", uc.path);
  12442. }
  12443. }
  12444. TEST(ParseUrlTest, QueryOnly) {
  12445. detail::UrlComponents uc;
  12446. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  12447. EXPECT_TRUE(uc.host.empty());
  12448. EXPECT_TRUE(uc.path.empty());
  12449. EXPECT_EQ("?q=1&r=2", uc.query);
  12450. }
  12451. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  12452. detail::UrlComponents uc;
  12453. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  12454. EXPECT_TRUE(uc.scheme.empty());
  12455. EXPECT_EQ("example.com", uc.host);
  12456. EXPECT_EQ("443", uc.port);
  12457. EXPECT_EQ("/path", uc.path);
  12458. }
  12459. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  12460. // If ipv6 regex working, regex match codepath is taken.
  12461. // else port will default to 80 in Client impl
  12462. int clientImplMagicPort = 80;
  12463. int port = 4321;
  12464. // above ports must be different to avoid false negative
  12465. EXPECT_NE(clientImplMagicPort, port);
  12466. std::string ipV6TestURL = "http://[ff06::c3]";
  12467. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  12468. CLIENT_PRIVATE_KEY_FILE);
  12469. EXPECT_EQ(cli.port(), port);
  12470. }
  12471. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  12472. auto file_path = "./www/dir/index.html";
  12473. auto dir_path = "./www/dir";
  12474. detail::FileStat stat_file(file_path);
  12475. EXPECT_TRUE(stat_file.is_file());
  12476. EXPECT_FALSE(stat_file.is_dir());
  12477. detail::FileStat stat_dir(dir_path);
  12478. EXPECT_FALSE(stat_dir.is_file());
  12479. EXPECT_TRUE(stat_dir.is_dir());
  12480. }
  12481. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  12482. // IPv4 with default HTTP port (80)
  12483. EXPECT_EQ("example.com",
  12484. detail::make_host_and_port_string("example.com", 80, false));
  12485. // IPv4 with default HTTPS port (443)
  12486. EXPECT_EQ("example.com",
  12487. detail::make_host_and_port_string("example.com", 443, true));
  12488. // IPv4 with non-default HTTP port
  12489. EXPECT_EQ("example.com:8080",
  12490. detail::make_host_and_port_string("example.com", 8080, false));
  12491. // IPv4 with non-default HTTPS port
  12492. EXPECT_EQ("example.com:8443",
  12493. detail::make_host_and_port_string("example.com", 8443, true));
  12494. // IPv6 with default HTTP port (80)
  12495. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  12496. // IPv6 with default HTTPS port (443)
  12497. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  12498. // IPv6 with non-default HTTP port
  12499. EXPECT_EQ("[::1]:8080",
  12500. detail::make_host_and_port_string("::1", 8080, false));
  12501. // IPv6 with non-default HTTPS port
  12502. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  12503. // IPv6 full address with default port
  12504. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  12505. detail::make_host_and_port_string(
  12506. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  12507. // IPv6 full address with non-default port
  12508. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  12509. detail::make_host_and_port_string(
  12510. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  12511. // IPv6 localhost with non-default port
  12512. EXPECT_EQ("[::1]:3000",
  12513. detail::make_host_and_port_string("::1", 3000, false));
  12514. // IPv6 with zone ID (link-local address) with default port
  12515. EXPECT_EQ("[fe80::1%eth0]",
  12516. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  12517. // IPv6 with zone ID (link-local address) with non-default port
  12518. EXPECT_EQ("[fe80::1%eth0]:8080",
  12519. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  12520. // Edge case: Port 443 with is_ssl=false (should add port)
  12521. EXPECT_EQ("example.com:443",
  12522. detail::make_host_and_port_string("example.com", 443, false));
  12523. // Edge case: Port 80 with is_ssl=true (should add port)
  12524. EXPECT_EQ("example.com:80",
  12525. detail::make_host_and_port_string("example.com", 80, true));
  12526. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  12527. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  12528. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  12529. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  12530. // Security fix: Already bracketed IPv6 should not get double brackets
  12531. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  12532. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  12533. EXPECT_EQ("[::1]:8080",
  12534. detail::make_host_and_port_string("[::1]", 8080, false));
  12535. EXPECT_EQ("[2001:db8::1]:8080",
  12536. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  12537. EXPECT_EQ("[fe80::1%eth0]",
  12538. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  12539. EXPECT_EQ("[fe80::1%eth0]:8080",
  12540. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  12541. // Edge case: Empty host (should return as-is)
  12542. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  12543. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  12544. // This is a known limitation but shouldn't crash
  12545. EXPECT_EQ("[host:name]",
  12546. detail::make_host_and_port_string("host:name", 80, false));
  12547. // Port number edge cases (no validation, but should not crash)
  12548. EXPECT_EQ("example.com:0",
  12549. detail::make_host_and_port_string("example.com", 0, false));
  12550. EXPECT_EQ("example.com:-1",
  12551. detail::make_host_and_port_string("example.com", -1, false));
  12552. EXPECT_EQ("example.com:65535",
  12553. detail::make_host_and_port_string("example.com", 65535, false));
  12554. EXPECT_EQ("example.com:65536",
  12555. detail::make_host_and_port_string("example.com", 65536, false));
  12556. }
  12557. #ifdef CPPHTTPLIB_SSL_ENABLED
  12558. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  12559. httplib::SSLClient cli("roblox.com", 443);
  12560. cli.set_follow_location(true);
  12561. auto res = cli.Get("/");
  12562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12563. EXPECT_EQ(StatusCode::OK_200, res->status);
  12564. }
  12565. #endif
  12566. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  12567. Server svr;
  12568. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12569. EXPECT_EQ(res.status, 400);
  12570. });
  12571. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12572. auto se = detail::scope_exit([&] {
  12573. svr.stop();
  12574. thread.join();
  12575. ASSERT_FALSE(svr.is_running());
  12576. });
  12577. svr.wait_until_ready();
  12578. Client cli(HOST, PORT);
  12579. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  12580. }
  12581. TEST(InvalidHeaderCharsTest, is_field_name) {
  12582. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  12583. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  12584. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  12585. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  12586. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  12587. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  12588. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  12589. EXPECT_FALSE(detail::fields::is_field_name(""));
  12590. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  12591. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  12592. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  12593. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  12594. }
  12595. TEST(InvalidHeaderCharsTest, is_field_value) {
  12596. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  12597. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  12598. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  12599. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  12600. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  12601. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  12602. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  12603. EXPECT_TRUE(detail::fields::is_field_value(""));
  12604. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  12605. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  12606. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  12607. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  12608. EXPECT_TRUE(detail::fields::is_field_value("0"));
  12609. }
  12610. TEST(InvalidHeaderCharsTest, OnServer) {
  12611. Server svr;
  12612. svr.Get("/test_name", [&](const Request &req, Response &res) {
  12613. std::string header = "Not Set";
  12614. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12615. res.set_header(header, "value");
  12616. res.set_content("Page Content Page Content", "text/plain");
  12617. });
  12618. svr.Get("/test_value", [&](const Request &req, Response &res) {
  12619. std::string header = "Not Set";
  12620. if (req.has_param("header")) { header = req.get_param_value("header"); }
  12621. res.set_header("X-Test", header);
  12622. res.set_content("Page Content Page Content", "text/plain");
  12623. });
  12624. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12625. auto se = detail::scope_exit([&] {
  12626. svr.stop();
  12627. thread.join();
  12628. ASSERT_FALSE(svr.is_running());
  12629. });
  12630. svr.wait_until_ready();
  12631. Client cli(HOST, PORT);
  12632. {
  12633. auto res = cli.Get(
  12634. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12636. EXPECT_EQ("Page Content Page Content", res->body);
  12637. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12638. }
  12639. {
  12640. auto res = cli.Get(
  12641. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  12642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12643. EXPECT_EQ("Page Content Page Content", res->body);
  12644. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  12645. }
  12646. }
  12647. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  12648. auto handled = false;
  12649. Server svr;
  12650. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  12651. thread t = thread([&] { svr.listen(HOST, PORT); });
  12652. auto se = detail::scope_exit([&] {
  12653. svr.stop();
  12654. t.join();
  12655. ASSERT_FALSE(svr.is_running());
  12656. ASSERT_FALSE(handled);
  12657. });
  12658. svr.wait_until_ready();
  12659. auto req = "POST /test HTTP/1.1\r\n"
  12660. "Content-Length: x\r\n"
  12661. "\r\n";
  12662. std::string response;
  12663. ASSERT_TRUE(send_request(1, req, &response));
  12664. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  12665. response.substr(0, response.find("\r\n")));
  12666. }
  12667. #ifndef _WIN32
  12668. TEST(Expect100ContinueTest, ServerClosesConnection) {
  12669. static constexpr char reject[] = "Unauthorized";
  12670. static constexpr char accept[] = "Upload accepted";
  12671. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  12672. Server svr;
  12673. svr.set_expect_100_continue_handler(
  12674. [](const Request & /*req*/, Response &res) {
  12675. res.status = StatusCode::Unauthorized_401;
  12676. res.set_content(reject, "text/plain");
  12677. return res.status;
  12678. });
  12679. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  12680. res.set_content(accept, "text/plain");
  12681. });
  12682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12683. auto se = detail::scope_exit([&] {
  12684. svr.stop();
  12685. thread.join();
  12686. ASSERT_FALSE(svr.is_running());
  12687. });
  12688. svr.wait_until_ready();
  12689. {
  12690. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  12691. curl_easy_init(), &curl_easy_cleanup};
  12692. ASSERT_NE(curl, nullptr);
  12693. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  12694. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  12695. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  12696. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  12697. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  12698. &curl_slist_free_all};
  12699. ASSERT_NE(list, nullptr);
  12700. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  12701. struct read_data {
  12702. size_t read_size;
  12703. size_t total_size;
  12704. } data = {0, total_size};
  12705. using read_callback_t =
  12706. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12707. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  12708. void *userdata) -> size_t {
  12709. read_data *d = (read_data *)userdata;
  12710. if (!userdata || d->read_size >= d->total_size) { return 0; }
  12711. std::fill_n(ptr, size * nmemb, 'A');
  12712. d->read_size += size * nmemb;
  12713. return size * nmemb;
  12714. };
  12715. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  12716. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  12717. std::vector<char> buffer;
  12718. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  12719. using write_callback_t =
  12720. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  12721. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  12722. void *userdata) -> size_t {
  12723. std::vector<char> *buf = (std::vector<char> *)userdata;
  12724. buf->reserve(buf->size() + size * nmemb + 1);
  12725. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  12726. return size * nmemb;
  12727. };
  12728. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  12729. {
  12730. const auto res = curl_easy_perform(curl.get());
  12731. ASSERT_EQ(res, CURLE_OK);
  12732. }
  12733. {
  12734. auto response_code = long{};
  12735. const auto res =
  12736. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  12737. ASSERT_EQ(res, CURLE_OK);
  12738. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  12739. }
  12740. {
  12741. auto dl = curl_off_t{};
  12742. const auto res =
  12743. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  12744. ASSERT_EQ(res, CURLE_OK);
  12745. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  12746. }
  12747. {
  12748. buffer.push_back('\0');
  12749. ASSERT_STRCASEEQ(buffer.data(), reject);
  12750. }
  12751. }
  12752. }
  12753. #endif
  12754. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  12755. // Regression test for #2458.
  12756. //
  12757. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  12758. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  12759. // ticket can make the client socket spuriously readable during the
  12760. // 100-continue wait. If the readiness is mistaken for an incoming response,
  12761. // the client withholds the body and then blocks reading a response that never
  12762. // comes, failing with `Failed to read connection`.
  12763. //
  12764. // A correct client (like curl) sends the body once no `100 Continue` arrives
  12765. // within the timeout. This raw OpenSSL server deliberately never sends
  12766. // `100 Continue`; the client must still deliver the body and receive 200.
  12767. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  12768. signal(SIGPIPE, SIG_IGN);
  12769. const auto port = PORT + 4;
  12770. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12771. ASSERT_NE(srv, INVALID_SOCKET);
  12772. int opt = 1;
  12773. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  12774. sockaddr_in addr{};
  12775. addr.sin_family = AF_INET;
  12776. addr.sin_port = htons(static_cast<uint16_t>(port));
  12777. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12778. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12779. ASSERT_EQ(0, ::listen(srv, 1));
  12780. std::atomic<size_t> server_body_bytes{0};
  12781. auto server_thread = std::thread([&] {
  12782. sockaddr_in cli_addr{};
  12783. socklen_t cli_len = sizeof(cli_addr);
  12784. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12785. if (cli == INVALID_SOCKET) { return; }
  12786. // Bound the lifetime of the server side so a buggy client (which never
  12787. // sends the body) cannot make this thread block forever on join.
  12788. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  12789. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  12790. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  12791. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  12792. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  12793. SSL *ssl = SSL_new(ctx);
  12794. SSL_set_fd(ssl, static_cast<int>(cli));
  12795. if (SSL_accept(ssl) > 0) {
  12796. // Read the request headers. Reading here also flushes the TLS 1.3
  12797. // session tickets to the client. Deliberately do NOT send
  12798. // `100 Continue`.
  12799. std::string buf;
  12800. char tmp[1024];
  12801. while (buf.find("\r\n\r\n") == std::string::npos) {
  12802. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12803. if (n <= 0) { break; }
  12804. buf.append(tmp, static_cast<size_t>(n));
  12805. }
  12806. // A correct client sends the body now; count what arrives.
  12807. auto pos = buf.find("\r\n\r\n");
  12808. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  12809. while (body < 4096) {
  12810. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  12811. if (n <= 0) { break; }
  12812. body += static_cast<size_t>(n);
  12813. }
  12814. server_body_bytes = body;
  12815. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  12816. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  12817. SSL_shutdown(ssl);
  12818. }
  12819. SSL_free(ssl);
  12820. detail::close_socket(cli);
  12821. SSL_CTX_free(ctx);
  12822. });
  12823. auto se = detail::scope_exit([&] {
  12824. server_thread.join();
  12825. detail::close_socket(srv);
  12826. });
  12827. SSLClient cli("127.0.0.1", port);
  12828. cli.enable_server_certificate_verification(false);
  12829. cli.set_connection_timeout(5, 0);
  12830. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  12831. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  12832. std::string body(4096, 'A');
  12833. auto res = cli.Put("/api/test", body, "application/json");
  12834. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  12835. EXPECT_EQ(StatusCode::OK_200, res->status);
  12836. EXPECT_EQ(body.size(), server_body_bytes.load());
  12837. }
  12838. #endif
  12839. template <typename S, typename C>
  12840. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  12841. svr.Get("/stream", [&](const Request &, Response &res) {
  12842. auto data = new std::string("01234567890123456789");
  12843. res.set_content_provider(
  12844. data->size(), "text/plain",
  12845. [&, data](size_t offset, size_t length, DataSink &sink) {
  12846. const size_t DATA_CHUNK_SIZE = 4;
  12847. const auto &d = *data;
  12848. std::this_thread::sleep_for(std::chrono::seconds(1));
  12849. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  12850. return true;
  12851. },
  12852. [data](bool success) {
  12853. EXPECT_FALSE(success);
  12854. delete data;
  12855. });
  12856. });
  12857. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  12858. auto i = new size_t(0);
  12859. res.set_content_provider(
  12860. "text/plain",
  12861. [i](size_t, DataSink &sink) {
  12862. if (*i < 5) {
  12863. std::this_thread::sleep_for(std::chrono::seconds(1));
  12864. sink.write("abcd", 4);
  12865. (*i)++;
  12866. } else {
  12867. sink.done();
  12868. }
  12869. return true;
  12870. },
  12871. [i](bool success) {
  12872. EXPECT_FALSE(success);
  12873. delete i;
  12874. });
  12875. });
  12876. svr.Get("/chunked", [&](const Request &, Response &res) {
  12877. auto i = new size_t(0);
  12878. res.set_chunked_content_provider(
  12879. "text/plain",
  12880. [i](size_t, DataSink &sink) {
  12881. if (*i < 5) {
  12882. std::this_thread::sleep_for(std::chrono::seconds(1));
  12883. sink.os << "abcd";
  12884. (*i)++;
  12885. } else {
  12886. sink.done();
  12887. }
  12888. return true;
  12889. },
  12890. [i](bool success) {
  12891. EXPECT_FALSE(success);
  12892. delete i;
  12893. });
  12894. });
  12895. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12896. auto se = detail::scope_exit([&] {
  12897. svr.stop();
  12898. listen_thread.join();
  12899. ASSERT_FALSE(svr.is_running());
  12900. });
  12901. svr.wait_until_ready();
  12902. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  12903. {
  12904. auto start = std::chrono::steady_clock::now();
  12905. auto res = cli.Get("/stream");
  12906. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12907. std::chrono::steady_clock::now() - start)
  12908. .count();
  12909. ASSERT_FALSE(res);
  12910. EXPECT_EQ(Error::Read, res.error());
  12911. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12912. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12913. }
  12914. {
  12915. auto start = std::chrono::steady_clock::now();
  12916. auto res = cli.Get("/stream_without_length");
  12917. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12918. std::chrono::steady_clock::now() - start)
  12919. .count();
  12920. ASSERT_FALSE(res);
  12921. EXPECT_EQ(Error::Read, res.error());
  12922. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12923. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12924. }
  12925. {
  12926. auto start = std::chrono::steady_clock::now();
  12927. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  12928. EXPECT_EQ("abcd", string(data, data_length));
  12929. return true;
  12930. });
  12931. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12932. std::chrono::steady_clock::now() - start)
  12933. .count();
  12934. ASSERT_FALSE(res);
  12935. EXPECT_EQ(Error::Read, res.error());
  12936. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  12937. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  12938. }
  12939. }
  12940. TEST(MaxTimeoutTest, ContentStream) {
  12941. time_t timeout = 2000;
  12942. time_t threshold = 200;
  12943. Server svr;
  12944. Client cli("localhost", PORT);
  12945. max_timeout_test(svr, cli, timeout, threshold);
  12946. }
  12947. #ifdef CPPHTTPLIB_SSL_ENABLED
  12948. TEST(MaxTimeoutTest, ContentStreamSSL) {
  12949. time_t timeout = 2000;
  12950. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  12951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12952. SSLClient cli("localhost", PORT);
  12953. cli.enable_server_certificate_verification(false);
  12954. max_timeout_test(svr, cli, timeout, threshold);
  12955. }
  12956. #endif
  12957. class EventDispatcher {
  12958. public:
  12959. EventDispatcher() {}
  12960. bool wait_event(DataSink *sink) {
  12961. unique_lock<mutex> lk(m_);
  12962. int id = id_;
  12963. // Wait with timeout to prevent hanging if client disconnects
  12964. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  12965. [&] { return cid_ == id; })) {
  12966. return false; // Timeout occurred
  12967. }
  12968. sink->write(message_.data(), message_.size());
  12969. return true;
  12970. }
  12971. void send_event(const string &message) {
  12972. lock_guard<mutex> lk(m_);
  12973. cid_ = id_++;
  12974. message_ = message;
  12975. cv_.notify_all();
  12976. }
  12977. private:
  12978. mutex m_;
  12979. condition_variable cv_;
  12980. atomic_int id_{0};
  12981. atomic_int cid_{-1};
  12982. string message_;
  12983. };
  12984. TEST(ClientInThreadTest, Issue2068) {
  12985. EventDispatcher ed;
  12986. Server svr;
  12987. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  12988. res.set_chunked_content_provider("text/event-stream",
  12989. [&](size_t /*offset*/, DataSink &sink) {
  12990. return ed.wait_event(&sink);
  12991. });
  12992. });
  12993. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12994. svr.wait_until_ready();
  12995. thread event_thread([&] {
  12996. int id = 0;
  12997. while (svr.is_running()) {
  12998. this_thread::sleep_for(chrono::milliseconds(500));
  12999. std::stringstream ss;
  13000. ss << "data: " << id << "\n\n";
  13001. ed.send_event(ss.str());
  13002. id++;
  13003. }
  13004. });
  13005. auto se = detail::scope_exit([&] {
  13006. svr.stop();
  13007. listen_thread.join();
  13008. event_thread.join();
  13009. ASSERT_FALSE(svr.is_running());
  13010. });
  13011. {
  13012. auto client = detail::make_unique<Client>(HOST, PORT);
  13013. client->set_read_timeout(std::chrono::minutes(10));
  13014. std::atomic<bool> stop{false};
  13015. std::thread t([&] {
  13016. client->Get("/event1",
  13017. [&](const char *, size_t) -> bool { return !stop; });
  13018. });
  13019. std::this_thread::sleep_for(std::chrono::seconds(2));
  13020. stop = true;
  13021. client->stop();
  13022. t.join();
  13023. // Reset client after thread has finished
  13024. client.reset();
  13025. }
  13026. }
  13027. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  13028. auto handled = false;
  13029. Server svr;
  13030. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  13031. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13032. auto se = detail::scope_exit([&] {
  13033. svr.stop();
  13034. t.join();
  13035. ASSERT_FALSE(svr.is_running());
  13036. ASSERT_FALSE(handled);
  13037. });
  13038. svr.wait_until_ready();
  13039. // Two Content-Length headers with different values — must be rejected
  13040. auto req = "POST /test HTTP/1.1\r\n"
  13041. "Content-Length: 5\r\n"
  13042. "Content-Length: 10\r\n"
  13043. "\r\n"
  13044. "hello";
  13045. std::string response;
  13046. ASSERT_TRUE(send_request(1, req, &response));
  13047. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  13048. response.substr(0, response.find("\r\n")));
  13049. }
  13050. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  13051. auto handled = false;
  13052. Server svr;
  13053. svr.Post("/test", [&](const Request &, Response &res) {
  13054. handled = true;
  13055. res.set_content("ok", "text/plain");
  13056. });
  13057. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13058. auto se = detail::scope_exit([&] {
  13059. svr.stop();
  13060. t.join();
  13061. ASSERT_FALSE(svr.is_running());
  13062. ASSERT_TRUE(handled);
  13063. });
  13064. svr.wait_until_ready();
  13065. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  13066. auto req = "POST /test HTTP/1.1\r\n"
  13067. "Content-Length: 5\r\n"
  13068. "Content-Length: 5\r\n"
  13069. "\r\n"
  13070. "hello";
  13071. std::string response;
  13072. ASSERT_TRUE(send_request(1, req, &response));
  13073. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  13074. }
  13075. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  13076. Server svr;
  13077. svr.Get("/", [](const Request &req, Response &res) {
  13078. EXPECT_EQ(2U, req.trailers.size());
  13079. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  13080. // Denied
  13081. EXPECT_FALSE(req.has_trailer("Content-Length"));
  13082. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  13083. // Accepted
  13084. EXPECT_TRUE(req.has_trailer("X-Hello"));
  13085. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  13086. EXPECT_TRUE(req.has_trailer("X-World"));
  13087. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  13088. res.set_content("ok", "text/plain");
  13089. });
  13090. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13091. auto se = detail::scope_exit([&] {
  13092. svr.stop();
  13093. t.join();
  13094. ASSERT_FALSE(svr.is_running());
  13095. });
  13096. svr.wait_until_ready();
  13097. const std::string req = "GET / HTTP/1.1\r\n"
  13098. "Transfer-Encoding: chunked\r\n"
  13099. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  13100. "\r\n"
  13101. "0\r\n"
  13102. "Content-Length: 10\r\n"
  13103. "Host: internal.local\r\n"
  13104. "Content-Type: malicious/content\r\n"
  13105. "Cookie: any\r\n"
  13106. "Set-Cookie: any\r\n"
  13107. "X-Forwarded-For: attacker.com\r\n"
  13108. "X-Real-Ip: 1.1.1.1\r\n"
  13109. "X-Hello: hello\r\n"
  13110. "X-World: world\r\n"
  13111. "\r\n";
  13112. std::string res;
  13113. ASSERT_TRUE(send_request(1, req, &res));
  13114. }
  13115. // A direct client that is not listed in trusted_proxies must not be able to
  13116. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  13117. // the peer address on the actual TCP connection determines whether the
  13118. // header is honored.
  13119. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  13120. Server svr;
  13121. // Deliberately does NOT include the loopback address the test client
  13122. // actually connects from, so the direct connection is not a trusted proxy.
  13123. svr.set_trusted_proxies({"203.0.113.66"});
  13124. std::string observed_remote_addr;
  13125. svr.Get("/ip", [&](const Request &req, Response &res) {
  13126. observed_remote_addr = req.remote_addr;
  13127. res.set_content("ok", "text/plain");
  13128. });
  13129. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13130. auto se = detail::scope_exit([&] {
  13131. svr.stop();
  13132. t.join();
  13133. ASSERT_FALSE(svr.is_running());
  13134. });
  13135. svr.wait_until_ready();
  13136. Client cli(HOST, PORT);
  13137. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  13138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13139. EXPECT_EQ(StatusCode::OK_200, res->status);
  13140. // The connecting peer is not a trusted proxy, so the spoofed header must be
  13141. // ignored entirely and the real connection-level address retained.
  13142. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13143. observed_remote_addr == "127.0.0.1");
  13144. }
  13145. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  13146. Server svr;
  13147. std::string observed_remote_addr;
  13148. std::string observed_xff;
  13149. svr.Get("/ip", [&](const Request &req, Response &res) {
  13150. observed_remote_addr = req.remote_addr;
  13151. observed_xff = req.get_header_value("X-Forwarded-For");
  13152. res.set_content("ok", "text/plain");
  13153. });
  13154. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13155. auto se = detail::scope_exit([&] {
  13156. svr.stop();
  13157. t.join();
  13158. ASSERT_FALSE(svr.is_running());
  13159. });
  13160. svr.wait_until_ready();
  13161. Client cli(HOST, PORT);
  13162. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  13163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13164. EXPECT_EQ(StatusCode::OK_200, res->status);
  13165. EXPECT_EQ(observed_xff, "203.0.113.66");
  13166. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13167. observed_remote_addr == "127.0.0.1");
  13168. }
  13169. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  13170. Server svr;
  13171. svr.set_trusted_proxies({"203.0.113.66"});
  13172. std::string observed_remote_addr;
  13173. std::string observed_xff;
  13174. svr.Get("/ip", [&](const Request &req, Response &res) {
  13175. observed_remote_addr = req.remote_addr;
  13176. observed_xff = req.get_header_value("X-Forwarded-For");
  13177. res.set_content("ok", "text/plain");
  13178. });
  13179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13180. auto se = detail::scope_exit([&] {
  13181. svr.stop();
  13182. t.join();
  13183. ASSERT_FALSE(svr.is_running());
  13184. });
  13185. svr.wait_until_ready();
  13186. Client cli(HOST, PORT);
  13187. auto res = cli.Get("/ip");
  13188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13189. EXPECT_EQ(StatusCode::OK_200, res->status);
  13190. EXPECT_EQ(observed_xff, "");
  13191. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13192. observed_remote_addr == "127.0.0.1");
  13193. }
  13194. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  13195. Server svr;
  13196. // Include the loopback address the test client actually connects from, so
  13197. // the direct connection itself is recognized as the trusted proxy hop.
  13198. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  13199. std::string observed_remote_addr;
  13200. std::string observed_xff;
  13201. svr.Get("/ip", [&](const Request &req, Response &res) {
  13202. observed_remote_addr = req.remote_addr;
  13203. observed_xff = req.get_header_value("X-Forwarded-For");
  13204. res.set_content("ok", "text/plain");
  13205. });
  13206. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13207. auto se = detail::scope_exit([&] {
  13208. svr.stop();
  13209. t.join();
  13210. ASSERT_FALSE(svr.is_running());
  13211. });
  13212. svr.wait_until_ready();
  13213. Client cli(HOST, PORT);
  13214. auto res = cli.Get(
  13215. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  13216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13217. EXPECT_EQ(StatusCode::OK_200, res->status);
  13218. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  13219. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13220. }
  13221. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  13222. Server svr;
  13223. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  13224. std::string observed_remote_addr;
  13225. std::string observed_xff;
  13226. svr.Get("/ip", [&](const Request &req, Response &res) {
  13227. observed_remote_addr = req.remote_addr;
  13228. observed_xff = req.get_header_value("X-Forwarded-For");
  13229. res.set_content("ok", "text/plain");
  13230. });
  13231. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13232. auto se = detail::scope_exit([&] {
  13233. svr.stop();
  13234. t.join();
  13235. ASSERT_FALSE(svr.is_running());
  13236. });
  13237. svr.wait_until_ready();
  13238. Client cli(HOST, PORT);
  13239. auto res = cli.Get(
  13240. "/ip",
  13241. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13243. EXPECT_EQ(StatusCode::OK_200, res->status);
  13244. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13245. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  13246. }
  13247. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  13248. Server svr;
  13249. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13250. std::string observed_remote_addr;
  13251. std::string observed_xff;
  13252. svr.Get("/ip", [&](const Request &req, Response &res) {
  13253. observed_remote_addr = req.remote_addr;
  13254. observed_xff = req.get_header_value("X-Forwarded-For");
  13255. res.set_content("ok", "text/plain");
  13256. });
  13257. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13258. auto se = detail::scope_exit([&] {
  13259. svr.stop();
  13260. t.join();
  13261. ASSERT_FALSE(svr.is_running());
  13262. });
  13263. svr.wait_until_ready();
  13264. Client cli(HOST, PORT);
  13265. auto res = cli.Get(
  13266. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. EXPECT_EQ(StatusCode::OK_200, res->status);
  13269. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  13270. // by the closest hop) is used. The leftmost entry is fully client-controlled
  13271. // and must not be selected.
  13272. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  13273. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  13274. }
  13275. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  13276. Server svr;
  13277. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  13278. std::string observed_remote_addr;
  13279. svr.Get("/ip", [&](const Request &req, Response &res) {
  13280. observed_remote_addr = req.remote_addr;
  13281. res.set_content("ok", "text/plain");
  13282. });
  13283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13284. auto se = detail::scope_exit([&] {
  13285. svr.stop();
  13286. t.join();
  13287. ASSERT_FALSE(svr.is_running());
  13288. });
  13289. svr.wait_until_ready();
  13290. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  13291. // a forged address and the trusted proxy's own address; the forged value must
  13292. // not win over the address the trusted proxy actually recorded.
  13293. Client cli(HOST, PORT);
  13294. auto res = cli.Get(
  13295. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  13296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13297. EXPECT_EQ(StatusCode::OK_200, res->status);
  13298. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  13299. }
  13300. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  13301. Server svr;
  13302. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13303. std::string observed_remote_addr;
  13304. std::string observed_xff;
  13305. svr.Get("/ip", [&](const Request &req, Response &res) {
  13306. observed_remote_addr = req.remote_addr;
  13307. observed_xff = req.get_header_value("X-Forwarded-For");
  13308. res.set_content("ok", "text/plain");
  13309. });
  13310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13311. auto se = detail::scope_exit([&] {
  13312. svr.stop();
  13313. t.join();
  13314. ASSERT_FALSE(svr.is_running());
  13315. });
  13316. svr.wait_until_ready();
  13317. Client cli(HOST, PORT);
  13318. auto res = cli.Get(
  13319. "/ip",
  13320. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. EXPECT_EQ(StatusCode::OK_200, res->status);
  13323. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  13324. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13325. }
  13326. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  13327. Server svr;
  13328. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  13329. std::string observed_remote_addr;
  13330. std::string observed_xff;
  13331. svr.Get("/ip", [&](const Request &req, Response &res) {
  13332. observed_remote_addr = req.remote_addr;
  13333. observed_xff = req.get_header_value("X-Forwarded-For");
  13334. res.set_content("ok", "text/plain");
  13335. });
  13336. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13337. auto se = detail::scope_exit([&] {
  13338. svr.stop();
  13339. t.join();
  13340. ASSERT_FALSE(svr.is_running());
  13341. });
  13342. svr.wait_until_ready();
  13343. std::string raw_req =
  13344. "GET /ip HTTP/1.1\r\n"
  13345. "Host: localhost\r\n"
  13346. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  13347. "Connection: close\r\n"
  13348. "\r\n";
  13349. std::string out;
  13350. ASSERT_TRUE(send_request(5, raw_req, &out));
  13351. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13352. // Header parser trims surrounding whitespace of the header value
  13353. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  13354. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  13355. }
  13356. // An X-Forwarded-For header whose value parses to zero IP segments must not
  13357. // crash the server (it used to call front() on an empty vector inside
  13358. // get_client_ip). The connection-level remote address must be retained instead.
  13359. static void run_malformed_xff_test(const std::string &xff_value) {
  13360. Server svr;
  13361. svr.set_trusted_proxies({"192.0.2.45"});
  13362. std::string observed_remote_addr;
  13363. svr.Get("/ip", [&](const Request &req, Response &res) {
  13364. observed_remote_addr = req.remote_addr;
  13365. res.set_content("ok", "text/plain");
  13366. });
  13367. int port = 0;
  13368. thread t = thread([&]() {
  13369. port = svr.bind_to_any_port(HOST);
  13370. svr.listen_after_bind();
  13371. });
  13372. auto se = detail::scope_exit([&] {
  13373. svr.stop();
  13374. t.join();
  13375. ASSERT_FALSE(svr.is_running());
  13376. });
  13377. svr.wait_until_ready();
  13378. Client cli(HOST, port);
  13379. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  13380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13381. EXPECT_EQ(StatusCode::OK_200, res->status);
  13382. EXPECT_TRUE(observed_remote_addr == "::1" ||
  13383. observed_remote_addr == "127.0.0.1");
  13384. }
  13385. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  13386. run_malformed_xff_test("");
  13387. }
  13388. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  13389. run_malformed_xff_test(",");
  13390. }
  13391. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  13392. run_malformed_xff_test(", , ,");
  13393. }
  13394. #ifndef _WIN32
  13395. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  13396. Server svr;
  13397. svr.Post("/post", [&](const Request &req, Response &res) {
  13398. res.set_content(req.body, "text/plain");
  13399. });
  13400. svr.Put("/put", [&](const Request &req, Response &res) {
  13401. res.set_content(req.body, "text/plain");
  13402. });
  13403. svr.Patch("/patch", [&](const Request &req, Response &res) {
  13404. res.set_content(req.body, "text/plain");
  13405. });
  13406. svr.Delete("/delete", [&](const Request &req, Response &res) {
  13407. res.set_content(req.body, "text/plain");
  13408. });
  13409. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13410. auto se = detail::scope_exit([&] {
  13411. svr.stop();
  13412. t.join();
  13413. ASSERT_FALSE(svr.is_running());
  13414. });
  13415. svr.wait_until_ready();
  13416. std::string resp;
  13417. // POST without Content-Length
  13418. ASSERT_TRUE(send_request(5,
  13419. "POST /post HTTP/1.1\r\n"
  13420. "Host: localhost\r\n"
  13421. "Connection: close\r\n"
  13422. "\r\n",
  13423. &resp));
  13424. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13425. // PUT without Content-Length
  13426. resp.clear();
  13427. ASSERT_TRUE(send_request(5,
  13428. "PUT /put HTTP/1.1\r\n"
  13429. "Host: localhost\r\n"
  13430. "Connection: close\r\n"
  13431. "\r\n",
  13432. &resp));
  13433. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13434. // PATCH without Content-Length
  13435. resp.clear();
  13436. ASSERT_TRUE(send_request(5,
  13437. "PATCH /patch HTTP/1.1\r\n"
  13438. "Host: localhost\r\n"
  13439. "Connection: close\r\n"
  13440. "\r\n",
  13441. &resp));
  13442. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13443. // DELETE without Content-Length
  13444. resp.clear();
  13445. ASSERT_TRUE(send_request(5,
  13446. "DELETE /delete HTTP/1.1\r\n"
  13447. "Host: localhost\r\n"
  13448. "Connection: close\r\n"
  13449. "\r\n",
  13450. &resp));
  13451. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  13452. }
  13453. #endif
  13454. //==============================================================================
  13455. // open_stream() Tests
  13456. //==============================================================================
  13457. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  13458. std::string result;
  13459. char buf[8192];
  13460. ssize_t n;
  13461. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13462. result.append(buf, static_cast<size_t>(n));
  13463. }
  13464. return result;
  13465. }
  13466. // Mock stream for unit tests
  13467. class MockStream : public Stream {
  13468. public:
  13469. std::string data;
  13470. size_t pos = 0;
  13471. ssize_t error_after = -1; // -1 = no error
  13472. explicit MockStream(const std::string &d, ssize_t err = -1)
  13473. : data(d), error_after(err) {}
  13474. bool is_readable() const override { return true; }
  13475. bool wait_readable() const override { return true; }
  13476. bool wait_writable() const override { return true; }
  13477. ssize_t read(char *ptr, size_t size) override {
  13478. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  13479. if (pos >= data.size()) return 0;
  13480. size_t limit =
  13481. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  13482. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  13483. std::memcpy(ptr, data.data() + pos, to_read);
  13484. pos += to_read;
  13485. return static_cast<ssize_t>(to_read);
  13486. }
  13487. ssize_t write(const char *, size_t) override { return -1; }
  13488. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  13489. ip = "127.0.0.1";
  13490. port = 0;
  13491. }
  13492. void get_local_ip_and_port(std::string &ip, int &port) const override {
  13493. ip = "127.0.0.1";
  13494. port = 0;
  13495. }
  13496. socket_t socket() const override { return INVALID_SOCKET; }
  13497. time_t duration() const override { return 0; }
  13498. };
  13499. TEST(StreamHandleTest, Basic) {
  13500. ClientImpl::StreamHandle handle;
  13501. EXPECT_FALSE(handle.is_valid());
  13502. handle.response = detail::make_unique<Response>();
  13503. handle.error = Error::Connection;
  13504. EXPECT_FALSE(handle.is_valid());
  13505. handle.error = Error::Success;
  13506. EXPECT_TRUE(handle.is_valid());
  13507. }
  13508. TEST(BodyReaderTest, Basic) {
  13509. MockStream stream("Hello, World!");
  13510. detail::BodyReader reader;
  13511. reader.stream = &stream;
  13512. reader.content_length = 13;
  13513. char buf[32];
  13514. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  13515. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  13516. EXPECT_TRUE(reader.eof);
  13517. }
  13518. TEST(BodyReaderTest, NoStream) {
  13519. detail::BodyReader reader;
  13520. char buf[32];
  13521. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13522. EXPECT_EQ(Error::Connection, reader.last_error);
  13523. }
  13524. TEST(BodyReaderTest, Error) {
  13525. MockStream stream("Hello, World!", 5);
  13526. detail::BodyReader reader;
  13527. reader.stream = &stream;
  13528. reader.content_length = 13;
  13529. char buf[32];
  13530. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  13531. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  13532. EXPECT_EQ(Error::Read, reader.last_error);
  13533. }
  13534. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  13535. // Mock-based StreamHandle tests relying on private internals are removed.
  13536. class OpenStreamTest : public ::testing::Test {
  13537. protected:
  13538. void SetUp() override {
  13539. svr_.Get("/hello", [](const Request &, Response &res) {
  13540. res.set_content("Hello World!", "text/plain");
  13541. });
  13542. svr_.Get("/large", [](const Request &, Response &res) {
  13543. res.set_content(std::string(10000, 'X'), "text/plain");
  13544. });
  13545. svr_.Get("/chunked", [](const Request &, Response &res) {
  13546. res.set_chunked_content_provider("text/plain",
  13547. [](size_t offset, DataSink &sink) {
  13548. if (offset < 15) {
  13549. sink.write("chunk", 5);
  13550. return true;
  13551. }
  13552. sink.done();
  13553. return true;
  13554. });
  13555. });
  13556. svr_.Get("/compressible", [](const Request &, Response &res) {
  13557. res.set_chunked_content_provider("text/plain", [](size_t offset,
  13558. DataSink &sink) {
  13559. if (offset < 100 * 1024) {
  13560. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  13561. sink.write(chunk.data(), chunk.size());
  13562. return true;
  13563. }
  13564. sink.done();
  13565. return true;
  13566. });
  13567. });
  13568. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  13569. [](const Request & /*req*/, Response &res) {
  13570. auto i = new int(0);
  13571. res.set_header("Trailer", "Content-Length, X-Allowed");
  13572. res.set_chunked_content_provider(
  13573. "text/plain",
  13574. [i](size_t /*offset*/, DataSink &sink) {
  13575. switch (*i) {
  13576. case 0: sink.os << "123"; break;
  13577. case 1: sink.os << "456"; break;
  13578. case 2: sink.os << "789"; break;
  13579. case 3: {
  13580. sink.done_with_trailer(
  13581. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  13582. } break;
  13583. }
  13584. (*i)++;
  13585. return true;
  13586. },
  13587. [i](bool success) {
  13588. EXPECT_TRUE(success);
  13589. delete i;
  13590. });
  13591. });
  13592. // Echo headers endpoint for header-related tests
  13593. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  13594. std::string body;
  13595. for (const auto &h : req.headers) {
  13596. body.append(h.first);
  13597. body.push_back(':');
  13598. body.append(h.second);
  13599. body.push_back('\n');
  13600. }
  13601. res.set_content(body, "text/plain");
  13602. });
  13603. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  13604. std::string body;
  13605. for (const auto &h : req.headers) {
  13606. body.append(h.first);
  13607. body.push_back(':');
  13608. body.append(h.second);
  13609. body.push_back('\n');
  13610. }
  13611. res.set_content(body, "text/plain");
  13612. });
  13613. port_ = svr_.bind_to_any_port("127.0.0.1");
  13614. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13615. svr_.wait_until_ready();
  13616. }
  13617. void TearDown() override {
  13618. svr_.stop();
  13619. if (thread_.joinable()) thread_.join();
  13620. }
  13621. Server svr_;
  13622. std::thread thread_;
  13623. int port_ = 0;
  13624. };
  13625. TEST_F(OpenStreamTest, Basic) {
  13626. Client cli("127.0.0.1", port_);
  13627. auto handle = cli.open_stream("GET", "/hello");
  13628. EXPECT_TRUE(handle.is_valid());
  13629. EXPECT_EQ("Hello World!", read_all(handle));
  13630. }
  13631. TEST_F(OpenStreamTest, SmallBuffer) {
  13632. Client cli("127.0.0.1", port_);
  13633. auto handle = cli.open_stream("GET", "/hello");
  13634. std::string result;
  13635. char buf[4];
  13636. ssize_t n;
  13637. while ((n = handle.read(buf, sizeof(buf))) > 0)
  13638. result.append(buf, static_cast<size_t>(n));
  13639. EXPECT_EQ("Hello World!", result);
  13640. }
  13641. TEST_F(OpenStreamTest, DefaultHeaders) {
  13642. Client cli("127.0.0.1", port_);
  13643. // open_stream GET should include Host, User-Agent and Accept-Encoding
  13644. {
  13645. auto handle = cli.open_stream("GET", "/echo-headers");
  13646. ASSERT_TRUE(handle.is_valid());
  13647. auto body = read_all(handle);
  13648. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  13649. std::string::npos);
  13650. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  13651. std::string::npos);
  13652. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  13653. }
  13654. // open_stream POST with body and no explicit content_type should NOT add
  13655. // text/plain Content-Type (behavior differs from non-streaming path), but
  13656. // should include Content-Length
  13657. {
  13658. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  13659. ASSERT_TRUE(handle.is_valid());
  13660. auto body = read_all(handle);
  13661. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  13662. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  13663. }
  13664. // open_stream POST with explicit Content-Type should preserve it
  13665. {
  13666. auto handle = cli.open_stream("POST", "/echo-headers", {},
  13667. {{"Content-Type", "application/custom"}},
  13668. "{}", "application/custom");
  13669. ASSERT_TRUE(handle.is_valid());
  13670. auto body = read_all(handle);
  13671. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  13672. }
  13673. // User-specified User-Agent must not be overwritten for stream API
  13674. {
  13675. auto handle = cli.open_stream("GET", "/echo-headers", {},
  13676. {{"User-Agent", "MyAgent/1.2"}});
  13677. ASSERT_TRUE(handle.is_valid());
  13678. auto body = read_all(handle);
  13679. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  13680. }
  13681. }
  13682. TEST_F(OpenStreamTest, Large) {
  13683. Client cli("127.0.0.1", port_);
  13684. auto handle = cli.open_stream("GET", "/large");
  13685. EXPECT_EQ(10000u, read_all(handle).size());
  13686. }
  13687. TEST_F(OpenStreamTest, ConnectionError) {
  13688. Client cli("127.0.0.1", 9999);
  13689. auto handle = cli.open_stream("GET", "/hello");
  13690. EXPECT_FALSE(handle.is_valid());
  13691. }
  13692. TEST_F(OpenStreamTest, Chunked) {
  13693. Client cli("127.0.0.1", port_);
  13694. auto handle = cli.open_stream("GET", "/chunked");
  13695. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13696. "Transfer-Encoding") == "chunked");
  13697. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  13698. }
  13699. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  13700. Client cli("127.0.0.1", port_);
  13701. auto handle =
  13702. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  13703. ASSERT_TRUE(handle.is_valid());
  13704. // Consume body to allow trailers to be received/parsed
  13705. auto body = read_all(handle);
  13706. // Explicitly parse trailers (ensure trailers are available for assertion)
  13707. handle.parse_trailers_if_needed();
  13708. EXPECT_EQ(std::string("123456789"), body);
  13709. // The response should include a Trailer header declaring both names
  13710. ASSERT_TRUE(handle.response);
  13711. EXPECT_TRUE(handle.response->has_header("Trailer"));
  13712. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  13713. handle.response->get_header_value("Trailer"));
  13714. // Prohibited trailer must not be present
  13715. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  13716. // Allowed trailer should be present
  13717. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  13718. EXPECT_EQ(std::string("yes"),
  13719. handle.response->get_trailer_value("X-Allowed"));
  13720. // Verify trailers are NOT present as regular headers
  13721. EXPECT_EQ(std::string(""),
  13722. handle.response->get_header_value("Content-Length"));
  13723. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  13724. }
  13725. static std::thread serve_single_response(std::promise<int> &port_promise,
  13726. const std::string &response) {
  13727. return std::thread([&port_promise, response] {
  13728. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13729. default_socket_options(srv);
  13730. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13731. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13732. sockaddr_in addr{};
  13733. addr.sin_family = AF_INET;
  13734. addr.sin_port = htons(0); // Let OS assign a free port
  13735. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13736. int opt = 1;
  13737. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13738. #ifdef _WIN32
  13739. reinterpret_cast<const char *>(&opt),
  13740. #else
  13741. &opt,
  13742. #endif
  13743. sizeof(opt));
  13744. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  13745. ::listen(srv, 1) != 0) {
  13746. port_promise.set_value(-1);
  13747. detail::close_socket(srv);
  13748. return;
  13749. }
  13750. socklen_t addr_len = sizeof(addr);
  13751. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  13752. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  13753. sockaddr_in cli_addr{};
  13754. socklen_t cli_len = sizeof(cli_addr);
  13755. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13756. if (cli != INVALID_SOCKET) {
  13757. // Read the complete HTTP request (until the blank line that terminates
  13758. // headers) before sending the response. If the server closes the socket
  13759. // while the client's request data is still unread in the kernel receive
  13760. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  13761. // connection on both sides: it discards the client's receive buffer
  13762. // (which already holds our response) and causes any in-progress write on
  13763. // the client to fail with ECONNRESET. Reading all request data first
  13764. // ensures close() emits a graceful FIN.
  13765. {
  13766. char rbuf[256];
  13767. std::string req;
  13768. while (req.find("\r\n\r\n") == std::string::npos) {
  13769. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  13770. if (n <= 0) { break; }
  13771. req.append(rbuf, static_cast<size_t>(n));
  13772. }
  13773. }
  13774. ::send(cli,
  13775. #ifdef _WIN32
  13776. static_cast<const char *>(response.c_str()),
  13777. static_cast<int>(response.size()),
  13778. #else
  13779. response.c_str(), response.size(),
  13780. #endif
  13781. 0);
  13782. detail::close_socket(cli);
  13783. }
  13784. detail::close_socket(srv);
  13785. });
  13786. }
  13787. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  13788. #ifndef _WIN32
  13789. signal(SIGPIPE, SIG_IGN);
  13790. #endif
  13791. std::promise<int> port_promise;
  13792. auto port_future = port_promise.get_future();
  13793. auto server_thread =
  13794. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  13795. "Content-Type: text/plain\r\n"
  13796. "Content-Length: not-a-number\r\n"
  13797. "Connection: close\r\n"
  13798. "\r\n"
  13799. "hello");
  13800. auto port = port_future.get();
  13801. ASSERT_GT(port, 0);
  13802. Client cli("127.0.0.1", port);
  13803. auto handle = cli.open_stream("GET", "/");
  13804. EXPECT_FALSE(handle.is_valid());
  13805. server_thread.join();
  13806. }
  13807. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  13808. #ifndef _WIN32
  13809. signal(SIGPIPE, SIG_IGN);
  13810. #endif
  13811. std::promise<int> port_promise;
  13812. auto port_future = port_promise.get_future();
  13813. auto server_thread = serve_single_response(
  13814. port_promise, "HTTP/1.1 200 OK\r\n"
  13815. "Content-Type: text/plain\r\n"
  13816. "Content-Length: 99999999999999999999999999\r\n"
  13817. "Connection: close\r\n"
  13818. "\r\n"
  13819. "hello");
  13820. auto port = port_future.get();
  13821. ASSERT_GT(port, 0);
  13822. // Historically std::stoull would throw std::out_of_range here and crash
  13823. // the process, then parsing silently clamped to a bogus framing length and
  13824. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  13825. // so the stream fails to open, matching the not-a-number case above. The
  13826. // process still must NOT terminate.
  13827. Client cli("127.0.0.1", port);
  13828. auto handle = cli.open_stream("GET", "/");
  13829. EXPECT_FALSE(handle.is_valid());
  13830. server_thread.join();
  13831. }
  13832. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13833. TEST_F(OpenStreamTest, Gzip) {
  13834. Client cli("127.0.0.1", port_);
  13835. auto handle = cli.open_stream("GET", "/compressible", {},
  13836. {{"Accept-Encoding", "gzip"}});
  13837. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  13838. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13839. }
  13840. #endif
  13841. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13842. TEST_F(OpenStreamTest, Brotli) {
  13843. Client cli("127.0.0.1", port_);
  13844. auto handle =
  13845. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  13846. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  13847. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13848. }
  13849. #endif
  13850. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  13851. TEST_F(OpenStreamTest, Zstd) {
  13852. Client cli("127.0.0.1", port_);
  13853. auto handle = cli.open_stream("GET", "/compressible", {},
  13854. {{"Accept-Encoding", "zstd"}});
  13855. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  13856. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  13857. }
  13858. #endif
  13859. #ifdef CPPHTTPLIB_SSL_ENABLED
  13860. class SSLOpenStreamTest : public ::testing::Test {
  13861. protected:
  13862. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  13863. void SetUp() override {
  13864. svr_.Get("/hello", [](const Request &, Response &res) {
  13865. res.set_content("Hello SSL World!", "text/plain");
  13866. });
  13867. svr_.Get("/chunked", [](const Request &, Response &res) {
  13868. res.set_chunked_content_provider("text/plain",
  13869. [](size_t offset, DataSink &sink) {
  13870. if (offset < 15) {
  13871. sink.write("chunk", 5);
  13872. return true;
  13873. }
  13874. sink.done();
  13875. return true;
  13876. });
  13877. });
  13878. svr_.Post("/echo", [](const Request &req, Response &res) {
  13879. res.set_content(req.body, req.get_header_value("Content-Type"));
  13880. });
  13881. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  13882. std::string body = req.body;
  13883. res.set_chunked_content_provider(
  13884. "text/plain", [body](size_t offset, DataSink &sink) {
  13885. if (offset < body.size()) {
  13886. sink.write(body.data() + offset, body.size() - offset);
  13887. }
  13888. sink.done();
  13889. return true;
  13890. });
  13891. });
  13892. port_ = svr_.bind_to_any_port("127.0.0.1");
  13893. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  13894. svr_.wait_until_ready();
  13895. }
  13896. void TearDown() override {
  13897. svr_.stop();
  13898. if (thread_.joinable()) thread_.join();
  13899. }
  13900. SSLServer svr_;
  13901. std::thread thread_;
  13902. int port_ = 0;
  13903. };
  13904. TEST_F(SSLOpenStreamTest, Basic) {
  13905. SSLClient cli("127.0.0.1", port_);
  13906. cli.enable_server_certificate_verification(false);
  13907. auto handle = cli.open_stream("GET", "/hello");
  13908. ASSERT_TRUE(handle.is_valid());
  13909. EXPECT_EQ("Hello SSL World!", read_all(handle));
  13910. }
  13911. TEST_F(SSLOpenStreamTest, Chunked) {
  13912. SSLClient cli("127.0.0.1", port_);
  13913. cli.enable_server_certificate_verification(false);
  13914. auto handle = cli.open_stream("GET", "/chunked");
  13915. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13916. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  13917. "Transfer-Encoding") == "chunked");
  13918. auto body = read_all(handle);
  13919. EXPECT_EQ("chunkchunkchunk", body);
  13920. }
  13921. TEST_F(SSLOpenStreamTest, Post) {
  13922. SSLClient cli("127.0.0.1", port_);
  13923. cli.enable_server_certificate_verification(false);
  13924. auto handle =
  13925. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  13926. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  13927. EXPECT_EQ(200, handle.response->status);
  13928. auto body = read_all(handle);
  13929. EXPECT_EQ("Hello SSL POST", body);
  13930. }
  13931. TEST_F(SSLOpenStreamTest, PostChunked) {
  13932. SSLClient cli("127.0.0.1", port_);
  13933. cli.enable_server_certificate_verification(false);
  13934. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  13935. "Chunked SSL Data", "text/plain");
  13936. ASSERT_TRUE(handle.is_valid());
  13937. EXPECT_EQ(200, handle.response->status);
  13938. auto body = read_all(handle);
  13939. EXPECT_EQ("Chunked SSL Data", body);
  13940. }
  13941. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  13942. // Content-Length is terminated by the server closing the connection. When the
  13943. // SSL peer sends a close_notify after the body, the client must treat it as a
  13944. // clean EOF and return a successful response rather than an error.
  13945. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  13946. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13947. ASSERT_TRUE(svr.is_valid());
  13948. svr.set_keep_alive_max_count(1);
  13949. const std::string expected_body = "Hello from connection-close response!";
  13950. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  13951. res.set_content_provider("text/plain",
  13952. [&](size_t offset, DataSink &sink) -> bool {
  13953. if (offset < expected_body.size()) {
  13954. sink.write(expected_body.data() + offset,
  13955. expected_body.size() - offset);
  13956. }
  13957. sink.done();
  13958. return true;
  13959. });
  13960. });
  13961. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  13962. auto se = detail::scope_exit([&] {
  13963. svr.stop();
  13964. listen_thread.join();
  13965. ASSERT_FALSE(svr.is_running());
  13966. });
  13967. svr.wait_until_ready();
  13968. SSLClient cli(HOST, PORT);
  13969. cli.enable_server_certificate_verification(false);
  13970. auto res = cli.Get("/no-content-length");
  13971. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  13972. EXPECT_EQ(StatusCode::OK_200, res->status);
  13973. EXPECT_EQ(expected_body, res->body);
  13974. }
  13975. #endif // CPPHTTPLIB_SSL_ENABLED
  13976. //==============================================================================
  13977. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  13978. // results for various scenarios.
  13979. //==============================================================================
  13980. TEST(ParityTest, GetVsOpenStream) {
  13981. Server svr;
  13982. const std::string path = "/parity";
  13983. const std::string content = "Parity test content: hello world";
  13984. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  13985. res.set_content(content, "text/plain");
  13986. });
  13987. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13988. auto se = detail::scope_exit([&] {
  13989. svr.stop();
  13990. t.join();
  13991. ASSERT_FALSE(svr.is_running());
  13992. });
  13993. svr.wait_until_ready();
  13994. Client cli(HOST, PORT);
  13995. // Non-stream path
  13996. auto r1 = cli.Get(path);
  13997. ASSERT_TRUE(r1);
  13998. EXPECT_EQ(StatusCode::OK_200, r1->status);
  13999. // Stream path
  14000. auto h = cli.open_stream("GET", path);
  14001. ASSERT_TRUE(h.is_valid());
  14002. EXPECT_EQ(r1->body, read_all(h));
  14003. }
  14004. // Helper to compress data with provided compressor type T
  14005. template <typename Compressor>
  14006. static std::string compress_payload_for_parity(const std::string &in) {
  14007. std::string out;
  14008. Compressor compressor;
  14009. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  14010. [&](const char *data, size_t n) {
  14011. out.append(data, n);
  14012. return true;
  14013. });
  14014. EXPECT_TRUE(ok);
  14015. return out;
  14016. }
  14017. // Helper function for compression parity tests
  14018. template <typename Compressor>
  14019. static void test_compression_parity(const std::string &original,
  14020. const std::string &path,
  14021. const std::string &encoding) {
  14022. const std::string compressed =
  14023. compress_payload_for_parity<Compressor>(original);
  14024. Server svr;
  14025. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  14026. res.set_content(compressed, "application/octet-stream");
  14027. res.set_header("Content-Encoding", encoding);
  14028. });
  14029. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  14030. auto se = detail::scope_exit([&] {
  14031. svr.stop();
  14032. t.join();
  14033. ASSERT_FALSE(svr.is_running());
  14034. });
  14035. svr.wait_until_ready();
  14036. Client cli(HOST, PORT);
  14037. // Non-streaming
  14038. {
  14039. auto res = cli.Get(path);
  14040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14041. EXPECT_EQ(StatusCode::OK_200, res->status);
  14042. EXPECT_EQ(original, res->body);
  14043. }
  14044. // Streaming
  14045. {
  14046. auto h = cli.open_stream("GET", path);
  14047. ASSERT_TRUE(h.is_valid());
  14048. EXPECT_EQ(original, read_all(h));
  14049. }
  14050. }
  14051. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14052. TEST(ParityTest, Gzip) {
  14053. test_compression_parity<detail::gzip_compressor>(
  14054. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  14055. }
  14056. #endif
  14057. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14058. TEST(ParityTest, Brotli) {
  14059. test_compression_parity<detail::brotli_compressor>(
  14060. "Hello, brotli parity test payload", "/parity-br", "br");
  14061. }
  14062. #endif
  14063. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  14064. TEST(ParityTest, Zstd) {
  14065. test_compression_parity<detail::zstd_compressor>(
  14066. "Zstandard parity test payload", "/parity-zstd", "zstd");
  14067. }
  14068. #endif
  14069. //==============================================================================
  14070. // New Stream API Tests
  14071. //==============================================================================
  14072. inline std::string read_body(httplib::stream::Result &result) {
  14073. std::string body;
  14074. while (result.next()) {
  14075. body.append(result.data(), result.size());
  14076. }
  14077. return body;
  14078. }
  14079. TEST(ClientConnectionTest, Basic) {
  14080. httplib::ClientConnection conn;
  14081. EXPECT_FALSE(conn.is_open());
  14082. conn.sock = 1;
  14083. EXPECT_TRUE(conn.is_open());
  14084. httplib::ClientConnection conn2(std::move(conn));
  14085. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  14086. conn2.sock = INVALID_SOCKET;
  14087. }
  14088. // Unified test server for all stream::* tests
  14089. class StreamApiTest : public ::testing::Test {
  14090. protected:
  14091. void SetUp() override {
  14092. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14093. res.set_content("Hello World!", "text/plain");
  14094. });
  14095. svr_.Get("/echo-params",
  14096. [](const httplib::Request &req, httplib::Response &res) {
  14097. std::string r;
  14098. for (const auto &p : req.params) {
  14099. if (!r.empty()) r += "&";
  14100. r += p.first + "=" + p.second;
  14101. }
  14102. res.set_content(r, "text/plain");
  14103. });
  14104. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14105. res.set_content(req.body, req.get_header_value("Content-Type"));
  14106. });
  14107. svr_.Post("/echo-headers",
  14108. [](const httplib::Request &req, httplib::Response &res) {
  14109. std::string r;
  14110. for (const auto &h : req.headers)
  14111. r += h.first + ": " + h.second + "\n";
  14112. res.set_content(r, "text/plain");
  14113. });
  14114. svr_.Post("/echo-params",
  14115. [](const httplib::Request &req, httplib::Response &res) {
  14116. std::string r = "params:";
  14117. for (const auto &p : req.params)
  14118. r += p.first + "=" + p.second + ";";
  14119. res.set_content(r + " body:" + req.body, "text/plain");
  14120. });
  14121. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  14122. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  14123. });
  14124. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14125. res.set_content("PUT:" + req.body, "text/plain");
  14126. });
  14127. svr_.Patch("/echo",
  14128. [](const httplib::Request &req, httplib::Response &res) {
  14129. res.set_content("PATCH:" + req.body, "text/plain");
  14130. });
  14131. svr_.Delete(
  14132. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  14133. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  14134. "text/plain");
  14135. });
  14136. svr_.Get("/head-test",
  14137. [](const httplib::Request &, httplib::Response &res) {
  14138. res.set_content("body for HEAD", "text/plain");
  14139. });
  14140. svr_.Options("/options",
  14141. [](const httplib::Request &, httplib::Response &res) {
  14142. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  14143. });
  14144. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  14145. svr_.wait_until_ready();
  14146. }
  14147. void TearDown() override {
  14148. svr_.stop();
  14149. if (thread_.joinable()) thread_.join();
  14150. }
  14151. httplib::Server svr_;
  14152. std::thread thread_;
  14153. };
  14154. // stream::Get tests
  14155. TEST_F(StreamApiTest, GetBasic) {
  14156. httplib::Client cli(HOST, PORT);
  14157. auto result = httplib::stream::Get(cli, "/hello");
  14158. ASSERT_TRUE(result.is_valid());
  14159. EXPECT_EQ(200, result.status());
  14160. EXPECT_EQ("Hello World!", read_body(result));
  14161. }
  14162. TEST_F(StreamApiTest, GetWithParams) {
  14163. httplib::Client cli(HOST, PORT);
  14164. httplib::Params params{{"foo", "bar"}};
  14165. auto result = httplib::stream::Get(cli, "/echo-params", params);
  14166. ASSERT_TRUE(result.is_valid());
  14167. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  14168. }
  14169. TEST_F(StreamApiTest, GetConnectionError) {
  14170. httplib::Client cli(HOST, 9999);
  14171. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  14172. }
  14173. TEST_F(StreamApiTest, Get404) {
  14174. httplib::Client cli(HOST, PORT);
  14175. auto result = httplib::stream::Get(cli, "/nonexistent");
  14176. EXPECT_TRUE(result.is_valid());
  14177. EXPECT_EQ(404, result.status());
  14178. }
  14179. // stream::Post tests
  14180. TEST_F(StreamApiTest, PostBasic) {
  14181. httplib::Client cli(HOST, PORT);
  14182. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  14183. "application/json");
  14184. ASSERT_TRUE(result.is_valid());
  14185. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  14186. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  14187. }
  14188. TEST_F(StreamApiTest, PostWithHeaders) {
  14189. httplib::Client cli(HOST, PORT);
  14190. httplib::Headers headers{{"X-Custom", "value"}};
  14191. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  14192. "text/plain");
  14193. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  14194. }
  14195. TEST_F(StreamApiTest, PostWithParams) {
  14196. httplib::Client cli(HOST, PORT);
  14197. httplib::Params params{{"k", "v"}};
  14198. auto result =
  14199. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  14200. auto body = read_body(result);
  14201. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  14202. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  14203. }
  14204. TEST_F(StreamApiTest, PostLarge) {
  14205. httplib::Client cli(HOST, PORT);
  14206. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  14207. size_t total = 0;
  14208. while (result.next()) {
  14209. total += result.size();
  14210. }
  14211. EXPECT_EQ(100u * 1024u, total);
  14212. }
  14213. // stream::Put/Patch tests
  14214. TEST_F(StreamApiTest, PutAndPatch) {
  14215. httplib::Client cli(HOST, PORT);
  14216. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  14217. EXPECT_EQ("PUT:test", read_body(put));
  14218. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  14219. EXPECT_EQ("PATCH:test", read_body(patch));
  14220. }
  14221. // stream::Delete tests
  14222. TEST_F(StreamApiTest, Delete) {
  14223. httplib::Client cli(HOST, PORT);
  14224. auto del1 = httplib::stream::Delete(cli, "/resource");
  14225. EXPECT_EQ("Deleted", read_body(del1));
  14226. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  14227. EXPECT_EQ("Deleted:data", read_body(del2));
  14228. }
  14229. // stream::Head/Options tests
  14230. TEST_F(StreamApiTest, HeadAndOptions) {
  14231. httplib::Client cli(HOST, PORT);
  14232. auto head = httplib::stream::Head(cli, "/head-test");
  14233. EXPECT_TRUE(head.is_valid());
  14234. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  14235. auto opts = httplib::stream::Options(cli, "/options");
  14236. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  14237. }
  14238. // SSL stream::* tests
  14239. #ifdef CPPHTTPLIB_SSL_ENABLED
  14240. class SSLStreamApiTest : public ::testing::Test {
  14241. protected:
  14242. void SetUp() override {
  14243. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  14244. res.set_content("Hello SSL!", "text/plain");
  14245. });
  14246. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  14247. res.set_content(req.body, "text/plain");
  14248. });
  14249. port_ = svr_.bind_to_any_port("127.0.0.1");
  14250. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  14251. svr_.wait_until_ready();
  14252. }
  14253. void TearDown() override {
  14254. svr_.stop();
  14255. if (thread_.joinable()) thread_.join();
  14256. }
  14257. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  14258. std::thread thread_;
  14259. int port_ = 0;
  14260. };
  14261. TEST_F(SSLStreamApiTest, GetAndPost) {
  14262. httplib::SSLClient cli("127.0.0.1", port_);
  14263. cli.enable_server_certificate_verification(false);
  14264. auto get = httplib::stream::Get(cli, "/hello");
  14265. EXPECT_EQ("Hello SSL!", read_body(get));
  14266. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  14267. EXPECT_EQ("test", read_body(post));
  14268. }
  14269. #endif
  14270. // Tests for Error::Timeout and Error::ConnectionClosed error types
  14271. // These errors are set in SocketStream/SSLSocketStream and propagated through
  14272. // BodyReader
  14273. TEST(ErrorHandlingTest, StreamReadTimeout) {
  14274. // Test that read timeout during streaming is detected
  14275. // Use a large content-length response where server delays mid-stream
  14276. Server svr;
  14277. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14278. // Send a large response with delay in the middle
  14279. res.set_content_provider(
  14280. 1000, // content_length
  14281. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  14282. if (offset < 100) {
  14283. // Send first 100 bytes immediately
  14284. std::string data(100, 'A');
  14285. sink.write(data.c_str(), data.size());
  14286. return true;
  14287. }
  14288. // Then delay longer than client timeout
  14289. std::this_thread::sleep_for(std::chrono::seconds(3));
  14290. std::string data(900, 'B');
  14291. sink.write(data.c_str(), data.size());
  14292. return true;
  14293. });
  14294. });
  14295. auto port = 8091;
  14296. std::thread t([&]() { svr.listen("localhost", port); });
  14297. svr.wait_until_ready();
  14298. Client cli("localhost", port);
  14299. cli.set_read_timeout(1, 0); // 1 second timeout
  14300. auto handle = cli.open_stream("GET", "/slow-stream");
  14301. ASSERT_TRUE(handle.is_valid());
  14302. char buf[256];
  14303. ssize_t total = 0;
  14304. ssize_t n;
  14305. bool got_error = false;
  14306. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14307. total += n;
  14308. }
  14309. if (n < 0) {
  14310. got_error = true;
  14311. // Should be timeout or read error
  14312. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14313. handle.get_read_error() == Error::Read)
  14314. << "Actual error: " << to_string(handle.get_read_error());
  14315. }
  14316. // Either we got an error, or we got less data than expected
  14317. EXPECT_TRUE(got_error || total < 1000)
  14318. << "Expected timeout but got all " << total << " bytes";
  14319. svr.stop();
  14320. t.join();
  14321. }
  14322. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  14323. // Test connection closed detection via BodyReader
  14324. Server svr;
  14325. std::atomic<bool> close_now{false};
  14326. svr.Get("/will-close", [&](const Request &, Response &res) {
  14327. res.set_content_provider(
  14328. 10000, // Large content_length that we won't fully send
  14329. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14330. if (offset < 100) {
  14331. std::string data(100, 'X');
  14332. sink.write(data.c_str(), data.size());
  14333. return true;
  14334. }
  14335. // Wait for signal then abort
  14336. while (!close_now) {
  14337. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14338. }
  14339. return false; // Abort - server will close connection
  14340. });
  14341. });
  14342. auto port = 8092;
  14343. std::thread t([&]() { svr.listen("localhost", port); });
  14344. svr.wait_until_ready();
  14345. Client cli("localhost", port);
  14346. auto handle = cli.open_stream("GET", "/will-close");
  14347. ASSERT_TRUE(handle.is_valid());
  14348. char buf[256];
  14349. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14350. EXPECT_GT(n, 0) << "First read should succeed";
  14351. // Signal server to close
  14352. close_now = true;
  14353. // Keep reading until error or EOF
  14354. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14355. // Keep reading
  14356. }
  14357. // Should get an error since content_length wasn't satisfied
  14358. if (n < 0) {
  14359. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14360. handle.get_read_error() == Error::Read)
  14361. << "Actual error: " << to_string(handle.get_read_error());
  14362. }
  14363. svr.stop();
  14364. t.join();
  14365. }
  14366. #ifdef CPPHTTPLIB_SSL_ENABLED
  14367. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  14368. // Test that read timeout during SSL streaming is detected
  14369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14370. svr.Get("/slow-stream", [](const Request &, Response &res) {
  14371. res.set_content_provider(
  14372. 1000, "text/plain",
  14373. [](size_t offset, size_t /*length*/, DataSink &sink) {
  14374. if (offset < 100) {
  14375. std::string data(100, 'A');
  14376. sink.write(data.c_str(), data.size());
  14377. return true;
  14378. }
  14379. std::this_thread::sleep_for(std::chrono::seconds(3));
  14380. std::string data(900, 'B');
  14381. sink.write(data.c_str(), data.size());
  14382. return true;
  14383. });
  14384. });
  14385. auto port = 8093;
  14386. std::thread t([&]() { svr.listen("localhost", port); });
  14387. svr.wait_until_ready();
  14388. SSLClient cli("localhost", port);
  14389. cli.enable_server_certificate_verification(false);
  14390. cli.set_read_timeout(1, 0); // 1 second timeout
  14391. auto handle = cli.open_stream("GET", "/slow-stream");
  14392. ASSERT_TRUE(handle.is_valid());
  14393. char buf[256];
  14394. ssize_t total = 0;
  14395. ssize_t n;
  14396. bool got_error = false;
  14397. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14398. total += n;
  14399. }
  14400. if (n < 0) {
  14401. got_error = true;
  14402. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  14403. handle.get_read_error() == Error::Read)
  14404. << "Actual error: " << to_string(handle.get_read_error());
  14405. }
  14406. EXPECT_TRUE(got_error || total < 1000)
  14407. << "Expected timeout but got all " << total << " bytes";
  14408. svr.stop();
  14409. t.join();
  14410. }
  14411. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  14412. // Test SSL connection closed detection
  14413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14414. std::atomic<bool> close_now{false};
  14415. svr.Get("/will-close", [&](const Request &, Response &res) {
  14416. res.set_content_provider(
  14417. 10000, "text/plain",
  14418. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  14419. if (offset < 100) {
  14420. std::string data(100, 'X');
  14421. sink.write(data.c_str(), data.size());
  14422. return true;
  14423. }
  14424. while (!close_now) {
  14425. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14426. }
  14427. return false;
  14428. });
  14429. });
  14430. auto port = 8094;
  14431. std::thread t([&]() { svr.listen("localhost", port); });
  14432. svr.wait_until_ready();
  14433. SSLClient cli("localhost", port);
  14434. cli.enable_server_certificate_verification(false);
  14435. auto handle = cli.open_stream("GET", "/will-close");
  14436. ASSERT_TRUE(handle.is_valid());
  14437. char buf[256];
  14438. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  14439. EXPECT_GT(n, 0);
  14440. // Signal server to close
  14441. close_now = true;
  14442. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  14443. // Keep reading
  14444. }
  14445. if (n < 0) {
  14446. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  14447. handle.get_read_error() == Error::Read)
  14448. << "Actual error: " << to_string(handle.get_read_error());
  14449. }
  14450. svr.stop();
  14451. t.join();
  14452. }
  14453. #endif
  14454. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  14455. using namespace httplib;
  14456. // Create a test file
  14457. const char *fname = "etag_testfile.txt";
  14458. const char *content = "etag-content";
  14459. {
  14460. std::ofstream ofs(fname);
  14461. ofs << content;
  14462. ASSERT_TRUE(ofs.good());
  14463. }
  14464. Server svr;
  14465. svr.set_mount_point("/static", ".");
  14466. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14467. svr.wait_until_ready();
  14468. Client cli(HOST, PORT);
  14469. // First request: should get 200 with ETag header
  14470. auto res1 = cli.Get("/static/etag_testfile.txt");
  14471. ASSERT_TRUE(res1);
  14472. ASSERT_EQ(200, res1->status);
  14473. ASSERT_TRUE(res1->has_header("ETag"));
  14474. std::string etag = res1->get_header_value("ETag");
  14475. EXPECT_FALSE(etag.empty());
  14476. // Verify ETag format: W/"hex-hex"
  14477. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  14478. EXPECT_EQ('W', etag[0]);
  14479. EXPECT_EQ('/', etag[1]);
  14480. EXPECT_EQ('"', etag[2]);
  14481. EXPECT_EQ('"', etag.back());
  14482. // Exact match: expect 304 Not Modified
  14483. Headers h2 = {{"If-None-Match", etag}};
  14484. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  14485. ASSERT_TRUE(res2);
  14486. EXPECT_EQ(304, res2->status);
  14487. // Wildcard match: expect 304 Not Modified
  14488. Headers h3 = {{"If-None-Match", "*"}};
  14489. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  14490. ASSERT_TRUE(res3);
  14491. EXPECT_EQ(304, res3->status);
  14492. // Non-matching ETag: expect 200
  14493. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  14494. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  14495. ASSERT_TRUE(res4);
  14496. EXPECT_EQ(200, res4->status);
  14497. // Multiple ETags with one matching: expect 304
  14498. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  14499. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  14500. ASSERT_TRUE(res5);
  14501. EXPECT_EQ(304, res5->status);
  14502. svr.stop();
  14503. t.join();
  14504. std::remove(fname);
  14505. }
  14506. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  14507. using namespace httplib;
  14508. Server svr;
  14509. svr.set_mount_point("/static", ".");
  14510. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14511. svr.wait_until_ready();
  14512. Client cli(HOST, PORT);
  14513. // Send If-None-Match: * to a non-existent file
  14514. Headers h = {{"If-None-Match", "*"}};
  14515. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  14516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14517. EXPECT_EQ(404, res->status);
  14518. svr.stop();
  14519. t.join();
  14520. }
  14521. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  14522. using namespace httplib;
  14523. // Create a test file
  14524. const char *fname = "etag_boundary_testfile.txt";
  14525. const char *content = "boundary-test";
  14526. {
  14527. std::ofstream ofs(fname);
  14528. ofs << content;
  14529. ASSERT_TRUE(ofs.good());
  14530. }
  14531. Server svr;
  14532. svr.set_mount_point("/static", ".");
  14533. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  14534. svr.wait_until_ready();
  14535. Client cli(HOST, PORT);
  14536. // Get the actual ETag
  14537. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  14538. ASSERT_TRUE(res1);
  14539. ASSERT_EQ(200, res1->status);
  14540. ASSERT_TRUE(res1->has_header("ETag"));
  14541. std::string etag = res1->get_header_value("ETag");
  14542. // Test 1: Very long ETag value (longer than actual ETag)
  14543. // Should NOT match and return 200 (not trigger out-of-bounds read)
  14544. Headers h1 = {{"If-None-Match", "W/"
  14545. "\"very-long-etag-value-that-is-much-longer-"
  14546. "than-the-actual-etag-value\""}};
  14547. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  14548. ASSERT_TRUE(res2);
  14549. EXPECT_EQ(200, res2->status); // Should not match
  14550. // Test 2: Long string followed by wildcard
  14551. // Should match on "*" and return 304 (without out-of-bounds read on the long
  14552. // string)
  14553. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  14554. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  14555. ASSERT_TRUE(res3);
  14556. EXPECT_EQ(304, res3->status); // Should match on "*"
  14557. // Test 3: Wildcard followed by long string
  14558. // Should match on "*" immediately and return 304
  14559. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  14560. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  14561. ASSERT_TRUE(res4);
  14562. EXPECT_EQ(304, res4->status); // Should match on "*"
  14563. // Test 4: Multiple long non-matching values
  14564. // Should NOT match and return 200 (test that all comparisons are safe)
  14565. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  14566. "W/\"second-long-non-matching-value\", "
  14567. "W/\"third-long-non-matching-value\""}};
  14568. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  14569. ASSERT_TRUE(res5);
  14570. EXPECT_EQ(200, res5->status); // Should not match
  14571. // Test 5: Single character that is not "*" (edge case)
  14572. Headers h5 = {{"If-None-Match", "X"}};
  14573. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  14574. ASSERT_TRUE(res6);
  14575. EXPECT_EQ(200, res6->status); // Should not match
  14576. svr.stop();
  14577. t.join();
  14578. std::remove(fname);
  14579. }
  14580. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  14581. using namespace httplib;
  14582. // Create a test file
  14583. const char *fname = "ims_testfile.txt";
  14584. const char *content = "if-modified-since-test";
  14585. {
  14586. std::ofstream ofs(fname);
  14587. ofs << content;
  14588. ASSERT_TRUE(ofs.good());
  14589. }
  14590. Server svr;
  14591. svr.set_mount_point("/static", ".");
  14592. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14593. svr.wait_until_ready();
  14594. Client cli(HOST, PORT);
  14595. // First request: should get 200 with Last-Modified header
  14596. auto res1 = cli.Get("/static/ims_testfile.txt");
  14597. ASSERT_TRUE(res1);
  14598. ASSERT_EQ(200, res1->status);
  14599. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14600. std::string last_modified = res1->get_header_value("Last-Modified");
  14601. EXPECT_FALSE(last_modified.empty());
  14602. // If-Modified-Since with same time: expect 304
  14603. Headers h2 = {{"If-Modified-Since", last_modified}};
  14604. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  14605. ASSERT_TRUE(res2);
  14606. EXPECT_EQ(304, res2->status);
  14607. // If-Modified-Since with future time: expect 304
  14608. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14609. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  14610. ASSERT_TRUE(res3);
  14611. EXPECT_EQ(304, res3->status);
  14612. // If-Modified-Since with past time: expect 200
  14613. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14614. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  14615. ASSERT_TRUE(res4);
  14616. EXPECT_EQ(200, res4->status);
  14617. // If-None-Match takes precedence over If-Modified-Since
  14618. // (send matching ETag with old If-Modified-Since -> should still be 304)
  14619. ASSERT_TRUE(res1->has_header("ETag"));
  14620. std::string etag = res1->get_header_value("ETag");
  14621. Headers h5 = {{"If-None-Match", etag},
  14622. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14623. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  14624. ASSERT_TRUE(res5);
  14625. EXPECT_EQ(304, res5->status);
  14626. svr.stop();
  14627. t.join();
  14628. std::remove(fname);
  14629. }
  14630. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  14631. using namespace httplib;
  14632. Server svr;
  14633. // Endpoint that returns compressible content
  14634. svr.Get("/compressible", [](const Request &, Response &res) {
  14635. // Return a large enough body to trigger compression
  14636. std::string body(1000, 'a');
  14637. res.set_content(body, "text/plain");
  14638. });
  14639. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14640. svr.wait_until_ready();
  14641. Client cli(HOST, PORT);
  14642. // Request with gzip support: should get Vary header when compressed
  14643. cli.set_compress(true);
  14644. auto res1 = cli.Get("/compressible");
  14645. ASSERT_TRUE(res1);
  14646. EXPECT_EQ(200, res1->status);
  14647. // If Content-Encoding is set, Vary should also be set
  14648. if (res1->has_header("Content-Encoding")) {
  14649. EXPECT_TRUE(res1->has_header("Vary"));
  14650. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  14651. }
  14652. // Request without Accept-Encoding header: should not have compression
  14653. Headers h_no_compress;
  14654. auto res2 = cli.Get("/compressible", h_no_compress);
  14655. ASSERT_TRUE(res2);
  14656. EXPECT_EQ(200, res2->status);
  14657. // Verify Vary header is present when compression is applied
  14658. // (the exact behavior depends on server configuration)
  14659. svr.stop();
  14660. t.join();
  14661. }
  14662. TEST(ETagTest, IfRangeWithETag) {
  14663. using namespace httplib;
  14664. // Create a test file with known content
  14665. const char *fname = "if_range_testfile.txt";
  14666. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  14667. {
  14668. std::ofstream ofs(fname);
  14669. ofs << content;
  14670. ASSERT_TRUE(ofs.good());
  14671. }
  14672. Server svr;
  14673. svr.set_mount_point("/static", ".");
  14674. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14675. svr.wait_until_ready();
  14676. Client cli(HOST, PORT);
  14677. // First request: get ETag
  14678. auto res1 = cli.Get("/static/if_range_testfile.txt");
  14679. ASSERT_TRUE(res1);
  14680. ASSERT_EQ(200, res1->status);
  14681. ASSERT_TRUE(res1->has_header("ETag"));
  14682. std::string etag = res1->get_header_value("ETag");
  14683. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  14684. // Since our server generates weak ETags (W/"..."), If-Range with our
  14685. // ETag should NOT result in partial content - it should return full content.
  14686. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  14687. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  14688. ASSERT_TRUE(res2);
  14689. // Weak ETag in If-Range -> full content (200), not partial (206)
  14690. EXPECT_EQ(200, res2->status);
  14691. EXPECT_EQ(content, res2->body);
  14692. EXPECT_FALSE(res2->has_header("Content-Range"));
  14693. // Range request with non-matching If-Range (ETag): should get 200 (full
  14694. // content)
  14695. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  14696. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  14697. ASSERT_TRUE(res3);
  14698. EXPECT_EQ(200, res3->status);
  14699. EXPECT_EQ(content, res3->body);
  14700. EXPECT_FALSE(res3->has_header("Content-Range"));
  14701. // Range request with strong ETag (hypothetical - our server doesn't generate
  14702. // strong ETags, but if client sends a strong ETag that doesn't match, it
  14703. // should return full content)
  14704. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  14705. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  14706. ASSERT_TRUE(res4);
  14707. EXPECT_EQ(200, res4->status);
  14708. EXPECT_EQ(content, res4->body);
  14709. EXPECT_FALSE(res4->has_header("Content-Range"));
  14710. svr.stop();
  14711. t.join();
  14712. std::remove(fname);
  14713. }
  14714. TEST(ETagTest, IfRangeWithDate) {
  14715. using namespace httplib;
  14716. // Create a test file
  14717. const char *fname = "if_range_date_testfile.txt";
  14718. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  14719. {
  14720. std::ofstream ofs(fname);
  14721. ofs << content;
  14722. ASSERT_TRUE(ofs.good());
  14723. }
  14724. Server svr;
  14725. svr.set_mount_point("/static", ".");
  14726. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14727. svr.wait_until_ready();
  14728. Client cli(HOST, PORT);
  14729. // First request: get Last-Modified
  14730. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  14731. ASSERT_TRUE(res1);
  14732. ASSERT_EQ(200, res1->status);
  14733. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14734. std::string last_modified = res1->get_header_value("Last-Modified");
  14735. // Range request with matching If-Range (date): should get 206
  14736. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  14737. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  14738. ASSERT_TRUE(res2);
  14739. EXPECT_EQ(206, res2->status);
  14740. EXPECT_EQ("FGHIJ", res2->body);
  14741. // Range request with old If-Range date: should get 200 (full content)
  14742. Headers h3 = {{"Range", "bytes=5-9"},
  14743. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  14744. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  14745. ASSERT_TRUE(res3);
  14746. EXPECT_EQ(200, res3->status);
  14747. EXPECT_EQ(content, res3->body);
  14748. // Range request with future If-Range date: should get 206
  14749. Headers h4 = {{"Range", "bytes=0-4"},
  14750. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  14751. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  14752. ASSERT_TRUE(res4);
  14753. EXPECT_EQ(206, res4->status);
  14754. EXPECT_EQ("ABCDE", res4->body);
  14755. svr.stop();
  14756. t.join();
  14757. std::remove(fname);
  14758. }
  14759. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  14760. using namespace httplib;
  14761. const char *fname = "etag_malformed.txt";
  14762. const char *content = "malformed-etag";
  14763. {
  14764. std::ofstream ofs(fname);
  14765. ofs << content;
  14766. ASSERT_TRUE(ofs.good());
  14767. }
  14768. Server svr;
  14769. svr.set_mount_point("/static", ".");
  14770. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14771. svr.wait_until_ready();
  14772. Client cli(HOST, PORT);
  14773. // baseline: should get 200 and an ETag
  14774. auto res1 = cli.Get("/static/etag_malformed.txt");
  14775. ASSERT_TRUE(res1);
  14776. ASSERT_EQ(200, res1->status);
  14777. ASSERT_TRUE(res1->has_header("ETag"));
  14778. // Malformed ETag value (missing quotes) should be treated as non-matching
  14779. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  14780. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  14781. ASSERT_TRUE(res_bad);
  14782. EXPECT_EQ(200, res_bad->status);
  14783. // Whitespace-only header value should be considered invalid / non-matching
  14784. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  14785. "Host: localhost\r\n"
  14786. "If-None-Match: \r\n"
  14787. "Connection: close\r\n"
  14788. "\r\n";
  14789. std::string out;
  14790. ASSERT_TRUE(send_request(5, raw_req, &out));
  14791. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  14792. svr.stop();
  14793. t.join();
  14794. std::remove(fname);
  14795. }
  14796. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  14797. using namespace httplib;
  14798. const char *fname = "ims_invalid_format.txt";
  14799. const char *content = "ims-bad-format";
  14800. {
  14801. std::ofstream ofs(fname);
  14802. ofs << content;
  14803. ASSERT_TRUE(ofs.good());
  14804. }
  14805. Server svr;
  14806. svr.set_mount_point("/static", ".");
  14807. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14808. svr.wait_until_ready();
  14809. Client cli(HOST, PORT);
  14810. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  14811. ASSERT_TRUE(res1);
  14812. ASSERT_EQ(200, res1->status);
  14813. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14814. // If-Modified-Since with invalid format should not result in 304
  14815. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  14816. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  14817. ASSERT_TRUE(res_bad);
  14818. EXPECT_EQ(200, res_bad->status);
  14819. // If-Range with invalid date format should be treated as mismatch -> full
  14820. // content (200)
  14821. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  14822. {"If-Range", "invalid-date"}};
  14823. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  14824. ASSERT_TRUE(res_ifrange);
  14825. EXPECT_EQ(200, res_ifrange->status);
  14826. svr.stop();
  14827. t.join();
  14828. std::remove(fname);
  14829. }
  14830. TEST(ETagTest, IfRangeWithMalformedETag) {
  14831. using namespace httplib;
  14832. const char *fname = "ifrange_malformed.txt";
  14833. const std::string content = "0123456789";
  14834. {
  14835. std::ofstream ofs(fname);
  14836. ofs << content;
  14837. ASSERT_TRUE(ofs.good());
  14838. }
  14839. Server svr;
  14840. svr.set_mount_point("/static", ".");
  14841. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14842. svr.wait_until_ready();
  14843. Client cli(HOST, PORT);
  14844. // First request: get ETag
  14845. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  14846. ASSERT_TRUE(res1);
  14847. ASSERT_EQ(200, res1->status);
  14848. ASSERT_TRUE(res1->has_header("ETag"));
  14849. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  14850. // full content (200)
  14851. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  14852. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  14853. ASSERT_TRUE(res2);
  14854. EXPECT_EQ(200, res2->status);
  14855. EXPECT_EQ(content, res2->body);
  14856. svr.stop();
  14857. t.join();
  14858. std::remove(fname);
  14859. }
  14860. TEST(ETagTest, ExtremeLargeDateValues) {
  14861. using namespace httplib;
  14862. const char *fname = "ims_extreme_date.txt";
  14863. const char *content = "ims-extreme-date";
  14864. {
  14865. std::ofstream ofs(fname);
  14866. ofs << content;
  14867. ASSERT_TRUE(ofs.good());
  14868. }
  14869. Server svr;
  14870. svr.set_mount_point("/static", ".");
  14871. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14872. svr.wait_until_ready();
  14873. Client cli(HOST, PORT);
  14874. auto res1 = cli.Get(std::string("/static/") + fname);
  14875. ASSERT_TRUE(res1);
  14876. ASSERT_EQ(200, res1->status);
  14877. ASSERT_TRUE(res1->has_header("Last-Modified"));
  14878. // Extremely large year that may overflow date parsing routines.
  14879. Headers h_large_date = {
  14880. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14881. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  14882. ASSERT_TRUE(res_bad);
  14883. // Expect server to treat this as invalid/mismatch and return full content
  14884. EXPECT_EQ(200, res_bad->status);
  14885. // If-Range with extremely large date should be treated as mismatch -> full
  14886. // content (200)
  14887. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  14888. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14889. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  14890. ASSERT_TRUE(res_ifrange);
  14891. EXPECT_EQ(200, res_ifrange->status);
  14892. svr.stop();
  14893. t.join();
  14894. std::remove(fname);
  14895. }
  14896. TEST(ETagTest, NegativeFileModificationTime) {
  14897. using namespace httplib;
  14898. const char *fname = "ims_negative_mtime.txt";
  14899. const std::string content = "negative-mtime";
  14900. {
  14901. std::ofstream ofs(fname);
  14902. ofs << content;
  14903. ASSERT_TRUE(ofs.good());
  14904. }
  14905. // Try to set file mtime to a negative value. This may fail on some
  14906. // platforms/filesystems; if it fails, the test will still verify server
  14907. // behaves safely by performing a regular conditional request.
  14908. #if defined(__APPLE__) || defined(__linux__)
  14909. bool set_negative = false;
  14910. do {
  14911. struct timeval times[2];
  14912. // access time: now
  14913. times[0].tv_sec = time(nullptr);
  14914. times[0].tv_usec = 0;
  14915. // modification time: negative (e.g., -1)
  14916. times[1].tv_sec = -1;
  14917. times[1].tv_usec = 0;
  14918. if (utimes(fname, times) == 0) { set_negative = true; }
  14919. } while (0);
  14920. #else
  14921. bool set_negative = false;
  14922. #endif
  14923. Server svr;
  14924. svr.set_mount_point("/static", ".");
  14925. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14926. svr.wait_until_ready();
  14927. Client cli(HOST, PORT);
  14928. auto res1 = cli.Get(std::string("/static/") + fname);
  14929. ASSERT_TRUE(res1);
  14930. ASSERT_EQ(200, res1->status);
  14931. bool has_last_modified = res1->has_header("Last-Modified");
  14932. std::string last_modified;
  14933. if (has_last_modified) {
  14934. last_modified = res1->get_header_value("Last-Modified");
  14935. }
  14936. if (set_negative) {
  14937. // If we successfully set a negative mtime, ensure server returns a
  14938. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  14939. // with an old date and ensure server handles it without crash.
  14940. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  14941. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  14942. ASSERT_TRUE(res2);
  14943. // Behavior may vary; at minimum ensure server responds (200 or 304).
  14944. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  14945. } else {
  14946. // Could not set negative mtime on this platform; fall back to verifying
  14947. // that normal invalid/malformed dates are treated safely (non-304).
  14948. Headers h_bad_date = {
  14949. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  14950. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  14951. ASSERT_TRUE(res_bad);
  14952. EXPECT_EQ(200, res_bad->status);
  14953. }
  14954. svr.stop();
  14955. t.join();
  14956. std::remove(fname);
  14957. }
  14958. //==============================================================================
  14959. // SSE Parsing Tests
  14960. //==============================================================================
  14961. class SSEParsingTest : public ::testing::Test {
  14962. protected:
  14963. // Test helper that mimics SSE parsing behavior
  14964. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  14965. int &retry_ms) {
  14966. // Blank line signals end of event
  14967. if (line.empty() || line == "\r") { return true; }
  14968. // Lines starting with ':' are comments (ignored)
  14969. if (!line.empty() && line[0] == ':') { return false; }
  14970. // Find the colon separator
  14971. auto colon_pos = line.find(':');
  14972. if (colon_pos == std::string::npos) {
  14973. // Line with no colon is treated as field name with empty value
  14974. return false;
  14975. }
  14976. std::string field = line.substr(0, colon_pos);
  14977. std::string value;
  14978. // Value starts after colon, skip optional single space
  14979. if (colon_pos + 1 < line.size()) {
  14980. size_t value_start = colon_pos + 1;
  14981. if (line[value_start] == ' ') { value_start++; }
  14982. value = line.substr(value_start);
  14983. // Remove trailing \r if present
  14984. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  14985. }
  14986. // Handle known fields
  14987. if (field == "event") {
  14988. msg.event = value;
  14989. } else if (field == "data") {
  14990. // Multiple data lines are concatenated with newlines
  14991. if (!msg.data.empty()) { msg.data += "\n"; }
  14992. msg.data += value;
  14993. } else if (field == "id") {
  14994. // Empty id is valid (clears the last event ID)
  14995. msg.id = value;
  14996. } else if (field == "retry") {
  14997. // Parse retry interval in milliseconds
  14998. {
  14999. int v = 0;
  15000. auto res =
  15001. detail::from_chars(value.data(), value.data() + value.size(), v);
  15002. if (res.ec == std::errc{}) { retry_ms = v; }
  15003. }
  15004. }
  15005. // Unknown fields are ignored per SSE spec
  15006. return false;
  15007. }
  15008. };
  15009. // Test: Single-line data
  15010. TEST_F(SSEParsingTest, SingleLineData) {
  15011. sse::SSEMessage msg;
  15012. int retry_ms = 3000;
  15013. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  15014. EXPECT_EQ(msg.data, "hello");
  15015. EXPECT_EQ(msg.event, "message");
  15016. // Blank line ends event
  15017. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15018. }
  15019. // Test: Multi-line data
  15020. TEST_F(SSEParsingTest, MultiLineData) {
  15021. sse::SSEMessage msg;
  15022. int retry_ms = 3000;
  15023. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  15024. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  15025. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  15026. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  15027. }
  15028. // Test: Custom event types
  15029. TEST_F(SSEParsingTest, CustomEventType) {
  15030. sse::SSEMessage msg;
  15031. int retry_ms = 3000;
  15032. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  15033. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  15034. EXPECT_EQ(msg.event, "update");
  15035. EXPECT_EQ(msg.data, "payload");
  15036. }
  15037. // Test: Event ID handling
  15038. TEST_F(SSEParsingTest, EventIdHandling) {
  15039. sse::SSEMessage msg;
  15040. int retry_ms = 3000;
  15041. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  15042. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  15043. EXPECT_EQ(msg.id, "12345");
  15044. }
  15045. // Test: Empty event ID (clears last event ID)
  15046. TEST_F(SSEParsingTest, EmptyEventId) {
  15047. sse::SSEMessage msg;
  15048. msg.id = "previous";
  15049. int retry_ms = 3000;
  15050. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  15051. EXPECT_EQ(msg.id, "");
  15052. }
  15053. // Test: Retry field parsing
  15054. TEST_F(SSEParsingTest, RetryFieldParsing) {
  15055. sse::SSEMessage msg;
  15056. int retry_ms = 3000;
  15057. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  15058. EXPECT_EQ(retry_ms, 5000);
  15059. }
  15060. // Test: Invalid retry value
  15061. TEST_F(SSEParsingTest, InvalidRetryValue) {
  15062. sse::SSEMessage msg;
  15063. int retry_ms = 3000;
  15064. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  15065. EXPECT_EQ(retry_ms, 3000); // Unchanged
  15066. }
  15067. // Test: Comments (lines starting with :)
  15068. TEST_F(SSEParsingTest, CommentsIgnored) {
  15069. sse::SSEMessage msg;
  15070. int retry_ms = 3000;
  15071. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  15072. EXPECT_EQ(msg.data, "");
  15073. EXPECT_EQ(msg.event, "message");
  15074. }
  15075. // Test: Colon in value
  15076. TEST_F(SSEParsingTest, ColonInValue) {
  15077. sse::SSEMessage msg;
  15078. int retry_ms = 3000;
  15079. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  15080. EXPECT_EQ(msg.data, "hello:world:test");
  15081. }
  15082. // Test: Line with no colon (field name only)
  15083. TEST_F(SSEParsingTest, FieldNameOnly) {
  15084. sse::SSEMessage msg;
  15085. int retry_ms = 3000;
  15086. // According to SSE spec, this is treated as field name with empty value
  15087. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  15088. // Since we don't recognize "data" without colon, data should be empty
  15089. EXPECT_EQ(msg.data, "");
  15090. }
  15091. // Test: Trailing \r handling
  15092. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  15093. sse::SSEMessage msg;
  15094. int retry_ms = 3000;
  15095. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  15096. EXPECT_EQ(msg.data, "hello");
  15097. }
  15098. // Test: Unknown fields ignored
  15099. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  15100. sse::SSEMessage msg;
  15101. int retry_ms = 3000;
  15102. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  15103. EXPECT_EQ(msg.data, "");
  15104. EXPECT_EQ(msg.event, "message");
  15105. }
  15106. // Test: Space after colon is optional
  15107. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  15108. sse::SSEMessage msg1, msg2;
  15109. int retry_ms = 3000;
  15110. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  15111. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  15112. EXPECT_EQ(msg1.data, "hello");
  15113. EXPECT_EQ(msg2.data, "hello");
  15114. }
  15115. // Test: SSEMessage clear
  15116. TEST_F(SSEParsingTest, MessageClear) {
  15117. sse::SSEMessage msg;
  15118. msg.event = "custom";
  15119. msg.data = "some data";
  15120. msg.id = "123";
  15121. msg.clear();
  15122. EXPECT_EQ(msg.event, "message");
  15123. EXPECT_EQ(msg.data, "");
  15124. EXPECT_EQ(msg.id, "");
  15125. }
  15126. // Test: Complete event parsing
  15127. TEST_F(SSEParsingTest, CompleteEventParsing) {
  15128. sse::SSEMessage msg;
  15129. int retry_ms = 3000;
  15130. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  15131. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  15132. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  15133. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  15134. // Blank line ends event
  15135. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  15136. EXPECT_EQ(msg.event, "notification");
  15137. EXPECT_EQ(msg.id, "evt-42");
  15138. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  15139. EXPECT_EQ(retry_ms, 1000);
  15140. }
  15141. //==============================================================================
  15142. // Integration Tests with Server
  15143. //==============================================================================
  15144. class SSEIntegrationTest : public ::testing::Test {
  15145. protected:
  15146. void SetUp() override {
  15147. stop_server_.store(false);
  15148. events_.clear();
  15149. server_ = httplib::detail::make_unique<Server>();
  15150. setup_server();
  15151. start_server();
  15152. }
  15153. void TearDown() override {
  15154. stop_server_.store(true);
  15155. event_cv_.notify_all();
  15156. server_->stop();
  15157. if (server_thread_.joinable()) { server_thread_.join(); }
  15158. }
  15159. void setup_server() {
  15160. // Simple SSE endpoint
  15161. server_->Get("/events", [this](const Request &req, Response &res) {
  15162. auto last_id = req.get_header_value("Last-Event-ID");
  15163. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  15164. res.set_chunked_content_provider(
  15165. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  15166. std::unique_lock<std::mutex> lock(event_mutex_);
  15167. if (event_cv_.wait_for(
  15168. lock, std::chrono::milliseconds(200), [this] {
  15169. return !events_.empty() || stop_server_.load();
  15170. })) {
  15171. if (stop_server_.load()) { return false; }
  15172. if (!events_.empty()) {
  15173. std::string event = events_.front();
  15174. events_.erase(events_.begin());
  15175. sink.write(event.data(), event.size());
  15176. return true;
  15177. }
  15178. }
  15179. return !stop_server_.load();
  15180. });
  15181. });
  15182. // Endpoint that returns error
  15183. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  15184. res.status = 500;
  15185. res.set_content("Internal Server Error", "text/plain");
  15186. });
  15187. // Endpoint for custom event types
  15188. server_->Get("/custom-events", [](const Request &, Response &res) {
  15189. res.set_chunked_content_provider(
  15190. "text/event-stream", [](size_t offset, DataSink &sink) {
  15191. if (offset == 0) {
  15192. std::string event = "event: update\ndata: updated\n\n"
  15193. "event: delete\ndata: deleted\n\n";
  15194. sink.write(event.data(), event.size());
  15195. }
  15196. return false; // End stream after sending
  15197. });
  15198. });
  15199. }
  15200. void start_server() {
  15201. port_ = server_->bind_to_any_port(HOST);
  15202. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15203. // Wait for server to start
  15204. while (!server_->is_running()) {
  15205. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15206. }
  15207. }
  15208. int get_port() const { return port_; }
  15209. void send_event(const std::string &event) {
  15210. std::lock_guard<std::mutex> lock(event_mutex_);
  15211. events_.push_back(event);
  15212. event_cv_.notify_all();
  15213. }
  15214. std::unique_ptr<Server> server_;
  15215. std::thread server_thread_;
  15216. std::mutex event_mutex_;
  15217. std::condition_variable event_cv_;
  15218. std::vector<std::string> events_;
  15219. std::atomic<bool> stop_server_{false};
  15220. std::string last_received_event_id_;
  15221. int port_ = 0;
  15222. };
  15223. // Test: Successful connection and on_open callback
  15224. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  15225. // Add a simple endpoint that sends one event and closes
  15226. server_->Get("/simple-event", [](const Request &, Response &res) {
  15227. res.set_chunked_content_provider(
  15228. "text/event-stream", [](size_t offset, DataSink &sink) {
  15229. if (offset == 0) {
  15230. std::string event = "data: hello\n\n";
  15231. sink.write(event.data(), event.size());
  15232. }
  15233. return false; // Close stream after sending
  15234. });
  15235. });
  15236. Client client("localhost", get_port());
  15237. sse::SSEClient sse(client, "/simple-event");
  15238. std::atomic<bool> open_called{false};
  15239. std::atomic<bool> message_received{false};
  15240. sse.on_open([&open_called]() { open_called.store(true); });
  15241. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  15242. if (msg.data == "hello") { message_received.store(true); }
  15243. });
  15244. sse.set_reconnect_interval(100);
  15245. sse.set_max_reconnect_attempts(1);
  15246. // Start async
  15247. sse.start_async();
  15248. // Wait for message to be processed
  15249. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15250. sse.stop();
  15251. EXPECT_TRUE(open_called.load());
  15252. EXPECT_TRUE(message_received.load());
  15253. }
  15254. // Test: on_message callback
  15255. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  15256. // Endpoint that sends multiple events then closes
  15257. server_->Get("/multi-event", [](const Request &, Response &res) {
  15258. res.set_chunked_content_provider(
  15259. "text/event-stream", [](size_t offset, DataSink &sink) {
  15260. if (offset == 0) {
  15261. std::string events = "data: message1\n\ndata: message2\n\n";
  15262. sink.write(events.data(), events.size());
  15263. }
  15264. return false;
  15265. });
  15266. });
  15267. Client client("localhost", get_port());
  15268. sse::SSEClient sse(client, "/multi-event");
  15269. std::vector<std::string> received_messages;
  15270. std::mutex messages_mutex;
  15271. sse.on_message([&](const sse::SSEMessage &msg) {
  15272. std::lock_guard<std::mutex> lock(messages_mutex);
  15273. received_messages.push_back(msg.data);
  15274. });
  15275. sse.set_reconnect_interval(100);
  15276. sse.set_max_reconnect_attempts(1);
  15277. sse.start_async();
  15278. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15279. sse.stop();
  15280. std::lock_guard<std::mutex> lock(messages_mutex);
  15281. EXPECT_GE(received_messages.size(), 2u);
  15282. if (received_messages.size() >= 2) {
  15283. EXPECT_EQ(received_messages[0], "message1");
  15284. EXPECT_EQ(received_messages[1], "message2");
  15285. }
  15286. }
  15287. // Test: on_event for specific types
  15288. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  15289. Client client("localhost", get_port());
  15290. sse::SSEClient sse(client, "/custom-events");
  15291. std::atomic<bool> update_received{false};
  15292. std::atomic<bool> delete_received{false};
  15293. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  15294. if (msg.data == "updated") { update_received.store(true); }
  15295. });
  15296. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  15297. if (msg.data == "deleted") { delete_received.store(true); }
  15298. });
  15299. sse.set_max_reconnect_attempts(1);
  15300. sse.start_async();
  15301. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  15302. sse.stop();
  15303. EXPECT_TRUE(update_received.load());
  15304. EXPECT_TRUE(delete_received.load());
  15305. }
  15306. // Test: on_error callback on connection failure
  15307. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  15308. // Connect to a non-existent port
  15309. Client client("localhost", 59999);
  15310. sse::SSEClient sse(client, "/events");
  15311. std::atomic<bool> error_called{false};
  15312. Error received_error = Error::Success;
  15313. sse.on_error([&](Error err) {
  15314. error_called.store(true);
  15315. received_error = err;
  15316. });
  15317. sse.set_reconnect_interval(50);
  15318. sse.set_max_reconnect_attempts(1);
  15319. sse.start_async();
  15320. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15321. sse.stop();
  15322. EXPECT_TRUE(error_called.load());
  15323. EXPECT_NE(received_error, Error::Success);
  15324. }
  15325. // Test: Last-Event-ID header sent on reconnect
  15326. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  15327. // Endpoint that sends event with ID
  15328. server_->Get("/event-with-id", [](const Request &, Response &res) {
  15329. res.set_chunked_content_provider(
  15330. "text/event-stream", [](size_t offset, DataSink &sink) {
  15331. if (offset == 0) {
  15332. std::string event = "id: evt-123\ndata: test\n\n";
  15333. sink.write(event.data(), event.size());
  15334. }
  15335. return false;
  15336. });
  15337. });
  15338. Client client("localhost", get_port());
  15339. sse::SSEClient sse(client, "/event-with-id");
  15340. std::atomic<bool> id_received{false};
  15341. sse.on_message([&](const sse::SSEMessage &msg) {
  15342. if (!msg.id.empty()) { id_received.store(true); }
  15343. });
  15344. sse.set_reconnect_interval(100);
  15345. sse.set_max_reconnect_attempts(1);
  15346. sse.start_async();
  15347. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15348. sse.stop();
  15349. EXPECT_TRUE(id_received.load());
  15350. EXPECT_EQ(sse.last_event_id(), "evt-123");
  15351. }
  15352. // Test: Manual stop
  15353. TEST_F(SSEIntegrationTest, ManualStop) {
  15354. // Endpoint that sends one event and stays open briefly
  15355. std::atomic<bool> handler_running{true};
  15356. server_->Get("/stay-open", [&handler_running](const Request &,
  15357. Response &res) {
  15358. res.set_chunked_content_provider(
  15359. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  15360. if (offset == 0) {
  15361. std::string event = "data: connected\n\n";
  15362. sink.write(event.data(), event.size());
  15363. }
  15364. // Keep connection open while handler_running is true
  15365. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  15366. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15367. }
  15368. return false;
  15369. });
  15370. });
  15371. Client client("localhost", get_port());
  15372. sse::SSEClient sse(client, "/stay-open");
  15373. std::atomic<bool> connected{false};
  15374. sse.on_open([&connected]() { connected.store(true); });
  15375. sse.set_reconnect_interval(100);
  15376. sse.set_max_reconnect_attempts(1);
  15377. sse.start_async();
  15378. // Wait for connection to establish
  15379. for (int i = 0; i < 20 && !connected.load(); ++i) {
  15380. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  15381. }
  15382. EXPECT_TRUE(connected.load());
  15383. EXPECT_TRUE(sse.is_connected());
  15384. // Signal handler to stop
  15385. handler_running.store(false);
  15386. // Stop SSE client
  15387. sse.stop();
  15388. EXPECT_FALSE(sse.is_connected());
  15389. }
  15390. // Test: SSEClient with custom headers
  15391. TEST_F(SSEIntegrationTest, CustomHeaders) {
  15392. // Setup a server endpoint that checks for custom header
  15393. std::atomic<bool> header_received{false};
  15394. server_->Get("/header-check", [&](const Request &req, Response &res) {
  15395. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  15396. header_received.store(true);
  15397. }
  15398. res.set_chunked_content_provider("text/event-stream",
  15399. [](size_t, DataSink &) { return false; });
  15400. });
  15401. Client client("localhost", get_port());
  15402. Headers headers = {{"X-Custom-Header", "custom-value"}};
  15403. sse::SSEClient sse(client, "/header-check", headers);
  15404. sse.set_max_reconnect_attempts(1);
  15405. sse.start_async();
  15406. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15407. sse.stop();
  15408. EXPECT_TRUE(header_received.load());
  15409. }
  15410. // Test: Reconnect interval configuration
  15411. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  15412. Client client("localhost", get_port());
  15413. sse::SSEClient sse(client, "/events");
  15414. auto &result = sse.set_reconnect_interval(500);
  15415. // Builder pattern should return reference to self
  15416. EXPECT_EQ(&result, &sse);
  15417. }
  15418. // Test: Max reconnect attempts
  15419. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  15420. // Connect to non-existent port to force reconnects
  15421. Client client("localhost", 59998);
  15422. sse::SSEClient sse(client, "/events");
  15423. std::atomic<int> error_count{0};
  15424. sse.on_error([&](Error) { error_count.fetch_add(1); });
  15425. sse.set_reconnect_interval(50);
  15426. sse.set_max_reconnect_attempts(2);
  15427. auto start = std::chrono::steady_clock::now();
  15428. sse.start(); // Blocking call
  15429. auto end = std::chrono::steady_clock::now();
  15430. // Should have stopped after 2 failed attempts
  15431. EXPECT_GE(error_count.load(), 2);
  15432. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  15433. auto duration =
  15434. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  15435. #ifdef _WIN32
  15436. // Windows is much slower for socket connection failures
  15437. EXPECT_LT(duration.count(), 7000);
  15438. #else
  15439. EXPECT_LT(duration.count(), 1000);
  15440. #endif
  15441. }
  15442. // Test: Multi-line data in integration
  15443. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  15444. // Endpoint with multi-line data
  15445. server_->Get("/multiline-data", [](const Request &, Response &res) {
  15446. res.set_chunked_content_provider(
  15447. "text/event-stream", [](size_t offset, DataSink &sink) {
  15448. if (offset == 0) {
  15449. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  15450. sink.write(event.data(), event.size());
  15451. }
  15452. return false;
  15453. });
  15454. });
  15455. Client client("localhost", get_port());
  15456. sse::SSEClient sse(client, "/multiline-data");
  15457. std::string received_data;
  15458. std::mutex data_mutex;
  15459. sse.on_message([&](const sse::SSEMessage &msg) {
  15460. std::lock_guard<std::mutex> lock(data_mutex);
  15461. received_data = msg.data;
  15462. });
  15463. sse.set_reconnect_interval(100);
  15464. sse.set_max_reconnect_attempts(1);
  15465. sse.start_async();
  15466. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15467. sse.stop();
  15468. std::lock_guard<std::mutex> lock(data_mutex);
  15469. EXPECT_EQ(received_data, "line1\nline2\nline3");
  15470. }
  15471. // Test: Auto-reconnect after server disconnection
  15472. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  15473. std::atomic<int> connection_count{0};
  15474. std::atomic<int> message_count{0};
  15475. // Endpoint that sends one event and closes, forcing reconnect
  15476. server_->Get("/reconnect-test",
  15477. [&connection_count](const Request &, Response &res) {
  15478. connection_count.fetch_add(1);
  15479. res.set_chunked_content_provider(
  15480. "text/event-stream", [](size_t offset, DataSink &sink) {
  15481. if (offset == 0) {
  15482. std::string event = "data: hello\n\n";
  15483. sink.write(event.data(), event.size());
  15484. }
  15485. return false; // Close connection after sending
  15486. });
  15487. });
  15488. Client client("localhost", get_port());
  15489. sse::SSEClient sse(client, "/reconnect-test");
  15490. sse.on_message([&message_count](const sse::SSEMessage &) {
  15491. message_count.fetch_add(1);
  15492. });
  15493. sse.set_reconnect_interval(100);
  15494. sse.set_max_reconnect_attempts(3);
  15495. sse.start_async();
  15496. // Wait long enough for multiple reconnects
  15497. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15498. sse.stop();
  15499. // Should have connected multiple times (initial + reconnects)
  15500. EXPECT_GE(connection_count.load(), 2);
  15501. // Should have received messages from multiple connections
  15502. EXPECT_GE(message_count.load(), 2);
  15503. }
  15504. // Test: Last-Event-ID sent on reconnect
  15505. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  15506. std::atomic<int> connection_count{0};
  15507. std::vector<std::string> received_last_event_ids;
  15508. std::mutex id_mutex;
  15509. // Endpoint that checks Last-Event-ID header and sends event with ID
  15510. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  15511. int conn = connection_count.fetch_add(1);
  15512. // Capture the Last-Event-ID header from each connection
  15513. {
  15514. std::lock_guard<std::mutex> lock(id_mutex);
  15515. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  15516. }
  15517. res.set_chunked_content_provider(
  15518. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  15519. if (offset == 0) {
  15520. std::string event =
  15521. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  15522. sink.write(event.data(), event.size());
  15523. }
  15524. return false;
  15525. });
  15526. });
  15527. Client client("localhost", get_port());
  15528. sse::SSEClient sse(client, "/reconnect-with-id");
  15529. sse.set_reconnect_interval(100);
  15530. sse.set_max_reconnect_attempts(3);
  15531. sse.start_async();
  15532. // Wait for at least 2 connections
  15533. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  15534. sse.stop();
  15535. // Verify behavior
  15536. std::lock_guard<std::mutex> lock(id_mutex);
  15537. EXPECT_GE(received_last_event_ids.size(), 2u);
  15538. // First connection should have no Last-Event-ID
  15539. if (!received_last_event_ids.empty()) {
  15540. EXPECT_EQ(received_last_event_ids[0], "");
  15541. }
  15542. // Second connection should have Last-Event-ID from first connection
  15543. if (received_last_event_ids.size() >= 2) {
  15544. EXPECT_EQ(received_last_event_ids[1], "event-0");
  15545. }
  15546. }
  15547. // Test: set_headers updates headers used on reconnect
  15548. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  15549. std::vector<std::string> received_tokens;
  15550. std::mutex token_mutex;
  15551. // Endpoint that captures Authorization header
  15552. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  15553. {
  15554. std::lock_guard<std::mutex> lock(token_mutex);
  15555. received_tokens.push_back(req.get_header_value("Authorization"));
  15556. }
  15557. res.set_chunked_content_provider(
  15558. "text/event-stream", [](size_t offset, DataSink &sink) {
  15559. if (offset == 0) {
  15560. std::string event = "data: hello\n\n";
  15561. sink.write(event.data(), event.size());
  15562. }
  15563. return false; // Close connection to trigger reconnect
  15564. });
  15565. });
  15566. Client client("localhost", get_port());
  15567. Headers headers = {{"Authorization", "Bearer old-token"}};
  15568. sse::SSEClient sse(client, "/auth-check", headers);
  15569. // Update headers on each successful connection
  15570. sse.on_open(
  15571. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  15572. sse.set_reconnect_interval(100);
  15573. sse.set_max_reconnect_attempts(3);
  15574. sse.start_async();
  15575. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15576. sse.stop();
  15577. std::lock_guard<std::mutex> lock(token_mutex);
  15578. ASSERT_GE(received_tokens.size(), 2u);
  15579. // First connection uses original header
  15580. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  15581. // Second connection uses updated header from set_headers
  15582. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  15583. }
  15584. // Test: 401 allows reconnection (so on_error can refresh headers)
  15585. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  15586. std::atomic<int> connection_count{0};
  15587. // Endpoint: returns 401 on first attempt, 200 on second
  15588. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  15589. int conn = connection_count.fetch_add(1);
  15590. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  15591. res.status = StatusCode::Unauthorized_401;
  15592. res.set_content("Unauthorized", "text/plain");
  15593. return;
  15594. }
  15595. res.set_chunked_content_provider(
  15596. "text/event-stream", [](size_t offset, DataSink &sink) {
  15597. if (offset == 0) {
  15598. std::string event = "data: authenticated\n\n";
  15599. sink.write(event.data(), event.size());
  15600. }
  15601. return false;
  15602. });
  15603. });
  15604. Client client("localhost", get_port());
  15605. Headers headers = {{"Authorization", "Bearer expired"}};
  15606. sse::SSEClient sse(client, "/auth-retry", headers);
  15607. std::atomic<bool> message_received{false};
  15608. // Refresh token on error
  15609. sse.on_error(
  15610. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  15611. sse.on_message([&](const sse::SSEMessage &msg) {
  15612. if (msg.data == "authenticated") { message_received.store(true); }
  15613. });
  15614. sse.set_reconnect_interval(100);
  15615. sse.set_max_reconnect_attempts(3);
  15616. sse.start_async();
  15617. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  15618. sse.stop();
  15619. // Should have reconnected after 401 and succeeded with new token
  15620. EXPECT_GE(connection_count.load(), 2);
  15621. EXPECT_TRUE(message_received.load());
  15622. }
  15623. TEST(Issue2318Test, EmptyHostString) {
  15624. {
  15625. httplib::Client cli_empty("", PORT);
  15626. auto res = cli_empty.Get("/");
  15627. ASSERT_FALSE(res);
  15628. EXPECT_EQ(httplib::Error::Connection, res.error());
  15629. }
  15630. {
  15631. httplib::Client cli(" ", PORT);
  15632. auto res = cli.Get("/");
  15633. ASSERT_FALSE(res);
  15634. EXPECT_EQ(httplib::Error::Connection, res.error());
  15635. }
  15636. }
  15637. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  15638. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  15639. Server svr;
  15640. // Set a small payload limit (1KB)
  15641. svr.set_payload_max_length(1024);
  15642. svr.Post("/test", [&](const Request &req, Response &res) {
  15643. res.set_content("Body size: " + std::to_string(req.body.size()),
  15644. "text/plain");
  15645. });
  15646. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15647. auto se = detail::scope_exit([&] {
  15648. svr.stop();
  15649. listen_thread.join();
  15650. });
  15651. svr.wait_until_ready();
  15652. // Create data that compresses well but exceeds limit when decompressed
  15653. // 8KB of repeated null bytes compresses to a very small size
  15654. std::string original_data(8 * 1024, '\0');
  15655. // Compress the data using gzip
  15656. std::string compressed_data;
  15657. detail::gzip_compressor compressor;
  15658. compressor.compress(original_data.data(), original_data.size(), true,
  15659. [&](const char *data, size_t size) {
  15660. compressed_data.append(data, size);
  15661. return true;
  15662. });
  15663. // Verify compression worked (compressed should be much smaller)
  15664. ASSERT_LT(compressed_data.size(), original_data.size());
  15665. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  15666. // Send compressed data with Content-Encoding: gzip
  15667. Client cli(HOST, PORT);
  15668. Headers headers = {{"Content-Encoding", "gzip"}};
  15669. auto res =
  15670. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  15671. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  15672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15673. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  15674. }
  15675. #endif
  15676. // ============================================================================
  15677. // OpenSSL-Specific Tests
  15678. // ============================================================================
  15679. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15680. X509 *readCertificate(const std::string &strFileName) {
  15681. std::ifstream inStream(strFileName);
  15682. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  15683. std::istreambuf_iterator<char>());
  15684. if (strCertPEM.empty()) return (nullptr);
  15685. BIO *pbCert = BIO_new(BIO_s_mem());
  15686. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  15687. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  15688. BIO_free(pbCert);
  15689. return (pCert);
  15690. }
  15691. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  15692. std::ifstream inStream(strFileName);
  15693. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  15694. std::istreambuf_iterator<char>());
  15695. if (strPrivateKeyPEM.empty()) return (nullptr);
  15696. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  15697. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  15698. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  15699. BIO_free(pbPrivKey);
  15700. return (pPrivateKey);
  15701. }
  15702. TEST(BindServerTest, UpdateCerts) {
  15703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15704. int port = svr.bind_to_any_port("0.0.0.0");
  15705. ASSERT_TRUE(svr.is_valid());
  15706. ASSERT_TRUE(port > 0);
  15707. X509 *cert = readCertificate(SERVER_CERT_FILE);
  15708. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  15709. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  15710. ASSERT_TRUE(cert != nullptr);
  15711. ASSERT_TRUE(ca_cert != nullptr);
  15712. ASSERT_TRUE(key != nullptr);
  15713. X509_STORE *cert_store = X509_STORE_new();
  15714. X509_STORE_add_cert(cert_store, ca_cert);
  15715. // svr.update_certs(cert, key, cert_store); // deprecated
  15716. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15717. CLIENT_CA_CERT_FILE);
  15718. ASSERT_TRUE(svr.is_valid());
  15719. svr.stop();
  15720. X509_STORE_free(cert_store);
  15721. X509_free(cert);
  15722. X509_free(ca_cert);
  15723. EVP_PKEY_free(key);
  15724. }
  15725. // Test that update_certs() updates client CA list correctly
  15726. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  15727. // Start with file-based constructor
  15728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15729. ASSERT_TRUE(svr.is_valid());
  15730. // Initially no client CA list should be set
  15731. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15732. ASSERT_TRUE(ssl_ctx != nullptr);
  15733. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  15734. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  15735. EXPECT_EQ(0, count_before);
  15736. // Now update with client CA (PEM string)
  15737. std::string cert_pem, key_pem, ca_pem;
  15738. read_file(SERVER_CERT_FILE, cert_pem);
  15739. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  15740. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  15741. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  15742. ASSERT_TRUE(svr.is_valid());
  15743. // Now client CA list should be set
  15744. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  15745. ASSERT_TRUE(ca_list_after != nullptr);
  15746. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  15747. }
  15748. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  15749. // Test that the file-path SSLServer constructor properly sets the client CA
  15750. // list that is sent to clients during the TLS handshake (CertificateRequest)
  15751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15752. ASSERT_TRUE(svr.is_valid());
  15753. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  15754. ASSERT_TRUE(ssl_ctx != nullptr);
  15755. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  15756. ASSERT_TRUE(ca_list != nullptr);
  15757. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  15758. }
  15759. #endif
  15760. // ============================================================================
  15761. // MbedTLS-Specific Tests
  15762. // ============================================================================
  15763. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15764. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  15765. using namespace httplib::tls;
  15766. // Track if callback was invoked
  15767. bool callback_invoked = false;
  15768. // The callback receives void* ctx which is actually MbedTlsContext*
  15769. // We can access the mbedtls_ssl_config via the context
  15770. auto setup_callback = [&callback_invoked](void *ctx) {
  15771. callback_invoked = true;
  15772. // Cast to MbedTlsContext* to access the ssl config
  15773. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  15774. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  15775. // Use static variables to hold certificate data (simplified for test)
  15776. static mbedtls_x509_crt own_cert;
  15777. static mbedtls_pk_context own_key;
  15778. static mbedtls_x509_crt ca_chain;
  15779. static bool initialized = false;
  15780. if (!initialized) {
  15781. mbedtls_x509_crt_init(&own_cert);
  15782. mbedtls_pk_init(&own_key);
  15783. mbedtls_x509_crt_init(&ca_chain);
  15784. // Load server certificate
  15785. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  15786. return false;
  15787. }
  15788. // Load server private key.
  15789. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  15790. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  15791. #if MBEDTLS_VERSION_MAJOR == 3
  15792. ,
  15793. mbedtls_ctr_drbg_random, nullptr
  15794. #endif
  15795. ) != 0) {
  15796. return false;
  15797. }
  15798. // Load CA chain for client verification
  15799. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  15800. return false;
  15801. }
  15802. initialized = true;
  15803. }
  15804. // Configure the SSL config
  15805. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  15806. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  15807. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15808. // Set minimum TLS version using mbedTLS native API
  15809. #if MBEDTLS_VERSION_MAJOR >= 3
  15810. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15811. #else
  15812. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15813. MBEDTLS_SSL_MINOR_VERSION_3);
  15814. #endif
  15815. return true;
  15816. };
  15817. SSLServer svr(setup_callback);
  15818. ASSERT_TRUE(svr.is_valid());
  15819. ASSERT_TRUE(callback_invoked);
  15820. svr.Get("/test", [&](const Request &req, Response &res) {
  15821. res.set_content("test", "text/plain");
  15822. auto cert = req.peer_cert();
  15823. ASSERT_TRUE(static_cast<bool>(cert));
  15824. auto common_name = cert.subject_cn();
  15825. EXPECT_EQ("Common Name", common_name);
  15826. });
  15827. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15828. auto se = detail::scope_exit([&] {
  15829. svr.stop();
  15830. t.join();
  15831. ASSERT_FALSE(svr.is_running());
  15832. });
  15833. svr.wait_until_ready();
  15834. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15835. cli.enable_server_certificate_verification(false);
  15836. cli.set_connection_timeout(30);
  15837. auto res = cli.Get("/test");
  15838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15839. ASSERT_EQ(StatusCode::OK_200, res->status);
  15840. }
  15841. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  15842. // context (owning mbedtls_ssl_config) before shutting down a still-open
  15843. // keep-alive SSL session, which reads through that config in
  15844. // mbedtls_ssl_close_notify.
  15845. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  15846. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15847. ASSERT_TRUE(svr.is_valid());
  15848. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15849. res.set_content("test", "text/plain");
  15850. });
  15851. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15852. auto se = detail::scope_exit([&] {
  15853. svr.stop();
  15854. t.join();
  15855. ASSERT_FALSE(svr.is_running());
  15856. });
  15857. svr.wait_until_ready();
  15858. {
  15859. SSLClient cli(HOST, PORT);
  15860. cli.enable_server_certificate_verification(false);
  15861. cli.set_keep_alive(true);
  15862. auto res = cli.Get("/test");
  15863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15864. ASSERT_EQ(StatusCode::OK_200, res->status);
  15865. // cli is destructed here with the keep-alive SSL session still open.
  15866. }
  15867. }
  15868. #endif
  15869. // WebSocket Tests
  15870. TEST(WebSocketTest, RSVBitsMustBeZero) {
  15871. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  15872. // defining the meaning of these bits has been negotiated.
  15873. auto make_frame = [](uint8_t first_byte) {
  15874. std::string frame;
  15875. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  15876. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  15877. frame += "Hello";
  15878. return frame;
  15879. };
  15880. // RSV1 set (0x40)
  15881. {
  15882. detail::BufferStream strm;
  15883. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  15884. ws::Opcode opcode;
  15885. std::string payload;
  15886. bool fin;
  15887. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15888. false, 1024));
  15889. }
  15890. // RSV2 set (0x20)
  15891. {
  15892. detail::BufferStream strm;
  15893. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  15894. ws::Opcode opcode;
  15895. std::string payload;
  15896. bool fin;
  15897. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15898. false, 1024));
  15899. }
  15900. // RSV3 set (0x10)
  15901. {
  15902. detail::BufferStream strm;
  15903. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  15904. ws::Opcode opcode;
  15905. std::string payload;
  15906. bool fin;
  15907. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15908. false, 1024));
  15909. }
  15910. // No RSV bits set - should succeed
  15911. {
  15912. detail::BufferStream strm;
  15913. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  15914. ws::Opcode opcode;
  15915. std::string payload;
  15916. bool fin;
  15917. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15918. false, 1024));
  15919. EXPECT_EQ(ws::Opcode::Text, opcode);
  15920. EXPECT_EQ("Hello", payload);
  15921. EXPECT_TRUE(fin);
  15922. }
  15923. }
  15924. TEST(WebSocketTest, ControlFrameValidation) {
  15925. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  15926. // payload length <= 125.
  15927. // Ping with FIN=0 - must be rejected
  15928. {
  15929. detail::BufferStream strm;
  15930. std::string frame;
  15931. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  15932. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15933. strm.write(frame.data(), frame.size());
  15934. ws::Opcode opcode;
  15935. std::string payload;
  15936. bool fin;
  15937. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15938. false, 1024));
  15939. }
  15940. // Close with FIN=0 - must be rejected
  15941. {
  15942. detail::BufferStream strm;
  15943. std::string frame;
  15944. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  15945. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  15946. strm.write(frame.data(), frame.size());
  15947. ws::Opcode opcode;
  15948. std::string payload;
  15949. bool fin;
  15950. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15951. false, 1024));
  15952. }
  15953. // Ping with payload_len=126 (extended length) - must be rejected
  15954. {
  15955. detail::BufferStream strm;
  15956. std::string frame;
  15957. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15958. frame += static_cast<char>(126); // payload_len=126 (>125)
  15959. frame += static_cast<char>(0x00); // extended length high byte
  15960. frame += static_cast<char>(126); // extended length low byte
  15961. frame += std::string(126, 'x');
  15962. strm.write(frame.data(), frame.size());
  15963. ws::Opcode opcode;
  15964. std::string payload;
  15965. bool fin;
  15966. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15967. false, 1024));
  15968. }
  15969. // Ping with FIN=1 and payload_len=125 - should succeed
  15970. {
  15971. detail::BufferStream strm;
  15972. std::string frame;
  15973. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  15974. frame += static_cast<char>(125); // payload_len=125
  15975. frame += std::string(125, 'x');
  15976. strm.write(frame.data(), frame.size());
  15977. ws::Opcode opcode;
  15978. std::string payload;
  15979. bool fin;
  15980. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  15981. false, 1024));
  15982. EXPECT_EQ(ws::Opcode::Ping, opcode);
  15983. EXPECT_EQ(125u, payload.size());
  15984. EXPECT_TRUE(fin);
  15985. }
  15986. }
  15987. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  15988. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  15989. // length MUST be 0.
  15990. // MSB set - must be rejected
  15991. {
  15992. detail::BufferStream strm;
  15993. std::string frame;
  15994. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  15995. frame += static_cast<char>(127); // 64-bit extended length
  15996. frame += static_cast<char>(0x80); // MSB set (invalid)
  15997. frame += std::string(7, '\0'); // remaining 7 bytes of length
  15998. strm.write(frame.data(), frame.size());
  15999. ws::Opcode opcode;
  16000. std::string payload;
  16001. bool fin;
  16002. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16003. false, 1024));
  16004. }
  16005. // MSB clear - should pass length parsing (will be rejected by max_len,
  16006. // but that's a different check; use a small length to verify)
  16007. {
  16008. detail::BufferStream strm;
  16009. std::string frame;
  16010. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  16011. frame += static_cast<char>(127); // 64-bit extended length
  16012. frame += std::string(7, '\0'); // high bytes = 0
  16013. frame += static_cast<char>(0x03); // length = 3
  16014. frame += "abc";
  16015. strm.write(frame.data(), frame.size());
  16016. ws::Opcode opcode;
  16017. std::string payload;
  16018. bool fin;
  16019. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  16020. false, 1024));
  16021. EXPECT_EQ(ws::Opcode::Text, opcode);
  16022. EXPECT_EQ("abc", payload);
  16023. }
  16024. }
  16025. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  16026. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  16027. // Valid UTF-8
  16028. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  16029. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  16030. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  16031. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  16032. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  16033. // Invalid UTF-8
  16034. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  16035. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  16036. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  16037. EXPECT_FALSE(
  16038. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  16039. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  16040. }
  16041. TEST(WebSocketTest, ConnectAndDisconnect) {
  16042. Server svr;
  16043. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16044. std::string msg;
  16045. while (ws.read(msg)) {}
  16046. });
  16047. auto port = svr.bind_to_any_port(HOST);
  16048. std::thread t([&]() { svr.listen_after_bind(); });
  16049. svr.wait_until_ready();
  16050. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16051. ASSERT_TRUE(client.connect());
  16052. EXPECT_TRUE(client.is_open());
  16053. client.close();
  16054. EXPECT_FALSE(client.is_open());
  16055. svr.stop();
  16056. t.join();
  16057. }
  16058. TEST(WebSocketTest, ValidURL) {
  16059. ws::WebSocketClient ws1("ws://localhost:8080/path");
  16060. EXPECT_TRUE(ws1.is_valid());
  16061. ws::WebSocketClient ws2("ws://example.com/path");
  16062. EXPECT_TRUE(ws2.is_valid());
  16063. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  16064. EXPECT_TRUE(ws3.is_valid());
  16065. #ifdef CPPHTTPLIB_SSL_ENABLED
  16066. ws::WebSocketClient wss1("wss://example.com/path");
  16067. EXPECT_TRUE(wss1.is_valid());
  16068. ws::WebSocketClient wss2("wss://example.com:443/path");
  16069. EXPECT_TRUE(wss2.is_valid());
  16070. #endif
  16071. }
  16072. TEST(WebSocketTest, InvalidURL) {
  16073. // No scheme
  16074. ws::WebSocketClient ws1("localhost:8080/path");
  16075. EXPECT_FALSE(ws1.is_valid());
  16076. // No path
  16077. ws::WebSocketClient ws2("ws://localhost:8080");
  16078. EXPECT_FALSE(ws2.is_valid());
  16079. // Empty string
  16080. ws::WebSocketClient ws3("");
  16081. EXPECT_FALSE(ws3.is_valid());
  16082. // Missing host
  16083. ws::WebSocketClient ws4("ws://:8080/path");
  16084. EXPECT_FALSE(ws4.is_valid());
  16085. // Port number overflow — should not crash
  16086. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  16087. EXPECT_FALSE(ws5.is_valid());
  16088. // Port out of range
  16089. ws::WebSocketClient ws6("ws://localhost:99999/path");
  16090. EXPECT_FALSE(ws6.is_valid());
  16091. }
  16092. TEST(WebSocketTest, UnsupportedScheme) {
  16093. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16094. ws::WebSocketClient ws1("http://localhost:8080/path");
  16095. EXPECT_FALSE(ws1.is_valid());
  16096. ws::WebSocketClient ws2("https://localhost:8080/path");
  16097. EXPECT_FALSE(ws2.is_valid());
  16098. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  16099. EXPECT_FALSE(ws3.is_valid());
  16100. #else
  16101. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  16102. std::invalid_argument);
  16103. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  16104. std::invalid_argument);
  16105. #endif
  16106. }
  16107. TEST(WebSocketTest, ConnectWhenInvalid) {
  16108. ws::WebSocketClient ws("not a valid url");
  16109. EXPECT_FALSE(ws.is_valid());
  16110. EXPECT_FALSE(ws.connect());
  16111. }
  16112. TEST(WebSocketTest, DefaultPort) {
  16113. ws::WebSocketClient ws1("ws://example.com/path");
  16114. EXPECT_TRUE(ws1.is_valid());
  16115. // ws:// defaults to port 80 (verified by successful parse)
  16116. #ifdef CPPHTTPLIB_SSL_ENABLED
  16117. ws::WebSocketClient ws2("wss://example.com/path");
  16118. EXPECT_TRUE(ws2.is_valid());
  16119. // wss:// defaults to port 443 (verified by successful parse)
  16120. #endif
  16121. }
  16122. TEST(WebSocketTest, IPv6LiteralAddress) {
  16123. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  16124. EXPECT_TRUE(ws1.is_valid());
  16125. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  16126. EXPECT_TRUE(ws2.is_valid());
  16127. }
  16128. TEST(WebSocketTest, ComplexPath) {
  16129. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  16130. EXPECT_TRUE(ws1.is_valid());
  16131. ws::WebSocketClient ws2("ws://localhost:8080/");
  16132. EXPECT_TRUE(ws2.is_valid());
  16133. }
  16134. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  16135. Server svr;
  16136. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16137. std::string msg;
  16138. while (ws.read(msg)) {}
  16139. });
  16140. auto port = svr.bind_to_any_port(HOST);
  16141. std::thread t([&]() { svr.listen_after_bind(); });
  16142. svr.wait_until_ready();
  16143. auto another_host = "example.com";
  16144. auto wrong_ip = "192.0.2.1";
  16145. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16146. client.set_hostname_addr_map({{another_host, wrong_ip}});
  16147. ASSERT_TRUE(client.connect());
  16148. EXPECT_TRUE(client.is_open());
  16149. client.close();
  16150. svr.stop();
  16151. t.join();
  16152. }
  16153. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  16154. Server svr;
  16155. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16156. std::string msg;
  16157. while (ws.read(msg)) {}
  16158. });
  16159. auto port = svr.bind_to_any_port(HOST);
  16160. std::thread t([&]() { svr.listen_after_bind(); });
  16161. svr.wait_until_ready();
  16162. auto wrong_ip = "192.0.2.1";
  16163. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  16164. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  16165. client.set_connection_timeout(1);
  16166. client.set_read_timeout(1);
  16167. client.set_write_timeout(1);
  16168. EXPECT_FALSE(client.connect());
  16169. EXPECT_FALSE(client.is_open());
  16170. svr.stop();
  16171. t.join();
  16172. }
  16173. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  16174. // A mapped value that is not an IP literal must be resolved. HOST resolves
  16175. // from the hosts file, so this test needs no external DNS. "target.invalid"
  16176. // (RFC 6761) is only a map key and the Host header value.
  16177. auto host = "target.invalid";
  16178. Server svr;
  16179. std::string received_host;
  16180. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16181. received_host = req.get_header_value("Host");
  16182. std::string msg;
  16183. while (ws.read(msg)) {}
  16184. });
  16185. auto port = svr.bind_to_any_port(HOST);
  16186. std::thread t([&]() { svr.listen_after_bind(); });
  16187. // ASSERT_* below returns from the test body, which would leave t joinable
  16188. // and make ~thread call std::terminate.
  16189. auto se = detail::scope_exit([&] {
  16190. svr.stop();
  16191. if (t.joinable()) { t.join(); }
  16192. });
  16193. svr.wait_until_ready();
  16194. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  16195. std::to_string(port) + "/ws");
  16196. client.set_hostname_addr_map({{host, HOST}});
  16197. ASSERT_TRUE(client.connect());
  16198. EXPECT_TRUE(client.is_open());
  16199. client.close();
  16200. svr.stop();
  16201. t.join();
  16202. // The mapping only redirects the connection; the identity stays host_.
  16203. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  16204. }
  16205. class WebSocketIntegrationTest : public ::testing::Test {
  16206. protected:
  16207. void SetUp() override {
  16208. server_ = httplib::detail::make_unique<Server>();
  16209. setup_server();
  16210. start_server();
  16211. }
  16212. void TearDown() override {
  16213. server_->stop();
  16214. if (server_thread_.joinable()) { server_thread_.join(); }
  16215. }
  16216. void setup_server() {
  16217. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16218. std::string msg;
  16219. ws::ReadResult ret;
  16220. while ((ret = ws.read(msg))) {
  16221. if (ret == ws::Binary) {
  16222. ws.send(msg.data(), msg.size());
  16223. } else {
  16224. ws.send(msg);
  16225. }
  16226. }
  16227. });
  16228. server_->WebSocket("/ws-echo-string",
  16229. [](const Request &, ws::WebSocket &ws) {
  16230. std::string msg;
  16231. while (ws.read(msg)) {
  16232. ws.send("echo: " + msg);
  16233. }
  16234. });
  16235. server_->WebSocket(
  16236. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16237. // Echo back request metadata
  16238. ws.send("path:" + req.path);
  16239. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16240. std::string msg;
  16241. while (ws.read(msg)) {}
  16242. });
  16243. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16244. std::string msg;
  16245. ws.read(msg); // wait for a message
  16246. ws.close();
  16247. });
  16248. server_->WebSocket("/ws-close-status",
  16249. [](const Request &, ws::WebSocket &ws) {
  16250. std::string msg;
  16251. ws.read(msg); // wait for a message
  16252. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16253. });
  16254. server_->WebSocket(
  16255. "/ws-subprotocol",
  16256. [](const Request &, ws::WebSocket &ws) {
  16257. std::string msg;
  16258. while (ws.read(msg)) {
  16259. ws.send(msg);
  16260. }
  16261. },
  16262. [](const std::vector<std::string> &protocols) -> std::string {
  16263. for (const auto &p : protocols) {
  16264. if (p == "graphql-ws") { return p; }
  16265. }
  16266. return "";
  16267. });
  16268. }
  16269. void start_server() {
  16270. port_ = server_->bind_to_any_port(HOST);
  16271. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16272. server_->wait_until_ready();
  16273. }
  16274. std::unique_ptr<Server> server_;
  16275. std::thread server_thread_;
  16276. int port_ = 0;
  16277. };
  16278. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16280. "/ws-echo");
  16281. ASSERT_TRUE(client.connect());
  16282. ASSERT_TRUE(client.is_open());
  16283. ASSERT_TRUE(client.send("Hello WebSocket"));
  16284. std::string msg;
  16285. EXPECT_EQ(ws::Text, client.read(msg));
  16286. EXPECT_EQ("Hello WebSocket", msg);
  16287. client.close();
  16288. }
  16289. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16290. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16291. "/ws-echo");
  16292. ASSERT_TRUE(client.connect());
  16293. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16294. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16295. std::string msg;
  16296. EXPECT_EQ(ws::Binary, client.read(msg));
  16297. EXPECT_EQ(binary_data, msg);
  16298. client.close();
  16299. }
  16300. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16301. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16302. "/ws-echo");
  16303. ASSERT_TRUE(client.connect());
  16304. for (int i = 0; i < 10; i++) {
  16305. auto text = "message " + std::to_string(i);
  16306. ASSERT_TRUE(client.send(text));
  16307. std::string msg;
  16308. ASSERT_TRUE(client.read(msg));
  16309. EXPECT_EQ(text, msg);
  16310. }
  16311. client.close();
  16312. }
  16313. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16314. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16315. "/ws-close");
  16316. ASSERT_TRUE(client.connect());
  16317. // Send a message to trigger the server to close
  16318. ASSERT_TRUE(client.send("trigger close"));
  16319. // The server will close, so read should return false
  16320. std::string msg;
  16321. EXPECT_FALSE(client.read(msg));
  16322. EXPECT_FALSE(client.is_open());
  16323. }
  16324. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16326. "/ws-echo");
  16327. ASSERT_TRUE(client.connect());
  16328. // 128KB message
  16329. std::string large_data(128 * 1024, 'X');
  16330. ASSERT_TRUE(client.send(large_data));
  16331. std::string msg;
  16332. ASSERT_TRUE(client.read(msg));
  16333. EXPECT_EQ(large_data, msg);
  16334. client.close();
  16335. }
  16336. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16337. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16338. "/ws-echo");
  16339. ASSERT_TRUE(client.connect());
  16340. const int num_threads = 4;
  16341. std::vector<std::thread> threads;
  16342. std::atomic<int> send_count{0};
  16343. for (int t = 0; t < num_threads; t++) {
  16344. threads.emplace_back([&client, &send_count, t]() {
  16345. for (int i = 0; i < 5; i++) {
  16346. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16347. if (client.send(text)) { send_count++; }
  16348. }
  16349. });
  16350. }
  16351. for (auto &th : threads) {
  16352. th.join();
  16353. }
  16354. int received = 0;
  16355. std::string msg;
  16356. while (received < send_count.load()) {
  16357. if (!client.read(msg)) { break; }
  16358. received++;
  16359. }
  16360. EXPECT_EQ(send_count.load(), received);
  16361. client.close();
  16362. }
  16363. TEST_F(WebSocketIntegrationTest, ReadString) {
  16364. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16365. "/ws-echo-string");
  16366. ASSERT_TRUE(client.connect());
  16367. ASSERT_TRUE(client.send("hello"));
  16368. std::string msg;
  16369. ASSERT_TRUE(client.read(msg));
  16370. EXPECT_EQ("echo: hello", msg);
  16371. ASSERT_TRUE(client.send("world"));
  16372. ASSERT_TRUE(client.read(msg));
  16373. EXPECT_EQ("echo: world", msg);
  16374. client.close();
  16375. }
  16376. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16377. Headers headers = {{"X-Test-Header", "test-value"}};
  16378. ws::WebSocketClient client(
  16379. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16380. ASSERT_TRUE(client.connect());
  16381. std::string msg;
  16382. ASSERT_TRUE(client.read(msg));
  16383. EXPECT_EQ("path:/ws-request-info", msg);
  16384. ASSERT_TRUE(client.read(msg));
  16385. EXPECT_EQ("header:test-value", msg);
  16386. client.close();
  16387. }
  16388. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16390. "/ws-echo");
  16391. client.set_read_timeout(1, 0); // 1 second
  16392. ASSERT_TRUE(client.connect());
  16393. // Don't send anything — server echo handler waits for a message,
  16394. // so read() should time out and return false.
  16395. std::string msg;
  16396. EXPECT_FALSE(client.read(msg));
  16397. }
  16398. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16400. "/ws-echo");
  16401. client.set_read_timeout(5, 0);
  16402. ASSERT_TRUE(client.connect());
  16403. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16404. // The server should reject it and close the connection.
  16405. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16406. client.send(oversized);
  16407. // The server's read() should have failed due to payload limit,
  16408. // so our read() should return false (connection closed).
  16409. std::string msg;
  16410. EXPECT_FALSE(client.read(msg));
  16411. }
  16412. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16413. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16414. "/ws-echo");
  16415. client.set_read_timeout(10, 0);
  16416. ASSERT_TRUE(client.connect());
  16417. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16418. // This should succeed.
  16419. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16420. ASSERT_TRUE(client.send(at_limit));
  16421. std::string msg;
  16422. ASSERT_TRUE(client.read(msg));
  16423. EXPECT_EQ(at_limit.size(), msg.size());
  16424. client.close();
  16425. }
  16426. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16428. "/nonexistent");
  16429. EXPECT_FALSE(client.connect());
  16430. EXPECT_FALSE(client.is_open());
  16431. }
  16432. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16434. "/ws-echo");
  16435. ASSERT_TRUE(client.connect());
  16436. ASSERT_TRUE(client.send(""));
  16437. std::string msg;
  16438. EXPECT_EQ(ws::Text, client.read(msg));
  16439. EXPECT_EQ("", msg);
  16440. client.close();
  16441. }
  16442. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16443. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16444. "/ws-echo");
  16445. // First connection
  16446. ASSERT_TRUE(client.connect());
  16447. ASSERT_TRUE(client.send("first"));
  16448. std::string msg;
  16449. ASSERT_TRUE(client.read(msg));
  16450. EXPECT_EQ("first", msg);
  16451. client.close();
  16452. EXPECT_FALSE(client.is_open());
  16453. // Reconnect using the same client object
  16454. ASSERT_TRUE(client.connect());
  16455. ASSERT_TRUE(client.is_open());
  16456. ASSERT_TRUE(client.send("second"));
  16457. ASSERT_TRUE(client.read(msg));
  16458. EXPECT_EQ("second", msg);
  16459. client.close();
  16460. }
  16461. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16462. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16463. "/ws-close-status");
  16464. ASSERT_TRUE(client.connect());
  16465. // Trigger the server to close with GoingAway status
  16466. ASSERT_TRUE(client.send("trigger"));
  16467. // read() should return false after receiving the close frame
  16468. std::string msg;
  16469. EXPECT_FALSE(client.read(msg));
  16470. EXPECT_FALSE(client.is_open());
  16471. }
  16472. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16473. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16474. "/ws-echo");
  16475. ASSERT_TRUE(client.connect());
  16476. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16477. EXPECT_FALSE(client.is_open());
  16478. }
  16479. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16480. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16481. ws::WebSocketClient client(
  16482. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16483. ASSERT_TRUE(client.connect());
  16484. // Server should have selected graphql-ws
  16485. EXPECT_EQ("graphql-ws", client.subprotocol());
  16486. client.close();
  16487. }
  16488. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16489. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16490. ws::WebSocketClient client(
  16491. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16492. ASSERT_TRUE(client.connect());
  16493. // Server should not have selected any subprotocol
  16494. EXPECT_TRUE(client.subprotocol().empty());
  16495. client.close();
  16496. }
  16497. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16498. // Connect without requesting any subprotocol
  16499. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16500. "/ws-subprotocol");
  16501. ASSERT_TRUE(client.connect());
  16502. EXPECT_TRUE(client.subprotocol().empty());
  16503. client.close();
  16504. }
  16505. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16506. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16507. "/ws-echo");
  16508. client.set_tcp_nodelay(true);
  16509. client.set_connection_timeout(3, 0);
  16510. bool socket_options_called = false;
  16511. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16512. ASSERT_TRUE(client.connect());
  16513. ASSERT_TRUE(client.is_open());
  16514. EXPECT_TRUE(socket_options_called);
  16515. ASSERT_TRUE(client.send("hello"));
  16516. std::string msg;
  16517. auto result = client.read(msg);
  16518. EXPECT_EQ(result, ws::ReadResult::Text);
  16519. EXPECT_EQ(msg, "hello");
  16520. client.close();
  16521. }
  16522. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16523. Server svr;
  16524. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16525. if (!req.has_header("Authorization")) {
  16526. res.status = StatusCode::Unauthorized_401;
  16527. res.set_content("Unauthorized", "text/plain");
  16528. return Server::HandlerResponse::Handled;
  16529. }
  16530. return Server::HandlerResponse::Unhandled;
  16531. });
  16532. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16533. std::string msg;
  16534. while (ws.read(msg)) {
  16535. ws.send(msg);
  16536. }
  16537. });
  16538. auto port = svr.bind_to_any_port("localhost");
  16539. std::thread t([&]() { svr.listen_after_bind(); });
  16540. svr.wait_until_ready();
  16541. // Without Authorization header - should be rejected before upgrade
  16542. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16543. EXPECT_FALSE(client1.connect());
  16544. // With Authorization header - should succeed
  16545. Headers headers = {{"Authorization", "Bearer token123"}};
  16546. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16547. headers);
  16548. ASSERT_TRUE(client2.connect());
  16549. ASSERT_TRUE(client2.send("hello"));
  16550. std::string msg;
  16551. ASSERT_TRUE(client2.read(msg));
  16552. EXPECT_EQ("hello", msg);
  16553. client2.close();
  16554. svr.stop();
  16555. t.join();
  16556. }
  16557. TEST(WebSocketTest, QueryStringInHandshake) {
  16558. Server svr;
  16559. std::mutex mtx;
  16560. std::string received_target;
  16561. std::string received_token;
  16562. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16563. {
  16564. std::lock_guard<std::mutex> lock(mtx);
  16565. received_target = req.target;
  16566. if (req.has_param("token")) {
  16567. received_token = req.get_param_value("token");
  16568. }
  16569. }
  16570. std::string msg;
  16571. while (ws.read(msg)) {
  16572. ws.send(msg);
  16573. }
  16574. });
  16575. auto port = svr.bind_to_any_port("localhost");
  16576. std::thread t([&]() { svr.listen_after_bind(); });
  16577. svr.wait_until_ready();
  16578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16579. "/ws?token=ABC&session=123");
  16580. ASSERT_TRUE(client.connect());
  16581. // Round-trip ensures the handler has run and captured the request.
  16582. ASSERT_TRUE(client.send("hello"));
  16583. std::string msg;
  16584. ASSERT_TRUE(client.read(msg));
  16585. EXPECT_EQ("hello", msg);
  16586. client.close();
  16587. {
  16588. std::lock_guard<std::mutex> lock(mtx);
  16589. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16590. EXPECT_EQ("ABC", received_token);
  16591. }
  16592. svr.stop();
  16593. t.join();
  16594. }
  16595. // Run a handshake against a throwaway server and hand the request the server
  16596. // received back to the caller, so tests can assert on the headers the client
  16597. // actually put on the wire.
  16598. static void capture_websocket_handshake_request(
  16599. const Headers &client_headers,
  16600. std::function<void(const Request &, int port)> verify) {
  16601. Server svr;
  16602. std::mutex mtx;
  16603. Request received;
  16604. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16605. {
  16606. std::lock_guard<std::mutex> lock(mtx);
  16607. received = req;
  16608. }
  16609. std::string msg;
  16610. while (ws.read(msg)) {
  16611. ws.send(msg);
  16612. }
  16613. });
  16614. auto port = svr.bind_to_any_port("localhost");
  16615. std::thread t([&]() { svr.listen_after_bind(); });
  16616. auto se = detail::scope_exit([&] {
  16617. svr.stop();
  16618. t.join();
  16619. });
  16620. svr.wait_until_ready();
  16621. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  16622. client_headers);
  16623. ASSERT_TRUE(client.connect());
  16624. ASSERT_TRUE(client.send("hello"));
  16625. std::string msg;
  16626. ASSERT_TRUE(client.read(msg));
  16627. client.close();
  16628. {
  16629. std::lock_guard<std::mutex> lock(mtx);
  16630. verify(received, port);
  16631. }
  16632. }
  16633. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  16634. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  16635. // Non-default port must be present in the Host header. Default ports
  16636. // (80/443) are omitted; that logic is covered by
  16637. // MakeHostAndPortStringTest.
  16638. EXPECT_EQ("localhost:" + std::to_string(port),
  16639. req.get_header_value("Host"));
  16640. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  16641. req.get_header_value("User-Agent"));
  16642. EXPECT_FALSE(req.has_header("Accept"));
  16643. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  16644. EXPECT_FALSE(req.has_header("Content-Length"));
  16645. });
  16646. }
  16647. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  16648. capture_websocket_handshake_request(
  16649. {{"Host", "example.com"},
  16650. {"User-Agent", "custom-agent"},
  16651. {"X-Custom", "value"}},
  16652. [](const Request &req, int) {
  16653. EXPECT_EQ("example.com", req.get_header_value("Host"));
  16654. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  16655. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  16656. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  16657. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  16658. });
  16659. }
  16660. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  16661. capture_websocket_handshake_request(
  16662. {{"Upgrade", "bogus"},
  16663. {"Connection", "close"},
  16664. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  16665. {"Sec-WebSocket-Version", "8"}},
  16666. [](const Request &req, int) {
  16667. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  16668. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  16669. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  16670. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  16671. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  16672. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  16673. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  16674. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  16675. req.get_header_value("Sec-WebSocket-Key"));
  16676. });
  16677. }
  16678. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  16679. // A header the client refuses to send must abort the handshake before any
  16680. // part of it reaches the wire; a lone request line would otherwise sit in
  16681. // the peer's buffer as a truncated request.
  16682. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16683. ASSERT_NE(INVALID_SOCKET, srv);
  16684. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  16685. sockaddr_in addr{};
  16686. addr.sin_family = AF_INET;
  16687. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  16688. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16689. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16690. ASSERT_EQ(0, ::listen(srv, 1));
  16691. sockaddr_in bound{};
  16692. socklen_t bound_len = sizeof(bound);
  16693. ASSERT_EQ(
  16694. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  16695. auto port = ntohs(bound.sin_port);
  16696. ssize_t received = -1;
  16697. std::thread t([&] {
  16698. // Bound every blocking call so a regression fails the test with a bad
  16699. // value instead of hanging the suite.
  16700. fd_set rfds;
  16701. FD_ZERO(&rfds);
  16702. FD_SET(srv, &rfds);
  16703. timeval tv{5, 0};
  16704. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  16705. 0) {
  16706. return;
  16707. }
  16708. sockaddr_in cli_addr{};
  16709. socklen_t cli_len = sizeof(cli_addr);
  16710. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16711. if (cli == INVALID_SOCKET) { return; }
  16712. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  16713. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16714. char buf[4096];
  16715. received = ::recv(cli, buf, sizeof(buf), 0);
  16716. });
  16717. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  16718. // connect() has already shut the socket down by the time it returns false,
  16719. // so the peer sees EOF without waiting for the client to be destroyed.
  16720. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  16721. {{"X-Bad", "a\r\nInjected: 1"}});
  16722. EXPECT_FALSE(client.connect());
  16723. t.join();
  16724. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  16725. EXPECT_EQ(0, received);
  16726. }
  16727. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  16728. // The socket path doubles as the URL host, so it must not contain '/'.
  16729. const char *shard = getenv("GTEST_SHARD_INDEX");
  16730. const std::string sock_path =
  16731. shard ? std::string("httplib-ws-") + shard + ".sock"
  16732. : std::string("httplib-ws.sock");
  16733. std::remove(sock_path.c_str());
  16734. Server svr;
  16735. std::mutex mtx;
  16736. std::string received_host;
  16737. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16738. {
  16739. std::lock_guard<std::mutex> lock(mtx);
  16740. received_host = req.get_header_value("Host");
  16741. }
  16742. std::string msg;
  16743. while (ws.read(msg)) {
  16744. ws.send(msg);
  16745. }
  16746. });
  16747. svr.set_address_family(AF_UNIX);
  16748. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  16749. auto se = detail::scope_exit([&] {
  16750. svr.stop();
  16751. t.join();
  16752. std::remove(sock_path.c_str());
  16753. });
  16754. svr.wait_until_ready();
  16755. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  16756. client.set_address_family(AF_UNIX);
  16757. ASSERT_TRUE(client.connect());
  16758. ASSERT_TRUE(client.send("hello"));
  16759. std::string msg;
  16760. ASSERT_TRUE(client.read(msg));
  16761. client.close();
  16762. {
  16763. std::lock_guard<std::mutex> lock(mtx);
  16764. // There is no host:port for a Unix socket, so the same "localhost"
  16765. // placeholder the HTTP client uses is expected.
  16766. EXPECT_EQ("localhost", received_host);
  16767. }
  16768. }
  16769. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16770. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16771. protected:
  16772. void SetUp() override {
  16773. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16774. SERVER_PRIVATE_KEY_FILE);
  16775. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16776. std::string msg;
  16777. ws::ReadResult ret;
  16778. while ((ret = ws.read(msg))) {
  16779. if (ret == ws::Binary) {
  16780. ws.send(msg.data(), msg.size());
  16781. } else {
  16782. ws.send(msg);
  16783. }
  16784. }
  16785. });
  16786. port_ = server_->bind_to_any_port(HOST);
  16787. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16788. server_->wait_until_ready();
  16789. }
  16790. void TearDown() override {
  16791. server_->stop();
  16792. if (server_thread_.joinable()) { server_thread_.join(); }
  16793. }
  16794. std::unique_ptr<SSLServer> server_;
  16795. std::thread server_thread_;
  16796. int port_ = 0;
  16797. };
  16798. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16799. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16800. "/ws-echo");
  16801. client.enable_server_certificate_verification(false);
  16802. ASSERT_TRUE(client.connect());
  16803. ASSERT_TRUE(client.is_open());
  16804. ASSERT_TRUE(client.send("Hello WSS"));
  16805. std::string msg;
  16806. EXPECT_EQ(ws::Text, client.read(msg));
  16807. EXPECT_EQ("Hello WSS", msg);
  16808. client.close();
  16809. }
  16810. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16811. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16812. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16813. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16814. // client (without calling close() first) is the only path that runs
  16815. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16816. // bug exactly.
  16817. //
  16818. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16819. // when linked against an instrumented libssl; run under Valgrind to catch it
  16820. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16821. // suite (the freed session otherwise stalls on the close handshake) — this test
  16822. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16823. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16824. {
  16825. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16826. "/ws-echo");
  16827. client.enable_server_certificate_verification(false);
  16828. client.set_read_timeout(2, 0);
  16829. client.set_write_timeout(2, 0);
  16830. ASSERT_TRUE(client.connect());
  16831. ASSERT_TRUE(client.is_open());
  16832. ASSERT_TRUE(client.send("still open"));
  16833. // Intentionally do NOT call client.close(): leaving scope runs
  16834. // shutdown_and_close() with the WebSocket still open, which must send the
  16835. // close frame while the TLS session is still alive.
  16836. }
  16837. }
  16838. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16839. // shutdown_and_close() at the start of connect(), reproducing the same
  16840. // use-after-free within the test body rather than at scope exit. The second
  16841. // connect must succeed and echo, proving the close handshake ran over a live
  16842. // session. See the note above about memory-tool requirements.
  16843. TEST_F(WebSocketSSLIntegrationTest,
  16844. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16845. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16846. "/ws-echo");
  16847. client.enable_server_certificate_verification(false);
  16848. client.set_read_timeout(2, 0);
  16849. client.set_write_timeout(2, 0);
  16850. ASSERT_TRUE(client.connect());
  16851. ASSERT_TRUE(client.is_open());
  16852. ASSERT_TRUE(client.send("still open"));
  16853. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16854. // the still-open connection, which must not touch a freed TLS session.
  16855. ASSERT_TRUE(client.connect());
  16856. ASSERT_TRUE(client.is_open());
  16857. ASSERT_TRUE(client.send("after reconnect"));
  16858. std::string msg;
  16859. EXPECT_EQ(ws::Text, client.read(msg));
  16860. EXPECT_EQ("after reconnect", msg);
  16861. client.close();
  16862. }
  16863. #endif
  16864. #ifdef CPPHTTPLIB_SSL_ENABLED
  16865. class WebSocketSSLCATest : public ::testing::Test {
  16866. protected:
  16867. void SetUp() override {
  16868. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16869. SERVER_PRIVATE_KEY_FILE);
  16870. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16871. std::string msg;
  16872. while (ws.read(msg)) {
  16873. ws.send(msg);
  16874. }
  16875. });
  16876. port_ = server_->bind_to_any_port("127.0.0.1");
  16877. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16878. server_->wait_until_ready();
  16879. }
  16880. void TearDown() override {
  16881. server_->stop();
  16882. if (server_thread_.joinable()) { server_thread_.join(); }
  16883. }
  16884. std::string url() const {
  16885. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16886. }
  16887. std::unique_ptr<SSLServer> server_;
  16888. std::thread server_thread_;
  16889. int port_ = 0;
  16890. };
  16891. // A custom CA loaded as PEM verifies the server with full certificate
  16892. // verification enabled
  16893. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16894. ws::WebSocketClient client(url());
  16895. std::string cert;
  16896. read_file(SERVER_CERT2_FILE, cert);
  16897. client.load_ca_cert_store(cert.c_str(), cert.size());
  16898. ASSERT_TRUE(client.connect());
  16899. ASSERT_TRUE(client.send("hello"));
  16900. std::string msg;
  16901. EXPECT_EQ(ws::Text, client.read(msg));
  16902. EXPECT_EQ("hello", msg);
  16903. client.close();
  16904. }
  16905. // A custom CA that does not cover the server must fail verification (the
  16906. // custom CA is exclusive; system certs are not loaded alongside it)
  16907. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16908. ws::WebSocketClient client(url());
  16909. std::string cert;
  16910. read_file(CLIENT_CA_CERT_FILE, cert);
  16911. client.load_ca_cert_store(cert.c_str(), cert.size());
  16912. ASSERT_FALSE(client.connect());
  16913. }
  16914. // Regression test: reconnecting with a native custom CA store used to reuse
  16915. // a store handle the previous TLS context had already freed (use-after-free
  16916. // under the OpenSSL backend). The context now lives as long as the client.
  16917. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16918. ws::WebSocketClient client(url());
  16919. std::string cert;
  16920. read_file(SERVER_CERT2_FILE, cert);
  16921. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16922. ASSERT_TRUE(client.connect());
  16923. client.close();
  16924. ASSERT_TRUE(client.connect());
  16925. ASSERT_TRUE(client.send("again"));
  16926. std::string msg;
  16927. EXPECT_EQ(ws::Text, client.read(msg));
  16928. EXPECT_EQ("again", msg);
  16929. client.close();
  16930. }
  16931. // Regression test: a certificate with a trusted chain but no identity match
  16932. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16933. // verification entirely for IP hosts, so this connection succeeded there.
  16934. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16935. // chain verification while the identity check must still fail.
  16936. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16938. ASSERT_TRUE(svr.is_valid());
  16939. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16940. std::string msg;
  16941. while (ws.read(msg)) {
  16942. ws.send(msg);
  16943. }
  16944. });
  16945. auto port = svr.bind_to_any_port("127.0.0.1");
  16946. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16947. auto se = detail::scope_exit([&] {
  16948. svr.stop();
  16949. t.join();
  16950. });
  16951. svr.wait_until_ready();
  16952. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16953. "/echo");
  16954. std::string cert;
  16955. read_file(SERVER_CERT_FILE, cert);
  16956. client.load_ca_cert_store(cert.c_str(), cert.size());
  16957. ASSERT_FALSE(client.connect());
  16958. }
  16959. #endif
  16960. #if !defined(_WIN32)
  16961. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16962. auto secret_dir = std::string("./symlink_test_secret");
  16963. auto served_dir = std::string("./symlink_test_served");
  16964. auto secret_file = secret_dir + "/secret.txt";
  16965. auto symlink_path = served_dir + "/escape";
  16966. // Setup: create directories and files
  16967. mkdir(secret_dir.c_str(), 0755);
  16968. mkdir(served_dir.c_str(), 0755);
  16969. {
  16970. std::ofstream ofs(secret_file);
  16971. ofs << "SECRET_DATA";
  16972. }
  16973. // Create symlink using absolute path so it resolves correctly
  16974. #ifdef PATH_MAX
  16975. char abs_secret[PATH_MAX];
  16976. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16977. #else
  16978. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16979. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16980. ASSERT_NE(nullptr, abs_secret);
  16981. #endif
  16982. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16983. auto se = detail::scope_exit([&] {
  16984. unlink(symlink_path.c_str());
  16985. unlink(secret_file.c_str());
  16986. rmdir(served_dir.c_str());
  16987. rmdir(secret_dir.c_str());
  16988. });
  16989. Server svr;
  16990. svr.set_mount_point("/", served_dir);
  16991. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16992. auto se2 = detail::scope_exit([&] {
  16993. svr.stop();
  16994. listen_thread.join();
  16995. });
  16996. svr.wait_until_ready();
  16997. Client cli("localhost", PORT);
  16998. // Symlink pointing outside base dir should be blocked
  16999. auto res = cli.Get("/escape/secret.txt");
  17000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17001. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17002. }
  17003. #endif
  17004. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  17005. // A GET request with Content-Length to a static file handler must have its
  17006. // body drained before the keep-alive connection is reused. Otherwise the
  17007. // unread body bytes are interpreted as the next HTTP request.
  17008. //
  17009. // The body is sent AFTER receiving the first response (as in the original
  17010. // PoC) so that the stream_line_reader cannot buffer it together with the
  17011. // headers of the first request.
  17012. Server svr;
  17013. svr.set_mount_point("/", "./www");
  17014. std::atomic<int> smuggled_count(0);
  17015. svr.Get("/smuggled", [&](const Request &, Response &res) {
  17016. smuggled_count++;
  17017. res.set_content("oops", "text/plain");
  17018. });
  17019. auto port = svr.bind_to_any_port("localhost");
  17020. thread t = thread([&] { svr.listen_after_bind(); });
  17021. auto se = detail::scope_exit([&] {
  17022. svr.stop();
  17023. t.join();
  17024. });
  17025. svr.wait_until_ready();
  17026. auto error = Error::Success;
  17027. auto sock = detail::create_client_socket(
  17028. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  17029. /*connection_timeout_sec=*/2, 0,
  17030. /*read_timeout_sec=*/2, 0,
  17031. /*write_timeout_sec=*/2, 0, std::string(), error);
  17032. ASSERT_NE(INVALID_SOCKET, sock);
  17033. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17034. // The "smuggled" request will be sent as the body of the outer GET
  17035. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17036. "Host: localhost\r\n"
  17037. "Connection: close\r\n"
  17038. "\r\n";
  17039. // Step 1: Send only the outer request headers (no body yet)
  17040. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17041. "Host: localhost\r\n"
  17042. "Content-Length: " +
  17043. std::to_string(smuggled.size()) +
  17044. "\r\n"
  17045. "\r\n";
  17046. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17047. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17048. // Step 2: Read the first response (server serves file without reading body)
  17049. std::string first_response;
  17050. char buf[4096];
  17051. for (;;) {
  17052. auto n = recv(sock, buf, sizeof(buf), 0);
  17053. if (n <= 0) break;
  17054. first_response.append(buf, static_cast<size_t>(n));
  17055. // Stop once we have a complete response (headers + body)
  17056. auto hdr_end = first_response.find("\r\n\r\n");
  17057. if (hdr_end != std::string::npos) {
  17058. // Check for Content-Length to know when the body is complete
  17059. auto cl_pos = first_response.find("Content-Length:");
  17060. if (cl_pos != std::string::npos) {
  17061. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17062. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17063. auto cl = std::stoul(
  17064. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17065. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17066. } else {
  17067. break; // No Content-Length, assume headers-only response
  17068. }
  17069. }
  17070. }
  17071. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17072. // Step 3: Now send the body, which looks like a new HTTP request.
  17073. // On a vulnerable server the keep-alive loop reads this as a second request.
  17074. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17075. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17076. // Step 4: Try to read a second response (should NOT exist after fix)
  17077. std::string second_response;
  17078. for (;;) {
  17079. auto n = recv(sock, buf, sizeof(buf), 0);
  17080. if (n <= 0) break;
  17081. second_response.append(buf, static_cast<size_t>(n));
  17082. }
  17083. // The smuggled request must NOT have been processed
  17084. EXPECT_EQ(0, smuggled_count.load());
  17085. }
  17086. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17087. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17088. // must be rejected with 400 Bad Request.
  17089. Server svr;
  17090. svr.Post("/test", [&](const Request &, Response &res) {
  17091. res.set_content("ok", "text/plain");
  17092. });
  17093. thread t = thread([&] { svr.listen(HOST, PORT); });
  17094. auto se = detail::scope_exit([&] {
  17095. svr.stop();
  17096. t.join();
  17097. ASSERT_FALSE(svr.is_running());
  17098. });
  17099. svr.wait_until_ready();
  17100. // Exact "chunked"
  17101. {
  17102. auto req = "POST /test HTTP/1.1\r\n"
  17103. "Host: localhost\r\n"
  17104. "Content-Length: 5\r\n"
  17105. "Transfer-Encoding: chunked\r\n"
  17106. "Connection: close\r\n"
  17107. "\r\n"
  17108. "hello";
  17109. std::string response;
  17110. ASSERT_TRUE(send_request(1, req, &response));
  17111. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17112. response.substr(0, response.find("\r\n")));
  17113. }
  17114. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17115. {
  17116. auto req = "POST /test HTTP/1.1\r\n"
  17117. "Host: localhost\r\n"
  17118. "Content-Length: 5\r\n"
  17119. "Transfer-Encoding: gzip, chunked\r\n"
  17120. "Connection: close\r\n"
  17121. "\r\n"
  17122. "hello";
  17123. std::string response;
  17124. ASSERT_TRUE(send_request(1, req, &response));
  17125. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17126. response.substr(0, response.find("\r\n")));
  17127. }
  17128. }
  17129. // Regression for issue #2450: a DELETE without Content-Length on a
  17130. // keep-alive connection must not let the post-response drain consume the
  17131. // next request's bytes.
  17132. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17133. Server svr;
  17134. std::atomic<int> delete_count(0);
  17135. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17136. delete_count++;
  17137. res.status = StatusCode::NoContent_204;
  17138. });
  17139. auto port = svr.bind_to_any_port(HOST);
  17140. thread t = thread([&] { svr.listen_after_bind(); });
  17141. auto se = detail::scope_exit([&] {
  17142. svr.stop();
  17143. t.join();
  17144. });
  17145. svr.wait_until_ready();
  17146. auto error = Error::Success;
  17147. auto sock = detail::create_client_socket(
  17148. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17149. /*connection_timeout_sec=*/2, 0,
  17150. /*read_timeout_sec=*/2, 0,
  17151. /*write_timeout_sec=*/2, 0, std::string(), error);
  17152. ASSERT_NE(INVALID_SOCKET, sock);
  17153. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17154. auto send_request_and_read_response = [&](const std::string &req,
  17155. std::string &out) -> bool {
  17156. auto sent = send(sock, req.data(), req.size(), 0);
  17157. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17158. char buf[4096];
  17159. for (;;) {
  17160. auto n = recv(sock, buf, sizeof(buf), 0);
  17161. if (n <= 0) { return !out.empty(); }
  17162. out.append(buf, static_cast<size_t>(n));
  17163. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17164. }
  17165. };
  17166. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17167. "Host: localhost\r\n"
  17168. "\r\n";
  17169. std::string resp1;
  17170. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17171. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17172. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17173. "Host: localhost\r\n"
  17174. "Connection: close\r\n"
  17175. "\r\n";
  17176. std::string resp2;
  17177. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17178. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17179. EXPECT_EQ(2, delete_count.load());
  17180. }
  17181. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17182. Server svr;
  17183. svr.Post("/ingest", [&](const Request &, Response &res,
  17184. const ContentReader &content_reader) {
  17185. auto consumed = content_reader([](const char *, size_t) { return false; });
  17186. EXPECT_FALSE(consumed);
  17187. res.status = StatusCode::Conflict_409;
  17188. res.set_header("Connection", "close");
  17189. });
  17190. auto port = svr.bind_to_any_port(HOST);
  17191. thread t = thread([&] { svr.listen_after_bind(); });
  17192. auto se = detail::scope_exit([&] {
  17193. svr.stop();
  17194. t.join();
  17195. });
  17196. svr.wait_until_ready();
  17197. auto error = Error::Success;
  17198. auto sock = detail::create_client_socket(
  17199. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17200. /*connection_timeout_sec=*/2, 0,
  17201. /*read_timeout_sec=*/1, 0,
  17202. /*write_timeout_sec=*/2, 0, std::string(), error);
  17203. ASSERT_NE(INVALID_SOCKET, sock);
  17204. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17205. std::string request = "POST /ingest HTTP/1.1\r\n"
  17206. "Host: localhost\r\n"
  17207. "Transfer-Encoding: chunked\r\n"
  17208. "\r\n"
  17209. "4\r\n"
  17210. "data\r\n";
  17211. auto sent = send(sock, request.data(), request.size(), 0);
  17212. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17213. std::string response;
  17214. ssize_t received = 0;
  17215. do {
  17216. char buf[4096];
  17217. received = recv(sock, buf, sizeof(buf), 0);
  17218. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17219. } while (received > 0);
  17220. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17221. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17222. EXPECT_EQ(0, received);
  17223. }
  17224. namespace no_proxy_test {
  17225. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17226. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17227. // calling listen().
  17228. class ScopedServer {
  17229. public:
  17230. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17231. ~ScopedServer() {
  17232. svr_.stop();
  17233. if (th_.joinable()) { th_.join(); }
  17234. }
  17235. Server &svr() { return svr_; }
  17236. int port() const { return port_; }
  17237. void listen() {
  17238. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17239. svr_.wait_until_ready();
  17240. }
  17241. private:
  17242. Server svr_;
  17243. std::thread th_;
  17244. int port_ = 0;
  17245. };
  17246. class ProxyAndTargetServers {
  17247. public:
  17248. ProxyAndTargetServers() {
  17249. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17250. proxy_hits_++;
  17251. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17252. res.set_content("via-proxy", "text/plain");
  17253. });
  17254. target_.Get(".*", [this](const Request &req, Response &res) {
  17255. target_hits_++;
  17256. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17257. res.set_content("direct", "text/plain");
  17258. });
  17259. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17260. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17261. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17262. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17263. proxy_mock_.wait_until_ready();
  17264. target_.wait_until_ready();
  17265. }
  17266. ~ProxyAndTargetServers() {
  17267. proxy_mock_.stop();
  17268. target_.stop();
  17269. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17270. if (target_thread_.joinable()) { target_thread_.join(); }
  17271. }
  17272. Server &proxy_mock() { return proxy_mock_; }
  17273. Server &target() { return target_; }
  17274. int proxy_port() const { return proxy_port_; }
  17275. int target_port() const { return target_port_; }
  17276. int proxy_hits() const { return proxy_hits_.load(); }
  17277. int target_hits() const { return target_hits_.load(); }
  17278. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17279. void reset_counters() {
  17280. proxy_hits_ = 0;
  17281. target_hits_ = 0;
  17282. last_had_proxy_authz_ = false;
  17283. }
  17284. private:
  17285. Server proxy_mock_;
  17286. Server target_;
  17287. std::thread proxy_thread_;
  17288. std::thread target_thread_;
  17289. int proxy_port_ = 0;
  17290. int target_port_ = 0;
  17291. std::atomic<int> proxy_hits_{0};
  17292. std::atomic<int> target_hits_{0};
  17293. std::atomic<bool> last_had_proxy_authz_{false};
  17294. };
  17295. inline std::unique_ptr<Client> make_client(const std::string &host,
  17296. ProxyAndTargetServers &s) {
  17297. auto cli = detail::make_unique<Client>(host, s.target_port());
  17298. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17299. cli->set_proxy("127.0.0.1", s.proxy_port());
  17300. return cli;
  17301. }
  17302. } // namespace no_proxy_test
  17303. using no_proxy_test::make_client;
  17304. using no_proxy_test::ProxyAndTargetServers;
  17305. TEST(NoProxyTest, ExactHostnameBypasses) {
  17306. ProxyAndTargetServers s;
  17307. auto cli = make_client("example.com", s);
  17308. cli->set_no_proxy({"example.com"});
  17309. auto res = cli->Get("/");
  17310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17311. EXPECT_EQ(0, s.proxy_hits());
  17312. EXPECT_EQ(1, s.target_hits());
  17313. }
  17314. TEST(NoProxyTest, SubdomainBypasses) {
  17315. ProxyAndTargetServers s;
  17316. auto cli = make_client("foo.example.com", s);
  17317. cli->set_no_proxy({"example.com"});
  17318. auto res = cli->Get("/");
  17319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17320. EXPECT_EQ(0, s.proxy_hits());
  17321. EXPECT_EQ(1, s.target_hits());
  17322. }
  17323. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17324. // Regression guard: "evilexample.com" must not be considered a subdomain
  17325. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17326. // check would let traffic bypass the proxy and leak credentials direct
  17327. // to the attacker host.
  17328. ProxyAndTargetServers s;
  17329. auto cli = make_client("evilexample.com", s);
  17330. cli->set_no_proxy({"example.com"});
  17331. auto res = cli->Get("/");
  17332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17333. EXPECT_GE(s.proxy_hits(), 1);
  17334. EXPECT_EQ(0, s.target_hits());
  17335. }
  17336. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17337. ProxyAndTargetServers s;
  17338. auto cli = make_client("example.com.evil.com", s);
  17339. cli->set_no_proxy({"example.com"});
  17340. auto res = cli->Get("/");
  17341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17342. EXPECT_GE(s.proxy_hits(), 1);
  17343. EXPECT_EQ(0, s.target_hits());
  17344. }
  17345. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17346. ProxyAndTargetServers s;
  17347. auto cli = make_client("example.com", s);
  17348. cli->set_no_proxy({".example.com"});
  17349. auto res = cli->Get("/");
  17350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17351. EXPECT_EQ(0, s.proxy_hits());
  17352. EXPECT_EQ(1, s.target_hits());
  17353. }
  17354. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17355. ProxyAndTargetServers s;
  17356. auto cli = make_client("Example.COM", s);
  17357. cli->set_no_proxy({"EXAMPLE.com"});
  17358. auto res = cli->Get("/");
  17359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17360. EXPECT_EQ(0, s.proxy_hits());
  17361. EXPECT_EQ(1, s.target_hits());
  17362. }
  17363. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17364. ProxyAndTargetServers s;
  17365. auto cli = make_client("example.com.", s);
  17366. cli->set_no_proxy({"example.com"});
  17367. auto res = cli->Get("/");
  17368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17369. EXPECT_EQ(0, s.proxy_hits());
  17370. EXPECT_EQ(1, s.target_hits());
  17371. }
  17372. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17373. // Trailing dots must be normalized on BOTH sides — host and entry.
  17374. // An implementation that only strips the host-side trailing dot would
  17375. // fail to match host "example.com" against entry "example.com." because
  17376. // a literal substring search would compare 11 chars against 12.
  17377. ProxyAndTargetServers s;
  17378. auto cli = make_client("example.com", s);
  17379. cli->set_no_proxy({"example.com."});
  17380. auto res = cli->Get("/");
  17381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17382. EXPECT_EQ(0, s.proxy_hits());
  17383. EXPECT_EQ(1, s.target_hits());
  17384. }
  17385. TEST(NoProxyTest, WildcardBypassesEverything) {
  17386. ProxyAndTargetServers s;
  17387. auto cli = make_client("anything.invalid.test", s);
  17388. cli->set_no_proxy({"*"});
  17389. auto res = cli->Get("/");
  17390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17391. EXPECT_EQ(0, s.proxy_hits());
  17392. EXPECT_EQ(1, s.target_hits());
  17393. }
  17394. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17395. ProxyAndTargetServers s;
  17396. Client cli("127.0.0.1", s.target_port());
  17397. cli.set_proxy("127.0.0.1", s.proxy_port());
  17398. cli.set_no_proxy({"127.0.0.1"});
  17399. auto res = cli.Get("/");
  17400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17401. EXPECT_EQ(0, s.proxy_hits());
  17402. EXPECT_EQ(1, s.target_hits());
  17403. }
  17404. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17405. ProxyAndTargetServers s;
  17406. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17407. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17408. cli.set_proxy("127.0.0.1", s.proxy_port());
  17409. cli.set_no_proxy({"::1"});
  17410. auto res = cli.Get("/");
  17411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17412. EXPECT_EQ(0, s.proxy_hits());
  17413. EXPECT_EQ(1, s.target_hits());
  17414. }
  17415. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17416. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17417. // must still be recognized as IPv6 for CIDR matching. Implementations
  17418. // that detect IPv6 only when the host begins with '[' would parse the
  17419. // host as a hostname and miss the match.
  17420. ProxyAndTargetServers s;
  17421. Client cli("fe80::1", s.target_port());
  17422. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17423. cli.set_proxy("127.0.0.1", s.proxy_port());
  17424. cli.set_no_proxy({"fe80::/10"});
  17425. auto res = cli.Get("/");
  17426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17427. EXPECT_EQ(0, s.proxy_hits());
  17428. EXPECT_EQ(1, s.target_hits());
  17429. }
  17430. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17431. ProxyAndTargetServers s;
  17432. Client cli("::1", s.target_port());
  17433. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17434. cli.set_proxy("127.0.0.1", s.proxy_port());
  17435. cli.set_no_proxy({"[::1]"});
  17436. auto res = cli.Get("/");
  17437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17438. EXPECT_EQ(0, s.proxy_hits());
  17439. EXPECT_EQ(1, s.target_hits());
  17440. }
  17441. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17442. ProxyAndTargetServers s;
  17443. Client cli("fe80::1", s.target_port());
  17444. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17445. cli.set_proxy("127.0.0.1", s.proxy_port());
  17446. cli.set_no_proxy({"[fe80::]/10"});
  17447. auto res = cli.Get("/");
  17448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17449. EXPECT_EQ(0, s.proxy_hits());
  17450. EXPECT_EQ(1, s.target_hits());
  17451. }
  17452. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17453. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17454. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17455. // tricks via address-family conversion.
  17456. ProxyAndTargetServers s;
  17457. Client cli("::ffff:127.0.0.1", s.target_port());
  17458. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17459. cli.set_proxy("127.0.0.1", s.proxy_port());
  17460. cli.set_no_proxy({"127.0.0.1"});
  17461. auto res = cli.Get("/");
  17462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17463. EXPECT_GE(s.proxy_hits(), 1);
  17464. EXPECT_EQ(0, s.target_hits());
  17465. }
  17466. TEST(NoProxyTest, IPv4CidrMatch) {
  17467. ProxyAndTargetServers s;
  17468. Client cli("127.0.0.1", s.target_port());
  17469. cli.set_proxy("127.0.0.1", s.proxy_port());
  17470. cli.set_no_proxy({"127.0.0.0/8"});
  17471. auto res = cli.Get("/");
  17472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17473. EXPECT_EQ(0, s.proxy_hits());
  17474. EXPECT_EQ(1, s.target_hits());
  17475. }
  17476. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17477. ProxyAndTargetServers s;
  17478. Client cli("127.0.0.1", s.target_port());
  17479. cli.set_proxy("127.0.0.1", s.proxy_port());
  17480. cli.set_no_proxy({"10.0.0.0/8"});
  17481. auto res = cli.Get("/");
  17482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17483. EXPECT_GE(s.proxy_hits(), 1);
  17484. EXPECT_EQ(0, s.target_hits());
  17485. }
  17486. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17487. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17488. // IPv4 target matches.
  17489. ProxyAndTargetServers s;
  17490. Client cli("127.0.0.1", s.target_port());
  17491. cli.set_proxy("127.0.0.1", s.proxy_port());
  17492. cli.set_no_proxy({"0.0.0.0/0"});
  17493. auto res = cli.Get("/");
  17494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17495. EXPECT_EQ(0, s.proxy_hits());
  17496. EXPECT_EQ(1, s.target_hits());
  17497. }
  17498. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  17499. ProxyAndTargetServers s;
  17500. Client cli("127.0.0.1", s.target_port());
  17501. cli.set_proxy("127.0.0.1", s.proxy_port());
  17502. cli.set_no_proxy({"127.0.0.1"});
  17503. auto res = cli.Get("/");
  17504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17505. EXPECT_EQ(0, s.proxy_hits());
  17506. EXPECT_EQ(1, s.target_hits());
  17507. }
  17508. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  17509. ProxyAndTargetServers s;
  17510. Client cli("127.0.0.1", s.target_port());
  17511. cli.set_proxy("127.0.0.1", s.proxy_port());
  17512. cli.set_no_proxy({"127.0.0.0/33"});
  17513. auto res = cli.Get("/");
  17514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17515. EXPECT_GE(s.proxy_hits(), 1);
  17516. EXPECT_EQ(0, s.target_hits());
  17517. }
  17518. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  17519. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17520. ProxyAndTargetServers s;
  17521. Client cli("127.0.0.1", s.target_port());
  17522. cli.set_proxy("127.0.0.1", s.proxy_port());
  17523. cli.set_no_proxy({"127.0.0.1/"});
  17524. auto res = cli.Get("/");
  17525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17526. EXPECT_GE(s.proxy_hits(), 1);
  17527. EXPECT_EQ(0, s.target_hits());
  17528. }
  17529. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17530. ProxyAndTargetServers s;
  17531. auto cli = make_client("internal.corp", s);
  17532. cli->set_proxy_basic_auth("u", "p");
  17533. cli->set_no_proxy({"internal.corp"});
  17534. auto res = cli->Get("/");
  17535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17536. EXPECT_EQ(1, s.target_hits());
  17537. EXPECT_EQ(0, s.proxy_hits());
  17538. EXPECT_FALSE(s.last_had_proxy_authz())
  17539. << "Proxy-Authorization must not be sent direct to the target";
  17540. }
  17541. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17542. ProxyAndTargetServers s;
  17543. auto cli = make_client("public.example", s);
  17544. cli->set_proxy_basic_auth("u", "p");
  17545. cli->set_no_proxy({"internal.corp"}); // does not match
  17546. auto res = cli->Get("/");
  17547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17548. EXPECT_GE(s.proxy_hits(), 1);
  17549. EXPECT_TRUE(s.last_had_proxy_authz());
  17550. }
  17551. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17552. ProxyAndTargetServers s;
  17553. auto cli = make_client("anything.test", s);
  17554. auto res = cli->Get("/");
  17555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17556. EXPECT_GE(s.proxy_hits(), 1);
  17557. EXPECT_EQ(0, s.target_hits());
  17558. }
  17559. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17560. ProxyAndTargetServers s;
  17561. auto cli = make_client("example.com", s);
  17562. cli->set_no_proxy({"example.com:8080"});
  17563. auto res = cli->Get("/");
  17564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17565. EXPECT_GE(s.proxy_hits(), 1);
  17566. EXPECT_EQ(0, s.target_hits());
  17567. }
  17568. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17569. ProxyAndTargetServers s;
  17570. auto cli = make_client("anything.test", s);
  17571. cli->set_no_proxy({"", " ", "\t"});
  17572. auto res = cli->Get("/");
  17573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17574. EXPECT_GE(s.proxy_hits(), 1);
  17575. EXPECT_EQ(0, s.target_hits());
  17576. }
  17577. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17578. // An entry with leading/trailing whitespace must still match — env-style
  17579. // values are commonly pasted with stray spaces and an implementation
  17580. // that feeds the raw token directly to inet_pton would fail to match
  17581. // valid CIDRs because of the spaces.
  17582. ProxyAndTargetServers s;
  17583. Client cli("127.0.0.1", s.target_port());
  17584. cli.set_proxy("127.0.0.1", s.proxy_port());
  17585. cli.set_no_proxy({" 127.0.0.0/8 "});
  17586. auto res = cli.Get("/");
  17587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17588. EXPECT_EQ(0, s.proxy_hits());
  17589. EXPECT_EQ(1, s.target_hits());
  17590. }
  17591. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17592. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17593. // go direct and must NOT carry Proxy-Authorization.
  17594. std::atomic<int> proxy_hits{0};
  17595. std::atomic<int> target_hits{0};
  17596. std::atomic<bool> target_saw_authz{false};
  17597. no_proxy_test::ScopedServer proxy_mock, target;
  17598. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17599. proxy_hits++;
  17600. res.status = 302;
  17601. res.set_header("Location", "http://127.0.0.1:" +
  17602. std::to_string(target.port()) + "/landed");
  17603. });
  17604. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17605. target_hits++;
  17606. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17607. res.set_content("direct", "text/plain");
  17608. });
  17609. proxy_mock.listen();
  17610. target.listen();
  17611. Client cli("public.example", target.port());
  17612. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17613. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17614. cli.set_proxy_basic_auth("u", "p");
  17615. cli.set_no_proxy({"127.0.0.1"});
  17616. cli.set_follow_location(true);
  17617. auto res = cli.Get("/redir");
  17618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17619. EXPECT_GE(proxy_hits.load(), 1);
  17620. EXPECT_GE(target_hits.load(), 1);
  17621. EXPECT_FALSE(target_saw_authz.load());
  17622. }
  17623. #ifdef CPPHTTPLIB_SSL_ENABLED
  17624. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17625. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17626. // proxy creds would be sent to the (possibly hostile) origin.
  17627. std::atomic<int> target_hits{0};
  17628. std::atomic<bool> target_saw_proxy_authz{false};
  17629. no_proxy_test::ScopedServer target;
  17630. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17631. target_hits++;
  17632. if (req.has_header("Proxy-Authorization")) {
  17633. target_saw_proxy_authz = true;
  17634. }
  17635. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17636. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17637. "nonce=\"abc\", algorithm=MD5");
  17638. });
  17639. target.listen();
  17640. // The proxy address is set to the target's port: the bypass MUST kick in;
  17641. // if it doesn't, the test still routes "via proxy" to the same server and
  17642. // the Proxy-Authorization assertion below catches the leak.
  17643. Client cli("evil.example", target.port());
  17644. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17645. cli.set_proxy("127.0.0.1", target.port());
  17646. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17647. cli.set_no_proxy({"evil.example"});
  17648. auto res = cli.Get("/x");
  17649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17650. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17651. EXPECT_EQ(1, target_hits.load());
  17652. EXPECT_FALSE(target_saw_proxy_authz.load());
  17653. }
  17654. #endif
  17655. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17656. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17657. std::atomic<int> proxy_hits{0};
  17658. std::atomic<int> bypass_hits{0};
  17659. std::atomic<bool> proxy_saw_c_url{false};
  17660. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17661. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17662. proxy_hits++;
  17663. if (req.path.find("/start") != std::string::npos) {
  17664. res.status = 302;
  17665. res.set_header("Location", "http://127.0.0.1:" +
  17666. std::to_string(bypass_server.port()) +
  17667. "/middle");
  17668. return;
  17669. }
  17670. if (req.path.find("/end") != std::string::npos) {
  17671. proxy_saw_c_url = true;
  17672. res.set_content("c-via-proxy", "text/plain");
  17673. return;
  17674. }
  17675. res.set_content("unexpected", "text/plain");
  17676. });
  17677. // public.example's "advertised" port is arbitrary (the request never lands
  17678. // there — it goes through the proxy), but use a dynamic value to stay
  17679. // friendly with sharded parallel runs.
  17680. int public_port = bypass_server.port();
  17681. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17682. bypass_hits++;
  17683. res.status = 302;
  17684. res.set_header("Location", "http://public.example:" +
  17685. std::to_string(public_port) + "/end");
  17686. });
  17687. proxy_mock.listen();
  17688. bypass_server.listen();
  17689. Client cli("public.example", public_port);
  17690. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17691. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17692. cli.set_no_proxy({"127.0.0.1"});
  17693. cli.set_follow_location(true);
  17694. auto res = cli.Get("/start");
  17695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17696. EXPECT_EQ(StatusCode::OK_200, res->status);
  17697. EXPECT_EQ("c-via-proxy", res->body);
  17698. EXPECT_GE(proxy_hits.load(), 2);
  17699. EXPECT_GE(bypass_hits.load(), 1);
  17700. EXPECT_TRUE(proxy_saw_c_url.load());
  17701. }
  17702. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17703. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17704. // request reconnects to the correct endpoint.
  17705. std::atomic<int> proxy_hits{0};
  17706. std::atomic<int> target_hits{0};
  17707. no_proxy_test::ScopedServer proxy_mock, target;
  17708. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17709. proxy_hits++;
  17710. res.set_content("via-proxy", "text/plain");
  17711. });
  17712. target.svr().Get(".*", [&](const Request &, Response &res) {
  17713. target_hits++;
  17714. res.set_content("direct", "text/plain");
  17715. });
  17716. proxy_mock.listen();
  17717. target.listen();
  17718. Client cli("public.example", target.port());
  17719. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17720. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17721. cli.set_keep_alive(true);
  17722. auto res1 = cli.Get("/a");
  17723. ASSERT_TRUE(res1);
  17724. EXPECT_EQ("via-proxy", res1->body);
  17725. EXPECT_EQ(1, proxy_hits.load());
  17726. EXPECT_EQ(0, target_hits.load());
  17727. cli.set_no_proxy({"public.example"});
  17728. auto res2 = cli.Get("/b");
  17729. ASSERT_TRUE(res2);
  17730. EXPECT_EQ("direct", res2->body);
  17731. EXPECT_EQ(1, proxy_hits.load());
  17732. EXPECT_EQ(1, target_hits.load());
  17733. }
  17734. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17735. namespace proxy_tunnel_test {
  17736. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17737. class ScopedSSLServer {
  17738. public:
  17739. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17740. port_ = svr_.bind_to_any_port("127.0.0.1");
  17741. }
  17742. ~ScopedSSLServer() {
  17743. svr_.stop();
  17744. if (th_.joinable()) { th_.join(); }
  17745. }
  17746. SSLServer &svr() { return svr_; }
  17747. int port() const { return port_; }
  17748. void listen() {
  17749. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17750. svr_.wait_until_ready();
  17751. }
  17752. private:
  17753. SSLServer svr_;
  17754. std::thread th_;
  17755. int port_ = 0;
  17756. };
  17757. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17758. class ScopedConnectProxy {
  17759. public:
  17760. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17761. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17762. if (listen_fd_ < 0) { return; }
  17763. int yes = 1;
  17764. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17765. sockaddr_in a{};
  17766. a.sin_family = AF_INET;
  17767. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17768. a.sin_port = 0;
  17769. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17770. return;
  17771. }
  17772. socklen_t alen = sizeof(a);
  17773. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17774. 0) {
  17775. return;
  17776. }
  17777. port_ = ntohs(a.sin_port);
  17778. if (::listen(listen_fd_, 1) != 0) { return; }
  17779. th_ = std::thread([this] { run(); });
  17780. }
  17781. ~ScopedConnectProxy() {
  17782. stop_ = true;
  17783. if (listen_fd_ >= 0) {
  17784. ::shutdown(listen_fd_, SHUT_RDWR);
  17785. ::close(listen_fd_);
  17786. }
  17787. if (th_.joinable()) { th_.join(); }
  17788. }
  17789. int port() const { return port_; }
  17790. int connect_hits() const { return connect_hits_.load(); }
  17791. private:
  17792. void run() {
  17793. while (!stop_.load()) {
  17794. fd_set rfds;
  17795. FD_ZERO(&rfds);
  17796. FD_SET(listen_fd_, &rfds);
  17797. timeval tv{0, 100 * 1000};
  17798. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17799. if (sel <= 0) { continue; }
  17800. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17801. if (client_fd < 0) { continue; }
  17802. std::string req;
  17803. char buf[2048];
  17804. while (req.find("\r\n\r\n") == std::string::npos) {
  17805. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17806. if (n <= 0) { break; }
  17807. req.append(buf, static_cast<size_t>(n));
  17808. }
  17809. if (req.compare(0, 7, "CONNECT") != 0) {
  17810. ::close(client_fd);
  17811. continue;
  17812. }
  17813. connect_hits_++;
  17814. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17815. ::send(client_fd, ok, std::strlen(ok), 0);
  17816. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17817. sockaddr_in o{};
  17818. o.sin_family = AF_INET;
  17819. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17820. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17821. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17822. 0) {
  17823. ::close(client_fd);
  17824. ::close(origin_fd);
  17825. continue;
  17826. }
  17827. auto forward = [](int from, int to) {
  17828. char b[8192];
  17829. for (;;) {
  17830. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17831. if (n <= 0) { break; }
  17832. ssize_t off = 0;
  17833. while (off < n) {
  17834. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17835. if (s <= 0) {
  17836. off = n;
  17837. break;
  17838. }
  17839. off += s;
  17840. }
  17841. }
  17842. ::shutdown(to, SHUT_WR);
  17843. };
  17844. std::thread t1([&] { forward(client_fd, origin_fd); });
  17845. std::thread t2([&] { forward(origin_fd, client_fd); });
  17846. t1.join();
  17847. t2.join();
  17848. ::close(client_fd);
  17849. ::close(origin_fd);
  17850. }
  17851. }
  17852. int forward_port_ = -1;
  17853. int listen_fd_ = -1;
  17854. int port_ = 0;
  17855. std::thread th_;
  17856. std::atomic<bool> stop_{false};
  17857. std::atomic<int> connect_hits_{0};
  17858. };
  17859. } // namespace proxy_tunnel_test
  17860. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17861. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17862. // retry; otherwise proxy creds would be sent to the origin.
  17863. std::atomic<int> origin_hits{0};
  17864. std::atomic<bool> origin_saw_proxy_authz{false};
  17865. proxy_tunnel_test::ScopedSSLServer origin;
  17866. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17867. origin_hits++;
  17868. if (req.has_header("Proxy-Authorization")) {
  17869. origin_saw_proxy_authz = true;
  17870. }
  17871. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17872. res.set_header("Proxy-Authenticate",
  17873. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17874. "algorithm=MD5");
  17875. });
  17876. origin.listen();
  17877. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17878. ASSERT_NE(0, proxy.port());
  17879. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  17880. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  17881. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  17882. // and answer with its own status, making this test flaky.
  17883. SSLClient cli("127.0.0.1", origin.port());
  17884. cli.enable_server_certificate_verification(false);
  17885. cli.set_proxy("127.0.0.1", proxy.port());
  17886. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17887. auto res = cli.Get("/x");
  17888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17889. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17890. EXPECT_EQ(1, origin_hits.load());
  17891. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17892. EXPECT_EQ(1, proxy.connect_hits());
  17893. }
  17894. #endif