test.cc 679 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371
  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. class WebSocketIntegrationTest : public ::testing::Test {
  16174. protected:
  16175. void SetUp() override {
  16176. server_ = httplib::detail::make_unique<Server>();
  16177. setup_server();
  16178. start_server();
  16179. }
  16180. void TearDown() override {
  16181. server_->stop();
  16182. if (server_thread_.joinable()) { server_thread_.join(); }
  16183. }
  16184. void setup_server() {
  16185. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16186. std::string msg;
  16187. ws::ReadResult ret;
  16188. while ((ret = ws.read(msg))) {
  16189. if (ret == ws::Binary) {
  16190. ws.send(msg.data(), msg.size());
  16191. } else {
  16192. ws.send(msg);
  16193. }
  16194. }
  16195. });
  16196. server_->WebSocket("/ws-echo-string",
  16197. [](const Request &, ws::WebSocket &ws) {
  16198. std::string msg;
  16199. while (ws.read(msg)) {
  16200. ws.send("echo: " + msg);
  16201. }
  16202. });
  16203. server_->WebSocket(
  16204. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  16205. // Echo back request metadata
  16206. ws.send("path:" + req.path);
  16207. ws.send("header:" + req.get_header_value("X-Test-Header"));
  16208. std::string msg;
  16209. while (ws.read(msg)) {}
  16210. });
  16211. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  16212. std::string msg;
  16213. ws.read(msg); // wait for a message
  16214. ws.close();
  16215. });
  16216. server_->WebSocket("/ws-close-status",
  16217. [](const Request &, ws::WebSocket &ws) {
  16218. std::string msg;
  16219. ws.read(msg); // wait for a message
  16220. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  16221. });
  16222. server_->WebSocket(
  16223. "/ws-subprotocol",
  16224. [](const Request &, ws::WebSocket &ws) {
  16225. std::string msg;
  16226. while (ws.read(msg)) {
  16227. ws.send(msg);
  16228. }
  16229. },
  16230. [](const std::vector<std::string> &protocols) -> std::string {
  16231. for (const auto &p : protocols) {
  16232. if (p == "graphql-ws") { return p; }
  16233. }
  16234. return "";
  16235. });
  16236. }
  16237. void start_server() {
  16238. port_ = server_->bind_to_any_port(HOST);
  16239. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16240. server_->wait_until_ready();
  16241. }
  16242. std::unique_ptr<Server> server_;
  16243. std::thread server_thread_;
  16244. int port_ = 0;
  16245. };
  16246. TEST_F(WebSocketIntegrationTest, TextEcho) {
  16247. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16248. "/ws-echo");
  16249. ASSERT_TRUE(client.connect());
  16250. ASSERT_TRUE(client.is_open());
  16251. ASSERT_TRUE(client.send("Hello WebSocket"));
  16252. std::string msg;
  16253. EXPECT_EQ(ws::Text, client.read(msg));
  16254. EXPECT_EQ("Hello WebSocket", msg);
  16255. client.close();
  16256. }
  16257. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  16258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16259. "/ws-echo");
  16260. ASSERT_TRUE(client.connect());
  16261. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  16262. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  16263. std::string msg;
  16264. EXPECT_EQ(ws::Binary, client.read(msg));
  16265. EXPECT_EQ(binary_data, msg);
  16266. client.close();
  16267. }
  16268. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  16269. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16270. "/ws-echo");
  16271. ASSERT_TRUE(client.connect());
  16272. for (int i = 0; i < 10; i++) {
  16273. auto text = "message " + std::to_string(i);
  16274. ASSERT_TRUE(client.send(text));
  16275. std::string msg;
  16276. ASSERT_TRUE(client.read(msg));
  16277. EXPECT_EQ(text, msg);
  16278. }
  16279. client.close();
  16280. }
  16281. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  16282. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16283. "/ws-close");
  16284. ASSERT_TRUE(client.connect());
  16285. // Send a message to trigger the server to close
  16286. ASSERT_TRUE(client.send("trigger close"));
  16287. // The server will close, so read should return false
  16288. std::string msg;
  16289. EXPECT_FALSE(client.read(msg));
  16290. EXPECT_FALSE(client.is_open());
  16291. }
  16292. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  16293. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16294. "/ws-echo");
  16295. ASSERT_TRUE(client.connect());
  16296. // 128KB message
  16297. std::string large_data(128 * 1024, 'X');
  16298. ASSERT_TRUE(client.send(large_data));
  16299. std::string msg;
  16300. ASSERT_TRUE(client.read(msg));
  16301. EXPECT_EQ(large_data, msg);
  16302. client.close();
  16303. }
  16304. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  16305. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16306. "/ws-echo");
  16307. ASSERT_TRUE(client.connect());
  16308. const int num_threads = 4;
  16309. std::vector<std::thread> threads;
  16310. std::atomic<int> send_count{0};
  16311. for (int t = 0; t < num_threads; t++) {
  16312. threads.emplace_back([&client, &send_count, t]() {
  16313. for (int i = 0; i < 5; i++) {
  16314. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  16315. if (client.send(text)) { send_count++; }
  16316. }
  16317. });
  16318. }
  16319. for (auto &th : threads) {
  16320. th.join();
  16321. }
  16322. int received = 0;
  16323. std::string msg;
  16324. while (received < send_count.load()) {
  16325. if (!client.read(msg)) { break; }
  16326. received++;
  16327. }
  16328. EXPECT_EQ(send_count.load(), received);
  16329. client.close();
  16330. }
  16331. TEST_F(WebSocketIntegrationTest, ReadString) {
  16332. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16333. "/ws-echo-string");
  16334. ASSERT_TRUE(client.connect());
  16335. ASSERT_TRUE(client.send("hello"));
  16336. std::string msg;
  16337. ASSERT_TRUE(client.read(msg));
  16338. EXPECT_EQ("echo: hello", msg);
  16339. ASSERT_TRUE(client.send("world"));
  16340. ASSERT_TRUE(client.read(msg));
  16341. EXPECT_EQ("echo: world", msg);
  16342. client.close();
  16343. }
  16344. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  16345. Headers headers = {{"X-Test-Header", "test-value"}};
  16346. ws::WebSocketClient client(
  16347. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  16348. ASSERT_TRUE(client.connect());
  16349. std::string msg;
  16350. ASSERT_TRUE(client.read(msg));
  16351. EXPECT_EQ("path:/ws-request-info", msg);
  16352. ASSERT_TRUE(client.read(msg));
  16353. EXPECT_EQ("header:test-value", msg);
  16354. client.close();
  16355. }
  16356. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  16357. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16358. "/ws-echo");
  16359. client.set_read_timeout(1, 0); // 1 second
  16360. ASSERT_TRUE(client.connect());
  16361. // Don't send anything — server echo handler waits for a message,
  16362. // so read() should time out and return false.
  16363. std::string msg;
  16364. EXPECT_FALSE(client.read(msg));
  16365. }
  16366. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  16367. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16368. "/ws-echo");
  16369. client.set_read_timeout(5, 0);
  16370. ASSERT_TRUE(client.connect());
  16371. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16372. // The server should reject it and close the connection.
  16373. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  16374. client.send(oversized);
  16375. // The server's read() should have failed due to payload limit,
  16376. // so our read() should return false (connection closed).
  16377. std::string msg;
  16378. EXPECT_FALSE(client.read(msg));
  16379. }
  16380. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  16381. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16382. "/ws-echo");
  16383. client.set_read_timeout(10, 0);
  16384. ASSERT_TRUE(client.connect());
  16385. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  16386. // This should succeed.
  16387. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  16388. ASSERT_TRUE(client.send(at_limit));
  16389. std::string msg;
  16390. ASSERT_TRUE(client.read(msg));
  16391. EXPECT_EQ(at_limit.size(), msg.size());
  16392. client.close();
  16393. }
  16394. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  16395. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16396. "/nonexistent");
  16397. EXPECT_FALSE(client.connect());
  16398. EXPECT_FALSE(client.is_open());
  16399. }
  16400. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  16401. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16402. "/ws-echo");
  16403. ASSERT_TRUE(client.connect());
  16404. ASSERT_TRUE(client.send(""));
  16405. std::string msg;
  16406. EXPECT_EQ(ws::Text, client.read(msg));
  16407. EXPECT_EQ("", msg);
  16408. client.close();
  16409. }
  16410. TEST_F(WebSocketIntegrationTest, Reconnect) {
  16411. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16412. "/ws-echo");
  16413. // First connection
  16414. ASSERT_TRUE(client.connect());
  16415. ASSERT_TRUE(client.send("first"));
  16416. std::string msg;
  16417. ASSERT_TRUE(client.read(msg));
  16418. EXPECT_EQ("first", msg);
  16419. client.close();
  16420. EXPECT_FALSE(client.is_open());
  16421. // Reconnect using the same client object
  16422. ASSERT_TRUE(client.connect());
  16423. ASSERT_TRUE(client.is_open());
  16424. ASSERT_TRUE(client.send("second"));
  16425. ASSERT_TRUE(client.read(msg));
  16426. EXPECT_EQ("second", msg);
  16427. client.close();
  16428. }
  16429. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  16430. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16431. "/ws-close-status");
  16432. ASSERT_TRUE(client.connect());
  16433. // Trigger the server to close with GoingAway status
  16434. ASSERT_TRUE(client.send("trigger"));
  16435. // read() should return false after receiving the close frame
  16436. std::string msg;
  16437. EXPECT_FALSE(client.read(msg));
  16438. EXPECT_FALSE(client.is_open());
  16439. }
  16440. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  16441. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16442. "/ws-echo");
  16443. ASSERT_TRUE(client.connect());
  16444. client.close(ws::CloseStatus::GoingAway, "client leaving");
  16445. EXPECT_FALSE(client.is_open());
  16446. }
  16447. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  16448. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  16449. ws::WebSocketClient client(
  16450. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16451. ASSERT_TRUE(client.connect());
  16452. // Server should have selected graphql-ws
  16453. EXPECT_EQ("graphql-ws", client.subprotocol());
  16454. client.close();
  16455. }
  16456. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  16457. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  16458. ws::WebSocketClient client(
  16459. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  16460. ASSERT_TRUE(client.connect());
  16461. // Server should not have selected any subprotocol
  16462. EXPECT_TRUE(client.subprotocol().empty());
  16463. client.close();
  16464. }
  16465. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  16466. // Connect without requesting any subprotocol
  16467. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16468. "/ws-subprotocol");
  16469. ASSERT_TRUE(client.connect());
  16470. EXPECT_TRUE(client.subprotocol().empty());
  16471. client.close();
  16472. }
  16473. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  16474. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  16475. "/ws-echo");
  16476. client.set_tcp_nodelay(true);
  16477. client.set_connection_timeout(3, 0);
  16478. bool socket_options_called = false;
  16479. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  16480. ASSERT_TRUE(client.connect());
  16481. ASSERT_TRUE(client.is_open());
  16482. EXPECT_TRUE(socket_options_called);
  16483. ASSERT_TRUE(client.send("hello"));
  16484. std::string msg;
  16485. auto result = client.read(msg);
  16486. EXPECT_EQ(result, ws::ReadResult::Text);
  16487. EXPECT_EQ(msg, "hello");
  16488. client.close();
  16489. }
  16490. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  16491. Server svr;
  16492. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  16493. if (!req.has_header("Authorization")) {
  16494. res.status = StatusCode::Unauthorized_401;
  16495. res.set_content("Unauthorized", "text/plain");
  16496. return Server::HandlerResponse::Handled;
  16497. }
  16498. return Server::HandlerResponse::Unhandled;
  16499. });
  16500. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  16501. std::string msg;
  16502. while (ws.read(msg)) {
  16503. ws.send(msg);
  16504. }
  16505. });
  16506. auto port = svr.bind_to_any_port("localhost");
  16507. std::thread t([&]() { svr.listen_after_bind(); });
  16508. svr.wait_until_ready();
  16509. // Without Authorization header - should be rejected before upgrade
  16510. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  16511. EXPECT_FALSE(client1.connect());
  16512. // With Authorization header - should succeed
  16513. Headers headers = {{"Authorization", "Bearer token123"}};
  16514. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  16515. headers);
  16516. ASSERT_TRUE(client2.connect());
  16517. ASSERT_TRUE(client2.send("hello"));
  16518. std::string msg;
  16519. ASSERT_TRUE(client2.read(msg));
  16520. EXPECT_EQ("hello", msg);
  16521. client2.close();
  16522. svr.stop();
  16523. t.join();
  16524. }
  16525. TEST(WebSocketTest, QueryStringInHandshake) {
  16526. Server svr;
  16527. std::mutex mtx;
  16528. std::string received_target;
  16529. std::string received_token;
  16530. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16531. {
  16532. std::lock_guard<std::mutex> lock(mtx);
  16533. received_target = req.target;
  16534. if (req.has_param("token")) {
  16535. received_token = req.get_param_value("token");
  16536. }
  16537. }
  16538. std::string msg;
  16539. while (ws.read(msg)) {
  16540. ws.send(msg);
  16541. }
  16542. });
  16543. auto port = svr.bind_to_any_port("localhost");
  16544. std::thread t([&]() { svr.listen_after_bind(); });
  16545. svr.wait_until_ready();
  16546. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  16547. "/ws?token=ABC&session=123");
  16548. ASSERT_TRUE(client.connect());
  16549. // Round-trip ensures the handler has run and captured the request.
  16550. ASSERT_TRUE(client.send("hello"));
  16551. std::string msg;
  16552. ASSERT_TRUE(client.read(msg));
  16553. EXPECT_EQ("hello", msg);
  16554. client.close();
  16555. {
  16556. std::lock_guard<std::mutex> lock(mtx);
  16557. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  16558. EXPECT_EQ("ABC", received_token);
  16559. }
  16560. svr.stop();
  16561. t.join();
  16562. }
  16563. // Run a handshake against a throwaway server and hand the request the server
  16564. // received back to the caller, so tests can assert on the headers the client
  16565. // actually put on the wire.
  16566. static void capture_websocket_handshake_request(
  16567. const Headers &client_headers,
  16568. std::function<void(const Request &, int port)> verify) {
  16569. Server svr;
  16570. std::mutex mtx;
  16571. Request received;
  16572. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16573. {
  16574. std::lock_guard<std::mutex> lock(mtx);
  16575. received = req;
  16576. }
  16577. std::string msg;
  16578. while (ws.read(msg)) {
  16579. ws.send(msg);
  16580. }
  16581. });
  16582. auto port = svr.bind_to_any_port("localhost");
  16583. std::thread t([&]() { svr.listen_after_bind(); });
  16584. auto se = detail::scope_exit([&] {
  16585. svr.stop();
  16586. t.join();
  16587. });
  16588. svr.wait_until_ready();
  16589. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  16590. client_headers);
  16591. ASSERT_TRUE(client.connect());
  16592. ASSERT_TRUE(client.send("hello"));
  16593. std::string msg;
  16594. ASSERT_TRUE(client.read(msg));
  16595. client.close();
  16596. {
  16597. std::lock_guard<std::mutex> lock(mtx);
  16598. verify(received, port);
  16599. }
  16600. }
  16601. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  16602. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  16603. // Non-default port must be present in the Host header. Default ports
  16604. // (80/443) are omitted; that logic is covered by
  16605. // MakeHostAndPortStringTest.
  16606. EXPECT_EQ("localhost:" + std::to_string(port),
  16607. req.get_header_value("Host"));
  16608. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  16609. req.get_header_value("User-Agent"));
  16610. EXPECT_FALSE(req.has_header("Accept"));
  16611. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  16612. EXPECT_FALSE(req.has_header("Content-Length"));
  16613. });
  16614. }
  16615. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  16616. capture_websocket_handshake_request(
  16617. {{"Host", "example.com"},
  16618. {"User-Agent", "custom-agent"},
  16619. {"X-Custom", "value"}},
  16620. [](const Request &req, int) {
  16621. EXPECT_EQ("example.com", req.get_header_value("Host"));
  16622. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  16623. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  16624. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  16625. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  16626. });
  16627. }
  16628. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  16629. capture_websocket_handshake_request(
  16630. {{"Upgrade", "bogus"},
  16631. {"Connection", "close"},
  16632. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  16633. {"Sec-WebSocket-Version", "8"}},
  16634. [](const Request &req, int) {
  16635. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  16636. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  16637. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  16638. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  16639. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  16640. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  16641. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  16642. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  16643. req.get_header_value("Sec-WebSocket-Key"));
  16644. });
  16645. }
  16646. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  16647. // A header the client refuses to send must abort the handshake before any
  16648. // part of it reaches the wire; a lone request line would otherwise sit in
  16649. // the peer's buffer as a truncated request.
  16650. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16651. ASSERT_NE(INVALID_SOCKET, srv);
  16652. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  16653. sockaddr_in addr{};
  16654. addr.sin_family = AF_INET;
  16655. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  16656. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16657. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16658. ASSERT_EQ(0, ::listen(srv, 1));
  16659. sockaddr_in bound{};
  16660. socklen_t bound_len = sizeof(bound);
  16661. ASSERT_EQ(
  16662. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  16663. auto port = ntohs(bound.sin_port);
  16664. ssize_t received = -1;
  16665. std::thread t([&] {
  16666. // Bound every blocking call so a regression fails the test with a bad
  16667. // value instead of hanging the suite.
  16668. fd_set rfds;
  16669. FD_ZERO(&rfds);
  16670. FD_SET(srv, &rfds);
  16671. timeval tv{5, 0};
  16672. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  16673. 0) {
  16674. return;
  16675. }
  16676. sockaddr_in cli_addr{};
  16677. socklen_t cli_len = sizeof(cli_addr);
  16678. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16679. if (cli == INVALID_SOCKET) { return; }
  16680. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  16681. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  16682. char buf[4096];
  16683. received = ::recv(cli, buf, sizeof(buf), 0);
  16684. });
  16685. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  16686. // connect() has already shut the socket down by the time it returns false,
  16687. // so the peer sees EOF without waiting for the client to be destroyed.
  16688. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  16689. {{"X-Bad", "a\r\nInjected: 1"}});
  16690. EXPECT_FALSE(client.connect());
  16691. t.join();
  16692. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  16693. EXPECT_EQ(0, received);
  16694. }
  16695. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  16696. // The socket path doubles as the URL host, so it must not contain '/'.
  16697. const char *shard = getenv("GTEST_SHARD_INDEX");
  16698. const std::string sock_path =
  16699. shard ? std::string("httplib-ws-") + shard + ".sock"
  16700. : std::string("httplib-ws.sock");
  16701. std::remove(sock_path.c_str());
  16702. Server svr;
  16703. std::mutex mtx;
  16704. std::string received_host;
  16705. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  16706. {
  16707. std::lock_guard<std::mutex> lock(mtx);
  16708. received_host = req.get_header_value("Host");
  16709. }
  16710. std::string msg;
  16711. while (ws.read(msg)) {
  16712. ws.send(msg);
  16713. }
  16714. });
  16715. svr.set_address_family(AF_UNIX);
  16716. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  16717. auto se = detail::scope_exit([&] {
  16718. svr.stop();
  16719. t.join();
  16720. std::remove(sock_path.c_str());
  16721. });
  16722. svr.wait_until_ready();
  16723. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  16724. client.set_address_family(AF_UNIX);
  16725. ASSERT_TRUE(client.connect());
  16726. ASSERT_TRUE(client.send("hello"));
  16727. std::string msg;
  16728. ASSERT_TRUE(client.read(msg));
  16729. client.close();
  16730. {
  16731. std::lock_guard<std::mutex> lock(mtx);
  16732. // There is no host:port for a Unix socket, so the same "localhost"
  16733. // placeholder the HTTP client uses is expected.
  16734. EXPECT_EQ("localhost", received_host);
  16735. }
  16736. }
  16737. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  16738. class WebSocketSSLIntegrationTest : public ::testing::Test {
  16739. protected:
  16740. void SetUp() override {
  16741. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  16742. SERVER_PRIVATE_KEY_FILE);
  16743. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  16744. std::string msg;
  16745. ws::ReadResult ret;
  16746. while ((ret = ws.read(msg))) {
  16747. if (ret == ws::Binary) {
  16748. ws.send(msg.data(), msg.size());
  16749. } else {
  16750. ws.send(msg);
  16751. }
  16752. }
  16753. });
  16754. port_ = server_->bind_to_any_port(HOST);
  16755. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16756. server_->wait_until_ready();
  16757. }
  16758. void TearDown() override {
  16759. server_->stop();
  16760. if (server_thread_.joinable()) { server_thread_.join(); }
  16761. }
  16762. std::unique_ptr<SSLServer> server_;
  16763. std::thread server_thread_;
  16764. int port_ = 0;
  16765. };
  16766. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  16767. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16768. "/ws-echo");
  16769. client.enable_server_certificate_verification(false);
  16770. ASSERT_TRUE(client.connect());
  16771. ASSERT_TRUE(client.is_open());
  16772. ASSERT_TRUE(client.send("Hello WSS"));
  16773. std::string msg;
  16774. EXPECT_EQ(ws::Text, client.read(msg));
  16775. EXPECT_EQ("Hello WSS", msg);
  16776. client.close();
  16777. }
  16778. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  16779. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  16780. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  16781. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  16782. // client (without calling close() first) is the only path that runs
  16783. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  16784. // bug exactly.
  16785. //
  16786. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  16787. // when linked against an instrumented libssl; run under Valgrind to catch it
  16788. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  16789. // suite (the freed session otherwise stalls on the close handshake) — this test
  16790. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  16791. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  16792. {
  16793. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16794. "/ws-echo");
  16795. client.enable_server_certificate_verification(false);
  16796. client.set_read_timeout(2, 0);
  16797. client.set_write_timeout(2, 0);
  16798. ASSERT_TRUE(client.connect());
  16799. ASSERT_TRUE(client.is_open());
  16800. ASSERT_TRUE(client.send("still open"));
  16801. // Intentionally do NOT call client.close(): leaving scope runs
  16802. // shutdown_and_close() with the WebSocket still open, which must send the
  16803. // close frame while the TLS session is still alive.
  16804. }
  16805. }
  16806. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  16807. // shutdown_and_close() at the start of connect(), reproducing the same
  16808. // use-after-free within the test body rather than at scope exit. The second
  16809. // connect must succeed and echo, proving the close handshake ran over a live
  16810. // session. See the note above about memory-tool requirements.
  16811. TEST_F(WebSocketSSLIntegrationTest,
  16812. ReconnectWhileOpenSendsCloseOverLiveSession) {
  16813. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  16814. "/ws-echo");
  16815. client.enable_server_certificate_verification(false);
  16816. client.set_read_timeout(2, 0);
  16817. client.set_write_timeout(2, 0);
  16818. ASSERT_TRUE(client.connect());
  16819. ASSERT_TRUE(client.is_open());
  16820. ASSERT_TRUE(client.send("still open"));
  16821. // Reconnect without closing first: connect() calls shutdown_and_close() on
  16822. // the still-open connection, which must not touch a freed TLS session.
  16823. ASSERT_TRUE(client.connect());
  16824. ASSERT_TRUE(client.is_open());
  16825. ASSERT_TRUE(client.send("after reconnect"));
  16826. std::string msg;
  16827. EXPECT_EQ(ws::Text, client.read(msg));
  16828. EXPECT_EQ("after reconnect", msg);
  16829. client.close();
  16830. }
  16831. #endif
  16832. #ifdef CPPHTTPLIB_SSL_ENABLED
  16833. class WebSocketSSLCATest : public ::testing::Test {
  16834. protected:
  16835. void SetUp() override {
  16836. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  16837. SERVER_PRIVATE_KEY_FILE);
  16838. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16839. std::string msg;
  16840. while (ws.read(msg)) {
  16841. ws.send(msg);
  16842. }
  16843. });
  16844. port_ = server_->bind_to_any_port("127.0.0.1");
  16845. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  16846. server_->wait_until_ready();
  16847. }
  16848. void TearDown() override {
  16849. server_->stop();
  16850. if (server_thread_.joinable()) { server_thread_.join(); }
  16851. }
  16852. std::string url() const {
  16853. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  16854. }
  16855. std::unique_ptr<SSLServer> server_;
  16856. std::thread server_thread_;
  16857. int port_ = 0;
  16858. };
  16859. // A custom CA loaded as PEM verifies the server with full certificate
  16860. // verification enabled
  16861. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  16862. ws::WebSocketClient client(url());
  16863. std::string cert;
  16864. read_file(SERVER_CERT2_FILE, cert);
  16865. client.load_ca_cert_store(cert.c_str(), cert.size());
  16866. ASSERT_TRUE(client.connect());
  16867. ASSERT_TRUE(client.send("hello"));
  16868. std::string msg;
  16869. EXPECT_EQ(ws::Text, client.read(msg));
  16870. EXPECT_EQ("hello", msg);
  16871. client.close();
  16872. }
  16873. // A custom CA that does not cover the server must fail verification (the
  16874. // custom CA is exclusive; system certs are not loaded alongside it)
  16875. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  16876. ws::WebSocketClient client(url());
  16877. std::string cert;
  16878. read_file(CLIENT_CA_CERT_FILE, cert);
  16879. client.load_ca_cert_store(cert.c_str(), cert.size());
  16880. ASSERT_FALSE(client.connect());
  16881. }
  16882. // Regression test: reconnecting with a native custom CA store used to reuse
  16883. // a store handle the previous TLS context had already freed (use-after-free
  16884. // under the OpenSSL backend). The context now lives as long as the client.
  16885. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  16886. ws::WebSocketClient client(url());
  16887. std::string cert;
  16888. read_file(SERVER_CERT2_FILE, cert);
  16889. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16890. ASSERT_TRUE(client.connect());
  16891. client.close();
  16892. ASSERT_TRUE(client.connect());
  16893. ASSERT_TRUE(client.send("again"));
  16894. std::string msg;
  16895. EXPECT_EQ(ws::Text, client.read(msg));
  16896. EXPECT_EQ("again", msg);
  16897. client.close();
  16898. }
  16899. // Regression test: a certificate with a trusted chain but no identity match
  16900. // for the server IP must be rejected. The Mbed TLS backend used to skip
  16901. // verification entirely for IP hosts, so this connection succeeded there.
  16902. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  16903. // chain verification while the identity check must still fail.
  16904. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  16905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16906. ASSERT_TRUE(svr.is_valid());
  16907. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  16908. std::string msg;
  16909. while (ws.read(msg)) {
  16910. ws.send(msg);
  16911. }
  16912. });
  16913. auto port = svr.bind_to_any_port("127.0.0.1");
  16914. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16915. auto se = detail::scope_exit([&] {
  16916. svr.stop();
  16917. t.join();
  16918. });
  16919. svr.wait_until_ready();
  16920. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  16921. "/echo");
  16922. std::string cert;
  16923. read_file(SERVER_CERT_FILE, cert);
  16924. client.load_ca_cert_store(cert.c_str(), cert.size());
  16925. ASSERT_FALSE(client.connect());
  16926. }
  16927. #endif
  16928. #if !defined(_WIN32)
  16929. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  16930. auto secret_dir = std::string("./symlink_test_secret");
  16931. auto served_dir = std::string("./symlink_test_served");
  16932. auto secret_file = secret_dir + "/secret.txt";
  16933. auto symlink_path = served_dir + "/escape";
  16934. // Setup: create directories and files
  16935. mkdir(secret_dir.c_str(), 0755);
  16936. mkdir(served_dir.c_str(), 0755);
  16937. {
  16938. std::ofstream ofs(secret_file);
  16939. ofs << "SECRET_DATA";
  16940. }
  16941. // Create symlink using absolute path so it resolves correctly
  16942. #ifdef PATH_MAX
  16943. char abs_secret[PATH_MAX];
  16944. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  16945. #else
  16946. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  16947. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  16948. ASSERT_NE(nullptr, abs_secret);
  16949. #endif
  16950. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  16951. auto se = detail::scope_exit([&] {
  16952. unlink(symlink_path.c_str());
  16953. unlink(secret_file.c_str());
  16954. rmdir(served_dir.c_str());
  16955. rmdir(secret_dir.c_str());
  16956. });
  16957. Server svr;
  16958. svr.set_mount_point("/", served_dir);
  16959. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16960. auto se2 = detail::scope_exit([&] {
  16961. svr.stop();
  16962. listen_thread.join();
  16963. });
  16964. svr.wait_until_ready();
  16965. Client cli("localhost", PORT);
  16966. // Symlink pointing outside base dir should be blocked
  16967. auto res = cli.Get("/escape/secret.txt");
  16968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16969. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16970. }
  16971. #endif
  16972. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  16973. // A GET request with Content-Length to a static file handler must have its
  16974. // body drained before the keep-alive connection is reused. Otherwise the
  16975. // unread body bytes are interpreted as the next HTTP request.
  16976. //
  16977. // The body is sent AFTER receiving the first response (as in the original
  16978. // PoC) so that the stream_line_reader cannot buffer it together with the
  16979. // headers of the first request.
  16980. Server svr;
  16981. svr.set_mount_point("/", "./www");
  16982. std::atomic<int> smuggled_count(0);
  16983. svr.Get("/smuggled", [&](const Request &, Response &res) {
  16984. smuggled_count++;
  16985. res.set_content("oops", "text/plain");
  16986. });
  16987. auto port = svr.bind_to_any_port("localhost");
  16988. thread t = thread([&] { svr.listen_after_bind(); });
  16989. auto se = detail::scope_exit([&] {
  16990. svr.stop();
  16991. t.join();
  16992. });
  16993. svr.wait_until_ready();
  16994. auto error = Error::Success;
  16995. auto sock = detail::create_client_socket(
  16996. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  16997. /*connection_timeout_sec=*/2, 0,
  16998. /*read_timeout_sec=*/2, 0,
  16999. /*write_timeout_sec=*/2, 0, std::string(), error);
  17000. ASSERT_NE(INVALID_SOCKET, sock);
  17001. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17002. // The "smuggled" request will be sent as the body of the outer GET
  17003. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  17004. "Host: localhost\r\n"
  17005. "Connection: close\r\n"
  17006. "\r\n";
  17007. // Step 1: Send only the outer request headers (no body yet)
  17008. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  17009. "Host: localhost\r\n"
  17010. "Content-Length: " +
  17011. std::to_string(smuggled.size()) +
  17012. "\r\n"
  17013. "\r\n";
  17014. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  17015. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  17016. // Step 2: Read the first response (server serves file without reading body)
  17017. std::string first_response;
  17018. char buf[4096];
  17019. for (;;) {
  17020. auto n = recv(sock, buf, sizeof(buf), 0);
  17021. if (n <= 0) break;
  17022. first_response.append(buf, static_cast<size_t>(n));
  17023. // Stop once we have a complete response (headers + body)
  17024. auto hdr_end = first_response.find("\r\n\r\n");
  17025. if (hdr_end != std::string::npos) {
  17026. // Check for Content-Length to know when the body is complete
  17027. auto cl_pos = first_response.find("Content-Length:");
  17028. if (cl_pos != std::string::npos) {
  17029. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  17030. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  17031. auto cl = std::stoul(
  17032. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  17033. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  17034. } else {
  17035. break; // No Content-Length, assume headers-only response
  17036. }
  17037. }
  17038. }
  17039. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  17040. // Step 3: Now send the body, which looks like a new HTTP request.
  17041. // On a vulnerable server the keep-alive loop reads this as a second request.
  17042. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  17043. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  17044. // Step 4: Try to read a second response (should NOT exist after fix)
  17045. std::string second_response;
  17046. for (;;) {
  17047. auto n = recv(sock, buf, sizeof(buf), 0);
  17048. if (n <= 0) break;
  17049. second_response.append(buf, static_cast<size_t>(n));
  17050. }
  17051. // The smuggled request must NOT have been processed
  17052. EXPECT_EQ(0, smuggled_count.load());
  17053. }
  17054. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17055. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  17056. // must be rejected with 400 Bad Request.
  17057. Server svr;
  17058. svr.Post("/test", [&](const Request &, Response &res) {
  17059. res.set_content("ok", "text/plain");
  17060. });
  17061. thread t = thread([&] { svr.listen(HOST, PORT); });
  17062. auto se = detail::scope_exit([&] {
  17063. svr.stop();
  17064. t.join();
  17065. ASSERT_FALSE(svr.is_running());
  17066. });
  17067. svr.wait_until_ready();
  17068. // Exact "chunked"
  17069. {
  17070. auto req = "POST /test HTTP/1.1\r\n"
  17071. "Host: localhost\r\n"
  17072. "Content-Length: 5\r\n"
  17073. "Transfer-Encoding: chunked\r\n"
  17074. "Connection: close\r\n"
  17075. "\r\n"
  17076. "hello";
  17077. std::string response;
  17078. ASSERT_TRUE(send_request(1, req, &response));
  17079. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17080. response.substr(0, response.find("\r\n")));
  17081. }
  17082. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  17083. {
  17084. auto req = "POST /test HTTP/1.1\r\n"
  17085. "Host: localhost\r\n"
  17086. "Content-Length: 5\r\n"
  17087. "Transfer-Encoding: gzip, chunked\r\n"
  17088. "Connection: close\r\n"
  17089. "\r\n"
  17090. "hello";
  17091. std::string response;
  17092. ASSERT_TRUE(send_request(1, req, &response));
  17093. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  17094. response.substr(0, response.find("\r\n")));
  17095. }
  17096. }
  17097. // Regression for issue #2450: a DELETE without Content-Length on a
  17098. // keep-alive connection must not let the post-response drain consume the
  17099. // next request's bytes.
  17100. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  17101. Server svr;
  17102. std::atomic<int> delete_count(0);
  17103. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  17104. delete_count++;
  17105. res.status = StatusCode::NoContent_204;
  17106. });
  17107. auto port = svr.bind_to_any_port(HOST);
  17108. thread t = thread([&] { svr.listen_after_bind(); });
  17109. auto se = detail::scope_exit([&] {
  17110. svr.stop();
  17111. t.join();
  17112. });
  17113. svr.wait_until_ready();
  17114. auto error = Error::Success;
  17115. auto sock = detail::create_client_socket(
  17116. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17117. /*connection_timeout_sec=*/2, 0,
  17118. /*read_timeout_sec=*/2, 0,
  17119. /*write_timeout_sec=*/2, 0, std::string(), error);
  17120. ASSERT_NE(INVALID_SOCKET, sock);
  17121. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17122. auto send_request_and_read_response = [&](const std::string &req,
  17123. std::string &out) -> bool {
  17124. auto sent = send(sock, req.data(), req.size(), 0);
  17125. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  17126. char buf[4096];
  17127. for (;;) {
  17128. auto n = recv(sock, buf, sizeof(buf), 0);
  17129. if (n <= 0) { return !out.empty(); }
  17130. out.append(buf, static_cast<size_t>(n));
  17131. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  17132. }
  17133. };
  17134. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  17135. "Host: localhost\r\n"
  17136. "\r\n";
  17137. std::string resp1;
  17138. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  17139. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  17140. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  17141. "Host: localhost\r\n"
  17142. "Connection: close\r\n"
  17143. "\r\n";
  17144. std::string resp2;
  17145. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  17146. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  17147. EXPECT_EQ(2, delete_count.load());
  17148. }
  17149. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  17150. Server svr;
  17151. svr.Post("/ingest", [&](const Request &, Response &res,
  17152. const ContentReader &content_reader) {
  17153. auto consumed = content_reader([](const char *, size_t) { return false; });
  17154. EXPECT_FALSE(consumed);
  17155. res.status = StatusCode::Conflict_409;
  17156. res.set_header("Connection", "close");
  17157. });
  17158. auto port = svr.bind_to_any_port(HOST);
  17159. thread t = thread([&] { svr.listen_after_bind(); });
  17160. auto se = detail::scope_exit([&] {
  17161. svr.stop();
  17162. t.join();
  17163. });
  17164. svr.wait_until_ready();
  17165. auto error = Error::Success;
  17166. auto sock = detail::create_client_socket(
  17167. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17168. /*connection_timeout_sec=*/2, 0,
  17169. /*read_timeout_sec=*/1, 0,
  17170. /*write_timeout_sec=*/2, 0, std::string(), error);
  17171. ASSERT_NE(INVALID_SOCKET, sock);
  17172. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  17173. std::string request = "POST /ingest HTTP/1.1\r\n"
  17174. "Host: localhost\r\n"
  17175. "Transfer-Encoding: chunked\r\n"
  17176. "\r\n"
  17177. "4\r\n"
  17178. "data\r\n";
  17179. auto sent = send(sock, request.data(), request.size(), 0);
  17180. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  17181. std::string response;
  17182. ssize_t received = 0;
  17183. do {
  17184. char buf[4096];
  17185. received = recv(sock, buf, sizeof(buf), 0);
  17186. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  17187. } while (received > 0);
  17188. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  17189. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  17190. EXPECT_EQ(0, received);
  17191. }
  17192. namespace no_proxy_test {
  17193. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  17194. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  17195. // calling listen().
  17196. class ScopedServer {
  17197. public:
  17198. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  17199. ~ScopedServer() {
  17200. svr_.stop();
  17201. if (th_.joinable()) { th_.join(); }
  17202. }
  17203. Server &svr() { return svr_; }
  17204. int port() const { return port_; }
  17205. void listen() {
  17206. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17207. svr_.wait_until_ready();
  17208. }
  17209. private:
  17210. Server svr_;
  17211. std::thread th_;
  17212. int port_ = 0;
  17213. };
  17214. class ProxyAndTargetServers {
  17215. public:
  17216. ProxyAndTargetServers() {
  17217. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  17218. proxy_hits_++;
  17219. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17220. res.set_content("via-proxy", "text/plain");
  17221. });
  17222. target_.Get(".*", [this](const Request &req, Response &res) {
  17223. target_hits_++;
  17224. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  17225. res.set_content("direct", "text/plain");
  17226. });
  17227. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  17228. target_port_ = target_.bind_to_any_port("127.0.0.1");
  17229. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  17230. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  17231. proxy_mock_.wait_until_ready();
  17232. target_.wait_until_ready();
  17233. }
  17234. ~ProxyAndTargetServers() {
  17235. proxy_mock_.stop();
  17236. target_.stop();
  17237. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  17238. if (target_thread_.joinable()) { target_thread_.join(); }
  17239. }
  17240. Server &proxy_mock() { return proxy_mock_; }
  17241. Server &target() { return target_; }
  17242. int proxy_port() const { return proxy_port_; }
  17243. int target_port() const { return target_port_; }
  17244. int proxy_hits() const { return proxy_hits_.load(); }
  17245. int target_hits() const { return target_hits_.load(); }
  17246. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  17247. void reset_counters() {
  17248. proxy_hits_ = 0;
  17249. target_hits_ = 0;
  17250. last_had_proxy_authz_ = false;
  17251. }
  17252. private:
  17253. Server proxy_mock_;
  17254. Server target_;
  17255. std::thread proxy_thread_;
  17256. std::thread target_thread_;
  17257. int proxy_port_ = 0;
  17258. int target_port_ = 0;
  17259. std::atomic<int> proxy_hits_{0};
  17260. std::atomic<int> target_hits_{0};
  17261. std::atomic<bool> last_had_proxy_authz_{false};
  17262. };
  17263. inline std::unique_ptr<Client> make_client(const std::string &host,
  17264. ProxyAndTargetServers &s) {
  17265. auto cli = detail::make_unique<Client>(host, s.target_port());
  17266. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  17267. cli->set_proxy("127.0.0.1", s.proxy_port());
  17268. return cli;
  17269. }
  17270. } // namespace no_proxy_test
  17271. using no_proxy_test::make_client;
  17272. using no_proxy_test::ProxyAndTargetServers;
  17273. TEST(NoProxyTest, ExactHostnameBypasses) {
  17274. ProxyAndTargetServers s;
  17275. auto cli = make_client("example.com", s);
  17276. cli->set_no_proxy({"example.com"});
  17277. auto res = cli->Get("/");
  17278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17279. EXPECT_EQ(0, s.proxy_hits());
  17280. EXPECT_EQ(1, s.target_hits());
  17281. }
  17282. TEST(NoProxyTest, SubdomainBypasses) {
  17283. ProxyAndTargetServers s;
  17284. auto cli = make_client("foo.example.com", s);
  17285. cli->set_no_proxy({"example.com"});
  17286. auto res = cli->Get("/");
  17287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17288. EXPECT_EQ(0, s.proxy_hits());
  17289. EXPECT_EQ(1, s.target_hits());
  17290. }
  17291. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  17292. // Regression guard: "evilexample.com" must not be considered a subdomain
  17293. // of "example.com". Without the dot-boundary rule, a naive endsWith
  17294. // check would let traffic bypass the proxy and leak credentials direct
  17295. // to the attacker host.
  17296. ProxyAndTargetServers s;
  17297. auto cli = make_client("evilexample.com", s);
  17298. cli->set_no_proxy({"example.com"});
  17299. auto res = cli->Get("/");
  17300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17301. EXPECT_GE(s.proxy_hits(), 1);
  17302. EXPECT_EQ(0, s.target_hits());
  17303. }
  17304. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  17305. ProxyAndTargetServers s;
  17306. auto cli = make_client("example.com.evil.com", s);
  17307. cli->set_no_proxy({"example.com"});
  17308. auto res = cli->Get("/");
  17309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17310. EXPECT_GE(s.proxy_hits(), 1);
  17311. EXPECT_EQ(0, s.target_hits());
  17312. }
  17313. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  17314. ProxyAndTargetServers s;
  17315. auto cli = make_client("example.com", s);
  17316. cli->set_no_proxy({".example.com"});
  17317. auto res = cli->Get("/");
  17318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17319. EXPECT_EQ(0, s.proxy_hits());
  17320. EXPECT_EQ(1, s.target_hits());
  17321. }
  17322. TEST(NoProxyTest, CaseInsensitiveHostname) {
  17323. ProxyAndTargetServers s;
  17324. auto cli = make_client("Example.COM", s);
  17325. cli->set_no_proxy({"EXAMPLE.com"});
  17326. auto res = cli->Get("/");
  17327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17328. EXPECT_EQ(0, s.proxy_hits());
  17329. EXPECT_EQ(1, s.target_hits());
  17330. }
  17331. TEST(NoProxyTest, TrailingDotIsNormalized) {
  17332. ProxyAndTargetServers s;
  17333. auto cli = make_client("example.com.", s);
  17334. cli->set_no_proxy({"example.com"});
  17335. auto res = cli->Get("/");
  17336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17337. EXPECT_EQ(0, s.proxy_hits());
  17338. EXPECT_EQ(1, s.target_hits());
  17339. }
  17340. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  17341. // Trailing dots must be normalized on BOTH sides — host and entry.
  17342. // An implementation that only strips the host-side trailing dot would
  17343. // fail to match host "example.com" against entry "example.com." because
  17344. // a literal substring search would compare 11 chars against 12.
  17345. ProxyAndTargetServers s;
  17346. auto cli = make_client("example.com", s);
  17347. cli->set_no_proxy({"example.com."});
  17348. auto res = cli->Get("/");
  17349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17350. EXPECT_EQ(0, s.proxy_hits());
  17351. EXPECT_EQ(1, s.target_hits());
  17352. }
  17353. TEST(NoProxyTest, WildcardBypassesEverything) {
  17354. ProxyAndTargetServers s;
  17355. auto cli = make_client("anything.invalid.test", s);
  17356. cli->set_no_proxy({"*"});
  17357. auto res = cli->Get("/");
  17358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17359. EXPECT_EQ(0, s.proxy_hits());
  17360. EXPECT_EQ(1, s.target_hits());
  17361. }
  17362. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  17363. ProxyAndTargetServers s;
  17364. Client cli("127.0.0.1", s.target_port());
  17365. cli.set_proxy("127.0.0.1", s.proxy_port());
  17366. cli.set_no_proxy({"127.0.0.1"});
  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, IPv6LiteralExactMatchAcrossEquivalentForms) {
  17373. ProxyAndTargetServers s;
  17374. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  17375. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  17376. cli.set_proxy("127.0.0.1", s.proxy_port());
  17377. cli.set_no_proxy({"::1"});
  17378. auto res = cli.Get("/");
  17379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17380. EXPECT_EQ(0, s.proxy_hits());
  17381. EXPECT_EQ(1, s.target_hits());
  17382. }
  17383. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  17384. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  17385. // must still be recognized as IPv6 for CIDR matching. Implementations
  17386. // that detect IPv6 only when the host begins with '[' would parse the
  17387. // host as a hostname and miss the match.
  17388. ProxyAndTargetServers s;
  17389. Client cli("fe80::1", s.target_port());
  17390. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17391. cli.set_proxy("127.0.0.1", s.proxy_port());
  17392. cli.set_no_proxy({"fe80::/10"});
  17393. auto res = cli.Get("/");
  17394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17395. EXPECT_EQ(0, s.proxy_hits());
  17396. EXPECT_EQ(1, s.target_hits());
  17397. }
  17398. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  17399. ProxyAndTargetServers s;
  17400. Client cli("::1", s.target_port());
  17401. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  17402. cli.set_proxy("127.0.0.1", s.proxy_port());
  17403. cli.set_no_proxy({"[::1]"});
  17404. auto res = cli.Get("/");
  17405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17406. EXPECT_EQ(0, s.proxy_hits());
  17407. EXPECT_EQ(1, s.target_hits());
  17408. }
  17409. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  17410. ProxyAndTargetServers s;
  17411. Client cli("fe80::1", s.target_port());
  17412. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  17413. cli.set_proxy("127.0.0.1", s.proxy_port());
  17414. cli.set_no_proxy({"[fe80::]/10"});
  17415. auto res = cli.Get("/");
  17416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17417. EXPECT_EQ(0, s.proxy_hits());
  17418. EXPECT_EQ(1, s.target_hits());
  17419. }
  17420. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  17421. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  17422. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  17423. // tricks via address-family conversion.
  17424. ProxyAndTargetServers s;
  17425. Client cli("::ffff:127.0.0.1", s.target_port());
  17426. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  17427. cli.set_proxy("127.0.0.1", s.proxy_port());
  17428. cli.set_no_proxy({"127.0.0.1"});
  17429. auto res = cli.Get("/");
  17430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17431. EXPECT_GE(s.proxy_hits(), 1);
  17432. EXPECT_EQ(0, s.target_hits());
  17433. }
  17434. TEST(NoProxyTest, IPv4CidrMatch) {
  17435. ProxyAndTargetServers s;
  17436. Client cli("127.0.0.1", s.target_port());
  17437. cli.set_proxy("127.0.0.1", s.proxy_port());
  17438. cli.set_no_proxy({"127.0.0.0/8"});
  17439. auto res = cli.Get("/");
  17440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17441. EXPECT_EQ(0, s.proxy_hits());
  17442. EXPECT_EQ(1, s.target_hits());
  17443. }
  17444. TEST(NoProxyTest, IPv4CidrNonMatch) {
  17445. ProxyAndTargetServers s;
  17446. Client cli("127.0.0.1", s.target_port());
  17447. cli.set_proxy("127.0.0.1", s.proxy_port());
  17448. cli.set_no_proxy({"10.0.0.0/8"});
  17449. auto res = cli.Get("/");
  17450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17451. EXPECT_GE(s.proxy_hits(), 1);
  17452. EXPECT_EQ(0, s.target_hits());
  17453. }
  17454. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  17455. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  17456. // IPv4 target matches.
  17457. ProxyAndTargetServers s;
  17458. Client cli("127.0.0.1", s.target_port());
  17459. cli.set_proxy("127.0.0.1", s.proxy_port());
  17460. cli.set_no_proxy({"0.0.0.0/0"});
  17461. auto res = cli.Get("/");
  17462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17463. EXPECT_EQ(0, s.proxy_hits());
  17464. EXPECT_EQ(1, s.target_hits());
  17465. }
  17466. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  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.1"});
  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, MalformedCidrPrefixIsDropped) {
  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({"127.0.0.0/33"});
  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, TrailingSlashCidrIsRejected) {
  17487. // Empty prefix after the slash must be rejected, not silently treated as /32.
  17488. ProxyAndTargetServers s;
  17489. Client cli("127.0.0.1", s.target_port());
  17490. cli.set_proxy("127.0.0.1", s.proxy_port());
  17491. cli.set_no_proxy({"127.0.0.1/"});
  17492. auto res = cli.Get("/");
  17493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17494. EXPECT_GE(s.proxy_hits(), 1);
  17495. EXPECT_EQ(0, s.target_hits());
  17496. }
  17497. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  17498. ProxyAndTargetServers s;
  17499. auto cli = make_client("internal.corp", s);
  17500. cli->set_proxy_basic_auth("u", "p");
  17501. cli->set_no_proxy({"internal.corp"});
  17502. auto res = cli->Get("/");
  17503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17504. EXPECT_EQ(1, s.target_hits());
  17505. EXPECT_EQ(0, s.proxy_hits());
  17506. EXPECT_FALSE(s.last_had_proxy_authz())
  17507. << "Proxy-Authorization must not be sent direct to the target";
  17508. }
  17509. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  17510. ProxyAndTargetServers s;
  17511. auto cli = make_client("public.example", s);
  17512. cli->set_proxy_basic_auth("u", "p");
  17513. cli->set_no_proxy({"internal.corp"}); // does not match
  17514. auto res = cli->Get("/");
  17515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17516. EXPECT_GE(s.proxy_hits(), 1);
  17517. EXPECT_TRUE(s.last_had_proxy_authz());
  17518. }
  17519. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  17520. ProxyAndTargetServers s;
  17521. auto cli = make_client("anything.test", s);
  17522. auto res = cli->Get("/");
  17523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17524. EXPECT_GE(s.proxy_hits(), 1);
  17525. EXPECT_EQ(0, s.target_hits());
  17526. }
  17527. TEST(NoProxyTest, PortSpecificEntryRejected) {
  17528. ProxyAndTargetServers s;
  17529. auto cli = make_client("example.com", s);
  17530. cli->set_no_proxy({"example.com:8080"});
  17531. auto res = cli->Get("/");
  17532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17533. EXPECT_GE(s.proxy_hits(), 1);
  17534. EXPECT_EQ(0, s.target_hits());
  17535. }
  17536. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  17537. ProxyAndTargetServers s;
  17538. auto cli = make_client("anything.test", s);
  17539. cli->set_no_proxy({"", " ", "\t"});
  17540. auto res = cli->Get("/");
  17541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17542. EXPECT_GE(s.proxy_hits(), 1);
  17543. EXPECT_EQ(0, s.target_hits());
  17544. }
  17545. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  17546. // An entry with leading/trailing whitespace must still match — env-style
  17547. // values are commonly pasted with stray spaces and an implementation
  17548. // that feeds the raw token directly to inet_pton would fail to match
  17549. // valid CIDRs because of the spaces.
  17550. ProxyAndTargetServers s;
  17551. Client cli("127.0.0.1", s.target_port());
  17552. cli.set_proxy("127.0.0.1", s.proxy_port());
  17553. cli.set_no_proxy({" 127.0.0.0/8 "});
  17554. auto res = cli.Get("/");
  17555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17556. EXPECT_EQ(0, s.proxy_hits());
  17557. EXPECT_EQ(1, s.target_hits());
  17558. }
  17559. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  17560. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  17561. // go direct and must NOT carry Proxy-Authorization.
  17562. std::atomic<int> proxy_hits{0};
  17563. std::atomic<int> target_hits{0};
  17564. std::atomic<bool> target_saw_authz{false};
  17565. no_proxy_test::ScopedServer proxy_mock, target;
  17566. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17567. proxy_hits++;
  17568. res.status = 302;
  17569. res.set_header("Location", "http://127.0.0.1:" +
  17570. std::to_string(target.port()) + "/landed");
  17571. });
  17572. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17573. target_hits++;
  17574. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  17575. res.set_content("direct", "text/plain");
  17576. });
  17577. proxy_mock.listen();
  17578. target.listen();
  17579. Client cli("public.example", target.port());
  17580. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17581. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17582. cli.set_proxy_basic_auth("u", "p");
  17583. cli.set_no_proxy({"127.0.0.1"});
  17584. cli.set_follow_location(true);
  17585. auto res = cli.Get("/redir");
  17586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17587. EXPECT_GE(proxy_hits.load(), 1);
  17588. EXPECT_GE(target_hits.load(), 1);
  17589. EXPECT_FALSE(target_saw_authz.load());
  17590. }
  17591. #ifdef CPPHTTPLIB_SSL_ENABLED
  17592. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  17593. // Direct origin replying 407 must not trigger the digest retry; otherwise
  17594. // proxy creds would be sent to the (possibly hostile) origin.
  17595. std::atomic<int> target_hits{0};
  17596. std::atomic<bool> target_saw_proxy_authz{false};
  17597. no_proxy_test::ScopedServer target;
  17598. target.svr().Get(".*", [&](const Request &req, Response &res) {
  17599. target_hits++;
  17600. if (req.has_header("Proxy-Authorization")) {
  17601. target_saw_proxy_authz = true;
  17602. }
  17603. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17604. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  17605. "nonce=\"abc\", algorithm=MD5");
  17606. });
  17607. target.listen();
  17608. // The proxy address is set to the target's port: the bypass MUST kick in;
  17609. // if it doesn't, the test still routes "via proxy" to the same server and
  17610. // the Proxy-Authorization assertion below catches the leak.
  17611. Client cli("evil.example", target.port());
  17612. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  17613. cli.set_proxy("127.0.0.1", target.port());
  17614. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17615. cli.set_no_proxy({"evil.example"});
  17616. auto res = cli.Get("/x");
  17617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17618. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17619. EXPECT_EQ(1, target_hits.load());
  17620. EXPECT_FALSE(target_saw_proxy_authz.load());
  17621. }
  17622. #endif
  17623. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  17624. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  17625. std::atomic<int> proxy_hits{0};
  17626. std::atomic<int> bypass_hits{0};
  17627. std::atomic<bool> proxy_saw_c_url{false};
  17628. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  17629. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  17630. proxy_hits++;
  17631. if (req.path.find("/start") != std::string::npos) {
  17632. res.status = 302;
  17633. res.set_header("Location", "http://127.0.0.1:" +
  17634. std::to_string(bypass_server.port()) +
  17635. "/middle");
  17636. return;
  17637. }
  17638. if (req.path.find("/end") != std::string::npos) {
  17639. proxy_saw_c_url = true;
  17640. res.set_content("c-via-proxy", "text/plain");
  17641. return;
  17642. }
  17643. res.set_content("unexpected", "text/plain");
  17644. });
  17645. // public.example's "advertised" port is arbitrary (the request never lands
  17646. // there — it goes through the proxy), but use a dynamic value to stay
  17647. // friendly with sharded parallel runs.
  17648. int public_port = bypass_server.port();
  17649. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  17650. bypass_hits++;
  17651. res.status = 302;
  17652. res.set_header("Location", "http://public.example:" +
  17653. std::to_string(public_port) + "/end");
  17654. });
  17655. proxy_mock.listen();
  17656. bypass_server.listen();
  17657. Client cli("public.example", public_port);
  17658. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17659. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17660. cli.set_no_proxy({"127.0.0.1"});
  17661. cli.set_follow_location(true);
  17662. auto res = cli.Get("/start");
  17663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17664. EXPECT_EQ(StatusCode::OK_200, res->status);
  17665. EXPECT_EQ("c-via-proxy", res->body);
  17666. EXPECT_GE(proxy_hits.load(), 2);
  17667. EXPECT_GE(bypass_hits.load(), 1);
  17668. EXPECT_TRUE(proxy_saw_c_url.load());
  17669. }
  17670. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  17671. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  17672. // request reconnects to the correct endpoint.
  17673. std::atomic<int> proxy_hits{0};
  17674. std::atomic<int> target_hits{0};
  17675. no_proxy_test::ScopedServer proxy_mock, target;
  17676. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  17677. proxy_hits++;
  17678. res.set_content("via-proxy", "text/plain");
  17679. });
  17680. target.svr().Get(".*", [&](const Request &, Response &res) {
  17681. target_hits++;
  17682. res.set_content("direct", "text/plain");
  17683. });
  17684. proxy_mock.listen();
  17685. target.listen();
  17686. Client cli("public.example", target.port());
  17687. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  17688. cli.set_proxy("127.0.0.1", proxy_mock.port());
  17689. cli.set_keep_alive(true);
  17690. auto res1 = cli.Get("/a");
  17691. ASSERT_TRUE(res1);
  17692. EXPECT_EQ("via-proxy", res1->body);
  17693. EXPECT_EQ(1, proxy_hits.load());
  17694. EXPECT_EQ(0, target_hits.load());
  17695. cli.set_no_proxy({"public.example"});
  17696. auto res2 = cli.Get("/b");
  17697. ASSERT_TRUE(res2);
  17698. EXPECT_EQ("direct", res2->body);
  17699. EXPECT_EQ(1, proxy_hits.load());
  17700. EXPECT_EQ(1, target_hits.load());
  17701. }
  17702. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  17703. namespace proxy_tunnel_test {
  17704. // SSLServer counterpart to no_proxy_test::ScopedServer.
  17705. class ScopedSSLServer {
  17706. public:
  17707. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  17708. port_ = svr_.bind_to_any_port("127.0.0.1");
  17709. }
  17710. ~ScopedSSLServer() {
  17711. svr_.stop();
  17712. if (th_.joinable()) { th_.join(); }
  17713. }
  17714. SSLServer &svr() { return svr_; }
  17715. int port() const { return port_; }
  17716. void listen() {
  17717. th_ = std::thread([this] { svr_.listen_after_bind(); });
  17718. svr_.wait_until_ready();
  17719. }
  17720. private:
  17721. SSLServer svr_;
  17722. std::thread th_;
  17723. int port_ = 0;
  17724. };
  17725. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  17726. class ScopedConnectProxy {
  17727. public:
  17728. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  17729. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  17730. if (listen_fd_ < 0) { return; }
  17731. int yes = 1;
  17732. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  17733. sockaddr_in a{};
  17734. a.sin_family = AF_INET;
  17735. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17736. a.sin_port = 0;
  17737. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  17738. return;
  17739. }
  17740. socklen_t alen = sizeof(a);
  17741. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  17742. 0) {
  17743. return;
  17744. }
  17745. port_ = ntohs(a.sin_port);
  17746. if (::listen(listen_fd_, 1) != 0) { return; }
  17747. th_ = std::thread([this] { run(); });
  17748. }
  17749. ~ScopedConnectProxy() {
  17750. stop_ = true;
  17751. if (listen_fd_ >= 0) {
  17752. ::shutdown(listen_fd_, SHUT_RDWR);
  17753. ::close(listen_fd_);
  17754. }
  17755. if (th_.joinable()) { th_.join(); }
  17756. }
  17757. int port() const { return port_; }
  17758. int connect_hits() const { return connect_hits_.load(); }
  17759. private:
  17760. void run() {
  17761. while (!stop_.load()) {
  17762. fd_set rfds;
  17763. FD_ZERO(&rfds);
  17764. FD_SET(listen_fd_, &rfds);
  17765. timeval tv{0, 100 * 1000};
  17766. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  17767. if (sel <= 0) { continue; }
  17768. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  17769. if (client_fd < 0) { continue; }
  17770. std::string req;
  17771. char buf[2048];
  17772. while (req.find("\r\n\r\n") == std::string::npos) {
  17773. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  17774. if (n <= 0) { break; }
  17775. req.append(buf, static_cast<size_t>(n));
  17776. }
  17777. if (req.compare(0, 7, "CONNECT") != 0) {
  17778. ::close(client_fd);
  17779. continue;
  17780. }
  17781. connect_hits_++;
  17782. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  17783. ::send(client_fd, ok, std::strlen(ok), 0);
  17784. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  17785. sockaddr_in o{};
  17786. o.sin_family = AF_INET;
  17787. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  17788. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  17789. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  17790. 0) {
  17791. ::close(client_fd);
  17792. ::close(origin_fd);
  17793. continue;
  17794. }
  17795. auto forward = [](int from, int to) {
  17796. char b[8192];
  17797. for (;;) {
  17798. ssize_t n = ::recv(from, b, sizeof(b), 0);
  17799. if (n <= 0) { break; }
  17800. ssize_t off = 0;
  17801. while (off < n) {
  17802. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  17803. if (s <= 0) {
  17804. off = n;
  17805. break;
  17806. }
  17807. off += s;
  17808. }
  17809. }
  17810. ::shutdown(to, SHUT_WR);
  17811. };
  17812. std::thread t1([&] { forward(client_fd, origin_fd); });
  17813. std::thread t2([&] { forward(origin_fd, client_fd); });
  17814. t1.join();
  17815. t2.join();
  17816. ::close(client_fd);
  17817. ::close(origin_fd);
  17818. }
  17819. }
  17820. int forward_port_ = -1;
  17821. int listen_fd_ = -1;
  17822. int port_ = 0;
  17823. std::thread th_;
  17824. std::atomic<bool> stop_{false};
  17825. std::atomic<int> connect_hits_{0};
  17826. };
  17827. } // namespace proxy_tunnel_test
  17828. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  17829. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  17830. // retry; otherwise proxy creds would be sent to the origin.
  17831. std::atomic<int> origin_hits{0};
  17832. std::atomic<bool> origin_saw_proxy_authz{false};
  17833. proxy_tunnel_test::ScopedSSLServer origin;
  17834. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  17835. origin_hits++;
  17836. if (req.has_header("Proxy-Authorization")) {
  17837. origin_saw_proxy_authz = true;
  17838. }
  17839. res.status = StatusCode::ProxyAuthenticationRequired_407;
  17840. res.set_header("Proxy-Authenticate",
  17841. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  17842. "algorithm=MD5");
  17843. });
  17844. origin.listen();
  17845. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  17846. ASSERT_NE(0, proxy.port());
  17847. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  17848. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  17849. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  17850. // and answer with its own status, making this test flaky.
  17851. SSLClient cli("127.0.0.1", origin.port());
  17852. cli.enable_server_certificate_verification(false);
  17853. cli.set_proxy("127.0.0.1", proxy.port());
  17854. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  17855. auto res = cli.Get("/x");
  17856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17857. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  17858. EXPECT_EQ(1, origin_hits.load());
  17859. EXPECT_FALSE(origin_saw_proxy_authz.load());
  17860. EXPECT_EQ(1, proxy.connect_hits());
  17861. }
  17862. #endif